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:
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' > .gitignoreCheck it worked
npx redocly --version
npx openapi-typescript --versionThe 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:
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
YAMLThe 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:
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
YAMLNow 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:
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
YAMLmaxLength 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
ls schemasThe 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:
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
YAMLOne 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:
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
YAMLWrite 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:
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
YAMLCheck it worked
ls pathsThe 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.1names the specification version. Tools use it to decide which rules apply.infoholds the title, the version of your API (not of OpenAPI), a one-linesummary, contact details and a licence.serverslists base URLs. OpenAPI 3.2 lets each one have aname.api.tickets.exampleuses a reserved test domain; replace it with your own.securityat the top level requires the bearer token on every operation unless the operation says otherwise, as the publicGETs do.tagsgroup operations. 3.2 addssummaryfor a short display name,parentto nest one tag under another, andkind, wherenavmarks tags meant for navigation.pathsmaps each URL to its file.componentsholds the pieces several operations share: theEventIdparameter, the error responses and the security scheme.
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.
YAMLThe 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:
npm run lintCheck 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.comon thelocalhostserver URL.operation-operationIdon the purchase inpaths/event-tickets.yaml.no-invalid-media-type-examples: the example sendsquantity: '2', a string, where the schema says integer.operation-4xx-response: the purchase lists no error responses at all.no-unused-componentsonConflict, 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:
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
YAMLThe 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:
cat > redocly.yaml <<'YAML'
extends:
- recommended
rules:
no-server-example.com: off
YAML
npm run lintCheck 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:
npm run bundle
npx redocly lint dist/openapi.yamlCheck it worked
grep -o '\$ref: .*' dist/openapi.yaml | sort | uniq -cEach 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:
cat > types.redocly.yaml <<'YAML'
extends:
- minimal
rules:
struct: off
no-server-example.com: off
YAML
npm run typesKeep 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
grep -n 'Event: components\["schemas"\]\["NewEvent"\]' src/api.d.ts
grep -n 'buyTickets: {' src/api.d.tsBoth 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:
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"]
}
JSONThe 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:
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 typecheckThe 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:
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:
cd ~/ticketing-api-demo
npm run mockIt prints Mock API on http://localhost:4010/v1. Back in the first terminal, run the client:
npm run clientCheck 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:
cd ~
rm -rf ~/ticketing-api-demoCheck it worked
ls ~/ticketing-api-demo 2>/dev/null || echo "removed"The command prints removed.
Next steps
- Turn the bundled file into a reference site people can browse: publish API reference docs from an OpenAPI file.
- If you skipped the design work, go back to designing REST endpoints, methods and status codes and compare your contract with the design.
- Give a frontend a realistic API before the server exists: mock an API in frontend development with MSW.
- Check a running server against its contract: test an API with pytest and Schemathesis.
Part of these paths
Related tutorials
- Design REST endpoints: resources, methods and status codesYou will design the endpoints of an event ticketing API on one page, build an Express 5 stub that follows it, and prove every status code in the design with curl.
- Publish API reference docs people can actually useYou will turn an OpenAPI file into a static reference page with Redocly CLI, add a hand-written guide with a quickstart, authentication, an error catalogue, rate limits and a changelog, and prove the curl, JavaScript and Python examples work against a local mock server.
- Mock an API during frontend development with Mock Service WorkerYou will build a Vite page against a mocked API with Mock Service Worker 3, drive its loading, error and empty states on demand, reuse the same mocks in Vitest, and switch to the real API with one environment variable.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials