64

Given the following OpenAPI definition

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

Which of the below objects are valid? Only A or A & B?

A. {"id": ""}
B. {"id": null}
C. {}

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?

Marcel Stör
  • 22,695
  • 19
  • 92
  • 198

1 Answers1

102

The required keyword in OpenAPI Schema Objects is taken from JSON Schema and means:

An object instance is valid against this keyword if every item in the [required] array is the name of a property in the instance.

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.

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 (see the notes about nulls below)
  3. {} is NOT valid:

    • ✗ does NOT validate against required

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
Helen
  • 87,344
  • 17
  • 243
  • 314
  • 1
    Great answer, thanks. Not your fault that the JSON schema spec doesn't align well with the JavaScript/JSON notion of `null`. – Marcel Stör Aug 08 '17 at 21:06
  • 1
    @MarcelStör JSON Schema does have the `null` type, and a nullable schema can be defined as `{"type": ["string", "null"]}`. But OpenAPI does not support `type: null` and uses the `nullable` attribute instead. – Helen Aug 09 '17 at 07:34
  • what implication does this have on a patch request? I am thinking of any attribute could be present but doesnt have to since its a patch. And does it mean I would need 2 models for patch and post? Post requires all but patch kinda nothing? – The Fool Dec 31 '21 at 21:49
  • @TheFool you'll need 2 models in that case. The POST model can be `allOf` of the PATCH model + the `required` list. [Example](https://community.smartbear.com/t5/Swagger-Open-Source-Tools/how-to-have-different-required-fields-for-the-create-put-and/m-p/196699/highlight/true#M915) – Helen Jan 05 '22 at 21:10