I'm developing a simple api with GAE standard and Cloud Endpoint to test the available quota feature.
Here's the Java Code using the EndPoint Framework annotation:
package com.example.skeleton;
import com.google.api.server.spi.config.*;
#Api(
name = "simpleapi",
version = "v1",
limitDefinitions = {
#ApiLimitMetric(
name = "read-requests",
displayName = "Read requests",
limit = 10
)
}
)
public class MyApi {
#ApiMethod(
name = "hellosecuredWithQuotas",
path = "hellosecuredWithQuotas",
httpMethod = ApiMethod.HttpMethod.GET,
apiKeyRequired= AnnotationBoolean.TRUE,
metricCosts = {
#ApiMetricCost(
name ="read-requests",
cost = 1
)
}
)
public Message helloSecuredWithQuotas(#Named("name") String name) {
return new Message("hello " + name);
}
}
So given the #Api annotations the quotas is 10 requests per minute.
I deploy the App in GAE.
I Generate the OpenAPI json file (see below for the generated content) and deploy it to Cloud Endpoint using gcloud CLI.
Finally I use the generated client to call the endpoint in a loop which is calling the endpoint more than 10 times per minute.
... but unfortunately I never receive the expected "HTTP status code of 429 Too Many Requests".
public class App {
public static void main(String []args) throws IOException {
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
Simpleapi simpleapi = new Simpleapi.Builder(httpTransport, jsonFactory, null)
.setApplicationName("test")
.build();
for (int i = 0; i < 1000 ; i++) {
Message titi = simpleapi.hellosecuredWithQuotas("foobar" + System.currentTimeMillis()).setKey("my-api-key-here").execute();
System.out.println(titi.getMessage());
}
}
}
Here is the generated openapi.json file:
{
"swagger": "2.0",
"info": {
"version": "1.0.0",
"title": "my-project-name-here.appspot.com"
},
"host": "my-project-name-here.appspot.com",
"basePath": "/_ah/api",
"schemes": [
"https"
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"paths": {
"/simpleapi/v1/hellosecuredWithQuotas": {
"get": {
"operationId": "SimpleapiHelloSecuredWithQuotas",
"parameters": [
{
"name": "name",
"in": "query",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "A successful response",
"schema": {
"$ref": "#/definitions/Message"
}
}
},
"security": [
{
"api_key": []
}
],
"x-google-quota": {
"metricCosts": {
"read-requests": 10
}
}
}
}
},
"securityDefinitions": {
"api_key": {
"type": "apiKey",
"name": "key",
"in": "query"
}
},
"definitions": {
"Message": {
"type": "object",
"properties": {
"message": {
"type": "string"
}
}
}
},
"x-google-management": {
"metrics": [
{
"name": "read-requests",
"valueType": "INT64",
"metricKind": "GAUGE"
}
],
"quota": {
"limits": [
{
"name": "read-requests",
"metric": "read-requests",
"values": {
"STANDARD": 10
},
"unit": "1/min/{project}",
"displayName": "Read requests"
}
]
}
}
}
I was able to get this to work by setting the limit value in the ApiLimitMetric configuration to a value 100 or greater. If you'd like to have a maximum of 10 requests per minute, you should set the limit to 100 and the cost value in the ApiMetricCost configuration on the method to 10. This would give you the same ratio of 1/10 as listed in your original post.
Related
I need to create an OpenAPI JSON file programmatically as my endpoints have a one-to-one mapping with the tables in the database. I need to create the components (Schemas) which needs to be referenced in response object. I am not able to create the OAI3Context object as I do not have a URL which needs to be passed as argument.
OpenAPI4J Maven entry in my pom.xml:
<!-- https://mvnrepository.com/artifact/org.openapi4j/openapi-parser -->
<dependency>
<groupId>org.openapi4j</groupId>
<artifactId>openapi-parser</artifactId>
<version>1.0.7</version>
</dependency>
Sample openapi.json file which I want to make programatically:
{
"openapi": "3.0.2",
"info": {
"contact": {
"email": "johndoe#TEST.com",
"name": "John Doe",
"url": "https://www.TEST.com/api/support"
},
"description": "TEST API based on the OpenAPI 3.0.2 specification.",
"license": {
"name": "TEST Inc",
"url": "https://www.TEST.com/licences/LICENSE-2.0.html"
},
"termsOfService": "https://www.TEST.com/api/terms",
"title": "TEST API - OpenAPI 3.0.2",
"version": "1.0.0"
},
"servers": [
{
"url": "http://localhost:8080/TEST-REST/api/",
"description": "descirption1"
}
],
"tags": [
{
"name": "connection",
"description": "Connection management API ",
"externalDocs": {
"description": "Connection management API",
"url": "http://www.TEST.com"
}
},
{
"name": "REST API",
"description": "TEST's non-crud APIs",
"externalDocs": {
"description": "TEST's non-crud APIs",
"url": "http://www.TEST.com"
}
},
{
"name": "objects",
"description": "TEST CRUD Operations on selected table",
"externalDocs": {
"description": "CRUD API TEST TEST. Can be done on selected tables",
"url": "http://www.TEST.com"
}
}
],
"paths": {
"/rest/authenticate": {
"description": "authenticate and get a token",
"summary": "authenticate and get a connection token",
"get": {
"tags": [
"connection"
],
"operationId": "authenticate",
"parameters": [
{
"required": true,
"schema": {
"description": "TEST datasource to connect to",
"type": "string"
},
"in": "query",
"name": "username"
},
{
"required": true,
"schema": {
"description": "password of the user",
"type": "string"
},
"in": "query",
"name": "password"
},
{
"required": true,
"schema": {
"description": "TEST datasource to connect to",
"type": "string"
},
"in": "query",
"name": "datasource"
},
{
"required": true,
"schema": {
"description": "TEST Service to connect to",
"type": "string"
},
"in": "query",
"name": "service"
},
{
"required": false,
"schema": {
"description": "User role",
"type": "string"
},
"in": "query",
"name": "role"
}
],
"responses": {
"200": {
"description": "Successful Connection",
"content": {
"application/json": {
"schema": {
"$ref" : "#/components/schemas/connection"
}
},
"application/xml": {
"schema": {
"$ref" : "#/components/schemas/connection"
}
}
}
},
"405": {
"description": "Invalid input"
}
}
}
}
},
"components": {
"schemas": {
"connection": {
"required": [
"connid"
],
"type": "object",
"properties": {
"connid": {
"type": "string",
"example": "TEST1_107c5a8c1799d4cf8bb5ce295ab38954"
}
}
}
}
}
}
My Java code:
package vish.api.test2;
import org.openapi4j.core.exception.EncodeException;
import org.openapi4j.parser.model.SerializationFlag;
import org.openapi4j.parser.model.v3.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class OpenAPICreator {
public static void main(String[] args) {
try {
OpenApi3 openApi3 = new OpenApi3();
openApi3.setOpenapi("3.0.2");
Info info = new Info();
openApi3.setInfo(info);
info.setTitle("vish API - OpenAPI 3.0.2");
info.setDescription("vish API based on the OpenAPI 3.0.2 specification.");
info.setTermsOfService("https://www.vish.com/api/terms");
Contact contact = new Contact();
contact.setName("Avik Chatterjee");
contact.setEmail("achatterjee#vish.com");
contact.setUrl("https://www.vish.com/api/support");
info.setContact(contact);
Components components = new Components();
Schema schema = new Schema();
components.setSchema("test", schema);
Schema schema2 = new Schema();
schema.setProperty("test2", schema2);
openApi3.setComponents(components);
String canonicalRef = schema2.getCanonicalRef();
System.out.println("canonicalRef = " + canonicalRef);
License license = new License();
license.setName("vish Inc");
license.setUrl("https://www.vish.com/licences/LICENSE-2.0.html");
info.setLicense(license);
info.setVersion("1.0.0");
ExternalDocs externalDocs = new ExternalDocs();
externalDocs.setDescription("vish API Description");
externalDocs.setUrl("https://www.vish.com");
Server server1 = new Server();
server1.setDescription("descirption1");
server1.setUrl("http://localhost:8080/LIMS-REST/api/");
/* Server server2 = new Server();
server2.setDescription("test diff descirption1");
server2.setUrl("http://localhost:8080/LIMS-REST/api/");*/
ArrayList<Server> serverArrayList = new ArrayList<>();
serverArrayList.add(server1);
//serverArrayList.add(server2);
openApi3.setServers(serverArrayList);
Tag connectionTag = new Tag();
Tag restTag = new Tag();
Tag objectsTag = new Tag();
List<Tag> tagList = new ArrayList<>();
tagList.add(connectionTag);
tagList.add(restTag);
tagList.add(objectsTag);
connectionTag.setName("connection");
connectionTag.setDescription("Connection management API ");
ExternalDocs authDocs = new ExternalDocs();
authDocs.setDescription("Connection management API");
authDocs.setUrl("http://www.vish.com");
connectionTag.setExternalDocs(authDocs);
restTag.setName("REST API");
restTag.setDescription("vish's non-crud APIs");
ExternalDocs listWFDocs = new ExternalDocs();
listWFDocs.setDescription("vish's non-crud APIs");
listWFDocs.setUrl("http://www.vish.com");
restTag.setExternalDocs(listWFDocs);
objectsTag.setName("objects");
objectsTag.setDescription("vish CRUD Operations on selected table");
ExternalDocs crudDocs = new ExternalDocs();
crudDocs.setDescription("CRUD API vish LIMS. Can be done on selected tables");
crudDocs.setUrl("http://www.vish.com");
objectsTag.setExternalDocs(crudDocs);
openApi3.setTags(tagList);
Schema connectionSchema = new Schema();
// connectionSchema.setre
// connectionSchema.setReference(oai3Context, new URL("http://localhost:8080/TEST-REST/"), "connection" );
components.setSchema("connection", connectionSchema);
connectionSchema.setType("Object");
Schema connIdSchema = new Schema();
connectionSchema.setType("string");
connectionSchema.setExample("TEST1_107c5a8c1799d4cf8bb5ce295ab38954");
connectionSchema.setProperty("connid", connIdSchema);
Path authPath = new Path();
Operation authOps = new Operation();
authPath.setOperation("get", authOps);
authPath.setDescription("authenticate and get a token");
authPath.setSummary("authenticate and get a connection token");
authOps.addTag(connectionTag.getName());
authOps.setOperationId("authenticate");
Parameter username = new Parameter();
username.setName("username");
username.setIn("query");
username.setRequired(true);
Schema userSchema = new Schema();
userSchema.setDescription("TEST datasource to connect to");
userSchema.setType("string");
username.setSchema(userSchema);
authOps.addParameter(username);
Parameter password = new Parameter();
password.setName("password");
password.setIn("query");
password.setRequired(true);
password.setRequired(true);
Schema pwdSchema = new Schema();
pwdSchema.setDescription("password of the user");
pwdSchema.setType("string");
password.setSchema(pwdSchema);
authOps.addParameter(password);
Parameter database = new Parameter();
database.setName("datasource");
database.setIn("query");
database.setRequired(true);
Schema dbSchema = new Schema();
dbSchema.setDescription("TEST datasource to connect to");
dbSchema.setType("string");
database.setSchema(dbSchema);
authOps.addParameter(database);
Parameter service = new Parameter();
service.setName("service");
service.setIn("query");
service.setRequired(true);
Schema serviceSchema = new Schema();
serviceSchema.setDescription("TEST Service to connect to");
serviceSchema.setType("string");
service.setSchema(serviceSchema);
authOps.addParameter(service);
Parameter role = new Parameter();
role.setName("role");
role.setIn("query");
role.setRequired(false);
Schema roleSchema = new Schema();
roleSchema.setDescription("User role");
roleSchema.setType("string");
role.setSchema(roleSchema);
authOps.addParameter(role);
Response resp_200 = new Response();
resp_200.setDescription("Successful Connection");
MediaType mediaType = new MediaType();
Schema resp200Schema = new Schema();
// resp200Schema.setReference(oai3Context, new URL("http://localhost:8080/TEST-REST/"), "connection");
mediaType.setSchema(resp200Schema);
resp_200.setContentMediaType("application/json", mediaType);
authOps.setResponse("200", resp_200);
Map<String, Path> pathMap = new HashMap<>();
pathMap.put("/rest/authenticate", authPath);
// pathMap.put("/rest/close", closePath);
openApi3.setPaths(pathMap);
SerializationFlag outAsJson = SerializationFlag.OUT_AS_JSON;
EnumSet<SerializationFlag> enumSet = EnumSet.of(outAsJson);
String openAPIJson = openApi3.toString(enumSet);
SerializationFlag outAsYaml = SerializationFlag.OUT_AS_YAML;
EnumSet<SerializationFlag> enumYamlSet = EnumSet.of(outAsYaml);
String yaml = openApi3.toString(enumYamlSet);
FileOutputStream fos1 = new FileOutputStream(new File("vish1.json"));
FileOutputStream fos2 = new FileOutputStream(new File("vish1.yaml"));
fos1.write(openAPIJson.getBytes(StandardCharsets.UTF_8));
fos2.write(yaml.getBytes(StandardCharsets.UTF_8));
// System.out.println("gson way = \n" + gson.toJson(openApi3) );
} catch (EncodeException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
To sum up, how do I create the following programmatically without creating an OpenAPI3Context and refer the component in my 'responses'?
"components": {
"schemas": {
"connection": {
"required": [
"connid"
],
"type": "object",
"properties": {
"connid": {
"type": "string",
"example": "TEST1_107c5a8c1799d4cf8bb5ce295ab38954"
}
}
}
}
}
I am looking to generate an api that take different content type.
The problem I am facing is that if I run several time my application I have different output documentation
#RestController
public class MyRestController {
#Operation(summary = "GetMyData", operationId = "gettt",
responses = #ApiResponse(responseCode = "204", content = #Content(mediaType = "application/vnd.something")))
#GetMapping(produces = "application/vnd.something")
public ResponseEntity<Void> getSomethingElse() {
return noContent().build();
}
#GetMapping(produces = TEXT_PLAIN_VALUE)
public String get() {
return "some text";
}
#GetMapping(produces = HAL_JSON_VALUE)
public EntityModel<JsonResponse> getHal() {
return EntityModel.of(new JsonResponse(),
linkTo(MyRestController.class).slash("somelink").withSelfRel()
);
}
#GetMapping(produces = APPLICATION_JSON_VALUE)
public JsonResponse getJson() {
return new JsonResponse();
}
}
It currently generate a wrong api-docs
"operationId": "gettt_1_1_1",
"responses": {
"200": {
"content": {
"application/hal+json": {
"schema": {
"$ref": "#/components/schemas/EntityModelJsonResponse"
}
},
"application/json": {
"schema": {
"$ref": "#/components/schemas/JsonResponse"
}
},
"text/plain": {
"schema": {
"type": "string"
}
}
},
"description": "OK"
},
"204": {
"content": {
"application/hal+json": {
"schema": {
"$ref": "#/components/schemas/EntityModelJsonResponse"
}
},
"application/vnd.something": {},
"text/plain": {
"schema": {
"type": "string"
}
}
},
"description": "No Content"
}
},
If I restart my server without changing the code the following response is generated
"operationId": "gettt_1",
"responses": {
"200": {
"content": {
"application/hal+json": {
"schema": {
"$ref": "#/components/schemas/EntityModelJsonResponse"
}
},
"application/json": {
"schema": {
"$ref": "#/components/schemas/JsonResponse"
}
},
"text/plain": {
"schema": {
"type": "string"
}
}
},
"description": "OK"
},
"204": {
"content": {
"application/vnd.something": {}
},
"description": "No Content"
}
},
I would expect that restarting my server will always generate the same documentation
Have you looked at the documentation?
https://springdoc.github.io/springdoc-openapi-demos/springdoc-properties.html#swagger-ui-properties
You can use the swagger-ui properties, without having to override the standard way of sorting (operationsSorter and tagsSorter).
For example:
springdoc.swagger-ui.operationsSorter=method
springdoc.swagger-ui.tagsSorter=alpha
If you want a an order on the server side, you can use OpenApiCustomiser, to sort the elements
This is a sample code that you can customize using Comparators, depending on the sorting logic you want:
Example, for alphabetical order sorting of schemas:
#Bean
public OpenApiCustomiser sortSchemasAlphabetically() {
return openApi -> {
Map<String, Schema> schemas = openApi.getComponents().getSchemas();
openApi.getComponents().setSchemas(new TreeMap<>(schemas));
};
}
Example for sorting tags, in alphabetical order:
#Bean
public OpenApiCustomiser sortTagsAlphabetically() {
return openApi -> openApi.setTags(openApi.getTags()
.stream()
.sorted(Comparator.comparing(tag -> StringUtils.stripAccents(tag.getName())))
.collect(Collectors.toList()));
}
You can have full control on the elements order, and you can sort them depending on your use case...
one other flag mentioned here:
springdoc:
writer-with-order-by-keys
I have been following the youtube tutorial : https://www.youtube.com/watch?v=HkMi5xPyz1g&t=1533s
public Object handleRequest(Map<String,Object> input, Context context) {
LexRequest lexRequest= LexRequestFactory.createLexRequest(input);
String orgbotcommand= lexRequest.getCommand()+" "+lexRequest.getOld_variable();
String content = String.format("command recieved by %s is %s",
lexRequest.getBotName(),
orgbotcommand);
Message message = new Message("Plain text",content);
DialogueAction dialogueAction = new DialogueAction("Close", "Fulfilled or Failed", message );
System.out.println(dialogueAction);
return new LexRespond(dialogueAction);
}
Above is the java code i am using.
it is giving me the desired output while testing with lambda function test events, but when i try to call this lambda function from my lex bot , it throws the error below:
An error has occurred: Invalid Lambda Response: Received invalid response
from Lambda: Can not construct instance of IntentResponse, problem: The
validated object is null at [Source: {"dialogueAction":
{"type":"Close","fulfillmentState":"Fulfilled or Failed","message":
{"contentType":"Plain text","content":"command recieved by OrgBot is Delete asd"}}}; line: 1, column: 168]
Output in lambda test event is :
{
"dialogueAction": {
"type": "Close",
"fulfillmentState": "Fulfilled or Failed",
"message": {
"contentType": "Plain text",
"content": "command recieved by OrgBotchatbot is delete asd"
}
}
}
I am new to Amazan lex and lambda. Please tell me what i am doing wrong
It is probably just your response formatting. Check out the Response Format Docs.
Firstly, contentType needs to be either 'PlainText' or 'SSML'.
So change 'Plain text' to be 'PlainText'
Message message = new Message("PlainText",content);
Secondly, the fulfillmentState needs to be either 'Fulfulled' or 'Failed'.
So remove 'or Failed' from your DialogueAction line to be:
DialogueAction dialogueAction = new DialogueAction("Close", "Fulfilled", message );
Thirdly, dialogAction. Lex must be American because it only accepts the response when you spell 'Dialogue' as 'Dialog'. So change what you need to in your code so that the response returns this:
{
"dialogAction": {
"type": "Close",
"fulfillmentState": "Fulfilled",
"message": {
"contentType": "PlainText",
"content": "command recieved by OrgBotchatbot is delete asd"
}
}
};
If you are using Lex v2, the expected response format is different from v1.
See https://docs.aws.amazon.com/lexv2/latest/dg/lambda.html#lambda-response-format
{
"sessionState": {
"activeContexts": [
{
"name": "string",
"contextAttributes": {
"key": "value"
},
"timeToLive": {
"timeToLiveInSeconds": number,
"turnsToLive": number
}
}
],
"sessionAttributes": {
"string": "string"
},
"dialogAction": {
"slotToElicit": "string",
"type": "Close | ConfirmIntent | Delegate | ElicitIntent | ElicitSlot"
},
"intent": {
"confirmationState": "Confirmed | Denied | None",
"name": "string",
"slots": {
"string": {
"value": {
"interpretedValue": "string",
"originalValue": "string",
"resolvedValues": [
"string"
]
}
},
"string": {
"shape": "List",
"value": {
"originalValue": "string",
"interpretedValue": "string",
"resolvedValues": [
"string"
]
},
"values": [
{
"shape": "Scalar",
"value": {
"originalValue": "string",
"interpretedValue": "string",
"resolvedValues": [
"string"
]
}
},
{
"shape": "Scalar",
"value": {
"originalValue": "string",
"interpretedValue": "string",
"resolvedValues": [
"string"
]
}
}
]
}
}
},
"state": "Failed | Fulfilled | InProgress | ReadyForFulfillment"
},
"messages": [
{
"contentType": "CustomPayload | ImageResponseCard | PlainText | SSML",
"content": "string",
"imageResponseCard": {
"title": "string",
"subtitle": "string",
"imageUrl": "string",
"buttons": [
{
"text": "string",
"value": "string"
}
]
}
}
],
"requestAttributes": {
"string": "string"
}
}
With the new V2, you don't need to fill out all the examples, here is a minimal version of the response in Python (say that you want to send a final message):
return {
"sessionState": {
"dialogAction": {
"type": "Close",
},
"intent": {
"name": "IntentName",
"state": "Fulfilled"
}
},
"messages": [
{
"contentType": "PlainText",
"content": "Thank you for doing business with me!"
}
]
}
The format of your output must follow specific minimal layouts.
I use the following two functions to make it easy.
Just call them from any function when you are ready to tell Lex
//SessionAttributes any session variables
//fulfillmentState - 'Fulfilled' or 'Failed' depending on if successful or not
//message - the actual response text you want lex to say/type
function close(sessionAttributes, fulfillmentState, message) {
return {
sessionAttributes,
dialogAction: {
type: 'Close',
fulfillmentState,
message,
},
};
}
function delegate(sessionAttributes, slots) {
return {
sessionAttributes,
dialogAction: {
type: 'Delegate',
slots,
},
};
}
i'm learning programming and want use DataTables and i have a problem. I don't know how to converted records...
I have code in spring boot
#RequestMapping(path="/seriess", method=RequestMethod.GET)
public Page<SeriesDao> showSeries(#RequestParam(defaultValue="0") int page)
{
Page<SeriesDao> sss = seriesRepository.findAll(new PageRequest(page, 20));
return sss;
}
#RequestMapping("/showSeries")
public ModelAndView model(){
ModelAndView model = new ModelAndView("showSeries");
return model;
}
Next I have json when i go to localhost:8080/seriess, i didn't copy all result (20)
{"content":[{"id":41,"name":"Average Weekly Earnings of All Employees: Total Private in Corpus Christi, TX (MSA)","file":"SMU48185800500000011.csv","cassid":"1d2e556b-031e-4c6f-aec4-981c4e907324","categoryid":3,"datefrom":"2006-12-31","dateto":"2016-09-30","frequency":5,"markers":null,"unit":"$ per Week","feed":"Macroeconomic_And_Major_Markets","createdate":1476567529000,"changedate":1483919401000}........and next 19 records ]
"last":false,"totalPages":25,"totalElements":488,"size":20,"number":0,"sort":null,"first":true,"numberOfElements":20}
This is my java script code. I have to correct convert this data from url, but i don't know how...
$(document).ready( function () {
$('#dataTable').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "seriess",
"dataSrc" : ""
}
},
"columns": [
{ "data": "id"},
{ "data": "name" },
{ "data": "file" },
{ "data": "cassid" },
{ "data": "categoryid" },
{ "data": "datefrom" },
{ "data": "dateto" },
{ "data": "frequency" },
{ "data": "markers" },
{ "data": "unit" },
{ "data": "feed" },
{ "data": "createdate" },
{ "data": "changedate" }
]
})});
Change
"ajax": {
"url": "seriess",
"dataSrc" : ""
}
}
to
"ajax": {
"url": "/seriess",
"dataSrc" : "content"
}
}
I have Spring web service from the following. JSON for swagger
{
"swagger": "2.0",
"info": {
"version": "1.0.0",
"title": "Extended User Management API",
"description": "This is communicate with an extended user management webservice to test the swagger API for learning"
},
"schemes": [
"http"
],
"basePath": "/UserManagement/rest/UserService",
"host": "127.0.0.1:8089",
"produces": [
"application/json"
],
"consumes": [
"application/json"
],
"paths": {
"/users": {
"get": {
"responses": {
"200": {
"description": "An array of users",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/User"
}
}
},
"default": {
"description": "Unexpected error",
"schema": {
"$ref": "#/definitions/Error"
}
}
}
}
},
"/addUser": {
"post": {
"summary": "Add an additional user",
"description": "This service is used to add and additional user to the list of users.",
"parameters": [
{
"name": "user_id",
"in": "query",
"description": "Unique id of the user to be added.",
"required": true,
"type": "integer",
"format": "int32"
},
{
"name": "name",
"in": "query",
"description": "Name of the user to be added.",
"required": true,
"type": "string"
},
{
"name": "profession",
"in": "query",
"description": "Profession of the user to be added.",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "OK"
},
"default": {
"description": "Unexpected error",
"schema": {
"$ref": "#/definitions/Error"
}
}
}
}
}
},
"definitions": {
"User": {
"type": "object",
"properties": {
"user_id": {
"type": "integer",
"format": "int32",
"description": "This is unique id that is assigned to each user."
},
"name": {
"type": "string",
"description": "This is the name of the user"
},
"profession": {
"type": "string",
"description": "This is the profession that the user holds"
}
}
},
"Error": {
"type": "object",
"properties": {
"code": {
"type": "integer",
"format": "int32"
},
"message": {
"type": "string"
},
"fields": {
"type": "string"
}
}
}
}
}
I generated the code and resolved all the error in the project. The I got the application to run in Spring boot main with out any problems. The issue that I'm facing now is that on accessing the get web service "/users", I'm getting an error from the service.
I tried debugging the spring application I came to find that the intended service is not even hit. The code for service is given below.
#javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringCodegen", date = "2016-10-24T09:36:32.738Z")
#Api(value = "users", description = "the users API")
public interface UsersApi {
#ApiOperation(value = "", notes = "", response = User.class, responseContainer = "List", tags={ })
#ApiResponses(value = {
#ApiResponse(code = 200, message = "An array of users", response = User.class),
#ApiResponse(code = 200, message = "Unexpected error", response = User.class) })
#RequestMapping(value = "/users",
produces = { "application/json" },
consumes = { "application/json" },
method = RequestMethod.GET)
ResponseEntity<List<User>> usersGet();
}
Implementation of this interface is given below
#javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringCodegen", date = "2016-10-24T09:36:32.738Z")
#Controller
public class UsersApiController implements UsersApi {
UserDao udao = new UserDao();
public ResponseEntity<List<User>> usersGet() {
return new ResponseEntity<List<User>>(udao.getAllUsers(), HttpStatus.OK);
}
}
Can please some one tell me what is the mistake that I made so that I can solve this.
Well you are using an unsupported media type as the exception says.
Have a look at your #RequestMapping annotation:
#RequestMapping(value = "/users",
produces = { "application/json" },
consumes = { "application/json" },
method = RequestMethod.GET)
ResponseEntity<List<User>> usersGet();
Either you remove the consumes key or you support the Content-Type in your GET request.
Edit: maybe it would be a better option to remove the consumes key. I don't think it is a good idea to consume any json in a GET request.