如何为含混合类型值的嵌套数组编写OpenAPI Schema?
为混合类型嵌套数组响应创建OpenAPI Schema
你的API返回的是表头+多行统计数据的嵌套数组结构,子数组分为两种类型:全字符串的表头行、混合类型的数据行。下面是对应的OpenAPI Schema定义方案:
核心思路
用oneOf区分两种子数组的结构,将整个响应定义为包含这两种子数组的数组。OpenAPI 3.1+推荐用prefixItems按顺序定义数据行的元素类型,3.0版本则用兼容写法。
完整Schema示例(OpenAPI 3.1+)
responses: '200': description: 统计数据查询成功 content: application/json: schema: type: array items: oneOf: # 表头行:固定字段名的字符串数组 - type: array items: type: string enum: - ["Time", "Attempts", "Successes", "Failures", "BookabilityRatio"] # 数据行:按顺序定义各元素类型 - type: array prefixItems: - type: string format: date # 明确日期格式为YYYY-MM-DD - type: integer - type: integer - type: integer - type: number format: float # 明确浮点数字格式 minItems: 5 maxItems: 5 # 固定数据行长度,避免无效数据
OpenAPI 3.0兼容写法
如果使用3.0版本,因为不支持prefixItems,可以把数据行的元素类型直接写成数组形式:
# 替换上方数据行的定义即可 - type: array items: - type: string format: date - type: integer - type: integer - type: integer - type: number format: float minItems: 5 maxItems: 5
关键说明
- 表头行用
enum强制限定字段名,确保返回的表头与预期完全一致,避免字段错位或名称错误。 format字段是可选的,但能更清晰地描述数据的具体格式,帮助调用方理解数据要求。minItems和maxItems固定子数组长度,防止返回长度不符的无效数据。
内容的提问来源于stack exchange,提问作者Pradeepta Kumar Khatoi
相关产品推荐
相关产品推荐

