How to define a property that can be string or null in OpenAPI (Swagger)?

I have a JSON schema file where one of the properties is defined as string or null :

 "type":["string", "null"] 

When converting to YAML (for use with OpenAPI / Swagger) it becomes:

 type: - 'null' - string 

but the Swagger editor shows an error:

A key of type "schema" must be a string

What is the correct way to define a nullable property in OpenAPI?

+11
source share
1 answer

type as an array of types

 type: - string - 'null' 

NOT ALLOWED in OpenAPI / Swagger (even if it is valid in the JSON schema). The OpenAPI type keyword requires one type and cannot be an array of types.

null support depends on which version of OpenAPI you are using:

  • In OpenAPI 3.0, use the nullable keyword to define types with a null value:

     type: string nullable: true # <---- 
  • OpenAPI 2.0 does not support null as a data type, so if you're using 2.0, you're out of luck. You can use type: string . However, some tools support x-nullable: true as a provider extension, although zeros are not part of the OpenAPI 2.0 specification.

+16
source

All Articles