如何为 OpenAPI 中的每个索引(即元组)定义一个具有具体项目定义的 JSON 数组?

2024-04-02

我需要在 OpenAPI 中定义带有数组的 JSON 响应。该数组始终包含 2 个项目,第一个项目始终是数字,第二个项目始终是字符串。

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

我发现 JSON 模式确实通过传递项目列表来支持这一点items而不是单个对象(source https://json-schema.org/understanding-json-schema/reference/array.html),但 OpenAPI 明确禁止这样做,并且只接受单个对象(source http://spec.openapis.org/oas/v3.0.2#schema-object)。那如何用 OpenAPI 来表达呢?


您需要 OpenAPI 3.1 来精确定义元组。在早期版本中,您只能定义没有特定项目顺序的通用数组。

开放API 3.1

您的示例可以定义为:

# 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 与 JSON Schema 2020-12 完全兼容,包括prefixItems关键字(的新名称的元组形式items https://json-schema.org/understanding-json-schema/reference/array.html#tuple-validation来自早期的 JSON 架构草案)。

OpenAPI 3.0.x 及更早版本

早期的 OpenAPI 版本没有描述元组的方法。您最多可以定义“一个由 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.

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.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何为 OpenAPI 中的每个索引(即元组)定义一个具有具体项目定义的 JSON 数组? 的相关文章

随机推荐