Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 685
Vaibhav Patil Avatar asked Jan 05 '18 10:01

Vaibhav Patil


People also ask

What are the formats supported by OpenAPI swagger for their definitions?

Format. An OpenAPI document that conforms to the OpenAPI Specification is itself a JSON object, which may be represented either in JSON or YAML format.

What are swagger properties?

The properties keyword is used to define the object properties – you need to list the property names and specify a schema for each property.

Is OpenAPI the same as swagger?

Although the terms once referred to the same thing, they can no longer be used interchangeably…even though some people still do. In 2021, OpenAPI refers to the industry-standard specification for RESTful API design. Swagger refers to a set of SmartBear tools.


1 Answers

This depends on the OpenAPI version.

OpenAPI 3.1

Your example is valid in OpenAPI 3.1, which is fully compatible with JSON Schema 2020-12.

type:   - 'null'   # Note the quotes around 'null'   - string  # same as type: ['null', string] 

The above is equivalent to:

oneOf:   - type: 'null'   # Note the quotes around 'null'   - type: string 

The nullable keyword used in OAS 3.0.x (see below) does not exist in OAS 3.1, it was removed in favor of the 'null' type.

OpenAPI 3.0.x

Nullable strings are defined as follows:

type: string nullable: true 

This is different from JSON Schema syntax because OpenAPI versions up to 3.0.x use their own flavor of JSON Schema ("extended subset"). One of the differences is that the type must be a single type and cannot be a list of types. Also there's no 'null' type; instead, the nullable keyword serves as a type modifier to allow null values.

OpenAPI 2.0

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

Consider migrating to OpenAPI v. 3 to get proper support for nulls.

like image 68
Helen Avatar answered Sep 22 '22 11:09

Helen