swagger - OpenAPI 中的 'required' 到底是什么意思

标签 swagger openapi

鉴于以下 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/

    相关文章:

    java - OpenAPI/Swagger 构建具有多个相同键的对象

    spring - 开放 API 代码生成器 Maven 插件使用旧的 Swagger 2 注释而不是 Swagger 3 注释

    enums - Swagger 避免删除公共(public)前缀

    java - Swagger + Spring : is it possible to preserve the fields order in the payload?

    node.js - NodeJS API 通过 ID 获取。如何检测未找到的项目?

    clojure - :body-params vs :form-params in compojure-api

    amazon-web-services - 当 lambda 和授权者返回 200 时,API 网关返回 500

    Swagger:如何让属性引用 OpenAPI 2.0 中的模型(即嵌套模型)?

    java - 使用 Swagger 注释显示自定义 HashMap 键

    Python转义变量名中的 '$'字符