Swagger setting path parameter data type - java

I am trying to set the path parameter as below
#PUT
#Path("{myParam}/myEndpoint")
#ApiOperation(value = SwaggerApiConst.EVENT)
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
#ApiImplicitParams({
#ApiImplicitParam(dataType = "long", name = "myParam", paramType = "path")
})
public Response group( #PathParam("myParam") Long myParam, SomeObj someObj) {
Trying to set the data type of parentAlarm as long, but it appears as integer in the swagger.json file.
'/myApi/{myParam}/myEndpoint':
put:
consumes:
- application/json
produces:
- application/json
parameters:
- type: integer
name: myEndpoint
in: path
required: true
- name: body
in: body
required: true
schema:
$ref: '#/definitions/SomeObj'
swagger version used is
<swagger.version>1.5.0</swagger.version>
#ApiImplicitParam seems to have no effect here. Is there an alternative ?

Swagger supports only integer and number datatypes. Long is specified as int64 and integer as int32. You can read more about the data types here - https://swagger.io/docs/specification/data-models/data-types/

Related

How to get Authorization header value with swagger-generated java class

I'm following the guide on https://swagger.io/docs/specification/2-0/authentication/
I have securityDefinitions defined as
securityDefinitions:
bearer_auth:
type: apiKey
in: header
name: Authorization
and the path is
/some-path:
get:
parameters:
- description: cursor
in: query
name: cursor
type: string
produces:
- application/json
responses:
...
tags:
- ...
security:
- bearer_auth: []
The generated method looks like
#GET
#Produces({"application/json"})
#ApiOperation(
authorizations = {#Authorization("bearer_auth")},
tags = {"..."}
)
#ApiResponses({#ApiResponse(
code = 200,
message = "...",
response = Response.class
)})
Response foo(#QueryParam("cursor") #ApiParam("cursor") String cursor);
I need to validate the bearer token specified by Authorization header on backend, but the header value is not part of the parameters.
How do I get it?

How can i set multiple response type in RestApi call

I do have one API call in which I have to return the byte format of the certificate and the response type is octet/stream.
However, if there is an error that occurs the error will be in application/JSON. How can I set both response types in swagger/rest-client?
For now,The contract is defined in swagger and I have to manually select content type in rest clients for each of the scenarios to see the response?
You can modify the response type following this approach:
#GetMapping("/public/download")
#ResponseBody
public ResponseEntity<Resource> download(HttpServletRequest request) {
if (fixedToken.equals(request.getHeader(HttpHeaders.AUTHORIZATION))) {
Resource file = fileStorageService.loadFileAsResource("fil-name-here", "folder");
return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file);
}
//Your custom response
Map response = new HashMap();
response.put("code", HttpStatus.FORBIDDEN.value());
response.put("message", "some message");
return new ResponseEntity(response, HttpStatus.FORBIDDEN);
}
In this example, if the token is valid, the API responds with the bytes. Otherwise, you will see this (as JSON):
{
"code": 403,
"message": "some message"
}
Important here: #ResponseBody
This is on spring-boot side, now if you need a static swagger file (.yaml) you need something like this:
paths:
/{file_name}:
get:
tags:
- "your app tag"
summary: "Download"
description: "Get file content"
operationId: "operationNameOnSpringBoot"
parameters:
- name: "file_name"
in: "path"
description: "file name"
required: true
schema:
type: "string"
responses:
200:
description: "successful operation"
content:
application/octet-stream:
schema:
type: string
format: binary
404:
description: "Not found"
content:
application/json:
schema:
$ref: "#/components/schemas/your_error_schema"

How to send object parameters in Swagger API definition?

