Search code examples
javaspring-bootspringfox

Swagger and Springfox Changing the example response for different status codes


I have a specific DTO I'm using to return as an example for Swagger documentation. How can I change the example in case I have a success 201 code?

Example responses in swagger:

Example responses in swagger

I use the annotations "@ApiModelProperty" to describe my objects, but finding no way on how to change the example for different response codes. In my code, I don't want to show the Errors list, as it's an optional property and it will just be available when non 201 codes are going to be produced.

Ideas?


Solution

  • You can do this with a couple of annotations as follows:

    import io.swagger.v3.oas.annotations.media.ExampleObject;
    
    @Operation(summary = "Your summary")
    @ApiResponses(value = { 
      @ApiResponse(responseCode = "200", description = "Your description", 
        content = { @Content(mediaType = "application/json", 
          schema = @Schema(implementation = YourModel.class),
          examples = [@ExampleObject(value = "{\"timestamp\": 1581552186590, \"status\": 404, \"error\": \"Not Found\", \"message\": \"Error message\", \"requestId\": \"62bcf95d\"}")]) })})