百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
T

typed-openapi

> 前端框架
开源

从 OpenAPI 规范生成无头 TypeScript API 客户端 - 可选地使用 @tanstack/react-query 客户端并配置 queryOptions

370 stars0 点赞0 次浏览
访问官网GitHub

工具介绍

从 OpenAPI 规范生成无头 TypeScript API 客户端 - 可选地使用 @tanstack/react-query 客户端并配置 queryOptions

typed-openapi

Generate a Typescript API client from an OpenAPI spec

See the documentation or try the online playground.

Features

  • Headless API client, bring your own fetcher (fetch, axios, ky, etc...) ! (You can generate that file with --default-fetcher — honors requestFormat for json / form-data / form-url / binary / text bodies)
  • Generates a fully typesafe API client with just types by default (instant suggestions)
  • Type-safe error handling: with discriminated unions and configurable success/error status codes
  • withResponse & throwOnStatusError: Get a union-style response object or throw on configured error status codes, with full type inference
  • TanStack Query integration: queryOptions, suspenseQueryOptions, infiniteQueryOptions (with pageParamKey), queryKeyFactory, and invalidate / invalidateEndpoint helpers — works with promise and Effect clients (Effect.runPromise when needed)
  • MSW mocks (--msw): request handlers + a typed method/path mock facade from schemas/examples; optional --msw-faker for @faker-js/faker
  • Auth from securitySchemes: default fetcher emits AuthCredentials + configureFetcher({ getAuth }) (apiKey / http / oauth2 / openIdConnect)
  • Closed objects by default: omitted 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).
  • Date / bigint transforms (--transform-dates, --transform-bigint): format: date-time|date → Date, format: int64 → bigint (types + runtime schema transforms; none-runtime revives ISO date strings)
  • Typed config: defineConfig + typed-openapi.config.ts (also JSON); auto-loaded when present
  • Or you can also generate a client with runtime validation using one of the following runtimes (first-party adapters):
    • zod v4 (--runtime zod) and v3 (--runtime zod3)
    • effect Schema v4 (--runtime effect) and v3 / @effect/schema (--runtime effect3)
    • valibot (--runtime valibot)
    • arktype (--runtime arktype)
    • TypeBox (--runtime typebox) and typia (--runtime typia)
  • Effect-native client (--client effect): methods return Effect with error channel TypedStatusError | HttpClientError (non-status failures remapped; original in cause)
  • Validate input and/or output (--validate-side) with optional onValidate hook
  • Coerce path/query/cookie/header primitives from strings (--coerce, default on when runtime ≠ none)
  • Cookie parameters, OAS defaults on runtime schemas, readOnly/writeOnly stripping (inlined objects; named $ref components stay shared — see stripReadWrite)
  • SSE (text/event-stream → ReadableStream; co-declared JSON is unioned into response types) and binary bodies/schemas (Blob)
  • Node-friendly FetcherResponse (no DOM Response dependency; avoids clash with OAS ApiResponse schemas) + request input types (InferSchemaInput / z.input / encoded)
  • Runtime type sidecar (default for runtime clients): emitted validators live in one module while their public types live in a sibling .types.d.ts file, keeping TypeScript responsive for large specs; opt out with --no-runtime-types
  • Filter endpoints/schemas (--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.

Install & usage

bash
pnpm add typed-openapi

It 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.

Config file (defineConfig)

typescript
// 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):

typescript
export default defineConfig({
  input: "./openapi.yaml",
  openapi: { additionalPropertiesDefault: true },
});

defaultFetcher can also be an object to customize the generated fetcher:

typescript
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:

typescript
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).

CLI

bash
npx typed-openapi -h
…

Non-goals

  • 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.

Usage Examples

API Client Setup

The generated client is headless - you need to provide your own fetcher. Here are ready-to-use examples:

  • Basic API Client - Simple, dependency-free wrapper
  • Validating API Client - With request/response validation

Or generate one with --default-fetcher (recommended).

Fetcher requestFormat contract

Fetcher.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).

Type-Safe Error Handling & Response Modes

You can choose between two response styles:

  • Direct data return (default):

    typescript
    const user = await api.get("/users/{id}", { path: { id: "123" } });
    // Throws TypedStatusError on error status (default)
  • Union-style response (withResponse):

    typescript
    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.

Generic Request Method

For dynamic endpoint calls or when you need more control:

typescript
// 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 endpoint

TanStack Query Integration

Generate TanStack Query wrappers for your endpoints with:

bash
npx typed-openapi api.yaml --tanstack

You get:

  • Type-safe queries and mutations with full error inference
  • queryOptions / suspenseQueryOptions for useQuery / useSuspenseQuery
  • infiniteQueryOptions({ initialPageParam, getNextPageParam, pageParamKey? }) for pagination
  • queryKeyFactory + invalidate / invalidateEndpoint / invalidateInfinite for cache control
  • withResponse and selectFn for advanced error and response handling
  • All mutation errors are Response-like and type-safe, matching your OpenAPI error schemas

MSW mocks

bash
npx typed-openapi api.yaml --msw
# optional: --msw-faker --msw-base-url https://api.example.com

Emits 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:

typescript
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.

Auth (securitySchemes)

With --default-fetcher, credentials from OAS components.securitySchemes are wired as:

typescript
import { configureFetcher } from "./api.client";

configureFetcher({
  getAuth: () => ({ petstore_auth: token, api_key: key }),
});

useQuery / fetchQuery / ensureQueryData

…

or if you need it in a router `before

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

TypeScriptarktypeeffectgeneratorio-ts

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类前端框架
定价开源

> 相关工具

R
React
用于构建用户界面的 JavaScript 库
V
Vue.js
渐进式 JavaScript 框架
N
Next.js
基于 React 的全栈 Web 框架