Skip to content
Tutorials Center
My learning

Topics

Lesson 60 of 133 ยท Networking and HTTP

OpenAPI and API Documentation

Describe a REST API with an OpenAPI 3.1 document, reuse schemas with $ref, validate requests from the spec and serve interactive documentation from Node.js.

An API without documentation is a guessing game. Developers read your source, try requests in a terminal, and still get surprised. Hand-written docs help, but they drift: someone adds a field, forgets the page, and now the docs lie. OpenAPI is the industry standard way to describe an HTTP API in a machine-readable file. One file can drive human-friendly documentation, client libraries in many languages, mock servers, contract tests and, as you will build here, the validation of incoming requests.

This lesson teaches the structure of an OpenAPI 3.1 document, how to reuse schemas, and the key idea: treat the description as the single source of truth and make your server read it. You will write a spec as a plain JavaScript object, build a small validator for the schema subset you need, and wire both into a Node.js server. It builds on Designing REST APIs, Request Bodies, JSON and Forms and Validating Input.

What an OpenAPI document contains

An OpenAPI document is JSON or YAML (they are interchangeable) with a few top-level parts:

Field Purpose
openapi The spec version, such as 3.1.0
info Title, version and description of your API (not the spec)
servers Base URLs where the API is available
paths Every URL, and under each URL, every HTTP method (an operation)
components Reusable pieces: schemas, parameters, responses, security schemes
security Which authentication is required by default

Each operation describes one endpoint: a summary, an operationId (a unique name that code generators use as a function name), its parameters (path, query, header), an optional requestBody and the possible responses, keyed by status code. The shapes of bodies are written in JSON Schema. OpenAPI 3.1 uses a full JSON Schema dialect, so things you may know from the JSON Schema world work as they are, for example type: ['string', 'null'] for a nullable value (3.0 used a special nullable: true).

flowchart TB
  D["OpenAPI document"] --> P["paths"]
  D --> C["components"]
  P --> OP["operation<br/>GET /books/{id}"]
  OP --> PR["parameters"]
  OP --> RB["requestBody"]
  OP --> RS["responses"]
  RB -->|"$ref"| S["components/schemas/Book"]
  RS -->|"$ref"| S
  C --> S

Operations point at shared schemas with $ref, so a type is defined once and used everywhere.

Writing a spec

Here is a small API for books, written as a JavaScript object. Because JSON and YAML are just data, a plain object works the same, and you can keep it in openapi.json, openapi.yaml, or build it in code. This TryIt also reads the spec back, the way a documentation tool does, and prints a summary table of the operations.

Node.js A small OpenAPI 3.1 document

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 node:readline or process.stdin), it gets the next line from this box.

A few details worth remembering:

  • In a paths key, URL parameters are written in curly braces: /books/{id}, and each must be declared in parameters with in: path and required: true.
  • Response keys are status codes (numeric keys in a JavaScript object become strings, exactly like JSON). You may use default as a catch-all, and ranges like 4XX.
  • $ref is a JSON Pointer into the same document. '#/components/schemas/Book' means "the Book entry in components.schemas". Use it for every type, parameter or error response that appears more than once.
  • allOf combines schemas: Book is a NewBook plus a required id. This keeps the input and output types in sync.
  • Add examples to bodies and description to everything. Generated documentation is only as good as the words in the spec.

Validating requests from the schema

The spec tells you what a valid request looks like, so you can reject invalid ones automatically instead of writing the same checks in every handler. Real projects use a validator library that implements the whole JSON Schema standard (Ajv is the most common one; frameworks such as Fastify do this for you). To see how it works, and to run it here without packages, we write a tiny validator for the subset used above: type, enum, required, properties, additionalProperties, string length, numeric bounds, items, allOf and $ref.

It returns a list of problems with a path to each bad value, so the client learns everything wrong at once.

Node.js A small JSON 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 node:readline or process.stdin), it gets the next line from this box.

Treat this as a teaching tool: a production validator also handles oneOf/anyOf, pattern, format (such as email or date-time), uniqueItems, remote $refs and many edge cases. Use a maintained library for real work, and compile each schema once at startup rather than interpreting it on every request.

A server driven by the spec

Now join the pieces. The server below loads the spec, finds the operation for each request by matching method and path against the paths keys, validates the path and query parameters and the JSON body, and only then calls the handler. Because routing and validation come from the description, adding an endpoint to the spec is what makes it exist, and the docs can never disagree with the behavior.

