Writing OpenAPI Specs and Generating TypeScript Clients

Illustration of an openapi.yaml spec card generating a typed TypeScript client card on a black and crimson background, illustrating OpenAPI TypeScript client generation.

OpenAPI TypeScript client generation means writing your API down once, as an OpenAPI spec, and letting a tool turn that spec into TypeScript types your frontend has to obey. If the backend renames a field, the frontend stops compiling instead of quietly showing undefined to users.

A lot of teams keep the API contract in three places: the backend code, a Postman collection someone updates when they remember, and a hand-written types.ts in the frontend. All three drift. A spec-first workflow collapses them into one file that both sides read. This post walks through a small spec, the generated types, a typed client used from a Next.js server component, and the checks that catch drift before it ships.

What this post covers

Tested on Next.js 16.4.3, React 19.3.1, TypeScript 5.9.3 (strict mode), openapi-typescript 7.13.0, openapi-fetch 0.17.0 and Node 20.19.2. Six runtime tests pass against a local HTTP server, five deliberate type errors are caught by the compiler, and the page builds and renders with next build and next start.

Writing the spec first

Spec-first means the contract is agreed before either side writes code. The frontend can start against a mock, the backend knows exactly what to return, and arguments about field names happen in a pull request on one YAML file instead of in a bug report three weeks later. It’s the API version of writing a web app requirements document before anyone opens an editor.

Here’s a small spec for a projects API, written against OpenAPI 3.1. It has a list endpoint with a filter, a create endpoint that can fail validation, and a single-item endpoint that can 404:

openapi: 3.1.0
info:
  title: Projects API
  version: 1.0.0
servers:
  - url: http://localhost:4010
paths:
  /projects:
    get:
      operationId: listProjects
      parameters:
        - name: status
          in: query
          required: false
          schema:
            $ref: '#/components/schemas/ProjectStatus'
      responses:
        '200':
          description: A list of projects
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/Project'
    post:
      operationId: createProject
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/NewProject'
      responses:
        '201':
          description: Created
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Project'
        '422':
          description: Validation failed
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ValidationError'
  /projects/{id}:
    get:
      operationId: getProject
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
      responses:
        '200':
          description: One project
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Project'
        '404':
          description: Not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/NotFound'
components:
  schemas:
    ProjectStatus:
      type: string
      enum: [active, paused, archived]
    Project:
      type: object
      required: [id, name, status, created_at]
      properties:
        id:
          type: integer
        name:
          type: string
        status:
          $ref: '#/components/schemas/ProjectStatus'
        budget:
          type: [number, 'null']
        created_at:
          type: string
          format: date-time
    NewProject:
      type: object
      required: [name]
      properties:
        name:
          type: string
          minLength: 1
        budget:
          type: [number, 'null']
    ValidationError:
      type: object
      required: [message, errors]
      properties:
        message:
          type: string
        errors:
          type: object
          additionalProperties:
            type: array
            items:
              type: string
    NotFound:
      type: object
      required: [message]
      properties:
        message:
          type: string

A few habits that pay off later:

  • Give every operation an operationId. Generators and docs tools use it for names, and it keeps them stable when paths change.
  • Put reusable shapes in components/schemas. Project is defined once and referenced everywhere, so the generated types have one name for it.
  • Be honest about nulls. In 3.1, type: [number, 'null'] says the field can be null. If the backend sometimes sends null and the spec doesn’t say so, the types will lie to you.
  • Describe the error responses too. The 422 and 404 bodies are part of the contract. More on why below.

If you’re deciding between a REST contract like this and GraphQL in the first place, I compared them in REST vs GraphQL for SaaS Public APIs.

Generating the types

openapi-typescript reads the spec and writes a single .d.ts file. There’s no runtime code in it, only types, so it adds nothing to your bundle.

npm i -D openapi-typescript typescript
npm i openapi-fetch
npx openapi-typescript openapi.yaml -o src/api.d.ts

Put the command in package.json so nobody has to remember the flags:

{
  "scripts": {
    "api:types": "openapi-typescript openapi.yaml -o src/api.d.ts"
  }
}

The output for the Project schema looks like this:

Project: {
    id: number;
    name: string;
    status: components["schemas"]["ProjectStatus"];
    budget?: number | null;
    created_at: string;
};

status is the union "active" | "paused" | "archived", budget is optional and nullable, and created_at is a plain string, because JSON has no date type. Parse it yourself where you need a Date.

I commit the generated file. It makes the type changes visible in code review next to the spec change that caused them, and the app builds without running the generator first.

A typed client with openapi-fetch

Types alone don’t stop you from typing /project instead of /projects in a fetch call. openapi-fetch is a thin wrapper around fetch that takes the generated paths type, so the URL, the path and query parameters, the request body and the response are all checked against the spec.

import createClient, { type Middleware } from "openapi-fetch";
import type { paths, components } from "../src/api";

export type Project = components["schemas"]["Project"];
export type NewProject = components["schemas"]["NewProject"];

const auth: Middleware = {
  async onRequest({ request }) {
    const token = process.env.API_TOKEN;
    if (token) request.headers.set("Authorization", `Bearer ${token}`);
    return request;
  },
};

export function makeApi(baseUrl = process.env.API_URL ?? "http://localhost:4010") {
  const client = createClient<paths>({ baseUrl });
  client.use(auth);
  return client;
}

export const api = makeApi();

export async function getProject(id: number): Promise<Project | null> {
  const { data, error, response } = await api.GET("/projects/{id}", {
    params: { path: { id } },
  });
  if (response.status === 404) return null;
  if (error) throw new Error(`getProject failed: ${response.status}`);
  return data;
}

The middleware adds the bearer token on every request, and the base URL comes from the environment. Keep this module server-side if the token is a secret. The API integration guide covers where keys should and shouldn’t live.

