Thuta Learning
API Tutorial
AdvancedWeb DevelopmentIntermediate

OpenAPI/Swagger

API TutorialLesson 2840 min

What you'll walk away with

  • Read the main parts of an OpenAPI document: info, paths, operationId, responses, components and $ref
  • Serve and validate a JSON spec and generate client functions from it
  • Explain how a contract test catches drift between spec and server
  • Tell apart a spec that renders in Swagger UI from a spec that is correct
  • Structure good API docs with examples, error documentation and a changelog

Explain it simply

Explain it simply

Think of a restaurant menu. It lists what is available, what it costs, what you can customise and what you will get back, so a customer can order without asking the kitchen. An OpenAPI document is the menu of an API: for every endpoint it states what it accepts, what it returns and which errors can occur.

What makes it special is that programs can read the menu as well as people. Tools can therefore produce web pages, client code, mock servers and checks from that single document. But if the menu is wrong, customers order wrongly too, so keeping the spec correct is part of the job.

Problem → Why → Solution

The problem: the docs say one thing, the server does another

A team writes its API docs by hand on a wiki page. In March, GET /users/1 returned id as a number. Later the backend moved to UUID-style ids, so id became a string, but nobody edited the wiki, and a partner's integration silently goes wrong in calculations such as user.id + 1.

A docs page rendered with Swagger UI can look polished and complete and still have the same problem if the spec was written months ago. A page that looks good proves only that the document is readable, not that it is correct.

partner.js
// The wiki (written in March) promises: GET /users/1 -> { "id": 1, "name": "..." }
const res = await fetch("https://api.example.com/v1/users/1");
const user = await res.json();

console.log(typeof user.id); // the docs promise "number", the server now sends "string"
console.log(user.id + 1);    // "11" instead of 2: wrong, with no error anywhere

Why do docs and code drift apart?

Hand-written docs and code are two sources of truth, and changing one does not change the other. The fix is to write the spec in a machine-readable form and check it in CI: lint it, compare real responses against it, and diff it against the last release. Then a mismatch is caught before it reaches production.

Core concept: OpenAPI is the contract written as data

OpenAPI is a standard for describing an HTTP API in a machine-readable, language-agnostic way, written in YAML or JSON. It covers paths, operations (method plus path), parameters (path, query, header, cookie), request bodies, responses and schemas by status code, authentication schemes and examples. The specification was formerly called Swagger and is now OpenAPI, while tools such as Swagger UI keep the older name. Because it is data, tools can render docs, generate clients, run mock servers, validate requests and responses and compare two versions.

The structure of a document is plain. openapi is the spec version, info holds the title and version, servers lists base URLs, paths lists the endpoints, and components holds reusable schemas, parameters and securitySchemes, which are referenced with $ref. Every operation needs an operationId, which must be unique in the document and which client generators use as the function name, and responses keyed by status code, including the errors. Many teams use OpenAPI 3.1, but some tools still support only 3.0, so check which version your tools handle.

There are two working styles. In design-first you write the spec first, review it with the people who will call the API and generate server stubs from it. In code-first the spec is generated from annotations or types in the code. Either way drift is the danger: the spec says integer while the server sends a string. In CI, lint the spec, run contract tests that check real responses against the schema, and compare the spec with the last release to catch breaking changes.

A spec cannot say everything. It covers the error model, pagination, authentication, rate limits, idempotency and webhooks only in part (OpenAPI 3.1 can describe webhooks, but delivery and retry behaviour still need prose), so explain in writing how to get a token, what the rate limit is and how to retry. Keep examples free of real secrets and personal data by using example.com and fake tokens.

Mental model: one document, many consumers
  1. Write or generate the spec
  2. Lint and validate in CI
  3. Generate docs, clients, mocks
  4. Contract-test the real server

Treat one spec as the source of truth and derive everything else from it.

General pattern: the skeleton of an OpenAPI document

yaml
openapi: 3.1.0
info: { title: <API name>, version: <document version> }
paths:
  /<resource>/{<param>}:
    <get | post | put | patch | delete>:
      operationId: <uniqueName>
      parameters: [<name, in, required, schema>]
      requestBody: { content: { <media type>: { schema: <schema> } } }
      responses:
        "<status>": { description: <text>, content: <media types> }
