问题
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