How to define a nested array in OpenAPI?

Viewed 809

I want to define this

     "locationPoly": [
          [-87.63466, 24.50182],
          [-80.03074, 24.50182],
          [-80.03074, 31.00107],
          [-87.63466, 31.00107],
          [-87.63466, 24.50182]
        ],

In my OpenAPI YAML schema, I defined it like this:

                  locationPoly:
                    type: array
                    properties:
                      type: array
                      properties:
                        type: number

But I am getting the "schema is invalid" error. Is there another way to define this?

2 Answers

Arrays must use the items keyword.

locationPoly:
  type: array
  items:
    type: array
    items:
      type: number

In your example, the locationPoly array appears to contain coordinates. A pair of coordinates can be considered a tuple (ordered list). If you're using OpenAPI 3.1 (or will be using it in the future), it has the prefixItems keyword to define tuples. This way you can provide separate descriptions for individual elements of the tuple (i.e., for the 1st and 2nd items of the inner arrays in your example).

# openapi: 3.1.0

  locationPoly:
    type: array
    items:
      $ref: '#/components/schemas/Coordinates'
...

Coordinates:
  type: array
  prefixItems:
    # The 1st item
    - type: number
      description: Latitude
      minimum: -90
      maximum: 90
    # The 2nd item
    - type: number
      description: Longitude
      minimum: -180
      maximum: 180
  minItems: 2
  maxItems: 2
  additionalItems: false # Can be omitted if maxItems is specified
Related