OpenAPI中“必需"的真正含义是什么 [英] What does 'required' in OpenAPI really mean
问题描述
给出以下OpenAPI定义,以下哪些对象有效.只是1.或1.和2.?
Given the following OpenAPI definition which of the below objects are valid. Just 1. or 1. and 2.?
Person:
required:
- id
type: object
properties:
id:
type: string
-
{"id": ""}
-
{"id": null}
-
{}
{"id": ""}
{"id": null}
{}
这归结为以下问题:"required = true"是否意味着必须存在非null 值"或"属性".
This boils down to the question whether "required = true" means "non-null value" or "property must be present".
The JSON schema validator at https://json-schema-validator.herokuapp.com/ says that 2. be invalid because null
doesn't satisfy the type: string
constraint. Note that it doesn't complain because id
is null but because null
is not a string. BUT how relevant is this for OpenAPI/Swagger?
推荐答案
The required
keyword in OpenAPI has the same meaning as in JSON Schema:
必填
如果对象实例的属性集包含此关键字的数组值中的所有元素,则该对象实例对该关键字有效.
An object instance is valid against this keyword if its property set contains all elements in this keyword's array value.
最新的JSON模式规范中的措辞(尽管不是OpenAPI使用的那个)更清晰:
The wording in the latest JSON Schema spec (although it's not the one used by OpenAPI) is more clear:
如果数组中的每个项目都是实例中属性的名称,则对象实例对此关键字有效.
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
分开评估,但一起作为组合模式.
That is, required
means "property must be present", regardless of the value. The type
, format
, etc. of the property value are separate constraints that are evaluated separately from required
, but together as a combined schema.
在您的示例中:
-
{"id": ""}
有效:
- ✓针对
required
进行验证
- ✓值
""
针对type: string
进行验证
- ✓ validates against
required
- ✓ the value
""
validates againsttype: string
{"id": null}
无效:
- ✓针对
required
进行验证
- ✗
null
不针对type: string
进行验证
- ✓ validates against
required
- ✗
null
does NOT validate againsttype: string
{}
无效:
- ✗不针对
required
进行验证
- ✗ does NOT validate against
required
请注意,OpenAPI不支持将null
作为类型,但是OpenAPI 3.0会添加将针对此OpenAPI 3.0架构进行验证:
Note that null
as a type is not supported in OpenAPI, but OpenAPI 3.0 adds the nullable
attribute to indicate that the value may be null
. So, {"id": null}
would validate against this OpenAPI 3.0 schema:
Person:
required:
- id
type: object
properties:
id:
type: string
nullable: true # <----
这篇关于OpenAPI中“必需"的真正含义是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!