OpenAPI 3.1
Define the property as anyOf
of the $ref
and type: 'null'
.
YAML version:
foo:
anyOf:
- type: 'null' # Note the quotes around 'null'
- $ref: '#/components/schemas/Foo'
JSON version:
"foo": {
"anyOf": [
{ "type": "null" },
{ "$ref": "#/components/schemas/Foo" }
]
}
Why use anyOf
and not oneOf
? oneOf
will fail validation if the referenced schema itself allows nulls, whereas anyOf
will work.
OpenAPI 3.0
YAML version:
foo:
nullable: true
allOf:
- $ref: '#/components/schemas/Foo'
JSON version:
"foo": {
"nullable": true,
"allOf": [
{ "$ref": "#/components/schemas/Foo" }
]
}
In OAS 3.0, wrapping $ref
into allOf
is needed to combine the $ref
with other keywords – because $ref
overwrites any sibling keywords. This is further discussed in the OpenAPI Specification repository: Reference objects don’t combine well with “nullable”