How to define a property that can be string or nul

2019-01-08 00:33发布

问题:

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

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

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

type:
  - 'null'
  - string

but the Swagger Editor shows an error:

Schema "type" key must be a string

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

回答1:

type as an array of types

type:
  - string
  - 'null'

is NOT valid in OpenAPI/Swagger (even though it's valid in JSON Schema). OpenAPI's type keyword requires a single type and cannot be an array of types.

Support for null depends on which version of OpenAPI you use:

  • In OpenAPI 3.0, use the nullable keyword to define nullable types:

    type: string
    nullable: true   # <----
    
  • OpenAPI 2.0 does not support null as the data type, so if you use 2.0, you are out of luck. You can only use type: string. That said, some tools support x-nullable: true as a vendor extension, even though nulls are not part of the OpenAPI 2.0 Specification.