tuplesopenapi

How to define a JSON array with concrete item definition for every index (i.e. a tuple) in OpenAPI?


I need to define in OpenAPI a JSON response with an array. The array always contains 2 items and the first one is always a number and second one is always a string.

[1, "a"]    //valid
["a", 1]    //invalid
[1]         //invalid
[1, "a", 2] //invalid

I've found out that JSON schema does support that by passing a list of items in items instead of single object (source), but OpenAPI explicitly forbids that and accepts only a single object (source). How can that be expressed in OpenAPI?


Solution

  • You need OpenAPI 3.1 to define tuples precisely. In earlier versions, you can only define generic arrays without a specific item order.

    OpenAPI 3.1

    Your example can be defined as:

    # openapi: 3.1.0
    
    type: array
    prefixItems:
      # The 1st item
      - type: integer
        description: Description of the 1st item
    
      # The 2nd item
      - type: string
        description: Description of the 2nd item
    
      # Define the 3rd etc. items if needed
      # ...
    
    # The total number of items in this tuple
    minItems: 2
    maxItems: 2
    additionalItems: false   # can be omitted if `maxItems` is specified
    

    OpenAPI 3.1 is fully compatible with JSON Schema 2020-12, including the prefixItems keyword (the new name for the tuple form of items from earlier JSON Schema drafts).

    OpenAPI 3.0.x and earlier

    Earlier OpenAPI versions do not have a way to describe tuples. The most you can do is define "an array of 2 items that can be either number or string", but you cannot specifically define the type of the 1st and 2nd items. You can, however, mention additional constraints in the schema description.

    # openapi: 3.0.0
    
    type: array
    items:
      oneOf:
        - type: integer
        - type: string
    minItems: 2
    maxItems: 2
    description: >-
      The first item in the array MUST be an integer,
      and the second item MUST be a string.
    

    If you are designing a new API rather than describing an existing one, a possible workaround is to use an object instead of an array to represent this data structure.