鉴于以下 OpenAPI 定义,以下哪些对象是有效的。只有 1. 还是 1. 和 2.?
Person:
required:
- id
type: object
properties:
id:
type: string
{"id": ""}
{"id": null}
{}
这归结为“required = true”是指“非空值”还是“属性必须存在”的问题。
JSON 模式验证器位于 https://json-schema-validator.herokuapp.com/说 2. 无效,因为
null
不满足type: string
约束。请注意,它不会提示,因为 id
为空,但因为 null
不是字符串。但是这与 OpenAPI/Swagger 的相关性如何?
最佳答案
required
OpenAPI 中的关键字与 JSON Schema 中的关键字含义相同:
required
An object instance is valid against this keyword if its property set contains all elements in this keyword's array value.
latest JSON Schema spec中的措辞(虽然它不是 OpenAPI 使用的)更清楚:
An object instance is valid against this keyword if every item in the array is the name of a property in the instance.
即,
required
意味着“属性必须存在”,无论值如何。 type
, format
等属性值是独立的约束,独立于 required
进行评估。 ,但一起作为一个组合模式。在你的例子中:
{"id": ""}
已验证:required
进行验证""
针对 type: string
进行验证{"id": null}
无效:required
进行验证null
不针对 type: string
进行验证{}
无效:required
进行验证请注意
null
作为 OpenAPI 不支持的类型,但 OpenAPI 3.0 添加了 nullable
属性来指示该值可能是 null
.所以,{"id": null}
将针对此 OpenAPI 3.0 架构进行验证:Person:
required:
- id
type: object
properties:
id:
type: string
nullable: true # <----
关于swagger - OpenAPI 中的 'required' 到底是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45575493/