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

纵饮孤独 提交于 2021-02-19 07:45:08

问题


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?


回答1:


OpenAPI 3.1

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).

Your example can be defined as:

type: array
prefixItems:
  - type: integer
  - type: string
minItems: 2
maxItems: 2
additionalItems: false   # can be omitted if `maxItems: 2` is specified

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.

来源:https://stackoverflow.com/questions/51179677/describe-array-with-implicitely-named-elements-in-openapi-swagger-specification

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!