Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 37 ยท Paths, Schemas and Components

OpenAPI Components and $ref: Reuse Schemas, Parameters and Responses

Keep OpenAPI documents DRY with components and $ref: schemas, parameters, responses, headers, examples, request bodies, local and external references, and resolving them.

As soon as an API has more than a couple of operations, you repeat yourself: the same Pet shape in five responses, the same limit parameter on ten lists, the same error body everywhere. OpenAPI solves this with the components object (a library of reusable definitions) and $ref (a pointer to one of them).

The components object

components can hold many kinds of reusable things, each in its own map:

YAML
components:
  schemas:         {}   # data shapes
  responses:       {}   # whole response objects
  parameters:      {}   # query/header/path/cookie parameters
  examples:        {}
  requestBodies:   {}
  headers:         {}
  securitySchemes: {}   # see the security chapter
  links:           {}
  callbacks:       {}
  pathItems:       {}   # 3.1

The keys inside each map (like Pet) must match ^[a-zA-Z0-9.\-_]+$. Use PascalCase for schemas (Pet, NewPet, Problem) and be consistent.

Using $ref

A reference is an object with just a $ref key that holds a URI. For things inside the same file it is a JSON Pointer starting with #/:

YAML
components:
  schemas:
    Pet:
      type: object
      required: [id, name]
      properties:
        id:   { type: integer, format: int64 }
        name: { type: string }
    Pets:
      type: array
      items:
        $ref: "#/components/schemas/Pet"
  parameters:
    LimitParam:
      name: limit
      in: query
      schema: { type: integer, minimum: 1, maximum: 100, default: 20 }
  responses:
    NotFound:
      description: Not found
paths:
  /pets:
    get:
      parameters:
        - $ref: "#/components/parameters/LimitParam"
      responses:
        "200":
          description: A page of pets
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Pets"
  /pets/{petId}:
    get:
      responses:
        "404":
          $ref: "#/components/responses/NotFound"

Read #/components/schemas/Pet as: start at the document root (#), then go into components, then schemas, then Pet. Each / descends one level.

flowchart LR
  OP["GET /pets<br/>response schema"] -- "$ref" --> PETS["components/schemas/Pets"]
  PETS -- "$ref" --> PET["components/schemas/Pet"]
  OP2["GET /pets/{petId}<br/>response schema"] -- "$ref" --> PET
  OP3["POST /pets<br/>request body"] -- "$ref" --> NEW["components/schemas/NewPet"]

One definition, many references: change Pet once and every operation follows.

Pointer escaping

In a JSON Pointer a / inside a key is written ~1 and a ~ is written ~0. This matters when you reference a path item whose key is a URL path:

YAML
$ref: "#/paths/~1pets~1{petId}/get"      # points to GET /pets/{petId}

References in 3.1: siblings and summary

  • In 3.0 other keys next to $ref were ignored.
  • In 3.1 a Reference Object may carry summary and description that override the target's, which helps when the same schema is used in different contexts.
  • For Schema Objects, 3.1 allows any JSON Schema keyword beside $ref (it then behaves like allOf).
YAML
owner:
  $ref: "#/components/schemas/Person"
  description: The current owner of the pet

External references

$ref may point to another file or URL, which lets you split large specifications:

YAML
schema:
  $ref: "./schemas/Pet.yaml"                      # relative file
schema:
  $ref: "./common.yaml#/components/schemas/Error" # a part of another file
schema:
  $ref: "https://example.com/schemas/pet.json"   # remote

Relative references are resolved against the location of the document that contains them. Tools can bundle (merge everything into one file) or dereference (replace every $ref by its content) before publishing.

Naming and organizing

  • One name, one meaning: avoid Pet and PetResponse that differ by one field; use NewPet for input and Pet for output.
  • Group shared error responses (BadRequest, Unauthorized, NotFound) under components.responses.
  • Put pagination, sorting and rate-limit headers in components.parameters and components.headers.
  • Do not create a component used once unless it makes the paths easier to read.

Resolve references with code

This stand-in resolves local $ref pointers and detects the classic mistakes: a pointer to a component that does not exist, and a reference cycle. Real bundlers perform the same job.

Python Stand-in: resolve $ref pointers

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.

Cycles are legal in OpenAPI (a Person may contain Pets that contain Person), but a tool that dereferences them naively would loop forever. Good tools keep a stack, like the stand-in above, and leave cyclic references in place.

Run a linter rule for unused components. Dead definitions pile up fast when operations change, and they show up in generated SDKs as useless classes.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does $ref: "#/components/schemas/Pet" mean?

    # is the document root, and the rest is a JSON Pointer path to the definition.
  2. 2. Under which key do you define a reusable query parameter?

    Reusable parameters live in components.parameters.
  3. 3. What is true about components that nothing references?

    Components are a library; unreferenced ones are just dead weight.
  4. 4. How do you write a slash inside a JSON Pointer key (for example a path /pets)?

    ~1 stands for / and ~0 for ~ in JSON Pointers.
  5. 5. What does bundling do?

    A bundler resolves external $refs and writes one document many tools can read.

Summary

  • components is the reusable library: schemas, parameters, responses, request bodies, headers, examples, security schemes and more.
  • $ref points to a definition by JSON Pointer; #/components/schemas/Pet is a local pointer.
  • In 3.1 a reference can carry summary and description.
  • External $refs split big documents; bundle before publishing.
  • Watch for dangling references, cycles and unused components.

Next: Composition: allOf, oneOf, anyOf and discriminator