Generating clients, servers and types

OpenAPI · Advanced · 12 min

Generated code removes a whole class of client/server mismatches.

Code generation turns the contract into code, so client and server cannot silently disagree.

Common generators:

  • OpenAPI Generator (community fork of Swagger Codegen): clients and server stubs for 50+ languages, highly configurable via templates.
  • openapi-typescript: generates TypeScript types only; pair with the tiny openapi-fetch client for type-safe calls without heavy generated code.
  • Microsoft Kiota, plus commercial SDK generators (Speakeasy, Stainless, Fern) for polished public SDKs.
  • Language-specific options like oapi-codegen (Go) or datamodel-code-generator (Python Pydantic models).

Code-first frameworks generate the document from code: FastAPI from type hints, NestJS and Spring via annotations, utoipa in Rust. The code is the source of truth and the document is exported in CI.

Design-first writes the document first, reviews it as an API design artefact, mocks it, then generates server interfaces and clients.

Either way:

  • Treat generated code as build output: regenerate in CI, do not hand-edit it.
  • Pin generator versions; output changes between releases.
  • Good operationIds, named component schemas and accurate required lists matter far more for SDK quality than any generator flag.

Example

# TypeScript types + a typed fetch client
npx openapi-typescript ./openapi.yaml -o ./src/api.d.ts

# src/client.ts
#   import createClient from "openapi-fetch";
#   import type { paths } from "./api";
#   const api = createClient<paths>({ baseUrl: "https://api.example.com/v2" });
#   const { data, error } = await api.GET("/books/{bookId}", {
#     params: { path: { bookId: "b1" } },
#   });           // data is typed as the 200 response schema

# A full SDK with OpenAPI Generator (Docker image avoids a Java install)
docker run --rm -v "$PWD:/local" openapitools/openapi-generator-cli generate \
  -i /local/openapi.yaml -g python -o /local/sdk/python \
  --additional-properties=packageName=bookstore

Remember

  • Generate types, clients and stubs from the same contract
  • Code-first exports the document; design-first starts from it
  • Regenerate in CI and never hand-edit generated code
  • operationIds and named schemas make or break SDK quality

Watch out for

  • Hand-editing generated clients, then losing the edits on the next regeneration.

Check yourself

  1. What mostly determines the readability of generated SDK method and type names?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: openapi-generator.tech/docs/usage