What does 'required' in OpenAPI really mean

假装没事ソ 提交于 2019-11-29 15:07:41

问题


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. {}

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?


回答1:


The required keyword in OpenAPI has the same meaning as in JSON Schema:

required

An object instance is valid against this keyword if its property set contains all elements in this keyword's array value.

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.

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.

In your example:

  1. {"id": ""} is valid:

    • ✓ validates against required
    • ✓ the value "" validates against type: string
  2. {"id": null} is NOT valid:

    • ✓ validates against required
    • null does NOT validate against type: string
  3. {} is NOT valid:

    • ✗ does NOT validate against required

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   # <----


来源:https://stackoverflow.com/questions/45575493/what-does-required-in-openapi-really-mean

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!