What is contract-first API development, and how does it differ from code-first?
In contract-first (also called API-first) development, the OpenAPI document is the first artifact you write. Teams review and merge it before anyone implements a handler, and both the server and its clients derive their types from that file. Code-first reverses the order. You write handlers, annotate them with decorators or comments, and a tool emits the spec from the running code. In that model the spec is a by-product, so it is only as accurate as the annotations.
The contract-first approach offers three practical advantages:
- One source of truth. Every type comes from the spec, so nobody hand-maintains a
Userinterface in each repo. - Drift becomes a compile error. If someone renames a field in the spec and regenerates, every handler and client call that uses the old name stops type-checking.
- Parallel work. Once the contract is merged, frontend, mobile and backend teams can build against it at the same time, using mocks until the server is ready.
openapi.yaml (reviewed in PR)
│
▼
generator
│
▼
generated types
┌──────────┬───────┴───────┬────────────┐
▼ ▼ ▼ ▼
server client runtime CI checks
handlers SDK validator (lint, diff)
Platform teams benefit most, along with APIs that have several consumers and organizations where different teams own each side of the API. Skip contract-first when one team owns both server and client in a single codebase, for throwaway prototypes, and during early exploration. At that stage, writing and reviewing the spec first can slow you down more than drift would hurt.
CONTRACT-FIRST
┌──────────────────────────┐
│ openapi.yaml │
│ written + reviewed in PR │
└────────────┬─────────────┘
▼
┌──────────────────────────┐
│ code generator │
└────────────┬─────────────┘
▼
┌──────────────────────────┐
│ generated TS types │
│ (request/response shapes)│
└────────────┬─────────────┘
┌─────────────────┬────────┴────────┬─────────────────┐
▼ ▼ ▼ ▼
┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ server │ │ client SDK │ │ runtime │ │ CI checks │
│ handlers │ │ (web, mobile)│ │ validator │ │ lint + diff │
│ implement ops│ │ typed calls │ │ checks bodies│ │ block drift │
└──────────────┘ └──────────────┘ └──────────────┘ └──────────────┘
Rename a field in the spec, regenerate: stale handlers and calls fail tsc.
Code-first contrast: handlers + annotations ──▶ emitter ──▶ spec (by-product)
In contract-first development the reviewed OpenAPI document feeds a generator whose types are shared by server handlers, client SDKs, runtime validation and CI checks, whereas code-first emits the spec as a by-product of annotated code.
How does contract-first code generation work?
The workflow is a loop with one input, the spec, and several outputs that all derive from it:
- Author and review the contract. A change to the API starts as a PR against
openapi.yaml. Reviewers discuss field names, required properties, status codes and error shapes before anyone writes implementation code. - Lint and bundle. A linter checks the document for structural errors and style rules. If the spec is split across files with
$ref, a bundling step resolves those references into a single document. - Generate types. The generator parses the bundled document and maps each schema to a TypeScript type: objects become interfaces,
requiredcontrols optional markers, enums become literal unions,oneOfbecomes a union andallOfan intersection. Operations are indexed by path, method andoperationId. With a type-only generator the output is a single declaration file and contains no runtime code. - Consume the types on both sides. Server handlers are annotated with the request and response types for their operation. Client code calls the API through a wrapper whose parameters and return values are derived from the same types.
- Validate at runtime from the same document. Because types are erased at compile time, a request validator built from the spec's JSON Schemas checks real payloads at the server boundary.
- Enforce in CI. CI regenerates the types, fails if the committed output differs, and compares the spec against the main branch to block breaking changes.
When the contract changes, you edit the spec, regenerate, and run tsc. The compiler then lists every handler and call site that no longer matches, and that list becomes the work for the change. The rest of this article covers each step in detail.
How should you structure an OpenAPI document so it generates good TypeScript types?
Treat the spec as source code that a compiler reads. Put every shared shape under components/schemas so it becomes a named type (components["schemas"]["Order"]) instead of an anonymous inline literal repeated per endpoint. Give every operation an operationId. Generated operation types are keyed by it, so a missing or unstable ID produces awkward names that break when someone renames a path.
Be explicit about presence. A property not listed in required becomes field?: T. Mark it nullable and it becomes T | null. These mean different things to a client (omitted versus deliberately cleared), so decide per field. A string enum becomes a literal union such as "pending" | "paid". Define one error schema and reference it from every 4xx/5xx response, so clients handle failures through a single type.
Some constructs don't map one-to-one:
| OpenAPI construct | Generated TypeScript | Caveat |
|---|---|---|
oneOf / anyOf |
Union A | B |
TypeScript can't express "exactly one" |
allOf |
Intersection A & B |
Conflicting properties collapse to never |
discriminator |
Union | Narrows only if each variant declares the tag as a single-value enum |
additionalProperties |
Index signature | Weakens checks on known keys |
format: date-time |
string |
No Date. Parse at the boundary |
format: int64 |
number |
Precision is lost above 2^53−1. Send large IDs as strings |
Authoring has real costs. YAML gets verbose, and reviewers struggle to read diffs of deeply nested schemas. Split the spec into files linked with $ref and add a bundling step that produces a single document for generation.
openapi: 3.1.0
info: { title: Orders API, version: 1.0.0 }
paths:
/orders/{orderId}:
get:
operationId: getOrder # TS: operations["getOrder"], stable across path renames
parameters:
- { name: orderId, in: path, required: true, schema: { type: string } }
responses:
"200":
description: The order
content:
application/json:
schema: { $ref: "#/components/schemas/Order" } # named type, not an inline literal
"404": { $ref: "#/components/responses/Error" } # every failure uses one shape
"500": { $ref: "#/components/responses/Error" }
components:
responses:
Error:
description: Any 4xx/5xx failure
content:
application/json:
schema: { $ref: "#/components/schemas/Error" }
schemas:
Order: # TS: components["schemas"]["Order"]
type: object
required: [id, status, createdAt, couponCode]
properties:
id: { type: string, description: int64 ID serialized as a string } # id: string, no precision loss
status: { type: string, enum: [pending, paid] } # status: "pending" | "paid"
createdAt: { type: string, format: date-time } # createdAt: string, parse to Date at the boundary
couponCode: { type: [string, "null"] } # required + nullable: couponCode: string | null (cleared)
note: { type: string } # not in required: note?: string (omitted)
Error:
type: object
required: [code, message]
properties:
code: { type: string } # code: string
message: { type: string } # message: string
An OpenAPI 3.1 spec fragment using a named Order schema, an operationId, explicit required fields, nullable versus optional properties, an enum, an int64 ID sent as a string, and a shared Error response, with comments showing the TypeScript each choice generates.
How does openapi-typescript code generation work?
Point openapi-typescript at that bundled document as a build step, for example npx openapi-typescript ./openapi.bundled.yaml -o ./src/api/schema.d.ts. The command parses the spec once and writes a single declaration file. Commit it or regenerate it in CI, but never edit it by hand.
The file exports three main interfaces:
pathsis keyed by URL template, then by HTTP method.componentsmirrorscomponents/schemas,parameters,responsesand the rest of that section.operationsis keyed byoperationId. This is why stable, meaningful operation IDs matter.
Navigating the output shape
Each operation follows a predictable structure:
- Responses:
paths['/orders/{id}']['get']['responses'][200]['content']['application/json']resolves to the response body type for that status code. - Parameters:
parametersholds separatepath,query,headerandcookieobjects. - Request body:
requestBodyhas the samecontentmap as a response.
Writing those index chains everywhere is noisy and fragile, so define a few generic helpers once:
RequestBody<P, M>indexes intorequestBody.content['application/json'].PathParams<P, M>andQueryParams<P, M>read fromparameters.pathandparameters.query.ResponseBody<P, M, S>takes a status code, so a 404 error shape stays distinct from the 200 success shape.
Constrain P to keyof paths and M to the methods that path defines. Then a typo in a route or method fails at compile time instead of at runtime.
Types only, no runtime code
The generated file contains no functions, classes or validators. It compiles away completely, adds nothing to your bundle and has no runtime dependency.
That is also its limit. These types describe what the contract promises, but they cannot check what actually arrives over the network. Runtime validation has to come from a separate layer.
// src/api/helpers.ts: generic helpers over the generated, type-only schema.d.ts
import type { paths } from "./schema";
type HttpMethod = "get" | "put" | "post" | "delete" | "options" | "head" | "patch" | "trace";
export type Path = keyof paths;
// Only methods the path actually defines. Undefined methods may be emitted as `?: never`.
export type Method<P extends Path> = {
[M in HttpMethod & keyof paths[P]]: [NonNullable<paths[P][M]>] extends [never] ? never : M;
}[HttpMethod & keyof paths[P]];
type Op<P extends Path, M extends Method<P>> = NonNullable<paths[P][M]>;
// JSON request body, or never if the operation takes none.
export type RequestBody<P extends Path, M extends Method<P>> =
Op<P, M> extends { requestBody?: { content: { "application/json": infer B } } } ? B : never;
export type PathParams<P extends Path, M extends Method<P>> =
Op<P, M> extends { parameters: { path?: infer T } } ? NonNullable<T> : never;
export type QueryParams<P extends Path, M extends Method<P>> =
Op<P, M> extends { parameters: { query?: infer T } } ? NonNullable<T> : never;
// Status is a type parameter, so a 404 error shape never merges with the 200 shape.
export type ResponseBody<
P extends Path,
M extends Method<P>,
S extends keyof Op<P, M>["responses"],
> = Op<P, M>["responses"][S] extends { content: { "application/json": infer B } } ? B : never;
// Usage: typos in the path, method or status fail at compile time.
type Order = ResponseBody<"/orders/{id}", "get", 200>;
type OrderNotFound = ResponseBody<"/orders/{id}", "get", 404>;
type OrderParams = PathParams<"/orders/{id}", "get">; // e.g. { id: string }
// type Bad = ResponseBody<"/order/{id}", "get", 200>; // error: not a key of paths
Generic helper types that index into the type-only output of openapi-typescript. They extract request bodies, path and query parameters, and per-status response bodies, and they reject unknown routes, methods or status codes at compile time.
How do you build a type-safe TypeScript client from the generated types?
Start with the client, where the generated types do the most work on their own. openapi-typescript emits a paths interface keyed by URL template, then by HTTP method. Each operation exposes parameters.path, parameters.query, requestBody and responses keyed by status code. A thin wrapper only needs two generic parameters: a path constrained to keyof paths and a method constrained to the keys of that path. From those, TypeScript derives everything else. Calling GET /orders/{orderId} without orderId fails to compile, as does a misspelled query parameter or a body that is missing a required field.
Responses need the most care. Map each status key to its application/json content type, then split them: 2xx statuses become { ok: true; data } and the rest become { ok: false; status; error }. Returning this discriminated result means callers must check ok before touching data, and the error payload type narrows to whatever the contract declares for that status. A blanket throw would lose that information.
The types stop at the boundary, so you write the glue yourself:
- Substituting and URL-encoding path parameters
- Serialising arrays and nested objects in query strings
- Setting headers and auth
- Choosing how to parse non-JSON or empty bodies, such as a 204
- Deciding what a network failure looks like
If you would rather not maintain this, openapi-fetch, from the same ecosystem, implements this pattern over the same paths type with a small runtime footprint.
import type { paths } from "./generated/api"; // emitted by openapi-typescript
const BASE_URL = "";
type Method = "get" | "post" | "put" | "patch" | "delete";
type Op<P extends keyof paths, M extends keyof paths[P]> = paths[P][M];
// Request side: path/query come from `parameters`, the body from `requestBody`
type Params<O> = O extends { parameters: infer X } ? X : {};
type Body<O> = O extends { requestBody: { content: { "application/json": infer B } } } ? { body: B } : {};
// Response side: one union member per declared status, 2xx => ok: true
type Json<R> = R extends { content: { "application/json": infer B } } ? B : undefined;
type Res<O> = O extends { responses: infer R } ? R : never;
type Result<O, R = Res<O>> = {
[S in keyof R]: `${S & (string | number)}` extends `2${string}`
? { ok: true; status: S; data: Json<R[S]> }
: { ok: false; status: S; error: Json<R[S]> };
}[keyof R];
export async function call<P extends keyof paths, M extends keyof paths[P] & Method>(
path: P, method: M, opts: Params<Op<P, M>> & Body<Op<P, M>>,
): Promise<Result<Op<P, M>>> {
// Types stop here; everything below is glue you own
const o = opts as { path?: Record<string, unknown>; query?: Record<string, unknown>; body?: unknown };
const url = new URL(String(path).replace(/\{(\w+)\}/g, (_, k) => encodeURIComponent(String(o.path?.[k]))), BASE_URL);
for (const [k, v] of Object.entries(o.query ?? {})) url.searchParams.set(k, String(v)); // arrays/objects: pick a style
const res = await fetch(url, { // network errors still reject: decide how to surface them
method: method.toUpperCase(),
headers: { "Content-Type": "application/json", Authorization: `Bearer ${process.env.API_TOKEN}` },
body: o.body === undefined ? undefined : JSON.stringify(o.body),
});
const payload = res.status === 204 ? undefined : await res.json(); // non-JSON bodies: your call
const out = res.ok ? { ok: true, status: res.status, data: payload } : { ok: false, status: res.status, error: payload };
return out as unknown as Result<Op<P, M>>;
}
// Omitting path.orderId or misspelling a query key is a compile error
const r = await call("/orders/{orderId}", "get", { path: { orderId: "ord_123" } });
if (r.ok) console.log(r.data); else console.error(r.status, r.error); // error type narrows by status
A thin fetch wrapper keyed by path and method that derives parameter, body and per-status response types from the openapi-typescript paths interface, returns a discriminated ok/error result, and marks the runtime glue that type-only generation leaves to you.
How do you type server handlers and validate requests at runtime?
On the server, the same paths type describes what each handler receives and returns. Annotate every handler with the operation's types, indexing into the path, method, and then the status code and media type for the response. A handler that returns a 200 body missing a required field, or a field with the wrong type, then fails to compile. If you rename a property in the spec and regenerate, every handler still using the old name breaks the build, which is the main payoff of contract-first.
That guarantee stops at compile time. TypeScript erases types, so at runtime the request body is whatever the client sent. A handler typed to receive { email: string } will still get { email: 42 } or an empty body if nothing checks it. Validate requests against the same spec, using either OpenAPI request-validation middleware or a JSON Schema validator compiled from the document's schemas. Reject failures with a 400 before your handler runs. For responses, run validation in your test suite rather than on every production request. Tests catch drift, such as a database column that is unexpectedly null, without adding that cost to each request.
The guarantees are only as strong as the weakest route. Enable strict in tsconfig, and consider noUncheckedIndexedAccess. Use typescript-eslint's no-explicit-any and consistent-type-assertions rules to ban any and as casts in handler code. A single cast, or a route left out of validation, removes the guarantee for that route without any error to tell you.
This adds a second tool and requires two checks against the same contract: types at build time and validation at runtime. You need both, because each covers a failure the other cannot.
How do you wire generation, linting and breaking-change checks into CI?
Add a generate script to package.json that runs openapi-typescript against the spec, and pin the generator to an exact version rather than a caret range. A minor release can change how unions, nullable fields or additionalProperties are emitted, and you want that change to arrive as its own reviewed commit, not mixed into an unrelated feature PR.
Next, decide where the generated file lives:
| Approach | Benefit | Cost |
|---|---|---|
| Commit generated types | Reviewers see the type impact; builds need no generator | Noisy diffs in review |
| Generate in CI only | Clean diffs | Builds depend on the generator; local types go stale |
If you commit the file, add a CI step that runs generate and then git diff --exit-code. The step fails when someone edited the spec without regenerating, or edited the output by hand.
Lint the spec on every PR, then diff it against main with an OpenAPI diff tool. Fail the build on breaking changes: removed fields, newly required parameters, and narrowed enums. Clients that were valid yesterday would reject or send invalid data after any of these.
Prefer additive changes. Mark a field deprecated: true before you remove it. For a published client package, bump the minor version for additive changes and the major version for breaking ones, so consumers' semver ranges decide when they pick up a break.
Illustrative estimate: assume a contract mismatch takes four engineer-hours to find in staging and ten minutes to fix when it shows up as a compile error in a PR. At two such bugs a month, that saves roughly eight hours a month.
How can contract-first code generation save engineering time?
The savings come from moving work earlier and removing work that is otherwise repeated in every consumer:
- No hand-maintained type copies. Without generation, each repo that calls the API keeps its own interfaces for requests and responses, and someone updates each copy when the API changes. With generation, a contract change becomes "edit the spec, regenerate, fix the compile errors" in each consumer.
- The compiler finds the impact of a change. After regenerating,
tsclists every handler and call site affected by a renamed field, a new required parameter or a changed enum. Engineers do not have to search the codebase or wait for an integration failure. - Fewer bugs found late. Mismatches that would otherwise appear in staging, in QA or as production errors fail the build in the PR that introduced them, where the author still has the context to fix them quickly.
- Less waiting between teams. Once the contract is merged, client teams build against generated types and mocks instead of waiting for a working server.
- Shorter API reviews and onboarding. Reviewers discuss a contract diff instead of reconstructing the API from handler code, and new engineers read one document to learn the API's shapes and error responses.
- Less glue code. Request validation comes from the same schemas, so you do not write per-route checks by hand.
Illustrative estimate: assume three consumer repos each hand-maintain types for the same API, and assume a field change takes about 30 minutes per repo to find the affected code, update the interface and verify it. That is about 90 minutes per change. With generation, assume a few minutes per repo to regenerate, plus time to fix whatever the compiler reports. At an assumed four such changes a month, hand-maintenance costs roughly six hours a month before counting any bugs that slip through. These inputs are assumptions. Substitute your own numbers for repo count, change frequency and time per update.
The savings are not free. Writing and reviewing the spec, setting up the pipeline and maintaining the client wrapper all take time up front. They pay off only when the contract has enough consumers and changes often enough to cover those costs.
When should you avoid contract-first code generation?
Contract-first generation is a poor fit in these situations:
- One team, one codebase, both ends. If the server and its only client live in the same TypeScript repository, they can import shared types directly. A spec and a generator add a translation layer without adding a consumer who benefits from it.
- Prototypes and early exploration. When the API shape changes several times a day, writing and reviewing the spec before each change slows you down more than drift would hurt. Write the contract once the shape stabilises.
- APIs that OpenAPI describes poorly. Long-lived connections, bidirectional messaging and APIs that are not request/response over HTTP do not fit the paths-and-operations model well. APIs that already have their own schema language, such as GraphQL or gRPC, should use that language's tooling instead.
- Heavily polymorphic payloads. If most of your schemas depend on deep
oneOf/allOfcombinations, open-endedadditionalPropertiesor formats that generate as plainstring, the generated types lose much of their precision. You pay for the pipeline but still need hand-written narrowing and runtime checks. - No one owns the spec. Contract-first only works if spec changes go through review and CI enforces regeneration and breaking-change checks. Without that discipline the spec goes stale, and stale types are worse than no types because they look trustworthy.
- Large existing APIs with no spec. Writing a complete contract by hand for a mature service is expensive. Emitting a spec from the existing code first, then switching to contract-first for new endpoints, is often more practical.
In these cases, prefer shared types inside one codebase, code-first spec emission, or the native tooling of the protocol you already use.
What are the alternatives to type-only OpenAPI generation?
Type-only generation is the narrowest option. Three other approaches move the contract boundary to different places, and each has its own costs.
| Approach | Generated code volume | Customisability | Runtime / HTTP client lock-in | Diff churn on spec change | Hand-written glue |
|---|---|---|---|---|---|
| Type-only generation | Small: one declarations file | High: you own fetch, retries, auth | None at runtime | Low, localised to changed types | Moderate: thin client wrapper, handler wiring |
| Full SDK/class generators | Large: models, API classes, serializers | Low: templates or post-processing | Generator's runtime and chosen HTTP library | High, often whole-file rewrites | Minimal for consumers |
| Server stub generators | Medium to large: routes, controllers, interfaces | Medium: you fill generated stubs | Tied to the target framework | Medium; regeneration can clash with edits | Business logic only |
| Code-first spec emission | None; spec is output | High in code, low in spec shape | Tied to the framework's decorators or schemas | Spec diffs follow refactors, sometimes unintentionally | Annotations on every route |
Full SDK generators make sense when external consumers work in several languages and expect an installable package. In that case the churn and lock-in fall on the vendor, not on each customer. Server stubs help when a team starts a new service from an agreed spec and the framework will not change. Code-first emission works for a single team that owns both ends. The risk is that a refactor can quietly change the public contract, so the breaking-change check from CI becomes mandatory. For internal TypeScript services, type-only generation keeps runtime dependencies at zero and keeps reviews readable.
The trade-off is about when you pay. Contract-first costs more up front: you write the spec, review it, and set up the pipeline. It pays off as the number of consumers and teams grows, because each new client starts from a contract that is already checked.
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 typescript, 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.
- Changing a shared variable is one edit and one review instead of editing every service's
.envby hand.
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.
- A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
- 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.