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}
{}
这归结为required = true"是指非空值"还是必须存在属性"的问题.
This boils down to the question whether "required = true" means "non-null value" or "property must be present".
https://json-schema-validator.herokuapp.com/上的 JSON 模式验证器 表示 2. 无效,因为 null
不满足 type: string
约束.请注意,它不会因为 id
为空而抱怨,而是因为 null
不是字符串.但这与 OpenAPI/Swagger 有多大关系?
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?
推荐答案
OpenAPI Schema Objects 中的 required
关键字取自 JSON Schema 意思是:
The required
keyword in OpenAPI Schema Objects is taken from JSON Schema and means:
如果[required
] 数组中的每一项都是实例中属性的名称,则对象实例对该关键字有效.
An object instance is valid against this keyword if every item in the [
required
] array is the name of a property in the instance.
换句话说,required
表示属性必须存在",无论其值如何.属性值的 type
、format
等是单独的约束,它们与 required
分开评估,但作为组合模式一起评估.
In other words, required
means "property must be present", regardless of its 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
进行验证(请参阅下面关于 null 的注释)
- ✓ validates against
required
- ✗
null
does NOT validate againsttype: string
(see the notes about nulls below)
{}
无效:
- ✗ 不针对
required
进行验证
请注意,OpenAPI 2.0 不支持将 'null'
作为类型,但在 OpenAPI 3.1 中支持 ,而 3.0 有 nullable
来处理空值.因此,{id": null}
对这个 OpenAPI 3 架构有效:
Note that 'null'
as a type is not supported in OpenAPI 2.0 but is supported in OpenAPI 3.1, and 3.0 has nullable
to handle nulls. So, {"id": null}
is valid against this OpenAPI 3 schema:
Person:
required:
- id
type: object
properties:
id:
# OAS 3.1
type: [string, 'null']
# OAS 3.0
# type: string
# nullable: true
这篇关于OpenAPI 中的“必需"到底是什么意思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!