Skip to main content

APIs · Intermediate · 26 min

Describe an API with an OpenAPI 3.2 document

By Padding · Updated 18 Nov 2026
Node.js 26.13 (node:26 image) · Redocly CLI 2.81.0 · openapi-typescript 7.13.0 · openapi-fetch 0.17.0 · TypeScript 5.9.3

You will write an OpenAPI 3.2 contract for a ticketing API by hand across several files, lint it clean with Redocly CLI 2, bundle it into one file and generate TypeScript types that a client uses against a mock server.

On this page

An OpenAPI document is a contract for an HTTP API, written in YAML or JSON. It lists every URL, which methods each one accepts, what the request and response bodies look like, which status codes come back and how callers authenticate. People read it as documentation. Tools read it to lint the design, draw reference pages, run mock servers, generate client code and test a running server against the promise.

You will write the contract for a small event ticketing API before any server exists. Organisers list events, anyone can browse them, and buyers reserve tickets with a bearer token. You write it by hand, split across short files so that each one stays readable, then check it with Redocly CLI, bundle it into one file and generate TypeScript types from it. A typed client then calls a mock server, and TypeScript refuses code that breaks the contract.

Version 3.2 of the OpenAPI Specification came out in September 2025, and the current patch is 3.2.1. It keeps the JSON Schema support of 3.1 and adds, among other things, nested tags and named servers, both of which you use here. Patch releases only fix wording, so tools treat 3.2.0 and 3.2.1 the same.

Step 1 · Set up a contract project

Make a throwaway folder and pin every tool. Redocly CLI lints and bundles the contract. openapi-typescript turns it into TypeScript types, and openapi-fetch is a small fetch wrapper that uses those types. openapi-typescript 7 declares TypeScript 5 as its peer, so this project uses TypeScript 5.9 rather than 7:

Bash
mkdir -p ~/ticketing-api-demo
cd ~/ticketing-api-demo
cat > package.json <<'JSON'
{
  "name": "ticketing-contract",
  "private": true,
  "type": "module",
  "scripts": {
    "lint": "redocly lint openapi.yaml",
    "bundle": "redocly bundle openapi.yaml -o dist/openapi.yaml",
    "types": "openapi-typescript dist/openapi.yaml -c types.redocly.yaml -o src/api.d.ts",
    "typecheck": "tsc",
    "mock": "node --env-file=.env mock-server.mjs",
    "client": "node --env-file=.env src/client.ts"
  },
  "dependencies": {
    "openapi-fetch": "0.17.0"
  },
  "devDependencies": {
    "@redocly/cli": "2.81.0",
    "@types/node": "26.6.6",
    "openapi-typescript": "7.13.0",
    "typescript": "5.9.3"
  }
}
JSON
npm install
mkdir -p schemas paths src
printf 'node_modules\n.env\n' > .gitignore

Check it worked

Bash
npx redocly --version
npx openapi-typescript --version

The first command prints 2.81.0 and the second v7.13.0.

Step 2 · Describe the data with reusable schemas

Start with the shapes of the data, because every operation refers to them. Each schema gets its own file in schemas/, named the way you want it to appear in the final contract. OpenAPI 3.2 schemas are JSON Schema, so type, required, minimum, pattern and examples mean what they mean there.

An organiser sends a NewEvent. Money is an integer in the currency's minor unit, kobo for naira or cents for shillings and rand, with an ISO 4217 code beside it. Integers avoid the rounding errors of decimal fractions, and the currency code lets one API sell tickets in Lagos, Nairobi and Accra without guessing:

Bash
cat > schemas/NewEvent.yaml <<'YAML'
type: object
description: What an organiser sends to list a new event.
required: [name, venue, city, startsAt, priceMinor, currency, capacity]
properties:
  name:
    type: string
    minLength: 1
    maxLength: 120
    examples: ['Lagos Jazz Night']
  venue:
    type: string
    maxLength: 120
  city:
    type: string
    maxLength: 80
  startsAt:
    type: string
    format: date-time
    description: Start time in RFC 3339 format, with a UTC offset.
  priceMinor:
    type: integer
    minimum: 0
    description: Price of one ticket in the currency's minor unit (kobo, cents).
  currency:
    type: string
    pattern: '^[A-Z]{3}$'
    description: ISO 4217 currency code.
    examples: [NGN, KES, GHS, ZAR]
  capacity:
    type: integer
    minimum: 1
