+ Both generators run on the same machine, with the same OpenAPI documents and the same
+ options, in separate Node.js processes. The{' '}
+
+ original swagger-typescript-api
+ {' '}
+ is the project this library is based on.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ All results
+
+
+ Ratio = time of the original ÷ time of {es.name}. Memory is the peak resident set size of
+ the cold-run process.
+
+
+
+
+
+
+
+
+
+ How it is measured
+
+
+
+ Same input: each run parses the document from JSON
+ and passes it as spec,
+ with output: false{' '}
+ (no disk writes) and silent: true.
+
+
+ Same options for both libraries: {optionList}.
+
+
+ Generation: one process per library and scenario, one
+ warm-up generation, then the median of {report.settings.warmRuns} generations.
+
+
+ Cold run: a new process per run that imports the
+ library and generates once (what a single CLI run costs), median of {report.settings.coldRuns} runs.
+
+
+ Versions: {es.name} is measured from the repository
+ {report.commit ? ` at commit ${report.commit}` : ''} (including changes not published to npm
+ yet), the original is the latest npm release, v{original.version}.
+
+
+ Isolation: every measurement is a separate Node.js
+ process, and the libraries alternate which one runs first.
+
+
+ Formatting is included, because both generators format
+ their output: {es.name} with oxfmt, the original with Biome (WebAssembly).
+
+
+
+
Keep in mind
+
+
+ The medium and large documents are synthetic (objects with enums, arrays, $refs,{' '}
+ oneOf and nullable fields, spread over tags).
+ Real documents have other shapes, so try yours in the{' '}
+
+ playground
+ {' '}
+ or run the benchmark with them.
+
+
+ The generated code is similar but not identical (different templates and formatters),
+ which is why the output sizes differ. In modular mode each module file of {es.name}{' '}
+ imports every data contract, so its modular output is bigger.
+
+
These numbers come from one machine; absolute times depend on the hardware.
+
+
+
+
+
+
+
+
+ Run it yourself
+
+
+ The benchmark lives in the repository (bench/compare).
+ It installs the original library in its own folder, runs every scenario and writes the
+ results shown on this page.
+
+
+
+ Read the docs
+
+
+
+
+ >
+ );
+}
diff --git a/docs/app/docs/page.tsx b/docs/app/docs/page.tsx
index d582c7e..43b8036 100644
--- a/docs/app/docs/page.tsx
+++ b/docs/app/docs/page.tsx
@@ -1,4 +1,4 @@
-import { ArrowRight, FlaskConical } from 'lucide-react';
+import { ArrowRight, Code2, FlaskConical } from 'lucide-react';
import type { Metadata } from 'next';
import Link from 'next/link';
import { MarkdownAsync } from 'react-markdown';
@@ -53,6 +53,12 @@ export default async function DocsPage() {
>
Try it in the playground
+
+ Using the generated client
+
+
+
+ Next: using the generated client
+
+
+ Install the AI agent skill
+
+
{/* Features */}
diff --git a/docs/app/skills/_lib/skill.ts b/docs/app/skills/_lib/skill.ts
new file mode 100644
index 0000000..2670212
--- /dev/null
+++ b/docs/app/skills/_lib/skill.ts
@@ -0,0 +1,83 @@
+import 'server-only';
+
+import { readdirSync, readFileSync, statSync } from 'node:fs';
+import path from 'node:path';
+
+import { findRepoFile } from '@/components/repo-files';
+
+export const SKILL_NAME = 'swagger-typescript-api-es';
+/** folder of the skill, relative to the repository root */
+export const SKILL_DIR = `skills/${SKILL_NAME}`;
+
+export interface SkillFile {
+ /** path relative to the skill folder, with `/` separators */
+ path: string;
+ lines: number;
+ bytes: number;
+ /** first markdown heading, if any */
+ heading: string | null;
+}
+
+export interface SkillInfo {
+ name: string;
+ description: string;
+ version: string | null;
+ files: SkillFile[];
+ /** SKILL.md without its front matter */
+ body: string;
+}
+
+function parseFrontMatter(text: string): { data: Record; body: string } {
+ const match = /^---\n([\s\S]*?)\n---\n?/.exec(text);
+ if (!match) return { data: {}, body: text };
+ const data: Record = {};
+ for (const line of match[1].split('\n')) {
+ const field = /^\s*([\w-]+):\s*(.*)$/.exec(line);
+ if (field && field[2]) data[field[1]] = field[2].replace(/^['"]|['"]$/g, '').trim();
+ }
+ return { data, body: text.slice(match[0].length) };
+}
+
+function walk(dir: string, base = ''): string[] {
+ const entries = readdirSync(/*turbopackIgnore: true*/ dir, { withFileTypes: true }).sort((a, b) => {
+ // files of a folder first (SKILL.md on top), then sub folders
+ if (a.isDirectory() !== b.isDirectory()) return a.isDirectory() ? 1 : -1;
+ return a.name.localeCompare(b.name);
+ });
+ const files: string[] = [];
+ for (const entry of entries) {
+ if (entry.name.startsWith('.')) continue;
+ const relative = base ? `${base}/${entry.name}` : entry.name;
+ if (entry.isDirectory()) files.push(...walk(path.join(/*turbopackIgnore: true*/ dir, entry.name), relative));
+ else if (entry.isFile()) files.push(relative);
+ }
+ return files;
+}
+
+/** Reads the skill folder at build time, so the page always lists its current files. */
+export function loadSkill(): SkillInfo | null {
+ const skillFile = findRepoFile(`${SKILL_DIR}/SKILL.md`, `name: ${SKILL_NAME}`);
+ if (!skillFile) return null;
+ const dir = path.dirname(skillFile);
+ const { data, body } = parseFrontMatter(readFileSync(/*turbopackIgnore: true*/ skillFile, 'utf8').replace(/\r\n/g, '\n'));
+
+ const files = walk(dir).map((relative): SkillFile => {
+ const absolute = path.join(/*turbopackIgnore: true*/ dir, relative);
+ const text = readFileSync(/*turbopackIgnore: true*/ absolute, 'utf8');
+ const heading = /^#{1,3} (.+)$/m.exec(relative === 'SKILL.md' ? body : text)?.[1]?.trim() ?? null;
+ return {
+ path: relative,
+ lines: text.split('\n').length - (text.endsWith('\n') ? 1 : 0),
+ bytes: statSync(/*turbopackIgnore: true*/ absolute).size,
+ heading,
+ };
+ });
+
+ return {
+ name: data.name ?? SKILL_NAME,
+ description: data.description ?? '',
+ version: data.version ?? null,
+ files,
+ body,
+ };
+}
diff --git a/docs/app/skills/page.tsx b/docs/app/skills/page.tsx
new file mode 100644
index 0000000..8623361
--- /dev/null
+++ b/docs/app/skills/page.tsx
@@ -0,0 +1,360 @@
+import {
+ AlertTriangle,
+ ArrowRight,
+ Braces,
+ ChevronRight,
+ FileCode2,
+ FileText,
+ Folder,
+ Plug,
+ Puzzle,
+ Rocket,
+ SlidersHorizontal,
+ Terminal,
+ type LucideIcon,
+} from 'lucide-react';
+import type { Metadata } from 'next';
+import Link from 'next/link';
+import type { Components } from 'react-markdown';
+import { MarkdownAsync } from 'react-markdown';
+import remarkGfm from 'remark-gfm';
+
+import { markdownComponents } from '@/app/docs/_lib/markdown-components';
+import { rehypeShiki } from '@/app/docs/_lib/rehype';
+import { CodeBlock } from '@/components/code-block';
+import { CopyButton } from '@/components/copy-button';
+import { GithubIcon } from '@/components/icons';
+import { site } from '@/components/site-config';
+import { SiteFooter } from '@/components/site-footer';
+
+import { loadSkill, SKILL_DIR } from './_lib/skill';
+
+export const dynamic = 'force-static';
+
+export const metadata: Metadata = {
+ title: 'AI agent skill',
+ description: `An agent skill for Claude Code and other coding agents: teach your agent to set up ${site.name}, write its config, pick options and use the generated client.`,
+ openGraph: { title: `AI agent skill · ${site.name}` },
+};
+
+/** exactly the command of the README "AI agent skill" section */
+const INSTALL_COMMAND = 'npx skills add hunghg255/swagger-typescript-api-es';
+
+const skillUrl = `${site.repo}/tree/main/${SKILL_DIR}`;
+const fileUrl = (file: string) => `${site.repo}/blob/main/${SKILL_DIR}/${file}`;
+
+const TOPICS: { icon: LucideIcon; title: string; body: string }[] = [
+ { icon: Rocket, title: 'Setup', body: 'Installing the package, Node.js and ESM requirements, the first generation.' },
+ { icon: Terminal, title: 'CLI and config file', body: 'Flags, swagger-typescript-api.config.ts, arrays of configs and precedence.' },
+ { icon: SlidersHorizontal, title: 'Options', body: 'Every generator option: input, output, client, types, extraction, naming.' },
+ { icon: Puzzle, title: 'Hooks', body: 'Renaming types and routes, changing parsed schemas and route data.' },
+ { icon: FileCode2, title: 'Templates', body: 'Copying the built-in Eta templates and overriding parts of the output.' },
+ { icon: Plug, title: 'The generated client', body: 'Creating the client, auth, errors, modular output and shared HttpClients.' },
+ { icon: AlertTriangle, title: 'Gotchas', body: 'The mistakes agents (and people) make, with the right fix for each.' },
+];
+
+const PROMPTS = [
+ 'Set up swagger-typescript-api-es in this project: generate an axios client from http://localhost:3000/api-json into src/api and add a gen-api script.',
+ 'Our spec is ./openapi.yaml. Generate a modular fetch client where every module shares one HttpClient.',
+ 'Send a bearer token with every request of the generated client and refresh it when it expires.',
+ 'Rename every generated type so that it ends with Dto, and keep the enums as union types.',
+ 'Methods return the whole response; make them resolve with the data directly and update the callers.',
+ 'Wrap the generated pets endpoints in React Query hooks, with request cancellation.',
+];
+
+const STEPS = [
+ {
+ title: 'Discovery',
+ body: 'At startup the agent only reads the name and description of each installed skill.',
+ },
+ {
+ title: 'Activation',
+ body: 'When your request matches the description, the agent reads SKILL.md: the workflow and rules.',
+ },
+ {
+ title: 'Details on demand',
+ body: 'Reference files (the full options list, patterns, …) are opened only when the task needs them.',
+ },
+];
+
+function Code({ children }: { children: React.ReactNode }) {
+ return {children};
+}
+
+function SectionHeading({ id, children }: { id: string; children: React.ReactNode }) {
+ return (
+
+ {children}
+
+ );
+}
+
+function formatSize(bytes: number) {
+ return bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} KB`;
+}
+
+/** SKILL.md preview: headings are demoted below the page's h2 and relative links point to GitHub */
+const previewComponents: Components = {
+ ...markdownComponents,
+ h1: ({ children }) =>
+ The repository ships an agent skill: a folder of instructions that Claude Code and other coding agents load
+ when you ask them to generate or use an API client. With it, the agent knows the CLI flags, the config
+ file, every option and the usual pitfalls, instead of guessing from the original swagger-typescript-api.
+
+ A skill is a folder with a SKILL.md file: a short front matter (a name and a description
+ of when to use it) followed by instructions in Markdown, plus optional reference files. Coding agents
+ such as Claude Code load skills from .claude/skills/ in your project or{' '}
+ ~/.claude/skills/ in your home folder.
+
+
+ Skills are loaded progressively, so an installed skill costs almost nothing until it is needed:
+
+
+ {STEPS.map((step, index) => (
+
+
+ {index + 1}
+
+
{step.title}
+
{step.body}
+
+ ))}
+
+
+ {skill?.description ? (
+
+ ) : null}
+
+
+
+
+ What it covers
+
+ {TOPICS.map(({ icon: Icon, title, body }) => (
+
+
+
+
+
{title}
+
{body}
+
+ ))}
+
+
The same ground as the human docs, written for an agent.
+
+ Read the docs
+
+
+
+
+
+
+ Install
+
With the skills CLI
+
+ Installs the skill of this repository with npx, nothing to add to your dependencies:
+
+
+
+
Manually
+
+ Copy the {SKILL_DIR} folder into a skills folder. In the project, the skill is shared with
+ everyone who clones it; in your home folder, it is available in all your projects.
+
+
+
+ Start a new agent session afterwards: skills are discovered when the session starts. Update the skill the
+ same way when a new version of the library is released.
+
+
+
+
+ Example prompts
+
+ No special syntax: ask for what you want and the agent loads the skill when the request is about
+ generating or using the client.
+
+
+ {PROMPTS.map((prompt) => (
+
+
+
{prompt}
+
+
+ ))}
+
+
+
+
+ What's inside
+ {skill ? (
+ <>
+
+ The files of {SKILL_DIR}, read when this site was built.
+
+
+ Using the generated client
+
+
+ Read the docs
+
+
+
+
+ >
+ );
+}
diff --git a/docs/app/usage/_lib/snippets.ts b/docs/app/usage/_lib/snippets.ts
new file mode 100644
index 0000000..03d1870
--- /dev/null
+++ b/docs/app/usage/_lib/snippets.ts
@@ -0,0 +1,634 @@
+/**
+ * Code examples of the /usage page.
+ *
+ * Every TypeScript snippet is type-checked (strict mode) against a client generated from
+ * `tests/fixtures/petstore.json` with the options of its `client` variant:
+ *
+ * - `fetch` default options
+ * - `axios` `httpClientType: 'axios'`
+ * - `single` `singleHttpClient: true`
+ * - `modular` `modular: true`
+ * - `modularSingle` `modular: true, singleHttpClient: true`
+ * - `unwrap` `unwrapResponseData: true`
+ * - `noThrow` `disableThrowOnError: true`
+ * - `routeTypes` `generateRouteTypes: true`
+ * - `config` checked against the library's own types
+ *
+ * The generated client is at `./api/` next to the snippet; `./api-client` exports `api`
+ * (a `new Api()`). `prelude` lines are prepended when checking and are not shown.
+ * Keep method names in sync with the fixture (`api.pets.listPets`, `api.pets.getPet`, ...).
+ */
+export type SnippetClient =
+ | 'fetch'
+ | 'axios'
+ | 'single'
+ | 'modular'
+ | 'modularSingle'
+ | 'unwrap'
+ | 'noThrow'
+ | 'routeTypes'
+ | 'config';
+
+export interface Snippet {
+ code: string;
+ lang: 'ts' | 'tsx' | 'bash';
+ /** file name shown above the code */
+ title?: string;
+ /** generated client the snippet is checked against (`null`: not type-checked, e.g. shell) */
+ client: SnippetClient | null;
+ /** hidden code prepended when type-checking */
+ prelude?: string;
+}
+
+const API = `import { api } from './api-client';\n`;
+
+export const SNIPPETS = {
+ generateCli: {
+ lang: 'bash',
+ title: 'Terminal',
+ client: null,
+ code: `npm i -D swagger-typescript-api-es
+
+# fetch client (default): writes src/api/Api.ts
+npx swagger-typescript-api-es -u ./openapi.json -o ./src/api
+
+# axios client (install axios in your app)
+npm i axios
+npx swagger-typescript-api-es -u ./openapi.json -o ./src/api --httpClientType axios`,
+ },
+
+ generateConfig: {
+ lang: 'ts',
+ title: 'swagger-typescript-api.config.ts',
+ client: 'config',
+ code: `import { defaultConfig } from 'swagger-typescript-api-es';
+
+export default defaultConfig({
+ input: './openapi.json', // or url: 'https://api.example.com/openapi.json'
+ output: './src/api',
+ name: 'Api.ts',
+ httpClientType: 'fetch', // or 'axios'
+});`,
+ },
+
+ fetchCreate: {
+ lang: 'ts',
+ title: 'src/api-client.ts',
+ client: 'fetch',
+ code: `import { Api } from './api/Api';
+
+export const api = new Api({
+ // default: the first \`servers[].url\` of the spec
+ baseUrl: 'https://petstore.example.com/v1',
+ // RequestInit defaults for every request
+ baseApiParams: {
+ credentials: 'include', // send cookies to another origin
+ headers: { 'X-Client': 'web' },
+ },
+});`,
+ },
+
+ axiosCreate: {
+ lang: 'ts',
+ title: 'src/api-client.ts',
+ client: 'axios',
+ code: `import { Api } from './api/Api';
+
+// any AxiosRequestConfig option is accepted and passed to axios.create()
+export const api = new Api({
+ baseURL: 'https://petstore.example.com/v1',
+ headers: { 'X-Client': 'web' },
+ timeout: 10_000,
+ withCredentials: true,
+});`,
+ },
+
+ axiosInstance: {
+ lang: 'ts',
+ title: 'src/api-client.ts',
+ client: 'axios',
+ code: `import axios from 'axios';
+
+import { Api } from './api/Api';
+
+const instance = axios.create({
+ baseURL: 'https://petstore.example.com/v1',
+ timeout: 10_000,
+});
+
+instance.interceptors.response.use(undefined, (error) => {
+ if (axios.isAxiosError(error) && error.response?.status === 401) {
+ window.location.assign('/login');
+ }
+ return Promise.reject(error);
+});
+
+// with \`instance\`, the other axios options of the config are ignored
+export const api = new Api({ instance });
+
+// the instance is always available as \`api.instance\`
+api.instance.defaults.headers.common['X-Client'] = 'web';`,
+ },
+
+ callMethods: {
+ lang: 'ts',
+ client: 'fetch',
+ prelude: API,
+ code: `import { PetStatus } from './api/Api';
+
+// query parameters are one object (all optional here)
+const { data: pets } = await api.pets.listPets({ status: PetStatus.Available, limit: 20 });
+
+// path parameters are positional arguments
+const { data: pet } = await api.pets.getPet(42);
+
+// the request body is typed from the schema (NewPet)
+const { data: created } = await api.pets.createPet({ name: 'Rex', tags: ['good-boy'] });
+
+// path parameters first, then the body
+await api.pets.updatePet(created.id, { name: 'Rex II' });
+await api.pets.deletePet(created.id);`,
+ },
+
+ requestParams: {
+ lang: 'ts',
+ client: 'fetch',
+ prelude: API,
+ code: `const controller = new AbortController();
+
+// the last argument of every method: RequestParams
+await api.pets.listPets(
+ { limit: 10 },
+ {
+ headers: { 'X-Request-Id': crypto.randomUUID() }, // merged over baseApiParams.headers
+ signal: controller.signal, // or any other RequestInit option
+ cache: 'no-store',
+ secure: false, // skip the securityWorker for this call
+ format: 'json', // how to read the body: 'json' | 'text' | 'blob' | ...
+ baseUrl: 'https://staging.petstore.example.com/v1',
+ }
+);`,
+ },
+
+ requestParamsAxios: {
+ lang: 'ts',
+ client: 'axios',
+ prelude: API,
+ code: `// axios: RequestParams is an AxiosRequestConfig (+ secure, type, format)
+await api.pets.listPets(
+ { limit: 10 },
+ { headers: { 'X-Request-Id': crypto.randomUUID() }, timeout: 5_000, secure: false }
+);`,
+ },
+
+ injectHeaders: {
+ lang: 'ts',
+ client: 'fetch',
+ prelude: `declare function getCsrfToken(): Promise;\n`,
+ code: `import { Api } from './api/Api';
+
+export const api = new Api({
+ // runs before every request with the merged headers; may be async
+ injectHeaders: async (headers: Record) => ({
+ ...headers,
+ 'Accept-Language': navigator.language,
+ 'X-CSRF-Token': await getCsrfToken(), // your own helper
+ }),
+});`,
+ },
+
+ securityWorker: {
+ lang: 'ts',
+ title: 'src/api-client.ts',
+ client: 'fetch',
+ code: `import { Api } from './api/Api';
+
+// the type argument is the type of your "security data", here an access token
+export const api = new Api({
+ // called for every \`secure\` request with the value given to setSecurityData()
+ securityWorker: (token) =>
+ token ? { headers: { Authorization: \`Bearer \${token}\` } } : {},
+});
+
+export async function login(username: string, password: string) {
+ const response = await fetch('/auth/login', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ username, password }),
+ });
+ const { accessToken } = (await response.json()) as { accessToken: string };
+ api.setSecurityData(accessToken); // every secure request now sends the token
+}
+
+export function logout() {
+ api.setSecurityData(null);
+}`,
+ },
+
+ securityWorkerAsync: {
+ lang: 'ts',
+ client: 'fetch',
+ prelude: `declare const auth: { getFreshToken(): Promise };\n`,
+ code: `import { Api } from './api/Api';
+
+// the worker may be async: refresh an expired token right before the request
+export const api = new Api({
+ securityWorker: async () => ({
+ headers: { Authorization: \`Bearer \${await auth.getFreshToken()}\` },
+ }),
+ // call the worker for every request, not only for routes with \`security\`
+ baseApiParams: { secure: true },
+});`,
+ },
+
+ securityWorkerAxios: {
+ lang: 'ts',
+ client: 'axios',
+ code: `import { Api } from './api/Api';
+
+export const api = new Api({
+ baseURL: 'https://petstore.example.com/v1',
+ // returns an AxiosRequestConfig
+ securityWorker: (token) =>
+ token ? { headers: { Authorization: \`Bearer \${token}\` } } : {},
+ secure: true, // optional: call the worker for every request
+});
+
+api.setSecurityData('my-jwt');`,
+ },
+
+ singleHttpClient: {
+ lang: 'ts',
+ title: 'src/api-client.ts',
+ client: 'single',
+ code: `import { Api, HttpClient } from './api/Api';
+
+// configure the transport once...
+export const http = new HttpClient({
+ baseUrl: 'https://petstore.example.com/v1',
+ securityWorker: (token) =>
+ token ? { headers: { Authorization: \`Bearer \${token}\` } } : {},
+});
+
+// ...and hand it to the Api (it is available as api.http)
+export const api = new Api(http);
+
+http.setSecurityData('my-jwt');
+const { data: pets } = await api.pets.listPets({ limit: 10 });`,
+ },
+
+ modularSeparate: {
+ lang: 'ts',
+ title: 'src/api-client.ts',
+ client: 'modular',
+ code: `import type { ApiConfig } from './api/http-client';
+import { Pets } from './api/Pets';
+import { Store } from './api/Store';
+
+const config: ApiConfig = {
+ baseUrl: 'https://petstore.example.com/v1',
+ securityWorker: (token) =>
+ token ? { headers: { Authorization: \`Bearer \${token}\` } } : {},
+};
+
+// every module class extends HttpClient: each one has its own state
+export const pets = new Pets(config);
+export const store = new Store(config);
+
+export function setToken(token: string | null) {
+ pets.setSecurityData(token);
+ store.setSecurityData(token);
+}`,
+ },
+
+ modularShared: {
+ lang: 'ts',
+ title: 'src/api-client.ts',
+ client: 'modularSingle',
+ code: `import type { Pet } from './api/data-contracts';
+import { HttpClient } from './api/http-client';
+import { Pets } from './api/Pets';
+import { Store } from './api/Store';
+import { Users } from './api/Users';
+
+export const http = new HttpClient({
+ baseUrl: 'https://petstore.example.com/v1',
+ securityWorker: (token) =>
+ token ? { headers: { Authorization: \`Bearer \${token}\` } } : {},
+});
+
+// one transport, one token, many modules
+export const api = {
+ pets: new Pets(http),
+ store: new Store(http),
+ users: new Users(http),
+};
+
+http.setSecurityData('my-jwt');
+const { data } = await api.pets.listPets({ limit: 10 });
+const first: Pet | undefined = data[0];`,
+ },
+
+ fetchErrors: {
+ lang: 'ts',
+ client: 'fetch',
+ prelude: API,
+ code: `// the spec's \`Error\` schema would shadow the global Error: rename it on import
+import type { Error as ApiError, HttpResponse } from './api/Api';
+
+try {
+ const response = await api.pets.getPet(42); // HttpResponse
+ console.log(response.status, response.data.name);
+} catch (e) {
+ if (e instanceof Response) {
+ // a non-2xx response rejects with the HttpResponse; \`error\` is the parsed body
+ const { status, error } = e as HttpResponse;
+ console.error(status, error.message);
+ } else {
+ throw e; // network error, aborted request, ...
+ }
+}`,
+ },
+
+ noThrow: {
+ lang: 'ts',
+ client: 'noThrow',
+ prelude: API,
+ code: `// generated with disableThrowOnError: true
+const response = await api.pets.getPet(42);
+
+if (response.ok) {
+ console.log(response.data.name); // Pet
+} else {
+ console.error(response.status, response.error.message); // the spec's error type
+}`,
+ },
+
+ axiosErrors: {
+ lang: 'ts',
+ client: 'axios',
+ prelude: API,
+ code: `import axios from 'axios';
+
+import type { Error as ApiError } from './api/Api';
+
+try {
+ const { data: pet, status } = await api.pets.getPet(42); // AxiosResponse
+ console.log(status, pet.name);
+} catch (e) {
+ if (axios.isAxiosError(e)) {
+ // non-2xx responses reject with an AxiosError (axios' validateStatus)
+ console.error(e.response?.status, e.response?.data.message);
+ } else {
+ throw e;
+ }
+}`,
+ },
+
+ unwrap: {
+ lang: 'ts',
+ client: 'unwrap',
+ prelude: API,
+ code: `// generated with unwrapResponseData: true
+const pets = await api.pets.listPets({ limit: 10 }); // Pet[]
+const pet = await api.pets.getPet(42); // Pet, not HttpResponse
+
+console.log(pets.length, pet.name);`,
+ },
+
+ cancelFetch: {
+ lang: 'ts',
+ client: 'fetch',
+ prelude: API,
+ code: `// tag a request with a cancelToken (string | number | symbol)...
+const search = api.pets.listPets({ tags: ['cat'] }, { cancelToken: 'pet-search' });
+
+// ...and abort it with the same token (e.g. when the user types again)
+api.abortRequest('pet-search');
+await search.catch((e: unknown) => console.log('aborted', e));
+
+// or pass your own AbortSignal
+await api.pets.listPets({ limit: 10 }, { signal: AbortSignal.timeout(5_000) });`,
+ },
+
+ cancelAxios: {
+ lang: 'ts',
+ client: 'axios',
+ prelude: API,
+ code: `import axios from 'axios';
+
+const controller = new AbortController();
+const search = api.pets.listPets({ tags: ['cat'] }, { signal: controller.signal });
+
+controller.abort();
+
+try {
+ await search;
+} catch (e) {
+ if (axios.isCancel(e)) console.log('request canceled');
+}`,
+ },
+
+ upload: {
+ lang: 'ts',
+ client: 'fetch',
+ prelude: API,
+ code: `// POST /pets/{petId}/photo is multipart/form-data (type: ContentType.FormData):
+// pass a plain object, the client builds the FormData
+export async function onPhotoSelected(petId: string, event: Event) {
+ const file = (event.target as HTMLInputElement).files?.[0];
+ if (!file) return;
+
+ const { data: photo } = await api.pets.uploadPetPhoto(petId, { file, caption: 'Rex' });
+ console.log(photo.url);
+}
+
+// application/x-www-form-urlencoded bodies are serialized for you as well
+await api.store.placeOrder({ petId: 'pet-1', quantity: 2 });`,
+ },
+
+ download: {
+ lang: 'ts',
+ client: 'fetch',
+ prelude: API,
+ code: `// routes whose response is \`format: binary\` are generated with format: 'blob'.
+// For anything else, override the format per call or use api.request():
+const { data: blob } = await api.request({
+ path: '/pets/export',
+ method: 'GET',
+ secure: true,
+ format: 'blob',
+});
+
+const link = document.createElement('a');
+link.href = URL.createObjectURL(blob);
+link.download = 'pets.csv';
+link.click();
+URL.revokeObjectURL(link.href);`,
+ },
+
+ customFetchRetry: {
+ lang: 'ts',
+ client: 'fetch',
+ code: `import { Api } from './api/Api';
+
+// retry GET requests on network errors and 5xx responses
+const fetchWithRetry: typeof fetch = async (input, init) => {
+ const retries = (init?.method ?? 'GET') === 'GET' ? 2 : 0;
+ for (let attempt = 0; ; attempt++) {
+ try {
+ const response = await fetch(input, init);
+ if (response.status < 500 || attempt >= retries) return response;
+ } catch (e) {
+ if (attempt >= retries || init?.signal?.aborted) throw e;
+ }
+ await new Promise((resolve) => setTimeout(resolve, 300 * 2 ** attempt));
+ }
+};
+
+export const api = new Api({ customFetch: fetchWithRetry });`,
+ },
+
+ customFetchTest: {
+ lang: 'ts',
+ title: 'pets.test.ts',
+ client: 'fetch',
+ code: `import { Api, type Pet } from './api/Api';
+
+const rex: Pet = { id: '1', name: 'Rex', createdAt: '2026-01-01T00:00:00Z' };
+
+// no network, no mocking library: answer with a Response
+const api = new Api({
+ customFetch: async (input) => {
+ if (String(input).endsWith('/pets/1')) return Response.json(rex);
+ return Response.json({ code: 404, message: 'Not found' }, { status: 404 });
+ },
+});
+
+const { data } = await api.pets.getPet(1);
+console.assert(data.name === 'Rex');`,
+ },
+
+ ssr: {
+ lang: 'ts',
+ client: 'fetch',
+ code: `import { Api } from './api/Api';
+
+// on the server, create a client per request and forward the caller's cookies
+export function createServerApi(cookie: string) {
+ return new Api({
+ baseUrl: process.env.PETSTORE_URL ?? 'https://petstore.example.com/v1',
+ baseApiParams: { headers: { cookie } },
+ });
+}`,
+ },
+
+ reactQuery: {
+ lang: 'tsx',
+ title: 'src/pets/queries.ts',
+ client: 'fetch',
+ code: `import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
+
+import { api } from '../api-client';
+import type { NewPet } from '../api/Api';
+
+export function usePets(limit = 20) {
+ return useQuery({
+ queryKey: ['pets', { limit }],
+ // pass React Query's signal so unmounted queries are canceled
+ queryFn: ({ signal }) => api.pets.listPets({ limit }, { signal }).then((r) => r.data),
+ });
+}
+
+export function useCreatePet() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: (pet: NewPet) => api.pets.createPet(pet).then((r) => r.data),
+ onSuccess: () => queryClient.invalidateQueries({ queryKey: ['pets'] }),
+ });
+}`,
+ },
+
+ swr: {
+ lang: 'tsx',
+ title: 'src/pets/pet-name.tsx',
+ client: 'fetch',
+ code: `import useSWR from 'swr';
+
+import { api } from '../api-client';
+
+export function PetName({ petId }: { petId: number }) {
+ const { data: pet, error, isLoading } = useSWR(['pet', petId] as const, ([, id]) =>
+ api.pets.getPet(id).then((r) => r.data)
+ );
+
+ if (isLoading) return
Loading…
;
+ if (error) return
Could not load the pet.
;
+ return
{pet?.name}
;
+}`,
+ },
+
+ node: {
+ lang: 'ts',
+ title: 'scripts/sync-inventory.ts',
+ client: 'fetch',
+ code: `import { openAsBlob } from 'node:fs';
+
+import { Api } from '../src/api/Api';
+
+// Node.js 18+ has fetch, FormData and File built in: the fetch client works as is
+const api = new Api({
+ baseUrl: process.env.PETSTORE_URL ?? 'https://petstore.example.com/v1',
+ securityWorker: (token) =>
+ token ? { headers: { Authorization: \`Bearer \${token}\` } } : {},
+});
+api.setSecurityData(process.env.PETSTORE_TOKEN ?? null);
+
+const { data: inventory } = await api.store.getInventory();
+console.table(inventory);
+
+// upload a file from disk
+const blob = await openAsBlob('./rex.jpg', { type: 'image/jpeg' });
+const file = new File([blob], 'rex.jpg', { type: blob.type });
+await api.pets.uploadPetPhoto('pet-1', { file });`,
+ },
+
+ typesContracts: {
+ lang: 'ts',
+ client: 'fetch',
+ code: `// every schema of components/schemas is exported
+// (from data-contracts.ts in modular mode)
+import { PetStatus, type Api, type NewPet, type Pet } from './api/Api';
+
+export const draft: NewPet = { name: 'Rex', status: PetStatus.Available };
+
+export function isAvailable(pet: Pet) {
+ return pet.status === PetStatus.Available;
+}
+
+// types of inline parameters and responses, derived from the methods
+type PetsApi = Api['pets'];
+export type ListPetsQuery = NonNullable[0]>;
+export type ListPetsResult = Awaited>['data']; // Pet[]`,
+ },
+
+ typesRoutes: {
+ lang: 'ts',
+ client: 'routeTypes',
+ code: `// generated with generateRouteTypes: true
+import type { Pets } from './api/Api';
+
+type Query = Pets.ListPets.RequestQuery; // { status?, tags?, limit?, sort? }
+type Body = Pets.CreatePet.RequestBody; // NewPet
+type Result = Pets.GetPet.ResponseBody; // Pet
+
+export function toSearchParams(query: Query) {
+ const entries = Object.entries(query).map(([key, value]) => [key, String(value)]);
+ return new URLSearchParams(entries);
+}
+
+export type { Body, Result };`,
+ },
+} satisfies Record;
+
+export type SnippetId = keyof typeof SNIPPETS;
diff --git a/docs/app/usage/_lib/ui.tsx b/docs/app/usage/_lib/ui.tsx
new file mode 100644
index 0000000..db40219
--- /dev/null
+++ b/docs/app/usage/_lib/ui.tsx
@@ -0,0 +1,56 @@
+import { ClientTabs } from '@/components/client-tabs';
+import { CodeBlock } from '@/components/code-block';
+import type { NavHeading } from '@/components/docs/docs-nav';
+
+import { SNIPPETS, type SnippetId } from './snippets';
+
+const LANG_LABEL = { ts: 'TypeScript', tsx: 'TSX', bash: 'Terminal' } as const;
+
+/** a verified code example of `snippets.ts` */
+export function Snippet({ id }: { id: SnippetId }) {
+ const snippet = SNIPPETS[id];
+ return (
+
+ );
+}
+
+/** fetch / axios variants of an example */
+export function SnippetTabs({ fetch, axios }: { fetch: SnippetId; axios: SnippetId }) {
+ return } axios={} />;
+}
+
+export function createHeadings>(map: T) {
+ const list: NavHeading[] = Object.entries(map).map(([id, { text, depth }]) => ({ id, text, depth }));
+
+ function Heading({ id, children }: { id: keyof T & string; children?: React.ReactNode }) {
+ const { text, depth } = map[id];
+ const Tag = depth === 2 ? 'h2' : 'h3';
+ return (
+
+
+ {children ?? text}
+
+ #
+
+
+
+ );
+ }
+
+ return { list, Heading };
+}
+
+/** highlighted aside (uses the docs blockquote style) */
+export function Note({ title = 'Note', children }: { title?: string; children: React.ReactNode }) {
+ return (
+
+
+ {title}. {children}
+
+
+ );
+}
diff --git a/docs/app/usage/page.tsx b/docs/app/usage/page.tsx
new file mode 100644
index 0000000..be2501b
--- /dev/null
+++ b/docs/app/usage/page.tsx
@@ -0,0 +1,444 @@
+import { ArrowRight, BookOpen, FlaskConical } from 'lucide-react';
+import type { Metadata } from 'next';
+import Link from 'next/link';
+
+import { DocsMobileNav, DocsSidebar, DocsToc } from '@/components/docs/docs-nav';
+import { site } from '@/components/site-config';
+import { SiteFooter } from '@/components/site-footer';
+
+import { createHeadings, Note, Snippet, SnippetTabs } from './_lib/ui';
+
+export const dynamic = 'force-static';
+
+export const metadata: Metadata = {
+ title: 'Using the generated client',
+ description: `What to do after generating a client with ${site.name}: create it, call endpoints, add headers and auth, handle errors, cancel requests, upload files, and use it with React Query, SWR and Node.js.`,
+ openGraph: { title: `Using the generated client · ${site.name}` },
+};
+
+const { list: headings, Heading } = createHeadings({
+ generate: { text: 'Generate the client', depth: 2 },
+ 'create-a-client': { text: 'Create a client', depth: 2 },
+ 'fetch-client': { text: 'fetch', depth: 3 },
+ 'axios-client': { text: 'axios', depth: 3 },
+ 'axios-instance': { text: 'Your own axios instance', depth: 3 },
+ 'client-options': { text: 'Client options', depth: 3 },
+ 'call-endpoints': { text: 'Call endpoints', depth: 2 },
+ 'request-params': { text: 'Per-request options', depth: 3 },
+ 'headers-and-auth': { text: 'Headers and auth', depth: 2 },
+ 'inject-headers': { text: 'injectHeaders', depth: 3 },
+ 'security-worker': { text: 'Tokens with securityWorker', depth: 3 },
+ 'secure-routes': { text: 'Secure routes', depth: 3 },
+ 'single-http-client': { text: 'Share one HttpClient', depth: 2 },
+ 'modular-output': { text: 'Modular output', depth: 2 },
+ 'responses-and-errors': { text: 'Responses and errors', depth: 2 },
+ 'fetch-responses': { text: 'fetch: HttpResponse', depth: 3 },
+ 'disable-throw-on-error': { text: 'disableThrowOnError', depth: 3 },
+ 'axios-responses': { text: 'axios: AxiosError', depth: 3 },
+ 'unwrap-response-data': { text: 'unwrapResponseData', depth: 3 },
+ cancellation: { text: 'Cancel requests', depth: 2 },
+ files: { text: 'Upload and download files', depth: 2 },
+ 'custom-fetch': { text: 'Custom fetch', depth: 2 },
+ 'react-query-swr': { text: 'React Query and SWR', depth: 2 },
+ nodejs: { text: 'Node.js', depth: 2 },
+ 'typing-tips': { text: 'Typing tips', depth: 2 },
+ 'data-contracts': { text: 'Data contracts', depth: 3 },
+ 'route-types': { text: 'Route types', depth: 3 },
+});
+
+/** `code` spans in table cells */
+function rich(text: string) {
+ return text.split(/(`[^`]+`)/).map((part, index) =>
+ part.startsWith('`') ? {part.slice(1, -1)} : part
+ );
+}
+
+const CLIENT_OPTIONS: [option: string, fetch: string, axios: string, description: string][] = [
+ ['Server URL', '`baseUrl`', '`baseURL`', 'Defaults to the first `servers[].url` of the spec.'],
+ ['Request defaults', '`baseApiParams`', 'any `AxiosRequestConfig` option', 'Headers, credentials, timeout, … for every request.'],
+ ['`securityWorker`', '✓', '✓', 'Returns extra request params for secure requests, from `setSecurityData()`.'],
+ ['Always secure', '`baseApiParams.secure`', '`secure`', 'Call the `securityWorker` for every request.'],
+ ['Response format', '`baseApiParams.format`', '`format`', 'Default way to read the response body.'],
+ ['`injectHeaders`', '✓', '✓', 'Rewrites the final headers of every request (may be async).'],
+ ['`customFetch`', '✓', '–', 'Replaces `fetch` (retries, tests, SSR).'],
+ ['`instance`', '–', '✓', 'Your own `AxiosInstance` instead of `axios.create()`.'],
+];
+
+export default function UsagePage() {
+ return (
+ <>
+
+
+
+
+
+
+
+
Usage
+
+ Using the generated client
+
+
+
+ You generated Api.ts. Now what? This guide covers everything after generation:
+ configuring the client, auth, errors, cancellation, files and framework integration. Every example
+ uses the petstore test schema of the repository and is type-checked in strict mode
+ against the code the generator emits today.
+
+
+
+
+ Generator docs
+
+
+ See the generated code
+
+
+
+
+
+
+
+ Install the generator as a dev dependency and point it at your schema. The generated files are plain
+ TypeScript with no runtime dependency, except axios for the axios client.
+
+
+
+ Or keep the options in a config file and run npx swagger-typescript-api-es (for example
+ from a gen-api script). All options are described in the{' '}
+ options reference.
+
+
+
+ The examples below use the generated names of the petstore schema: api.pets.listPets,{' '}
+ api.pets.getPet, api.store.getInventory, … Method names come from{' '}
+ operationId, and routes are grouped by the first path segment (/pets/… →{' '}
+ api.pets).
+
+
+
+
+ Create the client once, in its own module, and import it everywhere. Api extends{' '}
+ HttpClient, so the constructor takes the HTTP client config.
+
+
+ fetch
+
+
+
+ baseApiParams replaces the built-in defaults (
+ credentials: 'same-origin', redirect: 'follow',{' '}
+ referrerPolicy: 'no-referrer'), so repeat the ones you still want. In the same
+ way, baseUrl: undefined (an unset environment variable) removes the default server URL:
+ write process.env.API_URL ?? 'https://…'.
+
+
+ axios
+
+
+ The axios client passes the config to axios.create(), so every{' '}
+ AxiosRequestConfig option works.
+
+
+
+
+ Pass instance to reuse an axios instance that already has interceptors, retries or
+ a custom adapter. The client then uses it as is.
+
+ Each operation is a method. Path parameters come first as positional arguments, then the query object,
+ then the request body. The last argument is always an optional RequestParams. Everything is
+ typed from the schema, so a wrong field or a missing required property is a compile error.
+
+
+
+
+ RequestParams is the per-call escape hatch. For the fetch client it accepts any{' '}
+ RequestInit option plus secure, type, format,{' '}
+ baseUrl and cancelToken. For axios it is an AxiosRequestConfig{' '}
+ plus secure, type and format.
+
+
+
+
+
Headers are merged in this order, the last one wins:
+
+
+ client defaults: baseApiParams.headers (fetch) or headers (axios);
+
+
+ the headers of the call's RequestParams;
+
+
+ what the securityWorker returns, for secure requests;
+
+
+ the Content-Type of the operation (not set for multipart/form-data, the
+ browser adds the boundary);
+
+
+ finally injectHeaders can rewrite the result.
+
+
+
+ injectHeaders
+
+
+ Both clients accept injectHeaders: (headers) => headers | Promise<headers>. It
+ runs before every request, after all the merging, which makes it the place for values that change
+ over time: a CSRF token, the current locale, a tracing id.
+
+
+
+ Tokens with securityWorker
+
+
+ The type argument of Api is the type of your security data. Store it with{' '}
+ api.setSecurityData() after login, and the securityWorker turns it into
+ request params (usually an Authorization header) for every secure request.
+
+
+
The worker can be async, for example to refresh an expired token first:
+
+
+
+
+ Operations with a security requirement, their own or the schema's global one, are
+ generated with secure: true and a @secure JSDoc tag. Only those call the
+ worker. An operation with security: [] opts out (like GET / in the
+ petstore).
+
+
+ To send credentials with every request, set baseApiParams: {'{ secure: true }'} (fetch) or{' '}
+ secure: true (axios) in the client config.
+
+
+ To skip the worker for one call, pass {'{ secure: false }'} as RequestParams.
+
+
+
+
+
+ With singleHttpClient: true, Api no longer extends HttpClient:
+ it receives one in its constructor and keeps it in api.http. The transport (base URL,
+ auth, fetch or axios instance) is configured and replaced independently of the API surface, which
+ helps with dependency injection and tests.
+
+
+
+ HttpClient has private fields, so TypeScript treats the class of each generated output as
+ a different type. Share an instance between the modules of one output, not between two separately
+ generated APIs.
+
+
+
+
+ With modular: true the output is split into http-client.ts,{' '}
+ data-contracts.ts and one class per module (Pets.ts, Store.ts,{' '}
+ Users.ts, plus Common.ts for routes like GET /). By default each
+ module class extends HttpClient, so give them the same config:
+
+
+
+ Add singleHttpClient: true to share one client instead: one config, one{' '}
+ setSecurityData() call, and you can group the modules into a single object.
+
+
+
+
+
+ fetch: HttpResponse
+
+
+ Methods resolve with an HttpResponse<Data, Error>: the native{' '}
+ Response (status, headers, ok, …) with the parsed body in{' '}
+ data. A non-2xx response rejects with the same object, the parsed error
+ body in error, typed from the schema's error responses.
+
+
+
+ disableThrowOnError
+
+
+ Generate with disableThrowOnError: true to resolve every HTTP response and branch on{' '}
+ ok instead of using try/catch. Network errors still reject.
+
+
+
+ axios: AxiosError
+
+
+ The axios client resolves with an AxiosResponse<Data> and rejects with an{' '}
+ AxiosError. Pass the error type to axios.isAxiosError to type{' '}
+ e.response.data.
+
+
+
+ unwrapResponseData
+
+
+ Generate with unwrapResponseData: true to get the body directly. This works for both
+ clients; failed requests still reject (with the HttpResponse or the{' '}
+ AxiosError).
+
+
+
+
+
+ The fetch client can cancel by token: tag a request with cancelToken and call{' '}
+ api.abortRequest(token). Both clients also accept a standard AbortSignal{' '}
+ through signal. With the fetch client, cancelToken takes precedence over{' '}
+ signal.
+
+
+
+
+
+ Operations with a multipart/form-data body are generated with{' '}
+ type: ContentType.FormData. Pass a plain object that matches the schema:{' '}
+ File and Blob values are appended as they are, other objects are sent as
+ JSON. Do not set the Content-Type header yourself.
+
+
+
+ For downloads, the format decides how the body is read. Responses declared as{' '}
+ type: string, format: binary are generated with format: 'blob' and
+ typed File (at runtime the value is a Blob). For other routes, pass{' '}
+ format in RequestParams or call api.request():
+
+
+
+ With axios, format is the responseType: use 'blob' in
+ the browser and 'arraybuffer' or 'stream' in Node.js.
+
+
+
+
+ The fetch client calls customFetch instead of the global fetch when you pass
+ one. Wrap any fetch-compatible function: retries, logging, a polyfill, a test double.
+
+
+
In tests, answer with real Response objects: no network and no mocking library.
+
+
+ For server-side rendering, create one client per incoming request so that headers such as cookies are
+ never shared between users:
+
+
+
+ The client calls this.customFetch(…). Passing window.fetch itself can fail
+ with Illegal invocation in browsers; use (...args) => fetch(...args).
+
+
+
+
+ Generated methods return promises, so they plug into any data-fetching library. Map the response to
+ its data (or generate with unwrapResponseData and pass the method directly),
+ and forward the library's AbortSignal so unused requests are canceled.
+
+
+
+
+ A rejected request surfaces as the query's error: the HttpResponse{' '}
+ (fetch) or the AxiosError (axios).
+
+
+
+
+ Node.js 18 and later have fetch, FormData, Blob and{' '}
+ File built in, so the fetch client runs unchanged in scripts, CLIs and servers. The
+ axios client works too, with axios installed.
+
+
+
+
+
+
+ Every schema of components/schemas is exported as a type (and enums as{' '}
+ enums, or unions with generateUnionEnums). Import them from{' '}
+ Api.ts, or from data-contracts.ts in modular mode. Inline parameter and
+ response types can be derived from the methods.
+
+
+
+
+ With generateRouteTypes: true, each operation also gets a namespace with its{' '}
+ RequestParams, RequestQuery, RequestBody,{' '}
+ RequestHeaders and ResponseBody types, handy for forms, mocks and server
+ handlers. In modular mode they are written to PetsRoute.ts, StoreRoute.ts, …
+
+
+
+ Need a different shape? Customize the output with{' '}
+ hooks or custom templates,
+ and preview the result in the playground.
+
+
+
+
+
+ Reference
+
+ Options, CLI and hooks
+
+
+
+
+ AI agent skill
+
+ Teach your coding agent
+
+
+
+
+
+
+
+
+
+
+ >
+ );
+}
diff --git a/docs/components/benchmark/benchmark-chart.tsx b/docs/components/benchmark/benchmark-chart.tsx
new file mode 100644
index 0000000..ae2dd66
--- /dev/null
+++ b/docs/components/benchmark/benchmark-chart.tsx
@@ -0,0 +1,205 @@
+'use client';
+
+import { useState } from 'react';
+
+import { Segmented } from '@/components/ui/segmented';
+import {
+ type BenchmarkReport,
+ type BenchmarkResult,
+ type LibraryId,
+ type Metric,
+ formatMetric,
+ formatMs,
+ formatRatio,
+ metricValue,
+ ratio,
+ versionLabel,
+} from '@/lib/benchmark/types';
+
+const METRICS: { value: Metric; label: string; title: string; unitHint: string }[] = [
+ {
+ value: 'warm',
+ label: 'Generation',
+ title: 'Generation time (warm process, median)',
+ unitHint: 'lower is better · median of the measured runs after a warm-up run',
+ },
+ {
+ value: 'cold',
+ label: 'Cold run',
+ title: 'Cold run: import + one generation in a new process',
+ unitHint: 'lower is better · what a single CLI run costs',
+ },
+ {
+ value: 'memory',
+ label: 'Memory',
+ title: 'Peak memory (RSS) of a cold run',
+ unitHint: 'lower is better',
+ },
+];
+
+const SERIES: { id: LibraryId; className: string }[] = [
+ { id: 'es', className: 'bg-series-es' },
+ { id: 'original', className: 'bg-series-original' },
+];
+
+export function BenchmarkLegend({ report }: { report: BenchmarkReport }) {
+ return (
+