enum in OpenAPI: allowed values, null, and adding one later
Last checked and updated
enum lists the values a field may take; anything else is invalid. The values are compared exactly, so they are case sensitive, and they should be of the schema's type.
status:
type: string
enum: [draft, active, archived]
A mock server generated from this refuses another value and names the field:
$ curl -X POST http://127.0.0.1:4632/items -H 'content-type: application/json' \
-d '{"name":"a","status":"deleted","quantity":2}'
HTTP/1.1 422 Unprocessable Entity
{"errors":[{"in":"body","pointer":"/status","message":"must be equal to one of the allowed values"}],
"type":"https://apigit.com/mock/problems/invalid-request",
"title":"The request does not match the API description","status":422, ...}
and uses the first value in generated examples ("status":"draft"), which is a reason to list the most typical value first.
Allowing null
null has to pass two checks, the type and the enum. Both must allow it:
# OpenAPI 3.1
priority:
type: [string, "null"]
enum: [low, high, null]
# OpenAPI 3.0
priority:
type: string
nullable: true
enum: [low, high, null]
With this schema, "priority": null is accepted (the mock answers 201 Created). Leave null out of the enum and it is refused even though the type allows it. More on the two spellings: nullable in OpenAPI 3.0 and 3.1.
Describing each value
enum carries no descriptions. Three ways to document the values, from most to least portable:
- In the schema's
description: a short list, "draft: not visible to customers; ...". Every tool shows it. - In OpenAPI 3.1,
oneOfwith oneconstper value, each with its owntitleanddescription. It validates like an enum and documentation tools can show the texts. - Extensions such as
x-enum-descriptionsorx-enum-varnames. They work only in the generators that define them.
One value: enum or const
A field that always has the same value, such as the type of one variant under a discriminator, is const: card in OpenAPI 3.1 and enum: [card] in 3.0.
Adding a value later
| Where the enum is used | Adding a value | Removing a value |
|---|---|---|
| Request | safe: old clients keep sending old values | breaking: old clients send what is now refused |
| Response | can break clients: generated code can fail on a value it does not know | safe for clients that handle all values |
If a response enum is likely to grow, say so in its description, and tell client authors to handle unknown values. Some teams leave response fields as plain strings with the known values documented, for exactly this reason.
Common mistakes
- Values of the wrong type:
enum: [1, 2]undertype: stringcan never match. - YAML reading a value as something else: unquoted
no,onoroffcan become booleans in some YAML parsers. Quote them:enum: ["yes", "no"]. - An
enumand adefaultthat is not one of its values.