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

后端 未结 1 1553
北荒
北荒 2020-12-22 00:52

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条回答
  • 2020-12-22 01:44

    OpenAPI 3.1 (future version, not yet released)

    OAS 3.1 will be fully compatible with JSON Schema draft 2019-09, including the tuple form of items. In OAS 3.1, your example can be defined as:

    type: array
    items:
      - type: integer
      - type: string
    minItems: 2
    additionalItems: false
    

    OpenAPI 3.0.x and earlier

    Earlier OAS 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.

    0 讨论(0)
提交回复
热议问题