如何在OpenAPI 3.1.0中精准定义含2个特定对象的数组?
在OpenAPI 3.1.0中实现请求体variables数组的精确约束
针对你需要的约束——请求体中variables数组恰好包含2个指定对象,且每个对象的value类型与typeConstraint严格匹配——可以利用OpenAPI 3.1.0对JSON Schema 2020-12的支持,通过以下两种方式实现:
方式一:允许两个对象顺序任意
这种写法不限制数组元素的顺序,只要同时包含两个指定对象即可:
openapi: 3.1.0 info: title: 你的接口标题 version: 1.0.0 paths: /your-endpoint: post: summary: 你的接口描述 requestBody: required: true content: application/json: schema: type: object properties: variables: type: array # 强制数组恰好有2个元素 minItems: 2 maxItems: 2 items: type: object properties: name: type: string typeConstraint: type: string enum: [string, boolean] value: type: ["string", "boolean"] required: [name, typeConstraint, value] # 确保value类型与typeConstraint匹配 allOf: - if: properties: typeConstraint: const: string then: properties: value: type: string - if: properties: typeConstraint: const: boolean then: properties: value: type: boolean # 确保数组同时包含两个指定对象 allOf: - contains: properties: name: const: groupGuid typeConstraint: const: string required: [name, typeConstraint] - contains: properties: name: const: addMembership typeConstraint: const: boolean required: [name, typeConstraint] responses: '200': description: 成功响应
关键约束说明:
minItems: 2+maxItems: 2:强制数组长度严格为2- 内层
allOf+if/then:对单个对象做类型校验,确保typeConstraint为string时value是字符串,为boolean时value是布尔值 - 外层
allOf+contains:确保数组中同时存在groupGuid(类型约束string)和addMembership(类型约束boolean)两个对象
方式二:固定两个对象的顺序
如果要求数组元素必须按groupGuid在前、addMembership在后的顺序排列,可以用prefixItems(JSON Schema 2020-12新增)简化写法:
openapi: 3.1.0 info: title: 你的接口标题 version: 1.0.0 paths: /your-endpoint: post: summary: 你的接口描述 requestBody: required: true content: application/json: schema: type: object properties: variables: type: array minItems: 2 maxItems: 2 # 按顺序定义每个元素的约束 prefixItems: - type: object properties: name: const: groupGuid typeConstraint: const: string value: type: string required: [name, typeConstraint, value] - type: object properties: name: const: addMembership typeConstraint: const: boolean value: type: boolean required: [name, typeConstraint, value] responses: '200': description: 成功响应
这种写法更简洁,但限制了元素的顺序,适合对顺序有明确要求的场景。
内容的提问来源于stack exchange,提问作者ajh3
相关产品推荐
相关产品推荐