Here’s what the compiler now refuses. Every line marked @ts-expect-error is a real type error, and tsc would fail if any of them stopped being one:

import { api } from "./api";

export async function typeChecks() {
  // @ts-expect-error "done" is not a ProjectStatus
  await api.GET("/projects", { params: { query: { status: "done" } } });

  // @ts-expect-error path param id is required
  await api.GET("/projects/{id}", {});

  // @ts-expect-error name is required in NewProject
  await api.POST("/projects", { body: { budget: 500 } });

  // @ts-expect-error this path is not in the spec
  await api.GET("/project", {});

  const { data } = await api.GET("/projects/{id}", { params: { path: { id: 1 } } });
  if (data) {
    // @ts-expect-error budget can be null, so it must be checked first
    data.budget.toFixed(2);
  }
}

The last one is the case I care about most. Because the spec says budget can be null, the compiler makes you handle it. A hand-written type would likely have said budget: number, and the first project without a budget would crash the page.

Using it in a Next.js server component

In the App Router, the client works directly in a server component. The data and error fields are a discriminated pair: after checking error, TypeScript knows data is a Project[].

import { api } from "../../lib/api";

// Re-fetch at most once a minute instead of freezing the build-time result.
export const revalidate = 60;

export default async function ProjectsPage() {
  const { data, error } = await api.GET("/projects", {
    params: { query: { status: "active" } },
  });
  if (error) return <p>Could not load projects.</p>;

  return (
    <ul>
      {data.map((p) => (
        <li key={p.id}>
          {p.name} ({p.status}){p.budget != null && ` · budget ${p.budget}`}
        </li>
      ))}
    </ul>
  );
}

One thing that caught me while testing: without revalidate, Next.js 16 prerendered this page as static content at build time, so it would have shown the build-day project list forever. The fetch goes through openapi-fetch, but it’s still a normal fetch to Next.js, and the usual caching rules apply. Pick revalidate, or make the route dynamic if the data is per user.

Error responses are part of the contract

Because the 422 response is in the spec, its body is typed too. That lets you turn a validation failure into data the form can show, instead of a generic exception:

import { api, type NewProject, type Project } from "./api";

type Result =
  | { ok: true; project: Project }
  | { ok: false; errors: Record<string, string[]> };

export async function createProject(input: NewProject): Promise<Result> {
  const { data, error, response } = await api.POST("/projects", { body: input });
  if (data) return { ok: true, project: data };
  if (response.status === 422 && error) return { ok: false, errors: error.errors };
  throw new Error(`createProject failed: ${response.status}`);
}

openapi-fetch doesn’t throw on 4xx or 5xx. It returns error with the body typed from whatever the spec says for that status. I prefer that: the caller decides which failures are expected (a 404, a 422) and which ones should throw.

If your backend is Laravel, the 422 shape above matches its default validation response, a message plus an errors object keyed by field. Versioning matters once other clients depend on this contract; I covered that in Designing a Versioned REST API in Laravel.

Catching drift in CI

The whole point is that a contract change shows up as a compile error. To check that it really does, I renamed budget to budget_cents in the spec, regenerated, and ran tsc:

app/projects/page.tsx(16,35): error TS2339: Property 'budget' does not exist on type
'{ id: number; name: string; status: "active" | "paused" | "archived";
   budget_cents?: number | null | undefined; created_at: string; }'.

That’s the error you want to see in a pull request, not in production. Two CI steps make it reliable:

  • Regenerate and diff. Run npm run api:types, then git diff --exit-code src/api.d.ts. If someone edited the spec but didn’t regenerate, the job fails.
  • Type-check the app. Run tsc --noEmit (or let next build do it). If the spec changed in a way the frontend doesn’t handle yet, this fails.

If the backend generates the spec from its own code rather than the other way round, the same steps still work. Export the spec in the backend’s CI, commit it, and let the frontend job regenerate and type-check against it.

The tests

The runtime tests compile the client with tsc and run it against a small Node HTTP server that behaves like the spec, using Node’s built-in test runner:

TestResult
Query params are serialized from the typed objectPass, request was /projects?status=paused
Path params are filled inPass, request was /projects/1
A 404 comes back as null, not an exceptionPass
The auth middleware adds the bearer tokenPass
A 201 returns the created projectPass, body sent as JSON
A 422 comes back as field errorsPass
Five deliberate type errorsAll caught by tsc
Renaming a field in the spectsc fails on the page that uses it
next build and next startPage renders the list, revalidates every 60 seconds

The 422 test, since it’s the one that proves error bodies are part of the contract:

test("422 validation errors come back as data", async () => {
  const r = await create.createProject({ name: "" });
  assert.deepEqual(r, { ok: false, errors: { name: ["The name field is required."] } });
});

FAQ

What is OpenAPI TypeScript client generation?

It’s generating TypeScript types, and optionally a client, from an OpenAPI spec, so the frontend’s API calls are checked against the same contract the backend implements.

Should I use openapi-typescript or OpenAPI Generator?

openapi-typescript generates types only and pairs with a tiny fetch wrapper, which suits React and Next.js apps well. OpenAPI Generator produces full client classes in many languages, which helps when you ship SDKs for several platforms. For a single TypeScript frontend I’d start with the lighter option.

Should I commit the generated types?

I do. It keeps type changes visible in review and lets the app build without the generator. Pair it with a CI step that regenerates and fails on any diff.


I’m Shahrukh Akhtar (Shaz3e), CTO & Co-Founder of Diligent Creators Pvt. Ltd., a Technology Executive & Product Builder. I run client delivery and build SaaS products, including EloSync. You can find me on X, LinkedIn, Peerlist and GitHub.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *