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?
Related
Spring cloud contract multipart - generates test with only one multiPart file despite yaml contains 11.
I am trying to test contract, which has restrictions for MultipartFile size.
#PostMapping(value = "/{id}/attachments",
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public List<AttachmentInfo> uploadAttachment(#PathVariable("id") long id, #RequestPart("file") #Valid #Size(min = 1, max = 10) MultipartFile[] files) {
Yaml describes request of 11 files:
request:
method: POST
url: /v1/app/1/attachments
multipart:
named:
- paramName: "file"
fileName: 'readme1.txt'
fileContent: "file content"
contentType: 'text/plain'
- paramName: "file"
fileName: 'readme2.txt'
fileContent: "file content"
contentType: 'text/plain'
...
- paramName: "file"
fileName: 'readme11.txt'
fileContent: "file content"
contentType: 'text/plain'
headers:
Content-Type: "multipart/form-data; boundary=---------------------------10725086087847035033895950974"
matchers:
headers:
- key: Content-Type
regex: "multipart/form-data.*"
multipart:
named:
- paramName: file
- fileName:
predefined: non_empty
- fileContent:
predefined: non_empty
response:
status: 422
Maven plugin 'spring-cloud-contract-maven-plugin' 3.1.2 and 3.1.3 generates test, which contains only one multipart data - the last one 'readme11.txt' :
// given:
MockMvcRequestSpecification request = given()
.header("Content-Type", "multipart/form-data; boundary=---------------------------10725086087847035033895950974")
.multiPart("file", "readme11.txt", "file content".getBytes(), "text/plain");
// when:
ResponseOptions response = given().spec(request)
.post("/v1/app/1/attachments");
// then:
assertThat(response.statusCode()).isEqualTo(422);
How to validate Rest controller signature, restricted by size, with spring cloud contract test #Size(min = 1, max = 10) MultipartFile[] files ? spring-cloud.version: 2021.0.2
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/
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"
I need to get some respones from some URL.
For this purpose I use http://unirest.io/java.html and Java.
Map<String, String> map = new HashMap<>();
map.put(key1, value1);
...
map.put(keyN, valueN);
String authToken = "{token}";
HttpResponse<String> response = Unirest.post(url)
.header("Authorization","Bearer " + authToken)
.header("Content-Type", "application/json")
.fields(map)
.asString();
As a result I receive response.getStatus() = 302 and some unexpected body.
At the same time I use Postman software to get the same responses. The settings are the following:
POST: url
Authorization: Type -> Bearer Token; Token = {{authToken}} // get the value from the previous request
Header :
"Authorization" : "Bearer " + {{authToken}}
Content-Type: application/json
Body:
{
key1 : value1,
...
keyN : valueN
}
And I get some expected response.
What makes the difference?
A 302 is a redirect response. Is it possible Postman is following the redirect and returning the resultant page? Take a look at the Location header in the response you get in Java, and see if following that gives you the same results you're seeing in Postman.
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);