Define a null property in OpenAPI
To define a property that can be a string or null
in OpenAPI (Swagger), you use different methods depending on the OpenAPI specification version.
OpenAPI 3.1.0
OpenAPI 3.1.0 and later versions align with the JSON Schema specification, which simplifies the definition of nullable types. You can use an array for the type
keyword to specify multiple possible types, including null
.
Example:
openapi: 3.1.0
info:
title: API
version: 1.0.0
paths: {}
components:
schemas:
User:
type: object
properties:
username:
type: string
description: A required string
email:
type: [string, "null"]
description: Can be a string or null
In this example, the email
property can be either a string
or null
. This is the most straightforward and modern way to define a nullable type in OpenAPI.
OpenAPI 3.0.0
In OpenAPI 3.0.0, the nullable: true
keyword was introduced specifically to define properties that can be null
.
Example:
openapi: 3.0.0
info:
title: API
version: 1.0.0
paths: {}
components:
schemas:
User:
type: object
properties:
username:
type: string
description: A required string
email:
type: string
nullable: true
description: Can be a string or null
In this version, you must specify the primary type (e.g., string
, integer
) and then add nullable: true
to indicate that null
is also a valid value. Do not use an array for type
as it is not supported in this version.
OpenAPI 2.0 (Swagger 2.0)
Swagger 2.0 does not have a dedicated nullable
keyword or support for multiple types. The convention for defining a property that could be null
was to document it in the description.
Example:
swagger: '2.0'
info:
title: API
version: 1.0.0
paths: {}
definitions:
User:
type: object
properties:
username:
type: string
description: A required string
email:
type: string
description: Can be a string or null
For Swagger 2.0, the information that the email
property is nullable is conveyed solely through the description
field. This means that code generators and validation tools would not automatically enforce the nullability. It relies on the consumer of the API documentation to understand this convention.
The lack of a formal way to define nullability was one of the key reasons the nullable
keyword was added in OpenAPI 3.0.0 to improve clarity and machine-readability of the specification.