What is API-first design with OpenAPI code generation, and who should use it?

API-first design means the OpenAPI document is the source of truth for an API, and it exists before the implementation does. In practice, that looks like three habits:

  • The spec is written and reviewed first. Engineers argue about resource names, error shapes and pagination in a pull request against YAML, not after a handler has shipped and a client depends on its quirks.
  • The spec lives in version control. It sits next to the code or in a dedicated repository, with history, blame and tags. Anyone can see what the contract was at any release.
  • Changes go through pull requests. Adding a field or deprecating an endpoint is a reviewable diff, so consumers can object before the change lands.

OpenAPI code generation builds on that contract. From the spec, a generator produces server stubs (interfaces or handlers your implementation must satisfy) and typed clients (request and response models plus call methods). Treat this output as disposable. You regenerate it whenever the spec changes and never edit it by hand, because hand edits are lost on the next run.

The approach pays off most when one contract serves many parties:

  • Teams with several consumers of one API, where a web app, mobile apps and partner integrations would otherwise each hand-write the same client.
  • Platform teams publishing internal services, which need a stable, documented interface that other teams can adopt without meetings.
  • Polyglot organizations, where a single spec yields clients in each language and keeps them consistent.

It pays off least for a single-consumer API owned by one small team. There, the people writing the server and the client are usually the same, so the spec and generator add a step without removing much coordination.

How does OpenAPI code generation work from spec to compiled code?

The pipeline has six stages, and each one exists to keep a specific kind of mistake from reaching production.

From reviewed spec to generated code

  1. The spec is reviewed like code. It lives in version control, and changes go through pull requests. Reviewers judge the contract itself: names, required fields, error shapes. They don't have to infer it from an implementation diff.
  2. A linter runs before generation. Rules catch missing operationIds, inline schemas that would produce anonymous types, and inconsistent naming. These problems are cheap to fix in YAML and expensive to fix after they have shaped hundreds of generated identifiers.
  3. The openapi generator runs with a pinned version and a checked-in config file. Generator templates change between releases. An unpinned version can rewrite type names or method signatures with no change to the spec. The config records choices such as package names, date handling, and nullability mapping so that every developer and CI job produces identical output.
  4. Output lands in a do-not-edit directory. Server interfaces and typed clients are overwritten on every run, so manual edits there will be lost.
  5. Hand-written code implements the interfaces and wraps the clients. Business logic, retries, auth, and logging live outside the generated directory.

Why the compiler matters

  1. CI regenerates, compiles, and runs contract tests. Suppose the spec renames a field or makes a parameter required. The regenerated interface then no longer matches the implementation, and the build fails at every affected call site. Contract tests cover what types cannot express, such as status codes and serialization details.
+---------------------------+      +---------------------------+
| 1. openapi.yaml           |      | 2. spec linter            |
|    reviewed in PRs        |----->|    operationIds, inline   |
|    (version control)      |      |    schemas, naming        |
+---------------------------+      +-------------+-------------+
                                                 |
                                                 v
+---------------------------+      +---------------------------+
| generator config          |      | 3. openapi generator      |
| (checked in: packages,    |----->|    pinned version         |
|  dates, nullability)      |      |    same output everywhere |
+---------------------------+      +-------------+-------------+
                                                 |
                                                 v
+-------------+-----------------------------+------------------+
| 4. generated/   (DO NOT EDIT - overwritten every run)        |
|     server interfaces               typed clients            |
+-------------+-----------------------------+------------------+
              ^ implements                  ^ wraps
+-------------+-----------------------------+------------------+
| 5. hand-written code: business logic, retries, auth, logging |
+------------------------------+-------------------------------+
                               |
                               v
+--------------------------------------------------------------+
| 6. CI: regenerate -> compile -> contract tests               |
|    spec change vs. old impl = compile error at call sites    |
|    contract tests: status codes, serialization details       |
|    (compiler is the enforcement point)                       |
+--------------------------------------------------------------+

A reviewed and linted spec feeds a pinned generator with checked-in config. Generated interfaces and clients land in a do-not-edit directory, hand-written code implements and wraps them, and CI regenerates and compiles so that any contract change fails the build at every affected call site.

How do you write an OpenAPI spec that generates clean code?

