swagger springfox Override default response messages


Example

Springfox defines a set default response messages that are applied to all API controllers by default. This includes e.g. 201 - Created and 204 - No Content, as well as several 40x responses. There might be cases, in which the default response messages don't apply for your API. You have to build-in possibilities to deal with this:

  • You can turn of the default response message and define your own using the @ApiResponses annotation.
  • You can define your own response messages globally

Turn of default response messages

docket.useDefaultResponseMessages(false);

You can now set your individual response messages on a per-controller level. E.g.

 @ApiResponses(value = {
        @ApiResponse(code=400, message = "This is a bad request, please stick to the API description", response = RestApiExceptionModel.class),
        @ApiResponse(code=401, message = "Your request cannot be authorized.", response = RestApiExceptionModel.class)
 })

Set your own default response messages

ModelRef errorModel = new ModelRef("RestApiExceptionModel");
List<ResponseMessage> responseMessages = Arrays.asList(
        new ResponseMessageBuilder().code(401).message("Unauthorized").responseModel(errorModel).build(),
        new ResponseMessageBuilder().code(403).message("Forbidden").responseModel(errorModel).build(),
        new ResponseMessageBuilder().code(404).message("NotFound").responseModel(errorModel).build());

docket.globalResponseMessage(RequestMethod.POST, responseMessages)
        .globalResponseMessage(RequestMethod.PUT, responseMessages)
        .globalResponseMessage(RequestMethod.GET, responseMessages)
        .globalResponseMessage(RequestMethod.DELETE, responseMessages);