OpenAPI中“必需"的真正含义是什么 [英] What does 'required' in OpenAPI really mean

查看:74
本文介绍了OpenAPI中“必需"的真正含义是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下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

  1. {"id": ""}
  2. {"id": null}
  3. {}
  1. {"id": ""}
  2. {"id": null}
  3. {}

这归结为以下问题:"required = true"是否意味着必须存在非null "或"属性".

This boils down to the question whether "required = true" means "non-null value" or "property must be present".

位于 https://json-schema-validator.herokuapp.com/表示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中的required关键字与

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表示属性必须存在",而不管其值如何.属性值的typeformat等是单独的约束,它们与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.

在您的示例中:

  1. {"id": ""}有效:

  • ✓针对required
  • 进行验证
  • ✓值""针对type: string
  • 进行验证
  • ✓ validates against required
  • ✓ the value "" validates against type: string

{"id": null}无效:

  • ✓针对required
  • 进行验证
  • null不针对type: string
  • 进行验证
  • ✓ validates against required
  • null does NOT validate against type: 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