Generators translate the spec literally, so ambiguity in the spec turns into awkward or incorrect code. A few rules prevent most of it.

Give every operation a stable operationId. It becomes the method name on the client and the handler name on the server interface. Without one, generators derive names from the path and HTTP verb, producing names like getUsersByIdOrders. Renaming an operationId later is a breaking change for every caller, so choose it carefully the first time.

Name schemas under components/schemas. An inline request or response object has no name, so the generator invents one, such as InlineResponse200 or GetUser200Response. Those names are meaningless and can shift when the spec changes. A named schema like Order becomes a type of the same name that you can reuse and refer to in code reviews. The example below shows an inline response refactored this way.

Declare required explicitly, and keep it separate from nullability. Fields missing from required usually become optional (field?: T). Fields marked nullable become T | null. These are two different contracts. Mixing them up forces callers to check for both "absent" and "null" everywhere.

Keep naming consistent across files. Pick one casing convention for properties and schemas. Otherwise the generated code inherits the inconsistency.

Restrict composition. allOf maps cleanly to inheritance or intersection types. oneOf and anyOf do not map well to languages without union types. Generators often fall back to a wrapper object or an untyped map. If you need polymorphism, use oneOf with a discriminator whose propertyName is required in every variant. Avoid anyOf on payloads.

# BEFORE: inline response object, no operationId, no required list.
# Generators invent a type name (e.g. InlineResponse200) and make every field optional.
paths:
  /orders/{orderId}:
    get:
      responses:
        '200':
          description: The order
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string }
                  status: { type: string }
                  cancelledAt: { type: string, format: date-time }
---
# AFTER (OpenAPI 3.0.x): stable operationId, named schema, explicit required and nullable.
paths:
  /orders/{orderId}:
    get:
      operationId: getOrder          # becomes client method / server handler name
      responses:
        '200':
          description: The order
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Order'   # generated type is named Order
components:
  schemas:
    Order:
      type: object
      required: [id, status, cancelledAt]   # always present in the payload
      properties:
        id: { type: string }
        status: { type: string, enum: [pending, shipped, cancelled] }
        cancelledAt:
          type: string
          format: date-time
          nullable: true             # present but may be null -> T | null, not T?

An inline response object refactored into a named components schema with an operationId, an explicit required list, and a field that is required but nullable, so generators emit a reusable Order type instead of an InlineResponse200-style artifact.

How should you structure generated server stubs and typed clients in a codebase?

Treat generated code like a vendored dependency. Put it in its own directory or package, for example gen/ or api/generated/. Mark it as generated, and never edit it by hand, because the next run overwrites any edit.

Server stubs

Most server generators emit an interface or abstract class with one method per operation, plus routing glue that calls it. Your code implements that interface in a separate package. The benefit is that the compiler checks your work against the spec. If someone adds an operation or changes a parameter type, the build fails until a handler matches.

The cost is coupling. The stubs assume the generator's chosen framework, router, and request context. They may also expect their own way of wiring middleware or injecting dependencies. Check how they fit your existing auth middleware and DI container before adopting them. Generators that emit only interfaces and types, with no routing, are usually easier to fit in.

Typed clients

A generated client typically gives you:

  • request and response types
  • typed path, query, and header parameters
  • a hook for injecting auth headers or tokens

It usually does not encode your policies for timeouts, retries, or error handling. Add those in a thin hand-written wrapper that holds the generated client and exposes domain-level methods. Each wrapper method should:

  • set a deadline on the call
  • retry only idempotent operations
  • translate non-2xx responses into your own error types

The rest of the codebase depends on the wrapper. This keeps generator-specific names and signatures in one place, so regenerating or switching generators touches only that file.

// Assumed generator output in gen/ (names vary by generator; never edited by hand):
//   interface PetsApi { getPet(p: { petId: string }): Promise<Pet>; }
//   class PetsClient { getPet(p: { petId: string }, o?: { signal?: AbortSignal }):
//     Promise<{ status: number; data?: Pet }> }
import type { PetsApi, Pet } from "../gen/server";
import { PetsClient } from "../gen/client";

