How to add description to #requestbody? - spring

As shown in the picture, I want to add my description in my Swagger UI. The value "Example" (in name and description) comes from the parameter "Example" in the controller where I have used the #Requestbody. I am using Spring framework. How do I add my description to it?
This is my controller file
#ApiOperation(value = "It will be used to print the document of quotation.",response = GenerateDocPrintResponse.class)
#ApiResponses(value = {
#ApiResponse(code = 200, message = "Successfully retrieved list"),
#ApiResponse(code = 401, message = "You are not authorized to view the resource"),
#ApiResponse(code = 403, message = "Accessing the resource you were trying to reach is forbidden"),
#ApiResponse(code = 404, message = "The resource you were trying to reach is not found")
}
)
#RequestMapping(value = "/service/generateDocPrint", method = RequestMethod.POST)
public #ResponseBody String generateDocPrint(#RequestBody GetdocprintRequest Example,HttpServletRequest request, HttpServletResponse response,
#RequestBody String newJson) throws Exception {
................
}
This is my Pojo file
package com.iii.fw.models.generatedocprint;
import com.iii.fw.models.common.RequestHeader;
import io.swagger.annotations.ApiModelProperty;
public class GetdocprintRequest {
RequestHeader reqHeader;
private ReqPayloadGDP reqPayload;
public ReqPayloadGDP getReqPayload() {
return reqPayload;
}
public void setReqPayload(ReqPayloadGDP reqPayload) {
this.reqPayload = reqPayload;
}
public GetdocprintRequest withReqPayload(ReqPayloadGDP reqPayload) {
this.reqPayload = reqPayload;
return this;
}
}

#ApiOperation(value = "It will be used to print the document of quotation. ", notes = "put your description here ", response = )
Does this answer your question ?

Use the notes proptery.
Using notes, we can provide more details about the operation. For instance, we can place a text describing the endpoint's restrictions:
https://www.baeldung.com/swagger-apioperation-vs-apiresponse#2-the-notes-property
#ApiOperation(value = "Gets customer by ID", notes = "Customer must exist")

Related

MockMvc fails when request body is empty for Put and Post requests

I'm pretty new to unit testing with Spring and can't figure out why I can't MockMvc doesn't work with post when the request body is empty. The error I'm getting: java.lang.AssertionError:Response status expected:<200> but was <404>. I've gotten the get endpoint to work correctly so I think the rest controller is wired correctly. I'm just wondering how to write a unit test when a POST or PUT request lacks a body, but has params. I've tried different variations of the below such as chaining .contentType(MediaType.ALL).content(""), but I always get the same error.
UnitTest.java
#Test
public void shouldCreateSomething() throws Exception{
mockMvc.perform(post(somethingUri).param(idParameter, fieldParameter))
.andExpect(status().is(200));
}
RestAPI.java
#Operation(summary = "Updates something", responses = {
#ApiResponse(responseCode = "200", description = "Something was updated"),
#ApiResponse(responseCode = "406", description = "Something was invalid") })
#PutMapping(value = somethingUri)
public void updateSomething(
#Parameter(description = "Something's id", required = true) #RequestParam String id,
#Parameter(description = "Something's name to be updated", required = true) #RequestParam String name)
{
System.out.println("please work");
}
There ended up being 2 problems with my code.
The 404 error was probably caused by an incorrect URI.
Then the ensuing 400 error was caused by my malformed param. It should be:
#Test
public void shouldCreateSomething() throws Exception{
mockMvc.perform(post(somethingUri)
.param(idPropName, idParameter)
.param(fieldPropName,fieldParameter))
.andExpect(status().is(200));
}
So nothing to do with empty body at all

swagger doesn't recognize api description

I instatiate docket like this
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.config.internal"))
.paths(Predicates.or(PathSelectors.ant("/api**/**")))
.build();
}
I created a set of stub endpoints that imitate the real one for /login or /oauth.
#Api("Authentication")
#RequestMapping("/api")
public interface LoginEndpointApi {
#ApiOperation(value = "Github SSO endpoint", notes = "Endpoint for Github SSO authentication")
#ApiResponses({
#ApiResponse(code = 200, message = "HTML page of main application")
})
#GetMapping("/oauth/github")
default void oauthGithub() {
throw new UnsupportedOperationException();
}
#ApiOperation(value = "Get CSRF token", notes = "Returns current CSRF token")
#ApiResponses({
#ApiResponse(code = 200, message = "CSRF token response", response = String.class,
examples = #Example({#ExampleProperty(value = "015275eb-293d-4ce9-ba07-ff5e1c348092")}))
})
#GetMapping("/csrf-token")
default void csrfToken() {
throw new UnsupportedOperationException();
}
#ApiOperation(value = "Login endpoint", notes = "Login endpoint for authorization")
#ApiResponses({
#ApiResponse(code = 200, message = "Successful authentication")
})
#PostMapping("/login")
default void login(
#ApiParam(required = true, name = "login", value = "login body")
#RequestBody LoginRequest loginRequest) {
throw new UnsupportedOperationException();
}
}
But it doesn't recognize it. It is located in the same com.config.internal package as I described.
But the page swagger ui is empty and shows that No operations defined in spec!
What is the problem?
If you want to provide swagger documentation for your request mappings specified above you could simply describe it with .paths(Predicates.or(PathSelectors.ant("/api/**"))) path matchers. But if your path includes something more complicated like api + text without backslash separator then you should get known with
https://docs.spring.io/spring/docs/3.1.x/javadoc-api/org/springframework/util/AntPathMatcher.html

