Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swagger / springfox generating response example automatically

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?

like image 680
Tlink Avatar asked Dec 04 '18 16:12

Tlink


People also ask

Is Springfox deprecated?

springfox (documentationProvider): Springfox is deprecated for removal in version 7.0. 0 of openapi-generator. The project seems to be no longer maintained (last commit is of Oct 14, 2020). It works with Spring Boot 2.5.

How does Springfox work?

Springfox works by examining an application, once, at runtime to infer API semantics based on spring configurations, class structure and various compile time java Annotations.


1 Answers

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;
}
like image 127
oleg.cherednik Avatar answered Oct 01 '22 12:10

oleg.cherednik