// Server: hand-written implementation. If the spec adds or changes an operation,
// this class no longer satisfies PetsApi and the build fails.
export class PetsHandler implements PetsApi {
  constructor(private repo: { find(id: string): Promise<Pet> }) {}
  async getPet({ petId }: { petId: string }): Promise<Pet> {
    return this.repo.find(petId);
  }
}

// Client: thin wrapper that owns timeout, retry, and error policy.
export class PetNotFound extends Error {}
export class PetServiceError extends Error {}

export class PetService {
  constructor(private client: PetsClient, private timeoutMs = 2000) {}

  // GET is idempotent, so retrying it is safe. Do not reuse this loop for POST.
  async getPet(petId: string, attempts = 3): Promise<Pet> {
    for (let i = 1; ; i++) {
      try {
        const res = await this.client.getPet(
          { petId }, { signal: AbortSignal.timeout(this.timeoutMs) });
        if (res.status === 200 && res.data) return res.data;
        if (res.status === 404) throw new PetNotFound(petId);
        if (res.status < 500 || i >= attempts) throw new PetServiceError(`status ${res.status}`);
      } catch (err) {
        // Only timeouts, network errors, and 5xx reach another attempt.
        if (err instanceof PetNotFound || i >= attempts) throw err;
      }
      await new Promise((r) => setTimeout(r, 100 * 2 ** i)); // exponential backoff
    }
  }
}

This example implements a generated server interface in hand-written code and wraps a generated client with a timeout, retries for idempotent calls only, and domain error types. The generated names PetsApi, PetsClient, and the response shape are assumptions, not exact generator output.

Should you commit generated code or generate it at build time?

Once generated code sits behind a wrapper, the next decision is where it lives. Both options work; they shift costs to different places.

Concern Commit generated code Generate at build time
Code review noise Spec changes produce large generated diffs alongside the spec diff Reviewers see only the spec and wrapper changes
Reproducibility What compiled is exactly what is in the repo Depends on the generator and config being pinned
Onboarding Clone and build; no generator needed New developers need the generator toolchain working first
Tooling on machines and CI Only CI needs the generator, to verify output Every developer machine and CI job needs it
Generator upgrade diffs Visible in the pull request Hidden unless you deliberately diff output

Commit generated code when consumers lack your toolchain, for example a client library used by other teams, or when the generator is slow or awkward to install. Generate at build time when the generator is easy to run everywhere and diff noise would bury real changes. Many teams commit the output and add a CI check that regenerates it and fails if the result differs from what is committed.

Either way, pin the generator version and its configuration file in the repository. You can run the generator through a container image referenced by digest, or declare it as a dev dependency managed by your package manager's lockfile. Without a pin, two machines can produce different code from the same spec.

Treat generator upgrades as their own pull request. Templates, naming rules, nullability handling, and default options change between releases, so output can shift even when the spec does not. Regenerate, read the diff, and run the contract tests before merging.

#!/usr/bin/env bash
# scripts/check-generated.sh
# Regenerates the client with a pinned generator and fails if the result
# differs from what is committed. Run it locally and as a CI job.
set -euo pipefail

# Pin by digest, not tag: a tag can be re-pointed, a digest cannot.
# Change this only in a dedicated "upgrade generator" pull request.
# Placeholder digest: replace with the real one for the version you adopt.
GENERATOR_IMAGE="openapitools/openapi-generator-cli@sha256:0000000000000000000000000000000000000000000000000000000000000000"

SPEC="api/openapi.yaml"
CONFIG="api/generator-config.yaml" # options are versioned with the spec
OUT="src/generated/client"

# Remove old output first so files the generator no longer emits show up as deletions.
rm -rf "$OUT"

# Run as the current user so generated files are not owned by root.
docker run --rm \
  --user "$(id -u):$(id -g)" \
  -v "$PWD:/local" \
  "$GENERATOR_IMAGE" generate \
  -i "/local/$SPEC" \
  -g typescript-fetch \
  -c "/local/$CONFIG" \
  -o "/local/$OUT"

# git diff misses new untracked files, so check porcelain status too.
if [ -n "$(git status --porcelain -- "$OUT")" ]; then
  echo "Generated code is out of date. Run scripts/check-generated.sh and commit the result." >&2
  git status --short -- "$OUT" >&2
  git diff --stat -- "$OUT" >&2
  exit 1
fi

echo "Generated code matches the spec, config and pinned generator."