Spring boot - Request method 'POST' not supported.

please i have this error when trying to create a customer. Can some one help me? May be i am missing some thing. I have even try to change the #PostMapping to #RequestMapping till yet. Thks
My Controller code
`#PostMapping("CREATE_CUSTOMER_ENDPOINT")
#ResponseStatus(value = HttpStatus.OK)
#ApiResponses(value = {
#ApiResponse(code = 201, message = "The Customer was Created", response = CustomerDto.class),
#ApiResponse(code = 400, message = "Bad Request", response = ResponseError.class),
#ApiResponse(code = 500, message = "Unexpected error")
})
public ResponseEntity createCustomer(final HttpServletRequest request, #RequestBody CustomerDto customerDto)
{
if (log.isDebugEnabled()){
log.debug("[CustomerResource] POST {} : Creating customer ", CREATE_CUSTOMER_ENDPOINT);
}
if(customerDto.getUidpk()!=null) {
ResponseError error = new ResponseError(HttpStatus.BAD_REQUEST.getReasonPhrase(), "A customer Already exist with an Uidpk");
log.error("[CustomerResource] The customer Already exist ({}) with an Uidpk", customerDto.getUidpk());
return new ResponseEntity<>(error, null, HttpStatus.BAD_REQUEST);
}
CustomerDto result = customerService.createCustomer(customerDto);
log.debug("[CustomerResource] Customer created ({})", result.getUidpk());
return new ResponseEntity<>(result, HeaderUtil.putLocationHeader(request.getRequestURL().toString() + "/" + result.getUidpk()), HttpStatus.CREATED);
} `
My endpoints
private static final String CUSTOMER_SEARCH_USER_ID_ENDPOINT = "/customers/{userId:.+}";
private static final String CREATE_CUSTOMER_ENDPOINT= "/customer";
private static final String UPDATE_CUSTOMER_ENDPOINT= "/customer";
private static final String DELETE_CUSTOMER_ENDPOINT = CREATE_CUSTOMER_ENDPOINT + "/{uidpk}";
This is the response of Postman
Postman sample
When you send JSON payloads in HTTP request, you need to specify Content-Type HTTP header with value application/json.

ID Should Not Show Up for Model Schema with Swagger + Spring

I'm using Swagger2 with Springfox and Spring Boot. I have an endpoint defined like so:
#ApiOperation(value = "save", nickname = "Save Store")
#ApiResponses(value = {
#ApiResponse(code = 201, message = "Created"),
#ApiResponse(code = 401, message = "Unauthorized"),
#ApiResponse(code = 403, message = "Forbidden"),
#ApiResponse(code = 500, message = "Failure", response = ErrorResource.class)})
#RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
#ResponseStatus(HttpStatus.CREATED)
public void save(#Valid #RequestBody Store store, BindingResult bindingResult, HttpServletRequest request, HttpServletResponse response) {
if (bindingResult.hasErrors()) {
throw new InvalidRequestException("Invalid Store", bindingResult);
}
this.storeService.save(store);
response.setHeader("Location", request.getRequestURL().append("/").append(store.getId()).toString());
}
The generated API docs are showing the id of Store in the Model Schema. Technically, when creating a Store the JSON should not contain the id. I'm trying to figure out how to tell Swagger/Springfox to ignore the id but only for this endpoint.
You can hide a field from a model by annotating the property of the class with #ApiModelProperty and setting its hidden property to true.
import io.swagger.annotations.ApiModelProperty;
public class Store {
#ApiModelProperty(hidden = true)
private Long id;
}
Unfortunately, by doing so, you will hide the id field on every endpoint which uses the Store class as an input. Showing the field for another endpoint would require a separate class.

Swagger Springfox annotations not working

These are the method headers for the sample application I'm trying to make. Unfortunately I don't see the #ApiOperation or #ApiResponse or #ApiResponses annotations taking effect.
I also have a sample class and an Application class(which contains swagger configuration info and the like)
#Api(value = "/v1/", description = "Test API", produces = "application/json")
#RestController
#RequestMapping("/v1/")
class SampleRestController {
#ApiResponses(value = {
#ApiResponse(code = 200, message = "Successfully added"),
#ApiResponse(code = 416, message = "List is empty") })
#RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE, value = "samples/{sb}",
method = RequestMethod.GET)
public Map<String, String> sbs(#PathVariable("sb") String sb) {
}
#ApiOperation(
value = "Seeing where this shows up",
notes = "we should see this in the implememtation notes",
response = Sample.class,
httpMethod = "GET"
)
#ApiResponses(value = {
#ApiResponse(code = 200, message = "Successfully added"),
#ApiResponse(code = 416, message = "List is empty") })
#RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE, value = "samples/{pb}",
method = RequestMethod.GET)
public Sample ps(#PathVariable String pb) {
}
#RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE, value = "samples",
method = RequestMethod.GET)
public Collection<Map<String, String>> cs(#RequestParam(value = "cid", required = true, defaultValue = "")
String cid) {
}
}
Here is the relevant portion of my swagger json
{"swagger":"2.0","info":{"description":"All about the Samples","title":"Samples API","contact":{},"license":{}},"host":"localhost:8080","basePath":"/","tags":[{"name":"sample-rest-controller","description":"Sample Rest Controller"}],
"paths":{
"/v1/samples":{"get":{"tags":["sample-rest-controller"],"summary":"cs","operationId":"csUsingGET","consumes":["application/json"],"produces":["application/json"],"parameters":[{"name":"cid","in":"query","description":"cid","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"$ref":"#/definitions/Collection«Map«string,string»»"}},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}},
"/v1/samples/{pb}":{"get":{"tags":["sample-rest-controller"],"summary":"ps","operationId":"psUsingGET","consumes":["application/json"],"produces":["application/json"],"parameters":[{"name":"pb","in":"path","description":"pb","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"$ref":"#/definitions/Sample"}},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}},
"/v1/samples/{sb}":{"get":{"tags":["sample-rest-controller"],"summary":"sbs","operationId":"sbsUsingGET","consumes":["application/json"],"produces":["application/json"],"parameters":[{"name":"sb","in":"path","description":"sb","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"string"}}},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}}},
I'm using springfox-swagger2 version 2.1.1 and I'm viewing my UI through the default UI provided by swagger at their live demo app.
Can someone tell me what I'm doing wrong?
Thanks!
I was playing around and changed my import from
import com.wordnik.swagger.annotations.;
to
import io.swagger.annotations.;
and all the annotations appear to work.
So, looks like the com.wordnik.swagger.annotations import no longer works, or at least doesn't work properly?
Confirmed by Dilip Krish here

Resources