Generate TypeScript API Clients From OpenAPI
Stop maintaining API types by hand. Use OpenAPI to generate TypeScript clients, catch contract drift in CI, and keep frontend requests consistent.
A backend team renames a response field, updates the API documentation, and deploys. The frontend still compiles because its handwritten interface describes yesterday’s response. A user opens a screen and sees missing data—or a request fails in a way that only appears in production. This kind of contract drift is easy to miss when API shapes are repeated manually across documentation, client code, and UI types.
If a service already publishes an OpenAPI specification, the frontend should not independently re-create its request and response types. Generate a client from the contract, then make changes to that contract visible in the build process. This does not eliminate every integration bug, but it removes a common source of silent disagreement between teams.
What generation solves—and what it does not
OpenAPI describes endpoints, parameters, request bodies, response schemas, and—when maintained well—error responses. A generator can turn that description into TypeScript types and request functions. The important benefit is not fewer lines of code; it is one source of truth for the API contract.
Generation is useful when several frontend features consume the same service, when an API changes frequently, or when multiple teams need to agree on payload shapes. It is less valuable for a tiny, stable integration if introducing a generator costs more than maintaining a small client. The specification must also be accurate: generated code faithfully reproduces an incorrect or incomplete contract.
- The specification describes the contract; generated files are its output, not a second place to make edits.
- A generated client can verify compile-time shapes, but it cannot prove that a live server returns valid data.
- Authentication, retries, caching, and UI behavior still need deliberate ownership outside generated endpoint code.
Keep generated code at the boundary
Treat generated functions as infrastructure. Components should not need to know whether an endpoint was generated, how its URL is assembled, or how the transport handles headers. Put a small application-facing layer between the generated client and React. That layer can map wire-format responses into the shapes the UI needs, centralize error handling, and keep feature code independent of generator conventions.
import { client } from "./generated/client";
export async function getAccount(accountId: string) {
const { data, error } = await client.GET("/accounts/{accountId}", {
params: { path: { accountId } },
});
if (error) throw new Error("Account request failed");
return data;
}The exact call depends on the generator and the specification. The architectural point is the boundary: a feature calls a named application function, while generated transport details stay in one place. This complements the separation described in keeping API clients out of React components.
Make contract drift fail visibly
A generated client only helps when it is kept in sync with its source. Choose a workflow and enforce it. A common approach is to commit generated files and make CI regenerate them, then fail if the working tree changes. Another is to generate them during every build from a versioned specification. Either way, developers should not have to remember to refresh types after an API update.
- Obtain the authoritative OpenAPI document from the API team or a versioned build artifact.
- Run the same pinned generator version locally and in CI.
- Fail the check when generated output differs from what is committed.
- Review specification changes and generated diffs together, especially for renamed or removed fields.
npm run api:generate
git diff --exit-code -- src/api/generatedThat check catches a stale generated client, not a server that violates its published contract. Add integration or consumer-driven checks for important endpoints, and test critical UI states against realistic responses. For the runtime boundary, the advice in TypeScript runtime validation still applies: network data remains untrusted even when its TypeScript type was generated.
Decide what belongs in the specification
Some specification gaps create awkward or unsafe client code. If an endpoint can return several statuses, document the response for each status rather than describing only success. Mark optional and nullable fields accurately; they mean different things in TypeScript. Use stable operation identifiers and schemas, and avoid broad, ambiguous response types that force consumers to guess.
| Contract detail | Why the frontend cares |
|---|---|
| Required versus optional | Determines whether code can rely on a field being present. |
| Nullable versus absent | Separates an explicit empty value from a field that was not sent. |
| Error response schemas | Lets application code handle known failures without parsing arbitrary text. |
| Stable operation names | Makes generated functions easier to find and less fragile across revisions. |
Do not treat every generated type as a perfect domain model. API payloads reflect transport and compatibility decisions; UI models may need clearer names, defaults, or derived fields. Translate between them intentionally where the application needs a different shape, rather than altering generated output by hand.
A practical adoption checklist
- Start with one actively changing service or feature, not every endpoint in the product.
- Confirm who owns the specification and how frontend developers get its latest version.
- Pin the generator and its configuration so different machines produce the same output.
- Keep generated files separate from application code and prohibit manual edits to them.
- Add CI checks for drift and tests for the server behavior that types cannot verify.
- Review generated diffs for breaking changes instead of treating regeneration as a routine chore.
Generated clients work best as a contract-enforcement tool, not a substitute for collaboration. Agree on how breaking changes are announced, how long old fields remain available, and which team resolves a mismatch. When those responsibilities are clear, the frontend can adopt API changes deliberately instead of discovering them through user-visible failures.
For teams building complex React applications, WebMriya can help establish this boundary as part of complex application development—from the API contract and generated client to the feature-level code that consumes it.
Frequently asked questions
Does an OpenAPI-generated client replace runtime validation?
No. Generated TypeScript types help check your code at compile time, but they cannot verify what a server actually sends while the application is running. Validate data at runtime when the boundary or the consequences of invalid data warrant it.
Should generated client files be committed?
Either committing them and checking for drift in CI or generating them from a versioned specification during builds can work. Choose one consistent workflow, pin the generator, and make stale output visible.
Can React components call generated functions directly?
They can, but a small application-facing API layer usually scales better. It keeps generated transport details, error handling, and response mapping out of UI components.