A CI check for committed generated code. It runs the generator from a container image pinned by digest, uses a config file kept in the repository, and fails when the regenerated output differs from what is checked in.

How do you catch spec drift and breaking changes in CI?

Treat the spec as code with its own gates. Run them in order from cheapest to most expensive, so a malformed document fails in seconds and never reaches the slower steps.

Lint first. Style rules catch the problems that degrade generated code: missing operationIds, inline schemas that become anonymous types, inconsistent casing. These fail fast and need no running server.

Diff against main. Compare the branch's spec to the version on the main branch, for example by extracting it with git show origin/main:openapi.yaml. Fail the build on removed fields, narrowed or changed types, removed enum values, and parameters that became required. These are the changes that break existing clients. A reviewer reading YAML misses them easily.

Regenerate and compile. Run the generator, then build both the server and any in-repo clients. If a handler no longer matches its generated interface, compilation fails at that handler. If you commit generated code, add git diff --exit-code on the output directory so a stale commit fails too.

Run contract tests. Start the server and validate real responses against the document: status codes, error body shapes, and whether invalid input is rejected the way the spec says. Without this step, the spec only describes intent. Nothing checks that the server matches it.

An illustrative job outline, with tools as examples only:

  1. Lint the spec with a rule-based OpenAPI linter.
  2. Diff the spec against main with a breaking-change detector.
  3. Regenerate with openapi-generator, then build.
  4. Check generated output with git diff --exit-code.
  5. Boot the service and run schema-validating tests against it.

When should you avoid spec-first code generation, and what are the alternatives?

Spec-first pays off when several teams or languages consume a contract. In other cases, the overhead can cost more than it saves.

Early prototyping. If the API shape changes daily, every change means editing YAML, regenerating, and fixing call sites. Iterate in code first, then write the spec once the resource model settles.

Single-consumer internal endpoints. A contract with one known caller in the same repository adds a coordination layer that guards against nothing.

Weak generator output. Some language targets produce verbose, unidiomatic code with stack traces that are hard to read. Custom templates can fix this, but you then own a fork that must be kept in step with each generator upgrade.

Shared specs that grow too large. A monolithic spec makes every team wait on every other team's reviews. Splitting it into multiple files helps ownership, but $ref resolution across files, bundling steps, and uneven multi-file support across tools add their own failure modes.

Alternatives

Approach Source of truth Client typing Drift risk
Code-first, spec generated from annotations Server code Generated from the emitted spec Low for the server; clients drift if regeneration is skipped
Hand-written clients against a published spec Spec Manual High, because nothing enforces it
gRPC with Protocol Buffers .proto files Generated by protoc plugins Low; the wire format is bound to the schema
GraphQL with codegen Schema plus client queries Generated per query Low for validated queries; resolvers can still diverge

How does OpenAPI code generation affect development cost, and where do you start?

Most of the cost comes up front, and some of it recurs. Up front you write or extract the spec, wire generation and linting into CI, and learn the generator's options. After that you absorb output changes on every generator upgrade. Custom templates are the cost that grows quietly, because each upgrade means re-checking your overrides against upstream template changes.

The savings scale with the number of consumers. Every consumer stops hand-writing request and response models. Contract breaks show up as compile errors rather than integration bugs. New engineers learn the API from typed signatures instead of reading handler code.

Illustrative estimate (assumed numbers, not a benchmark)

Assumed inputs: 4 consumers, 30 endpoints, 0.5 hours per endpoint per consumer per year to hand-write and maintain models, and 60 hours per year of generation overhead for spec upkeep, CI, and upgrades.

  • Hand-written model cost = consumers × endpoints × hours per endpoint = 4 × 30 × 0.5 = 60 hours/year
  • Generation overhead = 60 hours/year

With these inputs, generation breaks even before you count the integration bugs it prevents. With one consumer the hand-written cost drops to 15 hours, so the case rests mostly on compile-time contract checking. Plug in your own numbers.

Where to start

  1. Extract or write a spec for one service whose contract changes often.
  2. Generate a client for one internal consumer and replace its hand-written models.
  3. Add spec linting and breaking-change diff checks to CI.
  4. Once the spec has stayed accurate through several releases, move the server onto generated interfaces.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to openapi code generation, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.