Stop Writing API Clients by Hand! Use openapi-ts Instead
Stop Writing API Clients by Hand! Use openapi-ts Instead
How many hours have you lost this month hand-crafting TypeScript interfaces for yet another REST API? If you're like most developers, the answer is too many. You copy-paste JSON responses into online converters. You maintain separate type definitions that drift out of sync with the backend. You write boilerplate fetch wrappers that every teammate implements slightly differently. It's tedious, error-prone, and frankly, a waste of your engineering talent.
But what if you could eliminate this entire category of busywork? What if your API contracts automatically generated pristine TypeScript SDKs, complete with runtime validation, reactive query hooks, and framework-specific clients? That's exactly what hey-api/openapi-ts delivers—and why industry giants like Vercel, OpenCode, and PayPal have already made the switch.
In this deep dive, I'll expose why manual API client development is silently killing your team's velocity, and how openapi-ts transforms your OpenAPI specifications into production-ready code that actually compiles. No more type mismatches. No more stale interfaces. Just effortless type safety from spec to production.
What is openapi-ts?
@hey-api/openapi-ts is a production-grade OpenAPI-to-TypeScript code generator that converts your API specifications into fully typed, ready-to-use SDKs. Born from the Hey API ecosystem, this tool has rapidly become the secret weapon for teams who refuse to compromise on developer experience.
The project gained massive credibility when Guillermo Rauch, CEO of Vercel, endorsed it with the quote: "OpenAPI codegen that just works." That endorsement isn't marketing fluff—it's recognition that openapi-ts solves a genuinely painful problem that every TypeScript shop faces.
Unlike brittle generators that produce broken types or ignore complex OpenAPI features, openapi-ts handles any valid OpenAPI specification across all versions. It runs in any Node.js 22+ environment and outputs code that passes strict TypeScript compilation without hand-tuning. The project sits at the intersection of several explosive trends: API-first development, type-safe full-stack frameworks, and the growing demand for generated over hand-written boilerplate.
What makes openapi-ts particularly compelling is its plugin architecture. Rather than forcing a one-size-fits-all approach, it offers 20+ plugins that adapt generated output to your specific stack—whether that's Zod schemas for runtime validation, TanStack Query hooks for reactive data fetching, or framework-specific HTTP clients for Next.js↗ Bright Coding Blog or Angular. This isn't just code generation; it's ecosystem integration.
Key Features That Separate openapi-ts from the Pack
Let's dissect what makes this tool genuinely special:
Production-Grade Code Generation The output isn't theoretical TypeScript—it compiles cleanly with strict settings enabled. The generator respects OpenAPI's full feature set including discriminators, polymorphism, circular references, and complex nested schemas that break lesser tools.
Universal OpenAPI Compatibility
Whether your spec is OpenAPI 2.0, 3.0, or 3.1, YAML or JSON, generated from FastAPI or hand-rolled—openapi-ts consumes it. This eliminates the "works with our spec but not yours" problem that plagues alternative generators.
Multi-Client HTTP Abstraction
Choose your weapon: native Fetch API, Axios for interceptors, Angular's HttpClient for enterprise apps, Next.js server components, Nuxt integrations, or the lightweight ky library. Each client is first-class, not an afterthought.
20+ Battle-Tested Plugins
The plugin ecosystem is where openapi-ts flexes hardest. Generate Zod schemas for form validation. Emit TanStack Query hooks with proper caching semantics. Produce Fastify route types for your backend. The plugin system is open and extensible—build your own if you have exotic requirements.
Hey API Registry Integration
For teams managing multiple APIs, the registry sync feature centralizes spec versioning and distribution. No more passing around swagger.json files or wondering which version your frontend is using.
Developer Experience Obsession
From the npx quick-start to the Vite plugin integration, every touchpoint is optimized for minimal friction. Configuration uses defineConfig() with full TypeScript IntelliSense. Error messages are actionable, not cryptic.
Real-World Use Cases Where openapi-ts Dominates
1. Microservices Frontend Teams
You're consuming APIs from five different backend teams, each with their own release cadence. Hand-maintaining types means constant breakage. With openapi-ts, you point at each service's OpenAPI endpoint, regenerate in CI, and type errors surface immediately when APIs change—not in production.
2. Full-Stack TypeScript Monorepos
Shared types between Next.js frontend and Node.js backend sound ideal until you manually sync them. openapi-ts generates both server and client artifacts from a single source of truth, eliminating the "where did this DTO come from?" debugging sessions.
3. Third-Party API Integration
Integrating with Stripe, Twilio, or any OpenAPI-documented service? Stop reading their docs for type shapes. Generate a fully typed SDK with proper error handling and response discrimination. Your autocomplete becomes better than their documentation.
4. Rapid Prototyping & MVPs
When speed matters, openapi-ts lets you go from backend spec to typed frontend calls in minutes. The generated TanStack Query hooks include proper loading, error, and caching states—infrastructure you'd otherwise build manually.
Step-by-Step Installation & Setup Guide
Instant Gratification with npx
The fastest path to victory:
npx @hey-api/openapi-ts -i hey-api/backend -o src/client
This single command fetches your spec and emits a complete client. But for real projects, you'll want proper installation.
Package Installation
npm:
npm install @hey-api/openapi-ts -D -E
pnpm:
pnpm add @hey-api/openapi-ts -D -E
yarn:
yarn add @hey-api/openapi-ts -D -E
bun:
bun add @hey-api/openapi-ts -D
Critical: Pin exact versions (
-E) during initial development. The project follows semver pre-1.0 conventions where minor versions may introduce breaking changes.
CLI Setup
Add to package.json:
"scripts": {
"openapi-ts": "openapi-ts"
}
Execute with npm run openapi-ts or equivalent.
Configuration File
Create openapi-ts.config.ts in your project root:
import { defineConfig } from '@hey-api/openapi-ts';
export default defineConfig({
input: 'https://api.example.com/openapi.json', // Your spec URL or local path
output: 'src/client',
});
Alternative formats supported via jiti loader:
CommonJS (openapi-ts.config.cjs):
/** @type {import('@hey-api/openapi-ts').UserConfig} */
module.exports = {
input: 'path/to/spec.yaml',
output: 'src/client',
};
ESM (openapi-ts.config.mjs):
/** @type {import('@hey-api/openapi-ts').UserConfig} */
export default {
input: 'path/to/spec.yaml',
output: 'src/client',
};
Vite Integration
For Vite-powered projects, seamless build-time generation:
npm install @hey-api/vite-plugin -D -E
Configure vite.config.ts:
import { heyApiPlugin } from '@hey-api/vite-plugin';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [
heyApiPlugin({
config: {
input: 'https://api.example.com/openapi.json',
output: 'src/client',
},
}),
],
});
This regenerates your client on every build—zero manual steps, zero stale types.
Input Configuration Nuances
Your input accepts:
- Local paths:
'./openapi.yaml' - Remote URLs:
'https://api.example.com/spec' - Hey API Registry references:
'hey-api/backend'(requires signup at app.heyapi.dev) - Raw OpenAPI objects: For programmatic composition
HTTPS Self-Signed Certificates: Development environments with self-signed certs require
NODE_TLS_REJECT_UNAUTHORIZED=0in your environment.
Output Handling
Treat output as a generated dependency—never hand-edit files inside. Your CI should regenerate these artifacts, and your .gitignore should exclude them if you prefer build-time generation.
REAL Code Examples from the Repository
Let's examine actual patterns from the openapi-ts ecosystem, with detailed explanations of what each generates and how to leverage it.
Example 1: Programmatic Client Generation
import { createClient } from '@hey-api/openapi-ts';
// Generate client from Node.js script or build tool
createClient({
input: 'hey-api/backend', // Registry reference for managed specs
output: 'src/client',
});
Before: This is the imperative API for build tools, custom CLIs, or dynamic generation scenarios. Unlike the CLI, createClient() gives you full programmatic control—wrap it in custom logging, conditional logic, or multi-spec orchestration. The function returns a Promise that resolves when generation completes, enabling sequential generation of multiple clients.
After execution: Your src/client directory contains sdk.gen.ts (service methods), types.gen.ts (interfaces), and optionally schemas.gen.ts (Zod/validation schemas). Import directly from these modules with full IntelliSense.
Example 2: Vite Plugin Configuration
import { heyApiPlugin } from '@hey-api/vite-plugin';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [
heyApiPlugin({
config: {
input: 'hey-api/backend', // sign up at app.heyapi.dev
output: 'src/client',
},
}),
],
});
Before: This integrates generation into Vite's plugin lifecycle. The plugin hooks into buildStart, ensuring fresh types before compilation. For large specs, this prevents the "I forgot to regenerate" bug that wastes debugging time.
After: Every vite dev or vite build automatically synchronizes your client. The config object accepts all standard openapi-ts options, so you can layer plugins, custom clients, and parser modifications without leaving your Vite configuration.
Example 3: Configuration with Type Safety
import { defineConfig } from '@hey-api/openapi-ts';
export default defineConfig({
input: 'hey-api/backend', // sign up at app.heyapi.dev
output: 'src/client',
});
Before: defineConfig() isn't just convention—it's type-safe configuration with full autocomplete for all options. The function accepts a UserConfig object where every property is documented via JSDoc. Your IDE surfaces available clients, plugins, and parser options without consulting documentation.
After: This minimal configuration generates TypeScript interfaces and a Fetch-based SDK. But the real power emerges when you extend it:
import { defineConfig } from '@hey-api/openapi-ts';
export default defineConfig({
input: 'https://api.example.com/openapi.json',
output: 'src/client',
plugins: [
'@hey-api/sdk', // Generate service methods
'@hey-api/typescript', // Generate type interfaces
'zod', // Generate Zod schemas for runtime validation
'@tanstack/react↗ Bright Coding Blog-query', // Generate query hooks with caching
],
client: '@hey-api/client-axios', // Switch from Fetch to Axios
});
This single configuration generates: typed service methods, Zod schemas for request/response validation, TanStack Query hooks with proper query keys and caching, all using Axios with interceptors. That's four separate code categories you'd otherwise write by hand.
Advanced Usage & Best Practices
Plugin Composition Strategy
Don't enable every plugin—curate for your stack. A Next.js app with React Query needs different plugins than an Angular enterprise application. Start minimal (@hey-api/sdk + @hey-api/typescript), then add validation and framework hooks as requirements emerge.
Custom Client Development
When none of the seven built-in clients fit, the custom client API lets you define request/response handling logic that openapi-ts wraps with generated types. This is how you'd integrate with legacy XMLHttpRequest wrappers or specialized enterprise HTTP layers.
Parser Customization
The parser stage is your escape hatch for malformed specs. Pre-process specs from third-party vendors that violate OpenAPI standards, or inject computed properties that your generators need. The parser operates on the normalized OpenAPI document before plugin execution.
CI/CD Integration
Generate clients in CI, not manually:
# .github/workflows/generate-client.yml
- name: Generate API Client
run: npx @hey-api/openapi-ts
- name: Type Check
run: tsc --noEmit
This catches API drift before merge, not after deployment.
Version Pinning Discipline
With pre-1.0 versioning, read migration notes before upgrading. The notes detail exactly which features changed—often your usage isn't impacted.
Comparison with Alternatives
| Feature | openapi-ts | openapi-generator | swagger-codegen | Orval |
|---|---|---|---|---|
| TypeScript Quality | Production-grade, strict | Verbose, often manual fixes | Dated patterns | Good, React-focused |
| Plugin Ecosystem | 20+ native plugins | Limited extensibility | Minimal | TanStack-focused |
| Framework Clients | 7+ first-class clients | Generic only | Generic only | Fetch/Axios |
| Runtime Validation | Zod, Valibot native | Manual integration | None | Limited |
| Query Hooks | All TanStack flavors | None | None | React Query only |
| Build Integration | Vite plugin, programmatic | CLI only | CLI only | CLI/generator |
| Registry Sync | Hey API Registry | None | None | None |
| Active Maintenance | Rapid iteration, MIT | Apache, slower | Community forks | Active |
The verdict: openapi-ts wins on ecosystem breadth and TypeScript ergonomics. Where alternatives generate code you must hand-fix, openapi-ts generates code you commit. The plugin model means you're not locked into one validation library or query framework—adapt as your stack evolves.
FAQ
Is openapi-ts free for commercial use? Yes, released under MIT License. No restrictions, no attribution required beyond the license file.
Does it support OpenAPI 3.1? Absolutely—all valid OpenAPI versions and formats are accepted, including the latest 3.1 specification with its improved JSON Schema alignment.
Can I use it without the Hey API Registry?
Yes. The registry is optional for spec management. Use local files or direct URLs as your input.
How do I handle authentication in generated clients? Configure your chosen HTTP client (Axios interceptors, Fetch middleware, etc.) separately. The generated SDK accepts client instances with pre-configured auth.
What if my OpenAPI spec has errors? The parser validates and reports issues. For unfixable third-party specs, use parser customization to normalize before generation.
Is there a migration path from openapi-generator?
Yes, the migration guide covers common patterns. The conceptual model differs—openapi-ts is plugin-centric versus template-centric.
Can I generate only types without the SDK?
Yes, configure only @hey-api/typescript plugin for pure type generation, or combine selectively.
Conclusion
Manual API client maintenance is a solved problem that too many teams still suffer through. @hey-api/openapi-ts doesn't just generate TypeScript—it generates confidence that your frontend and backend contracts stay synchronized, that your runtime validation matches your static types, and that your query logic handles caching correctly from day one.
The adoption by Vercel, PayPal, and OpenCode signals where the industry is heading. The question isn't whether generated clients will become standard—it's whether you'll adopt before or after your competitors do.
Stop writing API clients by hand. Stop debugging type mismatches at 2 AM. Start generating production-grade SDKs that actually work.
Star openapi-ts on GitHub and run that first npx command. Your future self—the one not maintaining hand-written interfaces—will thank you.
Outils recommandés
Explore on the BrightCoding network
Hand-picked resources from our other sites.
100+ AI Agent Skills Exposed: Why Devs Are Ditching Manual MCP Setup
Discover awesome-agent-skills-mcp: a zero-config MCP server unlocking 100+ curated AI agent skills from Anthropic, Vercel, Trail of Bits & more. Install in seco...
Generative AI for Beginners: 21 Lessons to Mastery
Master generative AI development with Microsoft's free 21-lesson course. Learn Python and TypeScript, build real applications with Azure OpenAI, GitHub Models,...
Th0rgal/open-ralph-wiggum: Multi-Agent AI Coding Loop CLI
Open Ralph Wiggum is a TypeScript CLI that wraps Claude Code, Codex, Copilot CLI, Cursor Agent, Qwen Code, and OpenCode in a self-correcting autonomous loop. Bu...
Continuez votre lecture
Why Alexandrie is the Ultimate Markdown Note-Taking App
Why CrossPaste is the Ultimate Game Changer for Clipboard Management
Why Chandra is the Ultimate OCR Tool for Handwriting and Tables
Stop Coding Alone: OPC-Skills Gives Your AI Agent Superpowers
Commentaires 0
Aucun commentaire pour l'instant. Soyez le premier à réagir !