SpringFox Swagger - Remove 200 Responses - spring-boot

I'm using Swagger annotations and SpringFox to produce a Swagger spec for my REST API (being built with Sprint Boot). I'm annotating each method with the #ApiResponse codes that will be returned. For example:
#DeleteMapping("/{pipelineName}")
#ApiOperation(value = "Delete a specific pipeline")
#ApiResponses({
#ApiResponse(code = 204, message = "Pipeline has been deleted"),
#ApiResponse(code = 404, message = "Pipeline does not exist")
})
public void deletePipeline(#PathVariable("pipelineName") #ApiParam(value = "Name of pipeline", required = true) String name){
...
}
However, something (I assume SpringFox) is adding a 200 response code to every API call regardless of whether it's defined or not. I'm aware that I can remove this by adding a #ResponseStatus annotation to each method, but a) that seems like unneccessary duplication of the #ApiResponse definitions and b) some methods could return one of multiple 2xx codes.
Is there a way or removing the 200 code that is added by default?

I believe you need to define the default response status for your method as you mentioned in your question.#ApiResponse is from Springfox, #ResponseStatus is from Spring framework. It is not exactly a duplication. An HTTP 200 response is the default behavior, and Springfox do not do anything to change that, so it just adds the additional codes on top of the automatically detected one.
Example for HTTP 204:
#ResponseStatus(value = HttpStatus.NO_CONTENT)
In your code:
DeleteMapping("/{pipelineName}")
#ApiOperation(value = "Delete a specific pipeline")
#ApiResponses({
#ApiResponse(code = 204, message = "Pipeline has been deleted"),
#ApiResponse(code = 404, message = "Pipeline does not exist")
})
#ResponseStatus(value = HttpStatus.NO_CONTENT)
public void deletePipeline(#PathVariable("pipelineName") #ApiParam(value = "Name of pipeline", required = true) String name){
...
}
For others that may be checking this topic: if Springfox is generating other HTTP codes, you may also need this.

What I would do is:
#DeleteMapping("/{pipelineName}")
#ApiOperation(value = "Delete a specific pipeline")
#ApiResponses({
#ApiResponse(code = 204, message = "Pipeline has been deleted"),
#ApiResponse(code = 404, message = "Pipeline does not exist")
})
public #ResponseBody ResponseEntity<Object> deletePipeline(#PathVariable("pipelineName") #ApiParam(value = "Name of pipeline", required = true) String name){
if (deleted) {
return new ResponseEntity<>("Pipeline has been deleted", HttpStatus.CREATED); //code 204
} else {
return new ResponseEntity<>("Pipeline does not exist", HttpStatus.NOT_FOUND); //code 404
}
}
Now, I wouldn't use 204 as a code to indicate that something was deleted, I would keep it at 200, but that's up to you.
Hope this helps!

Currently You can't remove standard 200 code. I found the same question on the github and developers said that is bug in springfox:
You can read about this in this link
I tried to remove the 200 code in 2.9.2 version of SpringFox and this bug is still exists

You need to mention useDefaultResponseMessages to false while creating the Docket object. Now it will document only that you have added in #ApiResponses.
new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.ty"))
.build()
.apiInfo(apiInfo)
.useDefaultResponseMessages(false);

Related

How to add description to #requestbody?

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")

For java Controller swagger-ui.html renders unexpected http codes

I have the following java endpoint inside a Springboot RestController annotated with some Swagger annotations for 4 ApiResponses:
#ApiResponses(value = {
#ApiResponse(code = 200, message = "Successfully sign in"),
#ApiResponse(code = 400, message = "Missing request body"),
#ApiResponse(code = 404, message = "Schema not found"),
#ApiResponse(code = 500, message = "Internal error")
})
#PostMapping(
path = "/login",
produces = "application/json; charset=utf-8")
public LoginResponse login(
#ApiParam(
name="cred",
value="Credenciales de quien intenta ingresar al sistema")
#RequestBody CredencialesRequest cred
) throws ControllerException {
return accessService.login(cred.getUsuario(), cred.getClave());
}
As you can see, I have declared 4 response codes as a possible HTTP responses: 200, 400, 404 and 500
When I run the application and go to http://localhost:8080/swagger-ui.html the UI shows the 4 codes that I have described in the endpoint. However, it shows MORE http codes. Please take a look at this picture:
The extra codes are: 201 (created), 401 (unauthorized) & 403 (forbidden). Why? For my use case, the "login" endpoint should be always accessible to any user, so at least, 401 & 403 doesn't make sense at all, in this context.
Just like it was said in the comments, in order to remove the extra http codes in the swagger UI, we need to modify our configuration file by adding useDefaultResponseMessages(false) to the api() method in our SwaggerConfig like this:
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.useDefaultResponseMessages(false) // I HAD TO ADD THIS LINE !!!!
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}
That's it !

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.

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