Generate a headless Typescript API client from an OpenAPI spec - optionally with a @tanstack/react-query client using queryOptions
Generate a headless Typescript API client from an OpenAPI spec - optionally with a @tanstack/react-query client using queryOptions
Generate a Typescript API client from an OpenAPI spec
See the documentation or try the online playground.
--default-fetcher — honors requestFormat for json /
form-data / form-url / binary / text bodies)queryOptions, suspenseQueryOptions, infiniteQueryOptions (with pageParamKey),
queryKeyFactory, and invalidate / invalidateEndpoint helpers — works with promise and Effect clients
(Effect.runPromise when needed)--msw): request handlers + a typed method/path mock facade from schemas/examples; optional --msw-faker for
@faker-js/fakersecuritySchemes: default fetcher emits AuthCredentials + configureFetcher({ getAuth }) (apiKey /
http / oauth2 / openIdConnect)additionalProperties is treated as false
so generated types and validators don't silently accept unknown keys. Opt into the
OpenAPI/JSON Schema default with --openapi-additional-properties-default /
openapi: { additionalPropertiesDefault: true }. Closed allOf members compose
(combined keys are accepted; unknown keys are rejected).--transform-dates, --transform-bigint): format: date-time|date → Date,
format: int64 → bigint (types + runtime schema transforms; none-runtime revives ISO date strings)defineConfig + typed-openapi.config.ts (also JSON); auto-loaded when present--client effect): methods return Effect with error channel
TypedStatusError | HttpClientError (non-status failures remapped; original in cause)--validate-side) with optional onValidate hook--coerce, default on when runtime ≠ none)$ref components stay shared — see stripReadWrite)text/event-stream → ReadableStream; co-declared JSON is unioned into response types) and binary
bodies/schemas (Blob)FetcherResponse (no DOM Response dependency; avoids clash with OAS ApiResponse schemas) +
request input types (InferSchemaInput / z.input / encoded).types.d.ts file, keeping TypeScript responsive for large specs; opt out with --no-runtime-types--endpoint / --schema, or endpointPatterns / schemaPatterns in config) and control
naming (--schema-naming)The main generated client is one file that can be used in the browser or in node. When a runtime is selected, a sibling
.types.d.ts sidecar is emitted by default so TypeScript stays responsive for large specs. Keep the sidecar with the
runtime module when committing, publishing, or copying generated output. Use --no-runtime-types when you need a single
checked file instead. Runtime schemas are emitted by typed-openapi's own Schema IR + runtime adapters (no Sinclair codegen).
Use --validation loose|formats|strict (or a fine-grained policy object) to control how deep OpenAPI constraints
(format, minLength, …) are applied. Install only the runtime selected for your generated client as a dependency in your
app.
With --runtime effect / effect3, the default API client is Effect-native (--client effect); other runtimes default
to the promise ApiClient. Install effect whenever you use --client effect and/or --runtime effect. Use
--runtime effect3 (+ @effect/schema) if you need the Effect Schema v3 adapter.
HTTP(S) OpenAPI inputs are supported; use --input-dir to choose where the default output file is written.
pnpm add typed-openapiIt exports a bunch of functions that can be used to build your own tooling on top of it. You can look at the CLI code so see how to use them.
defineConfig)// typed-openapi.config.ts
import { defineConfig } from "typed-openapi";
export default defineConfig({
// input: "./openapi.yaml", // optional — CLI positional still preferred when passed
output: "./src/api/client.ts",
runtime: "zod",
validation: "strict",
validateSide: "both",
defaultFetcher: true,
tanstack: "query.ts",
msw: "msw.ts",
transformDates: true,
format: true,
});Objects are closed when additionalProperties is omitted. Set openapi.additionalPropertiesDefault: true to follow the OpenAPI default (true when omitted):
export default defineConfig({
input: "./openapi.yaml",
openapi: { additionalPropertiesDefault: true },
});defaultFetcher can also be an object to customize the generated fetcher:
export default defineConfig({
input: "./openapi.yaml",
output: "./src/api/openapi.ts",
defaultFetcher: {
clientPath: "./openapi.ts",
envApiBaseUrl: "VITE_API_URL",
fetcherName: "fetchApi",
apiName: "api",
},
});Use a fine-grained validation policy when a preset needs an exception:
export default defineConfig({
input: "./openapi.yaml",
runtime: "zod",
validation: { preset: "strict", stringConstraints: false, numberConstraints: false },
});JSON (typed-openapi.config.json) still works. The CLI auto-loads typed-openapi.config.ts, .mts, .js, .mjs,
.json, .typed-openapi.json, or typed-openapi.json from the cwd. typed-openapi.config.ts is loaded via tsx
(shipped as a dependency).
npx typed-openapi -h…Shipping every historical runtime (yup / io-ts). TypeBox and Typia are available again via --runtime typebox /
--runtime typia; the adapter contract makes further runtimes easy to add. Primary focus remains zod, effect,
valibot, and arktype.
Being a full JSON Schema validator suite for exotic media types. Constraints (format, bounds, patterns, …) are
supported via --validation, but the priority remains a fast, typesafe API client.
Splitting the generated client into multiple files. Nope. Been there, done that. Let's keep it simple.
Basically, let's focus on having a fast and typesafe API client generation instead.
The generated client is headless - you need to provide your own fetcher. Here are ready-to-use examples:
Or generate one with --default-fetcher (recommended).
requestFormat contractFetcher.fetch receives requestFormat so the body can be encoded from the OpenAPI requestBody content type. Missing
entries in endpointRequestFormats default to "json".
requestFormat |
Body encoding (default fetcher) |
|---|---|
json |
JSON.stringify + application/json |
form-data |
FormData (let fetch set the multipart boundary) |
form-url |
URLSearchParams + application/x-www-form-urlencoded |
binary |
raw Blob / ArrayBuffer / Uint8Array / string + application/octet-stream |
text |
String(body) + text/plain |
Custom fetchers should honor the same table (or document if they only support JSON).
You can choose between two response styles:
Direct data return (default):
const user = await api.get("/users/{id}", { path: { id: "123" } });
// Throws TypedStatusError on error status (default)Union-style response (withResponse):
const result = await api.get("/users/{id}", { path: { id: "123" }, withResponse: true });
if (result.ok) {
// result.data is typed as User
} else {
// result.data is typed as your error schema for that status
}You can also control error throwing with throwOnStatusError.
All errors thrown by the client are instances of TypedStatusError and include the parsed error data.
For dynamic endpoint calls or when you need more control:
// Type-safe generic request method
const response = await api.request("GET", "/users/{id}", {
path: { id: "123" },
query: { include: ["profile", "settings"] },
});
const user = await response.json(); // Fully typed based on endpointGenerate TanStack Query wrappers for your endpoints with:
npx typed-openapi api.yaml --tanstackYou get:
queryOptions / suspenseQueryOptions for useQuery / useSuspenseQueryinfiniteQueryOptions({ initialPageParam, getNextPageParam, pageParamKey? }) for paginationqueryKeyFactory + invalidate / invalidateEndpoint / invalidateInfinite for cache controlwithResponse and selectFn for advanced error and response handlingnpx typed-openapi api.yaml --msw
# optional: --msw-faker --msw-base-url https://api.example.comEmits msw.handlers.ts with the standard handlers array plus a typed mock facade. Resolve a response or create an
overrideable handler by OpenAPI method/path, without one top-level export per endpoint:
import { HttpResponse } from "msw";
import { handlers, mock } from "./msw.handlers";
const pet = mock.get("/pet/{petId}").response();
const customPetHandler = mock.get("/pet/{petId}").handler(() => HttpResponse.json(pet));
server.use(...handlers, customPetHandler);Responses use schema examples/defaults (or faker with --msw-faker), and the generated MswPath / MswResponse types
keep method/path and response inference aligned with the OpenAPI document.
securitySchemes)With --default-fetcher, credentials from OAS components.securitySchemes are wired as:
import { configureFetcher } from "./api.client";
configureFetcher({
getAuth: () => ({ petstore_auth: token, api_key: key }),
});…or if you need it in a router `before
No open issues yet, or sync has not completed.