nullable in OpenAPI 3.0 and 3.1: how to say a value may be null
Last checked and updated
In OpenAPI 3.0 a value that may be null is marked nullable: true. OpenAPI 3.1 removed that keyword: there you add "null" to the type, type: [string, "null"]. A 3.1 file that still says nullable: true is a common migration bug, and a linter may not complain about it.
The two spellings
OpenAPI 3.0:
nickname:
type: string
nullable: true
OpenAPI 3.1:
nickname:
type: [string, "null"]
3.1 schemas are JSON Schema 2020-12, in which null is a type like any other, and type may be a list. The quotes around "null" matter in YAML: without them, null is YAML's empty value, not the string.
Nullable is not optional
| May be left out | May be null | |
|---|---|---|
Not in required, not nullable | yes | no |
In required, nullable | no | yes |
Not in required, nullable | yes | yes |
A client that sends "nickname": null to an API whose schema only makes nickname optional is sending an invalid body.
What the tools say
A file that declares openapi: 3.1.0 and still uses nullable: true passes a linter with the default rule set, and with the stricter best-practice rule set too. The only finding is unrelated:
$ apigit lint pets-31-wrong.yaml
pets-31-wrong.yaml
2:6 warn info-contact Info object must have "contact" object. (info)
1 problem (0 errors, 1 warning, 0 info, 0 hints)
So do not rely on a linter to catch this one: search the file for nullable after changing the version.
Converting the property correctly while moving from 3.0 to 3.1 does not change what the API accepts, but a tool that compares the two files sees the type change:
$ apigit breaking pets-30.yaml pets-31.yaml
1 change(s), 1 breaking.
Breaking
schema Pet: schema field "nickname" is now string|null, was string
The check read the 3.0 file's type as string and the 3.1 file's as string|null. When the only difference is the spelling of nullability, this report can be accepted; a real change from non-nullable to nullable in a response would break clients that do not expect null.
Migrating
| OpenAPI 3.0 | OpenAPI 3.1 |
|---|---|
type: string + nullable: true | type: [string, "null"] |
A referenced schema that may be null. 3.0 has no clean spelling: nullable only takes effect next to a type in the same schema, and siblings of $ref are ignored, so files use the convention nullable: true + allOf: [{ $ref: ... }], which tools read differently | oneOf: [{ $ref: ... }, { type: "null" }] |
nullable: true and enum: [a, b, null] | type: [string, "null"] and enum: [a, b, null] |
The enum case is the one people miss: in both versions null must be one of the enum's values, or null fails the enum even though the type allows it.