Damian
Damian

Reputation: 79

How to display a nested array example for a body parameter in Swagger UI?

I have a nested array as a parameter in the body of my POST method:

 parameters:
 - in: body
   name: matrix
   description: blabla
   schema:
     type: array
     items:
       schema:
         type: array
         items:
           schema:
             type: double

I would like to add an example for this array to be visible in Swagger UI. I tried the following, however it doesn't seem to work - nothing is displayed as example in the body field. If I enter [[1.0, 2.0],[3.0, 4.0]] manually in the body field in Swagger UI, it works just fine.

 parameters:
 - in: body
   name: matrix
   description: blabla
   schema:
     type: array
     items:
       schema:
         type: array
         items:
           schema:
             type: double
   example: [[1.0, 2.0],[3.0, 4.0]]

Update: After implementing Helen's suggestions, here is how it looks:

Upvotes: 2

Views: 1579

Answers (1)

Helen
Helen

Reputation: 97580

Here's the correct version:

  parameters:
    - in: body
      name: matrix
      description: blabla
      schema:
        type: array
        items:
          type: array
          items:
            type: number
            format: double
        example: [[1.0, 2.0],[3.0, 4.0]]

List of fixes:

  • No need for schema under items.
  • type: double should be type: number + format: double (see Data Types).
  • The array example should be alongside type: array in the schema. Parameters themselves do not support the example keyword.

You can use the online Swagger Editor to check your spec for syntax errors, it will flag the lines with errors.

Note for Swagger UI 2.x

Swagger UI 2.x does not display body parameter examples if the body is an array of primitives. The latest version, Swagger UI 3.x, does not have this issue.

A possible workaround for 2.x is to add the x-examples.default key to the body parameter and specify the example value as a string:

  parameters:
    - in: body
      name: matrix
      description: blabla
      schema:
        type: array
        items:
          type: array
          items:
            type: number
            format: double
        example: [[1.0, 2.0],[3.0, 4.0]]
      x-examples:
        default: '[[1.0, 2.0],[3.0, 4.0]]'  # <-----

Upvotes: 3

Related Questions