YAML

The Event the API returns is a NewEvent plus two fields the server owns. allOf reuses the first schema instead of copying it, and readOnly says clients never send these fields:

Bash
cat > schemas/Event.yaml <<'YAML'
description: An event that people can buy tickets for.
allOf:
  - $ref: ./NewEvent.yaml
  - type: object
    required: [id, ticketsLeft]
    properties:
      id:
        type: string
        readOnly: true
        examples: [evt_7kq2m9]
      ticketsLeft:
        type: integer
        minimum: 0
        readOnly: true
YAML

Now the ticket order a buyer sends, the ticket that comes back, and one error shape for every failure. The error follows RFC 9457 problem details, a standard JSON body with type, title, status and detail, so clients handle all errors the same way:

Bash
cat > schemas/TicketOrder.yaml <<'YAML'
type: object
description: A request to buy tickets for one event.
required: [holderName, holderEmail, quantity]
properties:
  holderName:
    type: string
    minLength: 1
    maxLength: 120
  holderEmail:
    type: string
    format: email
  quantity:
    type: integer
    minimum: 1
    maximum: 10
YAML
cat > schemas/Ticket.yaml <<'YAML'
type: object
description: Tickets reserved for one buyer.
required: [id, eventId, holderName, quantity, status, createdAt]
properties:
  id:
    type: string
    examples: [tkt_p4w8xa]
  eventId:
    type: string
  holderName:
    type: string
  quantity:
    type: integer
    minimum: 1
  status:
    type: string
    enum: [reserved, paid, cancelled]
  createdAt:
    type: string
    format: date-time
YAML
cat > schemas/Problem.yaml <<'YAML'
type: object
description: An error body in the RFC 9457 problem details format.
required: [type, title, status]
properties:
  type:
    type: string
    format: uri-reference
  title:
    type: string
  status:
    type: integer
  detail:
    type: string
YAML

maxLength counts Unicode code points, not bytes, so a name in Amharic script, or Yorùbá typed with precomposed letters, is not penalised for needing several bytes per letter in UTF-8. A letter written as a base letter plus combining tone marks counts each mark as well, so leave some headroom.

Check it worked

Bash
ls schemas

The list shows five files: Event.yaml, NewEvent.yaml, Problem.yaml, Ticket.yaml and TicketOrder.yaml.

Step 3 · Describe the operations

Each URL gets a file in paths/ holding its operations: one key per HTTP method. An operation has an operationId (a stable name that code generators turn into function names), a summary, tags, parameters, an optional requestBody and its responses. Schemas come in with $ref to the files you just wrote. Shared responses and parameters live in the root document, which you write in the next step, and are referenced with a JSON pointer after the #.

The /events collection has a public listing and an authenticated create. security: [] on the GET overrides the bearer token that the root document will require everywhere else. The request body carries a named example, which documentation tools show and linters check against the schema:

Bash
cat > paths/events.yaml <<'YAML'
get:
  operationId: listEvents
  summary: List upcoming events
  tags: [events]
  security: []
  parameters:
    - name: city
      in: query
      description: Only return events in this city.
      schema:
        type: string
    - name: limit
      in: query
      schema:
        type: integer
        minimum: 1
        maximum: 100
        default: 20
  responses:
    '200':
      description: Events, soonest first.
      content:
        application/json:
          schema:
            type: array
            items:
              $ref: ../schemas/Event.yaml
    '400':
      $ref: ../openapi.yaml#/components/responses/BadRequest
