OpenAPI 中 'required' 的真正含义是什么

What does 'required' in OpenAPI really mean

给定以下 OpenAPI 定义

Person:
  required:
    - id
  type: object
  properties:
    id:
      type: string

以下哪些对象是有效的?只是 1. 或 1. 和 2.?

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

这归结为“required = true”是指“非空 value”还是“属性[=38=”的问题] 必须存在"。

https://json-schema-validator.herokuapp.com/ 的 JSON 模式验证器说 2. 无效,因为 null 不满足 type: string 约束。请注意,它不会抱怨,因为 id 为空,但因为 null 不是字符串。但这对 OpenAPI/Swagger 有多重要?

OpenAPI Schema 对象中的 required 关键字取自 JSON Schema,意思是:

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 意味着 "属性 必须存在",而不管它的值 。 属性 值的 typeformat 等是单独的约束,它们与 required 分开评估,但一起作为组合架构。

在你的例子中:

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

    • ✓ 针对 required
    • 进行验证
    • ✓ 值 "" 针对 type: string
    • 进行验证
  2. {"id": null} 无效:

    • ✓ 针对 required
    • 进行验证
    • null 不针对 type: string 进行验证(请参阅下面关于空值的注释)
  3. {} 无效:

    • ✗ 未针对 required
    • 进行验证

请注意,'null' 作为一种类型在 OpenAPI 2.0 中不受支持,但 , and 3.0 has nullable 可以处理空值。因此,{"id": null} 针对此 OpenAPI 3 架构有效:

Person:
  required:
    - id
  type: object
  properties:
    id:
      # OAS 3.1
      type: [string, 'null']

      # OAS 3.0
      # type: string
      # nullable: true