Swagger / springfox generating response example automatically

Tlink picture Tlink · Dec 4, 2018 · Viewed 9.2k times · Source

Currently using springfox 2.9.2 to Swagger document an API created in Spring. I want to add example response in the documentation, like in this image;

enter image description here

my understanding is that I can do something similar to this:

@ApiResponses(value = {
    @ApiResponse(code = 200, message = "Success", 
            examples = @io.swagger.annotations.Example(
                value = {
                    @ExampleProperty(value = "{'snapshot':{'type': 'AAA'}}", mediaType = "application/json") 
                }))

I'm placing this code snippet just above the GET method in this case. unfortunately the 2 examples above always shows : identifier expected error

But I also see that I can do this too:

@ApiResponses(value = {
    ApiResponse(code = 200, message = "Success", response = MyModel.class,
    )
})

Also I see that I can add an example with @ApiOperation level:

@ApiOperation(value = "Create a Account", nickname = "createAccount", notes = "Create a account", response = AccountResponse.class, tags={  })

My questions are:

  1. How can I add an example JSON response to my Swagger documentation?

  2. It would be ideal to just point Swagger/Springfox to my model/bean and have it generate the example response automatically, and automatically update with each update for the bean/model. Is this what the second code snippet above is supposed to do?

Answer

oleg.cherednik picture oleg.cherednik · Oct 23, 2019

Define example with annotation for dto:

@ApiModel("Crop")
public class CropDto {

    @ApiModelProperty(name = "Unique guid", position = 1, example = "7aaee0e2-6884-4fd7-ba63-21d76723dce2")
    public UUID id;
    @ApiModelProperty(name = "Unique code", position = 2, example = "squ")
    public String code;
    @ApiModelProperty(name = "Unique name", position = 3, example = "Squash")
    public String name;
    @ApiModelProperty(position = 4, example = "Cucurbita pepo L.")
    public String description;
}