Linter rulesOpenAPIschema-no-optional-nullable-properties
schema-no-optional-nullable-properties
Since 0.0.1
This rule disallows schema properties that are both optional and nullable.
Rule Details
An optional nullable property represents an absent value in two ways: the property
may be omitted, or it may be present with the value null. Requiring a property
to be nullable or allowing it to be omitted makes the API contract unambiguous.
A property is nullable when its schema, or the schema it references, allows null:
- a
nulltype, e.g.type: [string, 'null']; nullable: truein OpenAPI 3.0 documents;nullinenumor asconst;- an
anyOforoneOfbranch allowingnull, e.g.anyOf: [{$ref: ...}, {type: 'null'}]; - an
allOfwhose every member allowsnull.
A property counts as required when the schema, one of its allOf members, or a schema
using it in allOf lists it in required.
In PATCH request bodies and application/merge-patch+json documents, null means
“remove this value” (RFC 7396), so optional nullable properties are expected there and
the rule skips them and every schema they contain.
Configuration
This rule accepts an object with the following options:
ignorePatchBodies: skip the schemas ofPATCHrequest bodies and merge-patch documents. Defaults totrue.
commands:
lint:
rules:
schema-no-optional-nullable-properties:
- warning
- ignorePatchBodies: false
Examples
Good. The nullable property is required.
components:
schemas:
User:
type: object
required: [middleName]
properties:
middleName:
type: [string, 'null']
Good. The optional property cannot be null.
components:
schemas:
User:
type: object
properties:
middleName:
type: string
Bad. middleName can be omitted or set to null.
components:
schemas:
User:
type: object
properties:
middleName:
type: [string, 'null']
When Not to Use It
Disable this rule when omission and an explicit null have distinct meanings in
your API.
Compatibility
This rule is compatible with all OpenAPI 3.x versions: it recognizes nullable: true
in OpenAPI 3.0 documents and null types in OpenAPI 3.1 and later.