components: { schemas: <reusable schemas>, securitySchemes: <auth> }

Anything in < > is a slot for your own value. An operation sits under its method and is built from parameters, requestBody and responses, and reusable schemas live in components and are pointed at with $ref.

Example: serve a spec, validate it, generate a client

This example starts a mock server with node:http and serves the spec at /openapi.json. The client then fetches the spec, checks its structure with validateSpec() (duplicate operationId, undeclared path parameters, missing $ref targets) and builds one function per operation with buildClient().

In the generated client, client.getUser({ id: 2 }) turns /users/{id} into /users/2. At the end the spec is deliberately broken (a parameter removed, a $ref to a schema that does not exist) to show what the validator catches. This validator illustrates the idea only; real projects use a linter such as Spectral.

openapi-client.mjs
import http from "node:http";

const json = (schema) => ({ "application/json": { schema } });
const ref = (name) => ({ $ref: "#/components/schemas/" + name });

const spec = {
  openapi: "3.1.0",
  info: { title: "Users API", version: "1.2.0" },
  paths: {
    "/users": {
      get: {
        operationId: "listUsers",
        parameters: [{ name: "limit", in: "query", schema: { type: "integer" } }],
        responses: {
          200: {
            description: "A list of users",
            content: json({ type: "array", items: ref("User") }),
          },
        },
      },
      post: {
        operationId: "createUser",
        requestBody: { required: true, content: json(ref("NewUser")) },
        responses: {
          201: { description: "Created", content: json(ref("User")) },
          422: { description: "Validation failed" },
        },
      },
    },
    "/users/{id}": {
      get: {
        operationId: "getUser",
        parameters: [
          { name: "id", in: "path", required: true, schema: { type: "integer" } },
        ],
        responses: {
          200: { description: "The user", content: json(ref("User")) },
          404: { description: "No such user" },
        },
      },
    },
  },
  components: {
    schemas: {
      NewUser: {
        type: "object",
        required: ["name"],
        properties: { name: { type: "string" } },
      },
      User: {
        type: "object",
        required: ["id", "name"],
        properties: { id: { type: "integer" }, name: { type: "string" } },
      },
    },
  },
};

function refsIn(node, found = []) {
  if (Array.isArray(node)) node.forEach((item) => refsIn(item, found));
  else if (node && typeof node === "object") {
    if (typeof node.$ref === "string") found.push(node.$ref);
    Object.values(node).forEach((value) => refsIn(value, found));
  }
  return found;
}

function validateSpec(doc) {
  const problems = [];
  if (!String(doc.openapi).startsWith("3.")) problems.push("openapi must be 3.x");
  const info = doc.info ?? {};
  if (!info.title || !info.version) problems.push("info needs title and version");

  const seen = new Set();
  for (const [path, item] of Object.entries(doc.paths ?? {})) {
    for (const [method, op] of Object.entries(item)) {
      const where = method.toUpperCase() + " " + path;
      if (!op.operationId) problems.push(where + ": missing operationId");
      else if (seen.has(op.operationId)) problems.push(where + ": duplicate operationId");
      seen.add(op.operationId);
      const responses = Object.keys(op.responses ?? {});
      if (responses.length === 0) problems.push(where + ": no responses");

      const params = op.parameters ?? [];
      const declared = params.filter((p) => p.in === "path").map((p) => p.name);
      for (const [, name] of path.matchAll(/\{(\w+)\}/g)) {
        if (!declared.includes(name)) {
          problems.push(where + ": path parameter {" + name + "} is not declared");
        }
      }
    }
  }
  for (const target of refsIn(doc)) {
    const name = target.replace("#/components/schemas/", "");
    if (!doc.components?.schemas?.[name]) problems.push("unresolved $ref: " + name);
  }
  return problems;
}

const users = [
  { id: 1, name: "Aye Chan" },
  { id: 2, name: "Hnin Su" },
  { id: 3, name: "Kyaw Zin" },
];

