liveBook · Manning

Enum keyword

As explained in Data-Oriented Programming: Reduce software complexity

The JSON Schema keyword that restricts a value to one of a specified set of allowed values.

When a request should accept only a closed list of values, replace a broad string constraint with JSON Schema's enum keyword. It makes the permitted choices explicit rather than trusting every string a client sends. section 7.2

A search request with controlled fields

A books search request can restrict fields to values such as publishers, number_of_pages, weight, physical_format, subjects, publish_date, and physical_dimensions. A requested field outside that list fails schema validation. section 7.2

Listing 7.5 Schema for the search request with enumeration values
{
  "type": "object",
  "properties": {
    "title": {"type": "string"},
    "fields": {
      "type": "array",
      "items": {
        "enum": [
          "publishers",
          "number_of_pages",
          "weight",
          "physical_format",
          "subjects",
          "publish_date",
          "physical_dimensions"
        ]
      }
    }
  }
}

Inspect the schema fragment that places enum inside the fields array's items schema. section 7.2

Use enum when:

  • The accepted values come from a known, closed list. section 7.2
  • The constrained value appears inside an array, place enum in the items schema. section 7.2
  • A validator checks whether submitted data conforms to the schema and returns true or false. section 7.2

How Data-Oriented Programming: Reduce software complexity covers it

How deep it goes
Explains the keyword, its array-item placement, and validation use, but stops short of implementation internals.
Examples
Uses a books search request whose fields include publishers, weight, number_of_pages, and other supported Open Library fields.
What it assumes
Assumes familiarity with JSON objects and arrays while introducing closed-list constraints through a concrete request schema.
What you can do after
Build it from scratch by writing an enum schema for permitted request values and validating submitted data against it.
How it connects
Connects JSON Schema with arrays, data validation, required properties, and web-service request payloads.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Data-Oriented Programming: Reduce software complexity. The section links point to the parts of the book it draws on.