sequenceDiagram
  participant C as Client
  participant S as Server
  participant O as Spec (paths)
  participant H as Handler
  C->>S: POST /books {json}
  S->>O: find operation for POST /books
  O-->>S: operation + requestBody schema
  S->>S: validate body against schema
  alt invalid
    S-->>C: 422 + list of problems
  else valid
    S->>H: createBook(body)
    H-->>S: result
    S-->>C: 201 + book
  end

The spec decides which operation matches and what input it accepts before any handler code runs.

Node.js Routing and validation driven by an OpenAPI document

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 node:readline or process.stdin), it gets the next line from this box.

Notice that DELETE /books/2 is rejected as "not in the API description": anything the spec does not list does not exist. Compare this with the earlier approach in Building a Router from Scratch, where every route and every check is code.

Two approaches exist, and teams pick one:

  • Spec first (design first). You write the OpenAPI file, review it with front-end and partner teams, then build the server and clients from it. Good for public APIs.
  • Code first. Your framework collects route definitions and schemas and generates the OpenAPI file. Good for fast-moving internal services. Either way, the file is checked into version control and checked in CI.

Serving documentation

Publishing the document is one route. Serve it at a well-known URL such as /openapi.json with Content-Type: application/json, and put an interactive viewer in front of it. Swagger UI, Redoc and Scalar are popular viewers; each is a static page (or a package) that loads your JSON and renders every operation with a "try it" console. A minimal page looks like this, shown read-only because the viewer is loaded from a CDN:

HTML
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Bookshelf API docs</title>
  </head>
  <body>
    <div id="docs"></div>
    <!-- a viewer script is loaded here and pointed at /openapi.json -->
  </body>
</html>

Whichever viewer you choose, pin its version and consider hosting the files yourself for production, since a docs page is a supply-chain dependency like any other.

What else the spec gives you

  • Client generation. Tools turn the file into typed clients (TypeScript, Python, Java and others), using each operationId as the function name. This is why those IDs must be unique and meaningful. With TypeScript (see TypeScript with Node.js), you can generate request and response types and keep front end and back end in step.
  • Mock servers. Front-end teams can build against a server that returns the examples before the real one exists.
  • Contract tests. A test can call the running API and check every response against the response schemas in the spec, catching drift in CI. See Testing HTTP Servers.
  • Linting. Rule sets check naming, required descriptions and consistent error shapes across a whole company.
  • Security. Declare authentication in components.securitySchemes (an API key, HTTP bearer token or OAuth 2 flow) and reference it in security, so the docs show clients how to authenticate. Describe the 429 response and its Retry-After header too, as covered in Rate Limiting and API Protection.

Keep one rule in mind: the spec describes the contract, it does not enforce your business rules. Uniqueness, permissions and cross-field checks still belong in your code. And document your errors: a shared Problem schema (see the RFC 9457 format in the REST lesson) referenced from every 4XX response gives clients one error shape to handle.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the purpose of the operationId field?

    operationId must be unique across the document. Client generators and routers use it as a stable name, independent of the URL.
  2. 2. What does "$ref - '#/components/schemas/Book'" do?

    $ref is a JSON Pointer into the document. Reusing schemas by reference keeps every place that mentions a Book consistent.
  3. 3. In OpenAPI 3.1, how do you say that a property may be a string or null?

    OpenAPI 3.1 uses full JSON Schema, where type can be an array of types. The old nullable keyword belongs to 3.0.
  4. 4. Why validate requests against the schema before the handler runs?

    Validating once at the boundary removes repeated checks from handlers and gives clients one consistent, complete list of problems.
  5. 5. What is a good way to prevent documentation from drifting away from the real API?

    When the server is built from the spec, or contract tests check responses against it, any mismatch shows up as a failure instead of a surprise for API users.

Summary

  • OpenAPI is a JSON or YAML description of an HTTP API: info, servers, paths with operations, and reusable components.
  • Request and response bodies are described with JSON Schema (3.1 uses the full dialect); share types with $ref and allOf, and give every operation a unique operationId.
  • A validator can check path and query parameters and JSON bodies against the spec, returning every problem with its location; use a maintained library such as Ajv in production and compile schemas once.
  • Driving routing and validation from the spec keeps the docs and the behavior in agreement; spec-first and code-first workflows both work if the file is versioned and tested.
  • Serve the document at /openapi.json and render it with a viewer; use it to generate clients, mocks and contract tests.
  • The spec states the contract; business rules, permissions and security still live in your code.

Next: Child Processes