Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 37 ยท Paths, Schemas and Components

OpenAPI Schema Objects and JSON Schema: Describing Your Data

Model your API data with OpenAPI schemas: objects, properties, required, additionalProperties, arrays, enums, defaults, examples, discriminators and JSON Schema in 3.1.

A schema describes the shape of data: which properties an object has, what type each one is, which are mandatory and which values are legal. Schemas are used in parameters, request bodies, response bodies and headers. In OpenAPI 3.1 the Schema Object is a superset of JSON Schema 2020-12, so everything you learn about JSON Schema applies directly, and vice versa.

An object schema, line by line

YAML
Pet:
  type: object
  description: A pet in the store.
  required: [id, name]
  properties:
    id:
      type: integer
      format: int64
      readOnly: true
    name:
      type: string
      minLength: 1
      maxLength: 80
      examples: [Fido]
    tag:
      type: [string, "null"]
    status:
      type: string
      enum: [available, pending, sold]
      default: available
    photoUrls:
      type: array
      items: { type: string, format: uri }
      maxItems: 10
    owner:
      type: object
      properties:
        id: { type: integer }
        email: { type: string, format: email }

Key ideas:

  • required is a list on the object that names mandatory properties. A property that is not listed is optional (it may be absent), which is different from a property that may be null.
  • properties names each property and gives its own schema.
  • Properties may be nested objects or arrays of anything.
  • description, examples, default and deprecated apply to any schema.

Optional versus nullable

You want Schema
Always present, never null in required, type: string
May be missing not in required
Present but may be null in required, type: [string, "null"]
Missing or null not in required, type: [string, "null"]

Choosing deliberately matters for generated code: a missing field and a null field often become different types in typed languages.

Extra properties: additionalProperties

By default an object may contain properties you did not list. Control that with additionalProperties:

YAML
# 1) Closed object: only the listed properties are allowed
Strict:
  type: object
  properties:
    name: { type: string }
  additionalProperties: false

# 2) A dictionary / map: any string key, values must be integers
Counters:
  type: object
  additionalProperties:
    type: integer

additionalProperties: false rejects typos but makes it hard to add fields later without breaking old clients (see versioning advice in REST API design). A dictionary (the second form) is how you describe maps like {"en": "Hello", "fr": "Bonjour"}.

In 3.1 there is also unevaluatedProperties: false, which works together with allOf (see composition).

Arrays

YAML
Tags:
  type: array
  items:
    type: string
  minItems: 0
  maxItems: 20
  uniqueItems: true

items is one schema for every element. For tuples (a fixed list of positions) 3.1 uses prefixItems:

YAML
Coordinate:
  type: array
  prefixItems:
    - type: number     # latitude
    - type: number     # longitude
  items: false          # nothing after the two numbers
  minItems: 2

enum and const

YAML
status: { type: string, enum: [available, pending, sold] }
kind:   { const: pet }            # 3.1: exactly this one value

An enum is a closed contract: adding a value later can break clients that handle values with a switch statement. For open lists, document the values in the description instead.

Examples and defaults inside schemas

In 3.1 use examples (a list); the older single example keyword is deprecated for schemas but still common in 3.0 documents.

Combining all of this: a validator stand-in

This stand-in is a compact recursive validator for the keywords you just met (type, required, properties, additionalProperties, items, enum, minimum, length keywords). It prints the JSON path of every problem, like real tools do.

Python Stand-in: a recursive schema validator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

OpenAPI additions to JSON Schema

OpenAPI adds a few keywords on top of JSON Schema:

Keyword Purpose
discriminator Tells clients which subtype to pick in oneOf/anyOf
xml Fine-tunes XML representation
externalDocs Link to more documentation
example Deprecated single example (use examples)

In 3.0 a few things differed from JSON Schema: nullable, boolean exclusiveMinimum, example, and the lack of type arrays. If you read older documents, translate them in your head to the 3.1 forms.

Tips for good schemas

  • Give every property a description; it becomes documentation and tooltips.
  • Use format and constraints that your server actually enforces; wrong promises create bugs.
  • Prefer small named schemas over giant inline ones (next lessons: components and $ref).
  • Keep request and response schemas distinct when they differ.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How do you mark a property as mandatory?

    required is an array on the object schema that lists property names.
  2. 2. What does additionalProperties: false do?

    It closes the object so unknown properties are invalid.
  3. 3. Which schema describes a map from any string key to an integer?

    A dictionary is an object with an additionalProperties schema.
  4. 4. In OpenAPI 3.1, the Schema Object is...

    3.1 aligned fully with JSON Schema 2020-12 and added a few OpenAPI keywords.
  5. 5. A field is present but may be null. Which is correct (3.1)?

    Present-but-null means it is required and its type allows null.

Summary

  • A schema defines type, structure and constraints; 3.1 schemas are JSON Schema 2020-12 plus a few extras.
  • Objects use properties and a required list; optional and nullable are different things.
  • additionalProperties closes an object or turns it into a dictionary.
  • Arrays use items (or prefixItems for tuples); enum and const fix allowed values.

Next: Components and $ref