问题描述
我需要在 OpenAPI 中定义一个带有数组的 JSON 响应.该数组始终包含 2 个项目,第一个始终是数字,第二个始终是字符串.
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
我发现 JSON 模式通过在 items
中传递项目列表而不是单个对象(source),但 OpenAPI 明确禁止这样做并且只接受一个对象(来源).如何在 OpenAPI 中表达?
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?
推荐答案
OpenAPI 3.1
OpenAPI 3.1 与 JSON Schema 2020-12 完全兼容,包括 prefixItems
关键字(元组形式的 items
来自早期 JSON Schema 草案).
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).
你的例子可以定义为:
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 及更早版本
早期的 OpenAPI 版本没有描述元组的方法.您最多可以定义可以是数字或字符串的 2 个项目的数组",但您不能具体定义第 1 项和第 2 项的类型.但是,您可以在架构 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.
这篇关于如何为 OpenAPI 中的每个索引(即元组)定义一个带有具体项目定义的 JSON 数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!