post:
  operationId: createEvent
  summary: List a new event
  tags: [events]
  requestBody:
    required: true
    content:
      application/json:
        schema:
          $ref: ../schemas/NewEvent.yaml
        examples:
          jazzNight:
            summary: A concert in Lagos priced in naira
            value:
              name: Lagos Jazz Night
              venue: Freedom Park
              city: Lagos
              startsAt: '2027-03-12T19:00:00+01:00'
              priceMinor: 1500000
              currency: NGN
              capacity: 400
  responses:
    '201':
      description: The event was created.
      headers:
        Location:
          description: URL of the new event.
          schema:
            type: string
      content:
        application/json:
          schema:
            $ref: ../schemas/Event.yaml
    '401':
      $ref: ../openapi.yaml#/components/responses/Unauthorised
    '422':
      $ref: ../openapi.yaml#/components/responses/ValidationFailed
YAML

One event, and one ticket, each have a path parameter in curly braces. The event ID is shared, so it is a reference; the ticket ID is written in place to show both forms:

Bash
cat > paths/event.yaml <<'YAML'
get:
  operationId: getEvent
  summary: Get one event
  tags: [events]
  security: []
  parameters:
    - $ref: ../openapi.yaml#/components/parameters/EventId
  responses:
    '200':
      description: The event.
      content:
        application/json:
          schema:
            $ref: ../schemas/Event.yaml
    '404':
      $ref: ../openapi.yaml#/components/responses/NotFound
YAML
cat > paths/ticket.yaml <<'YAML'
get:
  operationId: getTicket
  summary: Get a ticket
  tags: [tickets]
  parameters:
    - name: ticketId
      in: path
      required: true
      schema:
        type: string
  responses:
    '200':
      description: The ticket.
      content:
        application/json:
          schema:
            $ref: ../schemas/Ticket.yaml
    '401':
      $ref: ../openapi.yaml#/components/responses/Unauthorised
    '404':
      $ref: ../openapi.yaml#/components/responses/NotFound
YAML

Write the ticket purchase as a first draft. It has the kind of gaps a hurried first version has; leave them in, and the linter finds them in the next step:

Bash
cat > paths/event-tickets.yaml <<'YAML'
post:
  summary: Buy tickets for an event
  tags: [tickets]
  parameters:
    - $ref: ../openapi.yaml#/components/parameters/EventId
  requestBody:
    required: true
    content:
      application/json:
        schema:
          $ref: ../schemas/TicketOrder.yaml
        examples:
          twoTickets:
            value:
              holderName: Amina Bello
              holderEmail: amina@example.com
              quantity: '2'
  responses:
    '201':
      description: The tickets are reserved.
      content:
        application/json:
          schema:
            $ref: ../schemas/Ticket.yaml
YAML

Check it worked

Bash
ls paths

The list shows event-tickets.yaml, event.yaml, events.yaml and ticket.yaml. Nothing can check them yet, because the responses they point at do not exist until the next step.

Step 4 · Write the root document and lint it

openapi.yaml ties everything together. Read it top to bottom:

  • openapi: 3.2.1 names the specification version. Tools use it to decide which rules apply.
  • info holds the title, the version of your API (not of OpenAPI), a one-line summary, contact details and a licence.
  • servers lists base URLs. OpenAPI 3.2 lets each one have a name. api.tickets.example uses a reserved test domain; replace it with your own.
  • security at the top level requires the bearer token on every operation unless the operation says otherwise, as the public GETs do.
  • tags group operations. 3.2 adds summary for a short display name, parent to nest one tag under another, and kind, where nav marks tags meant for navigation.
  • paths maps each URL to its file.
  • components holds the pieces several operations share: the EventId parameter, the error responses and the security scheme.
Bash
cat > openapi.yaml <<'YAML'
openapi: 3.2.1
info:
  title: Ticketing API
  version: 1.0.0
  summary: List events and sell tickets for them.
  description: |
    Organisers list events. Anyone can browse them. Buyers reserve tickets
    with a bearer token from their account.
  contact:
    email: api@tickets.example
  license:
    name: MIT
    identifier: MIT
servers:
  - url: https://api.tickets.example/v1
    name: production
    description: Live data.
  - url: http://localhost:4010/v1
    name: local
    description: A mock or development server on your machine.
security:
  - bearerAuth: []
