How can I set a description and an example in Swagger with Swagger annotations?

105,783

Solution 1

I have similar issue with generating examples for body objects - annotation @Example and @ExampleProperty simply doesn't work for no reason in swagger 1.5.x. (I use 1.5.16)

My current solution is:
use @ApiParam(example="...") for non-body objects, e.g.:

public void post(@PathParam("userId") @ApiParam(value = "userId", example = "4100003") Integer userId) {}

for body objects create new class and annotate fields with @ApiModelProperty(value = " ", example = " "), e.g.:

@ApiModel(subTypes = {BalanceUpdate.class, UserMessage.class})
class PushRequest {
    @ApiModelProperty(value = "status", example = "push")
    private final String status;;
}

Solution 2

Actually the java doc for the example property of the @ApiParam annotation states that this is exclusively to be used for non-body parameters. Where the examples property may be used for body parameters.

I tested this annotation

@ApiParam(
  value = "A JSON value representing a transaction. An example of the expected schema can be found down here. The fields marked with an * means that they are required.",
  examples = @Example(value = 
    @ExampleProperty(
      mediaType = MediaType.APPLICATION_JSON,
      value = "{foo: whatever, bar: whatever2}"
    )
  )
)

which resulted in the following swagger to be generated for the corresponding method:

/transaction:
  post:
  ...
    parameters:
    ...
    - in: "body"
      name: "body"
      description: "A JSON value representing a transaction. An example of the expected\
        \ schema can be found down here. The fields marked with an * means that\
        \ they are required."
      required: false
      schema:
        type: "string"  
      x-examples:
        application/json: "{foo: whatever, bar: whatever2}"

However this value doesn't seem to be picked up by swagger-ui. I tried version 2.2.10 and the latest 3.17.4, but neither version used the x-examples property of the swagger.

There are some references for x-example (the one used for non-body parameters) in the code of swagger-ui but no match for x-examples. That is this doesn't seem to be supported by swagger-ui at the moment.

If you really need this example values to be present, your best option currently seems to be to change your method's signature and use a dedicated domain type for the body parameter. As stated in the comments already swagger will automatically pick up the structure of the domain type and print some nice information in swagger-ui:

Swagger-UI 2.2.10 with domain type info

Solution 3

Have you tried the following ?

@ApiModelProperty(
    value = "A JSON value representing a transaction. An example of the expected schema can be found down here. The fields marked with an * means that they are required.",
    example = "{foo: whatever, bar: whatever2}")

Have a nice day

Solution 4

Swagger.v3 Kotlin/Micronaut example:

@Post("/get-list")
fun getList(
        @RequestBody(description = "Get list of ...",
                content = [Content(
                        mediaType = "application/json",
                        schema = Schema(implementation = RequestDTO::class),
                        examples = [ExampleObject(value = """
                            {
                                "pagination": {
                                    "page": 0,
                                    "perPage": 10
                                },
                                "filter": {
                                    "property_1": "string",
                                    "property_2": "string"
                                },
                                "sort": {
                                    "field": "property_1",
                                    "order": "DESC"
                                }
                            }
                        """)]
                )]) @Body request: RequestDTO): Response<SomeDTO> { ... }
Share:
105,783
Roman
Author by

Roman

Updated on July 22, 2022

Comments

  • Roman
    Roman almost 2 years

    I am creating a REST Api using Spring boot, and auto generating the swagger documentation in controllers using swagger codegen. However, I am not able to set a description and example for a parameter of type String in a POST request. Here is mi code:

    import io.swagger.annotations.*;
    
    @Api(value = "transaction", tags = {"transaction"})
    @FunctionalInterface
    public interface ITransactionsApi {
        @ApiOperation(value = "Places a new transaction on the system.", notes = "Creates a new transaction in the system. See the schema of the Transaction parameter for more information ", tags={ "transaction", })
        @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Another transaction with the same messageId already exists in the system. No transaction was created."),
            @ApiResponse(code = 201, message = "The transaction has been correctly created in the system"),
            @ApiResponse(code = 400, message = "The transaction schema is invalid and therefore the transaction has not been created.", response = String.class),
            @ApiResponse(code = 415, message = "The content type is unsupported"),
            @ApiResponse(code = 500, message = "An unexpected error has occurred. The error has been logged and is being investigated.") })
    
        @RequestMapping(value = "/transaction",
            produces = { "text/plain" },
            consumes = { "application/json" },
            method = RequestMethod.POST)
        ResponseEntity<Void> createTransaction(
            @ApiParam(
                value = "A JSON value representing a transaction. An example of the expected schema can be found down here. The fields marked with an * means that they are required." ,
                example = "{foo: whatever, bar: whatever2}")
            @Valid @RequestBody String kambiTransaction) throws InvalidTransactionException;
    }
    

    The example property of the @ApiParam has been manually inserted by me, because the codegen was ignoring that part of the yaml (That is another question: why is the editor ignoring the example part?). Here is part of the yaml:

    paths:
      /transaction:
        post:
          tags:
            - transaction
          summary: Place a new transaction on the system.
          description: >
            Creates a new transaction in the system. See the schema of the Transaction parameter
            for more information
          operationId: createTransaction
          parameters:
            - $ref: '#/parameters/transaction'
          consumes:
            - application/json
          produces:
            - text/plain
          responses:
            '200':
              description: Another transaction with the same messageId already exists in the system. No transaction was created.
            '201':
              description: The transaction has been correctly created in the system
            '400':
              description: The transaction schema is invalid and therefore the transaction has not been created.
              schema:
                type: string
                description: error message explaining why the request is a bad request.
            '415':
              description: The content type is unsupported
            '500':
              $ref: '#/responses/Standard500ErrorResponse'
    
    parameters:
      transaction:
        name: kambiTransaction
        in: body
        required: true
        description: A JSON value representing a kambi transaction. An example of the expected schema can be found down here. The fields marked with an * means that they are required.
        schema:
          type: string
          example:
            {
              foo*: whatever,
              bar: whatever2
            }
    

    And finally, this is what swagger is showing:

    enter image description here

    Finally, the dependencies used in build.gradle are the following ones:

    compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.7.0'
    compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.7.0'
    

    So, Question is: Does anybody know how I can set the description and an example of a body parameter using swagger annotations?

    EDIT

    I've achieved to change the description using @ApiImplicitParam instead of @ApiParam, but example is still missing:

    @ApiImplicitParams({
        @ApiImplicitParam(
            name = "kambiTransaction",
            value = "A JSON value representing a transaction. An example of the expected schema can be found down here. The fields marked with * means that they are required. See the schema of KambiTransaction for more information.",
            required = true,
            dataType = "String",
            paramType = "body",
            examples = @Example(value = {@ExampleProperty(mediaType = "application/json", value = "{foo: whatever, bar: whatever2}")}))})