const server = http.createServer(async (req, res) => {
  const url = new URL(req.url, "http://localhost");
  const send = (status, data) => {
    res.writeHead(status, { "Content-Type": "application/json" });
    res.end(JSON.stringify(data));
  };
  if (url.pathname === "/openapi.json") return send(200, spec);
  if (url.pathname === "/users" && req.method === "GET") {
    const limit = Number(url.searchParams.get("limit") ?? users.length);
    return send(200, users.slice(0, limit));
  }
  if (url.pathname === "/users" && req.method === "POST") {
    let raw = "";
    for await (const chunk of req) raw += chunk;
    const body = JSON.parse(raw || "{}");
    if (typeof body.name !== "string") return send(422, { error: "name is required" });
    users.push({ id: users.length + 1, name: body.name });
    return send(201, users.at(-1));
  }
  const one = url.pathname.match(/^\/users\/(\d+)$/);
  if (one) {
    const user = users.find((u) => u.id === Number(one[1]));
    return user ? send(200, user) : send(404, { error: "not found" });
  }
  send(404, { error: "no such route" });
});

function buildClient(doc, baseUrl) {
  const client = {};
  for (const [path, item] of Object.entries(doc.paths)) {
    for (const [method, op] of Object.entries(item)) {
      client[op.operationId] = async ({ body, ...args } = {}) => {
        const fill = (_, name) => encodeURIComponent(args[name]);
        const route = path.replace(/\{(\w+)\}/g, fill);
        const query = new URLSearchParams();
        for (const p of op.parameters ?? []) {
          const value = args[p.name];
          if (p.in === "query" && value !== undefined) query.set(p.name, value);
        }
        const init = { method: method.toUpperCase() };
        if (body) {
          init.headers = { "Content-Type": "application/json" };
          init.body = JSON.stringify(body);
        }
        const qs = query.toString();
        const res = await fetch(baseUrl + route + (qs ? "?" + qs : ""), init);
        return { status: res.status, data: await res.json() };
      };
    }
  }
  return client;
}

await new Promise((resolve) => server.listen(0, resolve));
const base = "http://127.0.0.1:" + server.address().port;

const doc = await (await fetch(base + "/openapi.json")).json();
const problems = validateSpec(doc);
console.log("spec problems:", problems.length ? problems.join("; ") : "none");

const client = buildClient(doc, base);
console.log("generated:", Object.keys(client).join(", "));
const show = (label, r) => {
  console.log(label + " -> " + r.status + " " + JSON.stringify(r.data));
};
show("listUsers({ limit: 2 })", await client.listUsers({ limit: 2 }));
show("getUser({ id: 2 })", await client.getUser({ id: 2 }));
show("getUser({ id: 99 })", await client.getUser({ id: 99 }));
show("createUser(Mya)", await client.createUser({ body: { name: "Mya" } }));
show("createUser({})", await client.createUser({ body: {} }));

const broken = structuredClone(doc);
delete broken.paths["/users/{id}"].get.parameters;
const listOk = broken.paths["/users"].get.responses[200].content["application/json"];
listOk.schema = { $ref: "#/components/schemas/Customer" };
console.log("broken copy:");
validateSpec(broken).forEach((problem) => console.log("  - " + problem));
server.close();