tags:
  - name: events
    summary: Events
    description: Browse and list events.
    kind: nav
  - name: tickets
    summary: Tickets
    description: Reserve and look up tickets.
    parent: events
    kind: nav
paths:
  /events:
    $ref: paths/events.yaml
  /events/{eventId}:
    $ref: paths/event.yaml
  /events/{eventId}/tickets:
    $ref: paths/event-tickets.yaml
  /tickets/{ticketId}:
    $ref: paths/ticket.yaml
components:
  parameters:
    EventId:
      name: eventId
      in: path
      required: true
      description: The event's ID, such as evt_7kq2m9.
      schema:
        type: string
  responses:
    BadRequest:
      description: A query parameter is not valid.
      content:
        application/problem+json:
          schema:
            $ref: schemas/Problem.yaml
    Unauthorised:
      description: The bearer token is missing or not valid.
      content:
        application/problem+json:
          schema:
            $ref: schemas/Problem.yaml
    NotFound:
      description: Nothing exists at this URL.
      content:
        application/problem+json:
          schema:
            $ref: schemas/Problem.yaml
    Conflict:
      description: The request clashes with the current state, such as too few tickets left.
      content:
        application/problem+json:
          schema:
            $ref: schemas/Problem.yaml
    ValidationFailed:
      description: The body is well-formed JSON but breaks a rule in the schema.
      content:
        application/problem+json:
          schema:
            $ref: schemas/Problem.yaml
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: A token from the buyer's or organiser's account.
YAML

The security scheme describes how a token is sent, never a token itself. Real tokens stay out of the contract and out of the repository.

Lint the contract. Redocly follows every $ref across the files and checks the result against the 3.2 specification and its built-in recommended rules:

Bash
npm run lint

Check it worked

Redocly first says no configuration was provided, so it uses the recommended rules. It then prints each problem with the file, line and rule name, and ends with Woohoo! Your API description is valid. and You have 5 warnings. Valid means the structure is correct; the warnings are about quality. Four point at things to fix and one at a choice to record:

  • no-server-example.com on the localhost server URL.
  • operation-operationId on the purchase in paths/event-tickets.yaml.
  • no-invalid-media-type-examples: the example sends quantity: '2', a string, where the schema says integer.
  • operation-4xx-response: the purchase lists no error responses at all.
  • no-unused-components on Conflict, which nothing refers to yet.

If you see errors instead, the message names the file and line. The most common is a $ref path with a typo, reported as Can't resolve $ref.

Step 5 · Fix the warnings

Three of the warnings sit in the purchase draft, and one rewrite clears them and the unused Conflict component too: give the operation an operationId, make the example's quantity a number, and list the errors a buyer can actually meet. 409 Conflict is the sold-out case, and referring to it puts the unused component to work:

Bash
cat > paths/event-tickets.yaml <<'YAML'
post:
  operationId: buyTickets
  summary: Buy tickets for an event
  tags: [tickets]
  parameters:
    - $ref: ../openapi.yaml#/components/parameters/EventId
  requestBody:
    required: true
    content:
      application/json:
        schema:
          $ref: ../schemas/TicketOrder.yaml
        examples:
          twoTickets:
            summary: Two tickets for one buyer
            value:
              holderName: Amina Bello
              holderEmail: amina@example.com
              quantity: 2
  responses:
    '201':
      description: The tickets are reserved.
      content:
        application/json:
          schema:
            $ref: ../schemas/Ticket.yaml
    '401':
      $ref: ../openapi.yaml#/components/responses/Unauthorised
    '404':
      $ref: ../openapi.yaml#/components/responses/NotFound
    '409':
      $ref: ../openapi.yaml#/components/responses/Conflict
    '422':
      $ref: ../openapi.yaml#/components/responses/ValidationFailed
YAML

The localhost server is deliberate: it is where you run the mock. Rather than delete it or learn to ignore the warning, record the decision in a redocly.yaml file. Redocly reads it from the current folder, so everyone on the team, and your CI job, gets the same rules:

Bash
cat > redocly.yaml <<'YAML'
extends:
  - recommended
rules:
  no-server-example.com: off
YAML
npm run lint

Check it worked

The output is short: validating openapi.yaml..., the time it took, and Woohoo! Your API description is valid., with no warnings line. To see that Redocly understands the 3.2 tag fields and is not only skipping them, change parent: events to parent: event in openapi.yaml and lint again: the spec-no-invalid-tag-parents rule reports an error and the command fails. Change it back before you go on.

Step 6 · Bundle the contract into one file

Split files are pleasant to edit, but many tools want one file. redocly bundle follows every reference and writes a single document. Schemas referenced by file become entries in components/schemas, named after their files, which is why you named them Event.yaml and not event-schema.yaml:

Bash
npm run bundle
npx redocly lint dist/openapi.yaml

Check it worked

Bash
grep -o '\$ref: .*' dist/openapi.yaml | sort | uniq -c

Each line is a count followed by a $ref to '#/components/...', such as $ref: '#/components/schemas/Event' or $ref: '#/components/responses/NotFound'. No reference points at a file any more, and the lint of the bundle ends with Woohoo! Your API description is valid. This single file is the one you hand to other tools and other teams. Rebuild it whenever the source files change, rather than editing it.

Step 7 · Generate TypeScript types

openapi-typescript reads the bundle and writes one .d.ts file with a type for every path, operation and schema. It runs no code and makes no network calls.

It checks the file before generating, using an older Redocly engine that knows OpenAPI 3.1 but not the fields 3.2 added. On this contract it stops with errors such as Property kind is not expected here for the tags and servers. Those fields do not affect the types, and Redocly CLI 2 has already validated the structure, so give openapi-typescript its own small config that switches the structure check off:

Bash
cat > types.redocly.yaml <<'YAML'
extends:
  - minimal
rules:
  struct: off
  no-server-example.com: off
YAML
npm run types

Keep struct on in redocly.yaml. That file is your real check; this one only stops the generator repeating it with older rules.

Check it worked

Bash
grep -n 'Event: components\["schemas"\]\["NewEvent"\]' src/api.d.ts
grep -n 'buyTickets: {' src/api.d.ts

Both lines are found. The first shows allOf turned into an intersection type: an Event is a NewEvent with readonly id and readonly ticketsLeft added. The second is the purchase operation, with its request body and every response by status code.

Step 8 · Use the types in a client

Add a TypeScript config that matches what Node can run. Node 26 runs .ts files by stripping the types, so tsc only checks them and writes nothing:

Bash
cat > tsconfig.json <<'JSON'
{
  "compilerOptions": {
    "target": "esnext",
    "module": "nodenext",
    "strict": true,
    "noEmit": true,
    "allowImportingTsExtensions": true,
    "erasableSyntaxOnly": true,
    "verbatimModuleSyntax": true,
    "skipLibCheck": true,
    "types": ["node"]
  },
  "include": ["src"]
}
JSON

The client lists events in Lagos, then buys two tickets for the first one. createClient<paths> ties every call to the contract: the URL must be one of its paths, the query and body must match its schemas, and data and error have the types of the success and error responses. The base URL and the token come from environment variables, never from the code:

Bash
cat > src/client.ts <<'TS'
import createClient from "openapi-fetch";
import type { components, paths } from "./api.d.ts";

type TicketOrder = components["schemas"]["TicketOrder"];

const client = createClient<paths>({
  baseUrl: process.env.TICKETS_API_URL ?? "http://localhost:4010/v1",
});

const events = await client.GET("/events", {
  params: { query: { city: "Lagos", limit: 5 } },
});
if (!events.data) {
  throw new Error(`Listing events failed: ${events.response.status}`);
}
for (const event of events.data) {
  const price = (event.priceMinor / 100).toFixed(2);
  console.log(`${event.id}  ${event.name}  ${price} ${event.currency}  ${event.ticketsLeft} left`);
}

