Search code examples
yamlswaggeropenapi

How to add multiple example values for an array in OpenAPI/Swagger?


I am using Swagger OpenAPI Specification tool. I have a string array property in one of the definitions as follows:

cities:
    type: array
    items:
      type: string
      example: "Pune"

My API produces JSON result, so Swagger UI displays the following example for the response:

{
  "cities": [
    "Pune"
  ]
}

How can I add multiple example values for the cities array? Expecting the result as:

{
  "cities": [
    "Pune",
    "Mumbai",
    "Bangaluru"
  ]
}

Tried comma-separated strings in the example key like below:

cities:
    type: array
    items:
      type: string
      example: "Pune", "Mumbai", "Bangaluru"

But the Swagger Editor shows an error, "Bad indentation".

Is there any way to specify multiple values in the example key?

Update

User Helen below has given the correct answer. I had an indentation problem hence there were nested arrays (2d arrays)

Correct way:

cities:
    type: array
    items:
      type: string
    example: 
    - Pune
    - Mumbai

My way (which was wrong)

cities:
    type: array
    items:
      type: string
      example: 
      - Pune
      - Mumbai

Look for the indentation of the example key in the above two cases which makes the difference, its YAML indentation matters.


Solution

  • To display an array example with multiple items, add the example on the array level instead of item level:

    cities:
      type: array
      items:
        type: string
      example:
        - Pune
        - Mumbai
        - Bangaluru
    
      # or
      # example: [Pune, Mumbai, Bangaluru]
    

    In case of array of objects, the example would look like this:

    type: array
    items:
      type: object
      properties:
        id:
          type: integer
        name:
          type: string
    example:
      - id: 1
        name: Prashant
      - id: 2
        name: Helen