I have the following API definition endpoint:
paths:
/pricing/reservation:
get:
tags:
- Pricing
summary: Get a reservation base price
description: Returns the pricing for a reservation
operationId: getReservationPricing
produces:
- application/json
parameters:
- name: beginDate
in: query
description: reservation begin date
required: true
type: integer
format: int64
- name: endDate
in: query
description: reservation end date
required: true
type: integer
format: int64
- in: body
name: vehicle
description: Vehicle objec
required: true
schema:
$ref: '#/definitions/Vehicle'
responses:
200:
description: successful operation
schema:
type: number
format: float
404:
description: Vehicle not found
I want to request a Vehicle object by parameter and then, with the Bitbucket integration, generate the API interface in Java. That way I can override the API controller and define the endpoint logic.
My question is, is there a way to define a generic object from Swagger definition, or do I have (as I did in above code) to define my Swagger object definition and then map it in Java?
The API generated inteface with Swagger schema:
#ApiOperation(value = "Get a reservation base price", nickname = "getReservationPricing", notes = "Returns the pricing for a reservation", response = Float.class, authorizations = {
#Authorization(value = "api_key")
}, tags={ "Pricing", })
#ApiResponses(value = {
#ApiResponse(code = 200, message = "successful operation", response = Float.class),
#ApiResponse(code = 404, message = "Vehicle not found") })
#RequestMapping(value = "/pricing/reservation",
produces = { "application/json" },
method = RequestMethod.GET)
ResponseEntity<Float> getReservationPricing(#NotNull #ApiParam(value = "reservation begin date", required = true) #Valid #RequestParam(value = "beginDate", required = true) Long beginDate,#NotNull #ApiParam(value = "reservation end date", required = true) #Valid #RequestParam(value = "endDate", required = true) Long endDate,#ApiParam(value = "Vehicle object that needs to be added to the fleet" ,required=true ) #Valid #RequestBody Vehicle vechicle);
Thanks for your help!

How to convert JSON response to Java List- Using Rest Assured for API Testing

I have a nested JSON response. JsonResponse Screenshot
I want to get the the dictionary at 0th location from the list and then get a particular element from it.
For e.g. In response, {0} and {1}, I want to get complete {0} as a result. Then from {0}, I want to extract "Id" value only.
I don't want to use the JsonPath.read(JsonResponse String, JSON Path) everytime. So looking for some simple and better alternative.
How to convert JSON response to Java List. Below is the response.
Response resp = given().header("Authorization", "Bearer "+"dwded").
accept(ContentType.JSON).
when().
get("https://example.com");
return resp;
For testing a web-API or REST endpoint, I would recommend Karate.
So it becomes simple:
* def id = response[0].Id
In the swagger editor pet example.
responses:
200:
description: "successful operation"
schema:
type: "array"
items:
$ref: "#/definitions/Pet"
A model is generated from the
Pet:
type: "object"
properties:
name:
type: "string"
example: "doggie"
This generated a java class
public class Pet {
#JsonProperty("name")
private String name = null;
The api shows a REST that returns an entity that can be shown as an array of json objects
ResponseEntity<List<Pet>> findPetsByStatus( #NotNull#ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") #RequestParam(value = "status", required = true) List<String> status);

How can I set a description and an example in Swagger with Swagger annotations?

I am creating a REST Api using Spring boot, and auto generating the swagger documentation in controllers using swagger codegen. However, I am not able to set a description and example for a parameter of type String in a POST request. Here is mi code:
import io.swagger.annotations.*;
#Api(value = "transaction", tags = {"transaction"})
#FunctionalInterface
public interface ITransactionsApi {
#ApiOperation(value = "Places a new transaction on the system.", notes = "Creates a new transaction in the system. See the schema of the Transaction parameter for more information ", tags={ "transaction", })
#ApiResponses(value = {
#ApiResponse(code = 200, message = "Another transaction with the same messageId already exists in the system. No transaction was created."),
#ApiResponse(code = 201, message = "The transaction has been correctly created in the system"),
#ApiResponse(code = 400, message = "The transaction schema is invalid and therefore the transaction has not been created.", response = String.class),
#ApiResponse(code = 415, message = "The content type is unsupported"),
#ApiResponse(code = 500, message = "An unexpected error has occurred. The error has been logged and is being investigated.") })
#RequestMapping(value = "/transaction",
produces = { "text/plain" },
consumes = { "application/json" },
method = RequestMethod.POST)
ResponseEntity<Void> createTransaction(
#ApiParam(
value = "A JSON value representing a transaction. An example of the expected schema can be found down here. The fields marked with an * means that they are required." ,
example = "{foo: whatever, bar: whatever2}")
#Valid #RequestBody String kambiTransaction) throws InvalidTransactionException;
}
The example property of the #ApiParam has been manually inserted by me, because the codegen was ignoring that part of the yaml (That is another question: why is the editor ignoring the example part?). Here is part of the yaml:
paths:
/transaction:
post:
tags:
- transaction
summary: Place a new transaction on the system.
description: >
Creates a new transaction in the system. See the schema of the Transaction parameter
for more information
operationId: createTransaction
parameters:
- $ref: '#/parameters/transaction'
consumes:
- application/json
produces:
- text/plain
responses:
'200':
description: Another transaction with the same messageId already exists in the system. No transaction was created.
'201':
description: The transaction has been correctly created in the system
'400':
description: The transaction schema is invalid and therefore the transaction has not been created.
schema:
type: string
description: error message explaining why the request is a bad request.
'415':
description: The content type is unsupported
'500':
$ref: '#/responses/Standard500ErrorResponse'
parameters:
transaction:
name: kambiTransaction
in: body
required: true
description: A JSON value representing a kambi transaction. An example of the expected schema can be found down here. The fields marked with an * means that they are required.
schema:
type: string
example:
{
foo*: whatever,
bar: whatever2
}
And finally, this is what swagger is showing:
Finally, the dependencies used in build.gradle are the following ones:
compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.7.0'
compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.7.0'
So, Question is:
Does anybody know how I can set the description and an example of a body parameter using swagger annotations?
EDIT
I've achieved to change the description using #ApiImplicitParam instead of #ApiParam, but example is still missing:
#ApiImplicitParams({
#ApiImplicitParam(
name = "kambiTransaction",
value = "A JSON value representing a transaction. An example of the expected schema can be found down here. The fields marked with * means that they are required. See the schema of KambiTransaction for more information.",
required = true,
dataType = "String",
paramType = "body",
examples = #Example(value = {#ExampleProperty(mediaType = "application/json", value = "{foo: whatever, bar: whatever2}")}))})
I have similar issue with generating examples for body objects - annotation #Example and #ExampleProperty simply doesn't work for no reason in swagger 1.5.x. (I use 1.5.16)
My current solution is:
use #ApiParam(example="...") for non-body objects, e.g.:
public void post(#PathParam("userId") #ApiParam(value = "userId", example = "4100003") Integer userId) {}
for body objects create new class and annotate fields with #ApiModelProperty(value = " ", example = " "), e.g.:
#ApiModel(subTypes = {BalanceUpdate.class, UserMessage.class})
class PushRequest {
#ApiModelProperty(value = "status", example = "push")
private final String status;;
}
Actually the java doc for the example property of the #ApiParam annotation states that this is exclusively to be used for non-body parameters. Where the examples property may be used for body parameters.
I tested this annotation
#ApiParam(
value = "A JSON value representing a transaction. An example of the expected schema can be found down here. The fields marked with an * means that they are required.",
examples = #Example(value =
#ExampleProperty(
mediaType = MediaType.APPLICATION_JSON,
value = "{foo: whatever, bar: whatever2}"
)
)
)
which resulted in the following swagger to be generated for the corresponding method:
/transaction:
post:
...
parameters:
...
- in: "body"
name: "body"
description: "A JSON value representing a transaction. An example of the expected\
\ schema can be found down here. The fields marked with an * means that\
\ they are required."
required: false
schema:
type: "string"
x-examples:
application/json: "{foo: whatever, bar: whatever2}"
However this value doesn't seem to be picked up by swagger-ui. I tried version 2.2.10 and the latest 3.17.4, but neither version used the x-examples property of the swagger.
There are some references for x-example (the one used for non-body parameters) in the code of swagger-ui but no match for x-examples. That is this doesn't seem to be supported by swagger-ui at the moment.
If you really need this example values to be present, your best option currently seems to be to change your method's signature and use a dedicated domain type for the body parameter. As stated in the comments already swagger will automatically pick up the structure of the domain type and print some nice information in swagger-ui:
Have you tried the following ?
#ApiModelProperty(
value = "A JSON value representing a transaction. An example of the expected schema can be found down here. The fields marked with an * means that they are required.",
example = "{foo: whatever, bar: whatever2}")
Have a nice day
Swagger.v3 Kotlin/Micronaut example:
#Post("/get-list")
fun getList(
#RequestBody(description = "Get list of ...",
content = [Content(
mediaType = "application/json",
schema = Schema(implementation = RequestDTO::class),
examples = [ExampleObject(value = """
{
"pagination": {
"page": 0,
"perPage": 10
},
"filter": {
"property_1": "string",
"property_2": "string"
},
"sort": {
"field": "property_1",
"order": "DESC"
}
}
""")]
)]) #Body request: RequestDTO): Response<SomeDTO> { ... }
Using swagger 3.0.0 try this over the rest method
#Operation(
summary = "Finds a person",
description = "Finds a person by their Id.",
tags = { "People" },
responses = {
#ApiResponse(
description = "Success",
responseCode = "200",
content = #Content(mediaType = "application/json", schema = #Schema(implementation = Person.class))
),
#ApiResponse(description = "Not found", responseCode = "404", content = #Content),
#ApiResponse(description = "Internal error", responseCode = "500", content = #Content)
}
)
If you are using swagger 2.9.2 then Examples are not working there. These annotations are ignored
protected Map<String, Response> mapResponseMessages(Set<ResponseMessage> from) {
Map<String, Response> responses = newTreeMap();
for (ResponseMessage responseMessage : from) {
Property responseProperty;
ModelReference modelRef = responseMessage.getResponseModel();
responseProperty = modelRefToProperty(modelRef);
Response response = new Response()
.description(responseMessage.getMessage())
.schema(responseProperty);
**response.setExamples(Maps.<String, Object>newHashMap());**
response.setHeaders(transformEntries(responseMessage.getHeaders(), toPropertyEntry()));
Map<String, Object> extensions = new VendorExtensionsMapper()
.mapExtensions(responseMessage.getVendorExtensions());
response.getVendorExtensions().putAll(extensions);
responses.put(String.valueOf(responseMessage.getCode()), response);
}
return responses;
}
Try using swagger 3.0.0-Snapshot.
You need to change maven dependencies like this:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-spring-webmvc</artifactId>
<version>3.0.0-SNAPSHOT</version>
</dependency>
and change annotation on your Swagger config file to this: #EnableSwagger2WebMvc

Categories

Resources