Code breakdown

  1. Reusable schemasconst ref = (name) => ({ $ref: "#/components/schemas/" + name });

    Instead of rewriting the User schema in every operation, it is written once under components and pointed at with $ref. When User changes, one edit is enough.

  2. operationIdoperationId: "listUsers",

    This is the unique name of one operation. Client generators use it as the function name, which is why client.listUsers() exists; without it, generators invent ugly names derived from the path.

  3. Serve and consumeconst doc = await (await fetch(base + "/openapi.json")).json();

    The spec is served as an ordinary JSON endpoint, so a docs UI, a client generator and test tools can all read it from one URL.

  4. Check path parametersfor (const [, name] of path.matchAll(/\{(\w+)\}/g)) {

    It finds each {id} in the path and checks that it is declared as an in: path parameter. Without that, a generator would not know what value to substitute.

  5. Fill the pathconst fill = (_, name) => encodeURIComponent(args[name]);

    It replaces {id} in /users/{id} with the value passed to client.getUser({ id: 2 }). encodeURIComponent stops characters such as / and ? from breaking the path.

  6. One function per operationclient[op.operationId] = async ({ body, ...args } = {}) => {

    Each operation gets an async function. body is taken separately and the remaining arguments become path and query parameters. When the spec changes, the client follows automatically.

You should see
spec problems: none
generated: listUsers, createUser, getUser
listUsers({ limit: 2 }) -> 200 [{"id":1,"name":"Aye Chan"},{"id":2,"name":"Hnin Su"}]
getUser({ id: 2 }) -> 200 {"id":2,"name":"Hnin Su"}
getUser({ id: 99 }) -> 404 {"error":"not found"}
createUser(Mya) -> 201 {"id":4,"name":"Mya"}
createUser({}) -> 422 {"error":"name is required"}
broken copy:
  - GET /users/{id}: path parameter {id} is not declared
  - unresolved $ref: Customer

A fuller spec in YAML

The JSON above is abbreviated. A real spec also has servers, authentication, examples and error responses. The YAML below describes the same API more completely, with a bearer token and the 429 response from the rate-limit lesson. Look at what each operation carries.

openapi.yaml
openapi: 3.1.0
info:
  title: Users API
  version: 1.2.0
servers:
  - url: https://api.example.com/v1
security:
  - bearerAuth: []
paths:
  /users:
    get:
      operationId: listUsers
      summary: List users
      parameters:
        - name: limit
          in: query
          required: false
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 20
      responses:
        "200":
          description: A page of users
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: "#/components/schemas/User"
              example:
                - id: 1
                  name: Aye Chan
        "429":
          description: Rate limit exceeded
          headers:
            Retry-After:
              description: Seconds to wait before retrying
              schema:
                type: integer
  /users/{id}:
    get:
      operationId: getUser
      summary: Get one user
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
      responses:
        "200":
          description: The user
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/User"
        "404":
          description: No user with that id
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
  schemas:
    User:
      type: object
      required: [id, name]
      properties:
        id:
          type: integer
        name:
          type: string

A few details deserve attention. Status codes are quoted, as in "200", because YAML keys must be strings. security says the whole document needs a bearer token, and individual operations can override it. The 429 response lists Retry-After under headers, so client developers can write correct retry logic.

Keeping the spec honest: a contract test

A contract test compares a real response (or a test server's response) with the schema in the spec. If id turns into a string as in the problem, this check fails in CI and says which field disagrees. The check() below is a deliberately small validator for type, required and array items; real projects use a JSON Schema library such as ajv.

contract-test.mjs
const schemas = {
  User: {
    type: "object",
    required: ["id", "name"],
    properties: { id: { type: "integer" }, name: { type: "string" } },
  },
};

function typeOf(value) {
  if (Array.isArray(value)) return "array";
  if (value === null) return "null";
  if (Number.isInteger(value)) return "integer";
  return typeof value;
}

function check(schema, value, path = "$") {
  if (schema.$ref) return check(schemas[schema.$ref.split("/").pop()], value, path);
  const actual = typeOf(value);
  const numberOk = schema.type === "number" && actual === "integer";
  if (actual !== schema.type && !numberOk) {
    return [path + ": expected " + schema.type + ", got " + actual];
  }

  const errors = [];
  if (schema.type === "object") {
    for (const key of schema.required ?? []) {
      if (!(key in value)) errors.push(path + "." + key + ": required but missing");
    }
    for (const [key, sub] of Object.entries(schema.properties ?? {})) {
      if (key in value) errors.push(...check(sub, value[key], path + "." + key));
    }
  }
  if (schema.type === "array") {
    value.forEach((item, i) => {
      errors.push(...check(schema.items, item, path + "[" + i + "]"));
    });
  }
  return errors;
}

function report(label, errors) {
  const summary = errors.length ? errors.length + " problem(s)" : "matches the spec";
  console.log(label + ": " + summary);
  errors.forEach((error) => console.log("  - " + error));
}

const listUsers = { type: "array", items: { $ref: "#/components/schemas/User" } };
report("yesterday's response", check(listUsers, [{ id: 1, name: "Aye Chan" }]));
report("today's response", check(listUsers, [{ id: "2", name: "Hnin Su" }, { id: 3 }]));
text
yesterday's response: matches the spec
today's response: 2 problem(s)
  - $[0].id: expected integer, got string
  - $[1].name: required but missing
  • Lint: check the spec with a linter such as Spectral for missing descriptions, duplicate operationIds or missing error responses.
  • Contract test: check real responses against the schema; this is the main protection that keeps the docs true.
  • Breaking-change diff: compare with the last release's spec and catch removed fields and changed types in the pull request.

What good API documentation contains

PartThe question it answers
Reference (from the spec)What does each endpoint accept and return?
GuidesHow do I authenticate, paginate, respect limits and retry?
ExamplesWhich request and response can I copy and run?
Error catalogueWhy does each error happen and how do I fix it?
ChangelogWhat changed, and was it breaking?

Examples are the lifeblood of good docs. The curl below copies and runs without any real value, since $API_TOKEN is read from your own environment variable. Never put real emails, tokens or IDs copied from production logs into an example.

bash
curl -s "https://api.example.com/v1/users?limit=2" \
  -H "Authorization: Bearer $API_TOKEN"

For error docs, define one body shape for every error status. RFC 9457 (Problem Details) provides application/problem+json with type, title, status, detail and instance fields, which is a good base. Keep the changelog as dated entries and mark clearly whether each change is breaking.

json
{
  "type": "https://api.example.com/errors/validation",
  "title": "Validation failed",
  "status": 422,
  "detail": "name is required",
  "instance": "/v1/users"
}
text
2026-11-10  Added       limit query parameter on GET /users (default 20, max 100)
2026-11-10  Added       Retry-After header on every 429 response
2026-10-01  Deprecated  GET /v1/users; use /v2/users (sunset 2027-01-15)
2026-10-01  Breaking    v2 splits users.name into firstName and lastName

Swagger UI and the rest of the toolbox

Kind of toolExamplesJob
Docs viewerSwagger UI, RedocRender the spec as a web page
LinterSpectralCheck the spec against style rules
Code generatoropenapi-generatorProduce clients and server stubs
Mock serverPrismFake responses from the spec before the backend exists
Diff tooloasdiffFind breaking changes between two specs

Be careful with "Try it out"

The Try it out button in Swagger UI sends real requests from the browser, so calling an API on a different origin brings in the CORS rules: the API must allow the docs site's origin. Real tokens typed there can also linger in the browser, so point people at sandbox keys and fake data instead of production keys. Tools evolve, so check their current documentation.

In real projects

Where this shows up in real projects

Many teams run a CI pipeline on every pull request: lint the spec, diff it against the last release for breaking changes, and contract-test a test server. A frontend team can start before the backend exists by running a mock server such as Prism from the spec, and a TypeScript client can be generated from the same document. The docs site is published automatically at every release with Redoc or Swagger UI.

Tie the lesson back to the previous ones. Describe the rate-limit policy and the Retry-After header of 429 responses in the spec, keep one document per API version, and prepare CORS for the docs site's Try it out button. Rules the spec cannot express well, such as how to retry or how to use idempotency keys, belong in guide pages. That is how the docs become the real contract of the API.

Common mistakes

Common mistakes

1. Documenting only the success response

With only "200: OK" documented, client developers must guess how to handle 401, 404, 422 and 429. Document those statuses and the shape of the error body too.

2. Maintaining the spec by hand, apart from the code

Without a check in CI, the spec falls behind the code and drifts exactly as in the problem. Generate the spec from the code, or at least compare the two with contract tests.

3. Putting real data in examples

Emails, tokens and IDs copied from production logs become public in the docs for good. Use example.com, fake tokens and invented names.

4. Missing or duplicate operationId and empty descriptions

Without an operationId, generators invent names from the path and client functions become messy; duplicates make one function shadow another. Descriptions that just say "OK" explain nothing.

Best practices

Best practices

  • Give every endpoint at least one example and one error response, and use a single error body shape throughout.
  • Keep a dated changelog that separates additive from breaking changes, and record deprecation dates there too.
  • Viewing the spec in a docs viewer is not enough; make lint and contract tests blocking checks in CI.

Mini challenge

Mini challenge: generate reference docs from a spec

Write an OpenAPI-style object for a Tasks API yourself, then write describeOperations(spec). For each operation, print one aligned line of a docs table with method, path, operationId, inputs (query and path parameters plus body) and response status codes. This generates docs, not a client, from the spec.

  • Put three operations in the spec: GET /tasks (listTasks), POST /tasks (createTask) and DELETE /tasks/{id} (deleteTask)
  • listTasks has query parameters status and limit, createTask has a requestBody, deleteTask has a path parameter id
  • Response codes are listTasks: 200, 401; createTask: 201, 422; deleteTask: 204, 404
  • Show inputs as in: query:status, query:limit, add body when there is a requestBody, and show - when there are no inputs
  • Align the columns with padEnd before printing
describe-operations.mjs
// TODO: define const doc = { paths: { ... } } for the Tasks API described above

function describeOperations(spec) {
  const lines = [];
  // TODO: loop over spec.paths, then over each path item's methods
  // TODO: inputs = each parameter as "<in>:<name>", plus "body" when requestBody exists
  // TODO: build one line: METHOD, path, operationId, "in: ...", "out: <status codes>"
  // TODO: pad the first columns with padEnd so the lines align
  return lines;
}

// TODO: print every line returned by describeOperations(doc)

Expected: Three lines are printed: GET /tasks listTasks in: query:status, query:limit out: 200, 401 POST /tasks createTask in: body out: 201, 422 DELETE /tasks/{id} deleteTask in: path:id out: 204, 404

Show hint

Take each path with Object.entries(spec.paths) and loop over its methods. Response codes come from Object.keys(op.responses). Start with column widths 7, 13 and 12 and adjust as needed.

Show solution
describe-operations.mjs
const doc = {
  paths: {
    "/tasks": {
      get: {
        operationId: "listTasks",
        parameters: [
          { name: "status", in: "query" },
          { name: "limit", in: "query" },
        ],
        responses: { 200: {}, 401: {} },
      },
      post: {
        operationId: "createTask",
        requestBody: { required: true },
        responses: { 201: {}, 422: {} },
      },
    },
    "/tasks/{id}": {
      delete: {
        operationId: "deleteTask",
        parameters: [{ name: "id", in: "path", required: true }],
        responses: { 204: {}, 404: {} },
      },
    },
  },
};

function describeOperations(spec) {
  const lines = [];
  for (const [path, item] of Object.entries(spec.paths)) {
    for (const [method, op] of Object.entries(item)) {
      const inputs = (op.parameters ?? []).map((p) => p.in + ":" + p.name);
      if (op.requestBody) inputs.push("body");
      lines.push(
        method.toUpperCase().padEnd(7) +
          path.padEnd(13) +
          op.operationId.padEnd(12) +
          ("in: " + (inputs.join(", ") || "-")).padEnd(32) +
          "out: " + Object.keys(op.responses).join(", "),
      );
    }
  }
  return lines;
}

describeOperations(doc).forEach((line) => console.log(line));

Quick quiz 1 / 3

A spec renders nicely in Swagger UI and then sits untouched for months with no CI checks. What can you be sure of?

Quick quiz 2 / 3

Which statement about operationId in OpenAPI is correct?

Quick quiz 3 / 3

Which check can catch changing a response field from integer to string at the pull-request stage?

What to remember

  • OpenAPI describes an API in YAML or JSON as a machine-readable contract built from paths, operationId, responses, components and $ref.
  • Because the spec is data, tools can generate docs, clients, mock servers and validation from it.
  • A spec that renders well in Swagger UI is not proven correct; CI needs lint, contract tests and a breaking-change diff.
  • Good docs have guides, examples, an error catalogue and a changelog as well as reference pages, and examples must never contain secrets.

OpenAPI Specification — OpenAPI Initiative

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.