const order: TicketOrder = {
  holderName: "Amina Bello",
  holderEmail: "amina@example.com",
  quantity: 2,
};
const bought = await client.POST("/events/{eventId}/tickets", {
  params: { path: { eventId: events.data[0].id } },
  body: order,
  headers: { Authorization: `Bearer ${process.env.TICKETS_API_TOKEN ?? ""}` },
});
if (bought.error) {
  console.log(`Buying failed: ${bought.response.status} ${bought.error.title}`);
} else {
  console.log(`Ticket ${bought.data.id} is ${bought.data.status}`);
}

// @ts-expect-error The contract says quantity is an integer, so a string is rejected.
const wrong: TicketOrder = { holderName: "Test", holderEmail: "t@example.com", quantity: "2" };
void wrong;
TS
npm run typecheck

The last lines are a test of the types themselves. @ts-expect-error makes tsc fail if the next line does not have a type error, so a clean run proves the contract rejects quantity: "2", the same mistake the linter caught in the example.

To try the client, you need something that answers. Write a mock server that returns data shaped like the contract, and a private .env file with a random demo token, created readable only by you:

Bash
cat > mock-server.mjs <<'JS'
import { createServer } from "node:http";

const events = [
  {
    id: "evt_7kq2m9", name: "Lagos Jazz Night", venue: "Freedom Park", city: "Lagos",
    startsAt: "2027-03-12T19:00:00+01:00", priceMinor: 1500000, currency: "NGN",
    capacity: 400, ticketsLeft: 120,
  },
];

function send(res, status, body, type = "application/json") {
  res.writeHead(status, { "Content-Type": type });
  res.end(JSON.stringify(body));
}

createServer(async (req, res) => {
  const url = new URL(req.url, "http://localhost");
  if (req.method === "GET" && url.pathname === "/v1/events") {
    const city = url.searchParams.get("city");
    return send(res, 200, events.filter((e) => !city || e.city === city));
  }
  const match = url.pathname.match(/^\/v1\/events\/([^/]+)\/tickets$/);
  if (req.method === "POST" && match) {
    if (req.headers.authorization !== "Bearer " + process.env.TICKETS_API_TOKEN) {
      return send(res, 401, { type: "about:blank", title: "Unauthorised", status: 401 }, "application/problem+json");
    }
    let raw = "";
    for await (const chunk of req) raw += chunk;
    const order = JSON.parse(raw);
    return send(res, 201, {
      id: "tkt_p4w8xa", eventId: match[1], holderName: order.holderName,
      quantity: order.quantity, status: "reserved", createdAt: new Date().toISOString(),
    });
  }
  send(res, 404, { type: "about:blank", title: "Not found", status: 404 }, "application/problem+json");
}).listen(4010, "127.0.0.1", () => console.log("Mock API on http://localhost:4010/v1"));
JS
(umask 077 && node -e 'console.log("TICKETS_API_TOKEN=" + crypto.randomUUID())' > .env)

Start the mock in your second terminal, from the same folder, and leave it running:

Bash
cd ~/ticketing-api-demo
npm run mock

It prints Mock API on http://localhost:4010/v1. Back in the first terminal, run the client:

Bash
npm run client

Check it worked

npm run typecheck prints nothing after its header and exits cleanly. The client prints evt_7kq2m9 Lagos Jazz Night 15000.00 NGN 120 left and then Ticket tkt_p4w8xa is reserved. Now delete the // @ts-expect-error line in src/client.ts and run npm run typecheck again: it fails with something like Type 'string' is not assignable to type 'number', pointing at quantity. Put the line back.

The mock hand-builds its answers, so nothing stops it drifting from the contract. Its job here is only to give the client something to call. To check a real server against the contract, use a contract-testing tool such as Schemathesis, covered in its own tutorial.

Step 9 · Clean up

Stop the mock with Ctrl+C in the second terminal.

If you want to keep the contract for the next tutorial, copy dist/openapi.yaml somewhere first. Then remove the demo folder, which also deletes the .env file with the demo token:

Bash
cd ~
rm -rf ~/ticketing-api-demo

Check it worked

Bash
ls ~/ticketing-api-demo 2>/dev/null || echo "removed"

The command prints removed.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.