Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 39 ยท Documentation and Testing

Documenting APIs with OpenAPI

Learn the OpenAPI Specification: paths, operations, schemas, parameters, responses and security schemes, and use a spec to generate docs and validate requests.

An API without documentation is a guessing game. Even the best-designed API needs a reference that says which endpoints exist, what to send, what comes back, and which errors to expect. The industry standard for describing a REST API is the OpenAPI Specification (OAS, formerly Swagger): a YAML or JSON file that is readable by humans and by machines.

A single spec file can generate interactive documentation (Swagger UI, Redoc, Scalar), client libraries and server stubs, mock servers, and automatic request and response validation in tests. In this lesson you will learn the structure of an OpenAPI 3.1 document, write one, and then put a spec to work in code.

One spec, many uses

Docs Interactive reference pages.
SDKs Generated client code.
Tests Validate responses.
Mocks Fake server from the spec.

Write it once, use it everywhere.

1 / 2

Anatomy of an OpenAPI document

The top-level keys of an OpenAPI 3.1 file:

Key Purpose
openapi The spec version, such as 3.1.0
info Title, version of your API, description, contact, license
servers Base URLs (production, staging)
paths Every endpoint and its operations
components Reusable schemas, parameters, responses and security schemes
security Which security scheme applies globally
tags Groups of operations for the docs

A complete small spec

This describes a notes API with one list and one create operation. Read it top to bottom; it is plain data.

YAML
openapi: 3.1.0
info:
  title: Notes API
  version: 1.0.0
  description: Create and read personal notes.
servers:
  - url: https://api.example.com/v1
paths:
  /notes:
    get:
      summary: List notes
      operationId: listNotes
      tags: [Notes]
      parameters:
        - name: limit
          in: query
          schema: { type: integer, minimum: 1, maximum: 100, default: 20 }
        - name: after
          in: query
          description: Cursor from a previous response
          schema: { type: string }
      responses:
        "200":
          description: A page of notes
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/Note" }
                  nextCursor: { type: [string, "null"] }
        "401": { $ref: "#/components/responses/Unauthorized" }
    post:
      summary: Create a note
      operationId: createNote
      tags: [Notes]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/NewNote" }
      responses:
        "201":
          description: Created
          headers:
            Location: { schema: { type: string } }
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Note" }
        "422":
          description: Validation failed
        "401": { $ref: "#/components/responses/Unauthorized" }
  /notes/{noteId}:
    get:
      summary: Get one note
      operationId: getNote
      parameters:
        - name: noteId
          in: path
          required: true
          schema: { type: integer }
      responses:
        "200":
          description: The note
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Note" }
        "404":
          description: No such note
components:
  schemas:
    NewNote:
      type: object
      required: [title]
      properties:
        title: { type: string, minLength: 1, maxLength: 120 }
        body: { type: string, maxLength: 10000 }
      additionalProperties: false
    Note:
      allOf:
        - $ref: "#/components/schemas/NewNote"
        - type: object
          required: [id, createdAt]
          properties:
            id: { type: integer }
            createdAt: { type: string, format: date-time }
  responses:
    Unauthorized:
      description: Missing or invalid credentials
      headers:
        WWW-Authenticate: { schema: { type: string } }
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
security:
  - bearerAuth: []

Key ideas:

  • Paths and operations: each path has operations named after HTTP methods. operationId is a unique name that code generators turn into method names.
  • Parameters live in the query, path, header or cookie. Path parameters are always required.
  • Schemas use JSON Schema (OpenAPI 3.1 is fully compatible with it): type, required, properties, enum, minimum, maxLength, format.
  • $ref points at a reusable definition in components, keeping the spec free of copy-paste. allOf combines schemas.
  • Responses are keyed by status code and describe the body and headers. Document the errors, not only the happy path.
  • Security schemes describe how to authenticate: http with bearer, apiKey in a header, oauth2 with flows and scopes, or openIdConnect. See OAuth 2.0 Flows and API Keys.

Using a spec in code

A spec is only valuable if it stays true. The trick is to make code and spec share the same source. The demo below embeds the spec as data and uses it for two jobs: printing a documentation summary, and validating incoming request bodies against the schema, so the documented contract and the enforced contract cannot drift apart.

Node.js Generate docs and validate from a spec

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.

In real projects use a maintained validator (Ajv for JSON Schema, or middleware that validates against your OpenAPI file) instead of hand-written checks.

Writing good API documentation

A generated reference is necessary but not enough. Good docs add:

  1. A quickstart: from zero to a first successful call in five minutes, with copy-paste curl and the real base URL.
  2. Authentication guide: how to get a key or token, which scopes exist, how to refresh.
  3. Examples for every operation, in the spec (example / examples), with realistic data and the error responses.
  4. Conventions page: pagination, filtering, errors (Problem Details), rate limits, idempotency, versioning and deprecation policy.
  5. Changelog with dates and migration notes.
  6. Error catalog: each error code, what it means and how to fix it.
  7. Runnable samples or a "Try it" console, SDKs and a Postman collection generated from the spec.

Lint the spec in CI (for example with Spectral) with rules such as "every operation has an operationId, a summary and a 4xx response", and diff it against the last release to catch breaking changes (API Versioning and Evolution).

A tiny linter shows the idea. It checks a spec against some of those rules and reports each problem with its location:

Node.js Lint an OpenAPI spec

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.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is an OpenAPI document?

    It describes endpoints, inputs, outputs and security, so tools can generate docs, clients, mocks and tests.
  2. 2. What does $ref do?

    $ref avoids copy-paste by referencing, for example, #/components/schemas/Note.
  3. 3. Where is a path parameter like noteId declared?

    Path parameters are part of the URL, so they are always required and declared under parameters.
  4. 4. Why should a spec document error responses?

    Developers handle failures as much as successes, so 4xx responses belong in the contract.
  5. 5. How can you keep a spec from drifting away from the real API?

    Using the spec for validation and contract checks makes mismatches fail loudly.

Summary

  • OpenAPI describes an API in a YAML or JSON file: info, servers, paths, components, security.
  • Operations list parameters, request bodies and responses (including errors); schemas use JSON Schema and $ref for reuse.
  • Security schemes document bearer tokens, API keys, OAuth 2.0 and OpenID Connect.
  • Generate docs, SDKs and mocks from the spec, and use it to validate requests and responses.
  • Good documentation adds a quickstart, auth guide, examples, conventions, changelog and an error catalog.

Next: Testing REST APIs