OpenAPI optional object default value

Viewed 1891

Suppose you have the following OpenAPI requestBody specification:

requestBody:
  required: true
  content:
    application/json:
      schema:
        type: object
        properties:
          field1:
            type: number
            default: 1
          field2:
            type: object
            properties:
              subfield:
                type: number
                default: 2

The request body contains:

  • a number field with default value 1
  • an object field, containing itself a number field with default value 2

If a client sends an empty payload, we should agree that field1 value is supposed to be 1, but what about field2 value?

  1. field2 is not specified, so it must be considered as null
  2. field2 should be an object build with default values: {subfield: 2}
  3. OpenAPI does not answer this question and that's up to me to decide what my application should do
1 Answers

Correct behaviour would be your alternative 1, with a twist.

field2 should be considered to be "not present" and not null as there is some difference between those cases, see https://github.com/OAI/OpenAPI-Specification/issues/1775 for some discussion related to that difference.

From a validation point-of-view field2 is not declared as nullable an object like {"field2": null} should not be valid, but {} would be.

Whether "not present" or null should be handled differently is up to your application.

Related