Documenting with OpenAPI

A Spec That Generates Docs, Clients, and Tests

Documenting with OpenAPI

OpenAPI describes your API in YAML or JSON. Generate Swagger UI, TypeScript clients, mocks — for free.

4 min read Level 2/5 #express#openapi#swagger
What you'll learn
  • Recognize OpenAPI shape
  • Generate it from Zod schemas
  • Serve interactive docs

OpenAPI (formerly Swagger) is a YAML/JSON spec that describes HTTP APIs. Generate the spec, get docs, clients, and mocks for free.

What An OpenAPI Spec Looks Like

openapi: 3.1.0
info:
  title: My API
  version: 1.0.0
paths:
  /users/{id}:
    get:
      summary: Get a user
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: ok
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        '404':
          description: not found
components:
  schemas:
    User:
      type: object
      properties:
        id:    { type: string }
        email: { type: string, format: email }
        name:  { type: string }

Generate It From Zod

Hand-writing this is painful. Generate it from your existing Zod schemas:

npm install zod-openapi
import { z } from "zod";
import { extendZodWithOpenApi, createDocument } from "zod-openapi";

extendZodWithOpenApi(z);

const UserSchema = z.object({
  id:    z.string().openapi({ example: "u_123" }),
  email: z.string().email(),
  name:  z.string(),
}).openapi({ ref: "User" });

const openApiDoc = createDocument({
  openapi: "3.1.0",
  info: { title: "My API", version: "1.0.0" },
  paths: {
    "/users/{id}": {
      get: {
        summary: "Get a user",
        requestParams: { path: z.object({ id: z.string() }) },
        responses: {
          "200": { description: "ok", content: { "application/json": { schema: UserSchema } } },
        },
      },
    },
  },
});

One source of truth: your Zod schemas drive both runtime validation AND the OpenAPI spec.

Serve Swagger UI

npm install swagger-ui-express
import swaggerUi from "swagger-ui-express";

app.use("/docs", swaggerUi.serve, swaggerUi.setup(openApiDoc));

Visit /docs — an interactive HTML explorer for your API.

What You Get From OpenAPI

  • Interactive docs — Swagger UI, Redoc, Scalar
  • Client SDKsopenapi-typescript generates TS clients
  • Mock servers — Prism mocks a server from the spec
  • Postman collections — import OpenAPI as a Postman collection
  • Server stubs — generate Express skeletons

When To Adopt

  • Multi-team APIs where the contract is the integration point
  • Public APIs (devs expect OpenAPI/Swagger)
  • Anywhere typed clients matter (a TS frontend consuming your API)

For tiny internal APIs, it’s overkill. Reach for it when the API has external consumers.

End of Chapter

That wraps building REST APIs. Next chapter: auth and security.

Auth Overview →