openapi-codegen
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseOpenAPI Code Generation Core Knowledge
OpenAPI代码生成核心知识
Deep Knowledge: Usewith technology:mcp__documentation__fetch_docsfor comprehensive documentation.openapi-codegen
深度知识: 使用工具并指定技术类型为mcp__documentation__fetch_docs,可获取完整文档。openapi-codegen
openapi-typescript (Types Only)
openapi-typescript(仅生成类型)
Generates TypeScript types from OpenAPI schemas. Lightweight, no runtime.
bash
undefined从OpenAPI schema生成TypeScript类型。轻量级,无运行时依赖。
bash
undefinedInstallation
Installation
npm install -D openapi-typescript
npm install -D openapi-typescript
Generate types
Generate types
npx openapi-typescript ./openapi.yaml -o ./src/types/api.ts
npx openapi-typescript https://api.example.com/openapi.json -o ./src/types/api.ts
undefinednpx openapi-typescript ./openapi.yaml -o ./src/types/api.ts
npx openapi-typescript https://api.example.com/openapi.json -o ./src/types/api.ts
undefinedGenerated Types Usage
生成类型的使用方法
typescript
import type { paths, components } from './types/api';
// Schema types
type User = components['schemas']['User'];
type CreateUserDto = components['schemas']['CreateUserDto'];
// Request/Response types
type CreateUserRequest = paths['/users']['post']['requestBody']['content']['application/json'];
type UserResponse = paths['/users/{id}']['get']['responses']['200']['content']['application/json'];
type UsersListResponse = paths['/users']['get']['responses']['200']['content']['application/json'];
// Path parameters
type UserPathParams = paths['/users/{id}']['get']['parameters']['path'];typescript
import type { paths, components } from './types/api';
// Schema types
type User = components['schemas']['User'];
type CreateUserDto = components['schemas']['CreateUserDto'];
// Request/Response types
type CreateUserRequest = paths['/users']['post']['requestBody']['content']['application/json'];
type UserResponse = paths['/users/{id}']['get']['responses']['200']['content']['application/json'];
type UsersListResponse = paths['/users']['get']['responses']['200']['content']['application/json'];
// Path parameters
type UserPathParams = paths['/users/{id}']['get']['parameters']['path'];With openapi-fetch
结合openapi-fetch使用
typescript
import createClient from 'openapi-fetch';
import type { paths } from './types/api';
const client = createClient<paths>({
baseUrl: 'https://api.example.com',
});
// Fully typed requests
const { data, error } = await client.GET('/users/{id}', {
params: { path: { id: '123' } },
});
const { data } = await client.POST('/users', {
body: { name: 'John', email: 'john@example.com' },
});
// Query parameters
const { data } = await client.GET('/users', {
params: { query: { status: 'active', page: 1 } },
});typescript
import createClient from 'openapi-fetch';
import type { paths } from './types/api';
const client = createClient<paths>({
baseUrl: 'https://api.example.com',
});
// 完全类型化的请求
const { data, error } = await client.GET('/users/{id}', {
params: { path: { id: '123' } },
});
const { data } = await client.POST('/users', {
body: { name: 'John', email: 'john@example.com' },
});
// 查询参数
const { data } = await client.GET('/users', {
params: { query: { status: 'active', page: 1 } },
});openapi-generator-cli (Full Client)
openapi-generator-cli(完整客户端生成)
Generates complete API clients with fetch/axios implementations.
bash
undefined生成包含fetch/axios实现的完整API客户端。
bash
undefinedInstallation
Installation
npm install -D @openapitools/openapi-generator-cli
npm install -D @openapitools/openapi-generator-cli
Generate TypeScript Fetch client
Generate TypeScript Fetch client
npx @openapitools/openapi-generator-cli generate
-i openapi.yaml
-g typescript-fetch
-o ./src/api-client
-i openapi.yaml
-g typescript-fetch
-o ./src/api-client
npx @openapitools/openapi-generator-cli generate
-i openapi.yaml
-g typescript-fetch
-o ./src/api-client
-i openapi.yaml
-g typescript-fetch
-o ./src/api-client
Generate TypeScript Axios client
Generate TypeScript Axios client
npx @openapitools/openapi-generator-cli generate
-i openapi.yaml
-g typescript-axios
-o ./src/api-client
-i openapi.yaml
-g typescript-axios
-o ./src/api-client
undefinednpx @openapitools/openapi-generator-cli generate
-i openapi.yaml
-g typescript-axios
-o ./src/api-client
-i openapi.yaml
-g typescript-axios
-o ./src/api-client
undefinedConfiguration File
配置文件
yaml
undefinedyaml
undefinedopenapitools.json
openapitools.json
{
"$schema": "https://raw.githubusercontent.com/OpenAPITools/openapi-generator-cli/master/apps/generator-cli/src/config.schema.json",
"spaces": 2,
"generator-cli": {
"version": "7.0.0",
"generators": {
"typescript-client": {
"generatorName": "typescript-fetch",
"output": "#{cwd}/src/api-client",
"inputSpec": "#{cwd}/openapi.yaml",
"additionalProperties": {
"supportsES6": true,
"npmName": "@myorg/api-client",
"typescriptThreePlus": true,
"withInterfaces": true
}
}
}
}
}
undefined{
"$schema": "https://raw.githubusercontent.com/OpenAPITools/openapi-generator-cli/master/apps/generator-cli/src/config.schema.json",
"spaces": 2,
"generator-cli": {
"version": "7.0.0",
"generators": {
"typescript-client": {
"generatorName": "typescript-fetch",
"output": "#{cwd}/src/api-client",
"inputSpec": "#{cwd}/openapi.yaml",
"additionalProperties": {
"supportsES6": true,
"npmName": "@myorg/api-client",
"typescriptThreePlus": true,
"withInterfaces": true
}
}
}
}
}
undefinedGenerated Client Usage
生成客户端的使用方法
typescript
import { Configuration, UsersApi } from './api-client';
const config = new Configuration({
basePath: 'https://api.example.com',
accessToken: () => localStorage.getItem('token') || '',
});
const usersApi = new UsersApi(config);
// Typed API calls
const users = await usersApi.listUsers({ status: 'active' });
const user = await usersApi.getUserById({ id: '123' });
const newUser = await usersApi.createUser({
createUserDto: { name: 'John', email: 'john@example.com' },
});typescript
import { Configuration, UsersApi } from './api-client';
const config = new Configuration({
basePath: 'https://api.example.com',
accessToken: () => localStorage.getItem('token') || '',
});
const usersApi = new UsersApi(config);
// 类型化的API调用
const users = await usersApi.listUsers({ status: 'active' });
const user = await usersApi.getUserById({ id: '123' });
const newUser = await usersApi.createUser({
createUserDto: { name: 'John', email: 'john@example.com' },
});swagger-typescript-api
swagger-typescript-api
Fast, customizable generator with template support.
bash
undefined快速、可定制的代码生成工具,支持模板自定义。
bash
undefinedInstallation
Installation
npm install -D swagger-typescript-api
npm install -D swagger-typescript-api
Generate
Generate
npx swagger-typescript-api -p ./openapi.yaml -o ./src/api -n api.ts
undefinednpx swagger-typescript-api -p ./openapi.yaml -o ./src/api -n api.ts
undefinedConfiguration
配置选项
bash
npx swagger-typescript-api \
-p ./openapi.yaml \
-o ./src/api \
-n api.ts \
--axios \ # Use axios instead of fetch
--modular \ # Separate files per tag
--route-types \ # Generate route types
--extract-request-body \ # Extract request body types
--extract-response-body # Extract response body typesbash
npx swagger-typescript-api \
-p ./openapi.yaml \
-o ./src/api \
-n api.ts \
--axios \ # 使用axios替代fetch
--modular \ # 按标签拆分文件
--route-types \ # 生成路由类型
--extract-request-body \ # 提取请求体类型
--extract-response-body # 提取响应体类型Generated Client Usage
生成客户端的使用方法
typescript
import { Api } from './api/api';
const api = new Api({
baseUrl: 'https://api.example.com',
securityWorker: () => ({
headers: { Authorization: `Bearer ${getToken()}` },
}),
});
// Typed API calls
const users = await api.users.usersList({ status: 'active' });
const user = await api.users.usersDetail('123');
const newUser = await api.users.usersCreate({
name: 'John',
email: 'john@example.com',
});typescript
import { Api } from './api/api';
const api = new Api({
baseUrl: 'https://api.example.com',
securityWorker: () => ({
headers: { Authorization: `Bearer ${getToken()}` },
}),
});
// 类型化的API调用
const users = await api.users.usersList({ status: 'active' });
const user = await api.users.usersDetail('123');
const newUser = await api.users.usersCreate({
name: 'John',
email: 'john@example.com',
});trpc-openapi (Export tRPC as OpenAPI)
trpc-openapi(将tRPC导出为OpenAPI)
Generate OpenAPI spec from tRPC router. Useful for external API consumers.
bash
npm install trpc-openapi从tRPC路由生成OpenAPI规范,适用于外部API消费者。
bash
npm install trpc-openapiDefine OpenAPI Endpoints
定义OpenAPI端点
typescript
import { initTRPC } from '@trpc/server';
import { OpenApiMeta } from 'trpc-openapi';
import { z } from 'zod';
const t = initTRPC.meta<OpenApiMeta>().create();
export const appRouter = t.router({
getUser: t.procedure
.meta({
openapi: {
method: 'GET',
path: '/users/{id}',
tags: ['users'],
summary: 'Get user by ID',
},
})
.input(z.object({ id: z.string() }))
.output(z.object({
id: z.string(),
name: z.string(),
email: z.string(),
}))
.query(({ input }) => getUserById(input.id)),
createUser: t.procedure
.meta({
openapi: {
method: 'POST',
path: '/users',
tags: ['users'],
summary: 'Create a new user',
},
})
.input(z.object({
name: z.string(),
email: z.string().email(),
}))
.output(z.object({
id: z.string(),
name: z.string(),
email: z.string(),
}))
.mutation(({ input }) => createUser(input)),
});typescript
import { initTRPC } from '@trpc/server';
import { OpenApiMeta } from 'trpc-openapi';
import { z } from 'zod';
const t = initTRPC.meta<OpenApiMeta>().create();
export const appRouter = t.router({
getUser: t.procedure
.meta({
openapi: {
method: 'GET',
path: '/users/{id}',
tags: ['users'],
summary: 'Get user by ID',
},
})
.input(z.object({ id: z.string() }))
.output(z.object({
id: z.string(),
name: z.string(),
email: z.string(),
}))
.query(({ input }) => getUserById(input.id)),
createUser: t.procedure
.meta({
openapi: {
method: 'POST',
path: '/users',
tags: ['users'],
summary: 'Create a new user',
},
})
.input(z.object({
name: z.string(),
email: z.string().email(),
}))
.output(z.object({
id: z.string(),
name: z.string(),
email: z.string(),
}))
.mutation(({ input }) => createUser(input)),
});Generate OpenAPI Document
生成OpenAPI文档
typescript
import { generateOpenApiDocument } from 'trpc-openapi';
import { appRouter } from './router';
const openApiDocument = generateOpenApiDocument(appRouter, {
title: 'My API',
version: '1.0.0',
baseUrl: 'https://api.example.com',
});
// Save to file
import fs from 'fs';
fs.writeFileSync('./openapi.json', JSON.stringify(openApiDocument, null, 2));typescript
import { generateOpenApiDocument } from 'trpc-openapi';
import { appRouter } from './router';
const openApiDocument = generateOpenApiDocument(appRouter, {
title: 'My API',
version: '1.0.0',
baseUrl: 'https://api.example.com',
});
// 保存到文件
import fs from 'fs';
fs.writeFileSync('./openapi.json', JSON.stringify(openApiDocument, null, 2));REST Handler
REST处理器
typescript
import { createOpenApiNextHandler } from 'trpc-openapi';
import { appRouter } from './router';
// Next.js API route: pages/api/[...trpc].ts
export default createOpenApiNextHandler({
router: appRouter,
createContext: () => ({}),
});typescript
import { createOpenApiNextHandler } from 'trpc-openapi';
import { appRouter } from './router';
// Next.js API路由:pages/api/[...trpc].ts
export default createOpenApiNextHandler({
router: appRouter,
createContext: () => ({}),
});Production Readiness
生产环境就绪指南
CI/CD Integration
CI/CD集成
yaml
undefinedyaml
undefined.github/workflows/generate-client.yml
.github/workflows/generate-client.yml
name: Generate API Client
on:
push:
paths:
- 'openapi.yaml'
jobs:
generate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install dependencies
run: npm ci
- name: Generate types
run: npx openapi-typescript ./openapi.yaml -o ./src/types/api.ts
- name: Check for changes
id: check
run: |
if git diff --quiet src/types/api.ts; then
echo "changed=false" >> $GITHUB_OUTPUT
else
echo "changed=true" >> $GITHUB_OUTPUT
fi
- name: Commit and push
if: steps.check.outputs.changed == 'true'
run: |
git config --local user.email "bot@example.com"
git config --local user.name "API Generator Bot"
git add src/types/api.ts
git commit -m "chore: regenerate API types"
git pushundefinedname: Generate API Client
on:
push:
paths:
- 'openapi.yaml'
jobs:
generate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install dependencies
run: npm ci
- name: Generate types
run: npx openapi-typescript ./openapi.yaml -o ./src/types/api.ts
- name: Check for changes
id: check
run: |
if git diff --quiet src/types/api.ts; then
echo "changed=false" >> $GITHUB_OUTPUT
else
echo "changed=true" >> $GITHUB_OUTPUT
fi
- name: Commit and push
if: steps.check.outputs.changed == 'true'
run: |
git config --local user.email "bot@example.com"
git config --local user.name "API Generator Bot"
git add src/types/api.ts
git commit -m "chore: regenerate API types"
git pushundefinedPackage Scripts
包脚本配置
json
{
"scripts": {
"generate:types": "openapi-typescript ./openapi.yaml -o ./src/types/api.ts",
"generate:client": "openapi-generator-cli generate -c openapitools.json",
"generate:all": "npm run generate:types && npm run generate:client",
"precommit": "npm run generate:types && git add src/types/api.ts"
}
}json
{
"scripts": {
"generate:types": "openapi-typescript ./openapi.yaml -o ./src/types/api.ts",
"generate:client": "openapi-generator-cli generate -c openapitools.json",
"generate:all": "npm run generate:types && npm run generate:client",
"precommit": "npm run generate:types && git add src/types/api.ts"
}
}Watch Mode Development
开发模式下的监听功能
bash
undefinedbash
undefinedopenapi-typescript with watch
openapi-typescript的监听模式
npx openapi-typescript ./openapi.yaml -o ./src/types/api.ts --watch
npx openapi-typescript ./openapi.yaml -o ./src/types/api.ts --watch
Or use nodemon
或使用nodemon
npx nodemon --watch openapi.yaml --exec "npx openapi-typescript ./openapi.yaml -o ./src/types/api.ts"
undefinednpx nodemon --watch openapi.yaml --exec "npx openapi-typescript ./openapi.yaml -o ./src/types/api.ts"
undefinedValidation Before Generation
生成前的规范验证
bash
undefinedbash
undefinedValidate spec first
先验证规范
npx @redocly/cli lint openapi.yaml
npx @redocly/cli lint openapi.yaml
Then generate
再执行生成
npx openapi-typescript ./openapi.yaml -o ./src/types/api.ts
undefinednpx openapi-typescript ./openapi.yaml -o ./src/types/api.ts
undefinedMonitoring Metrics
监控指标
| Metric | Target |
|---|---|
| Generated type coverage | 100% of endpoints |
| Build time with generation | < 30s |
| Type errors after generation | 0 |
| Spec validation errors | 0 |
| 指标 | 目标值 |
|---|---|
| 生成类型覆盖率 | 100% 端点覆盖 |
| 包含生成步骤的构建时间 | < 30秒 |
| 生成后的类型错误数 | 0 |
| 规范验证错误数 | 0 |
Checklist
检查清单
- OpenAPI spec validation in CI
- Automated type generation on spec changes
- Generated code committed or gitignored
- Version pinned for generator CLI
- Custom templates documented
- API client initialization documented
- Error handling patterns documented
- Authentication setup in client
- Breaking change detection
- Generated code tested
- 在CI中加入OpenAPI规范验证
- 规范变更时自动触发类型生成
- 生成代码已提交至仓库或添加到.gitignore
- 生成器CLI版本已固定
- 自定义模板已文档化
- API客户端初始化方法已文档化
- 错误处理模式已文档化
- 客户端中的认证配置已完成
- 已配置破坏性变更检测
- 生成代码已通过测试
When NOT to Use This Skill
不适用本技能的场景
- Writing OpenAPI specifications (use skill)
openapi - GraphQL type generation (use skill)
graphql-codegen - tRPC type-safe APIs (use skill)
trpc - Manual API client implementation
- Simple APIs where manual types suffice
- 编写OpenAPI规范(请使用技能)
openapi - GraphQL类型生成(请使用技能)
graphql-codegen - tRPC类型安全API开发(请使用技能)
trpc - 手动实现API客户端
- 简单API场景,手动编写类型即可满足需求
Anti-Patterns
反模式
| Anti-Pattern | Why It's Bad | Solution |
|---|---|---|
| Committing generated code to git | Merge conflicts, stale code | Add to .gitignore, generate in CI/build |
| Not versioning generator CLI | Inconsistent output | Pin generator versions in package.json |
| Editing generated files manually | Changes lost on regeneration | Extend or wrap generated code |
| No validation before generation | Invalid types generated | Validate spec with @redocly/cli first |
| Using different generators across team | Type inconsistencies | Standardize on one generator |
| Generating from remote spec without caching | Slow builds, network dependency | Cache spec locally or use schema registry |
| Not updating on spec changes | Type/runtime mismatch | Run generation in CI on spec updates |
| Missing error handling in generated code | Poor error UX | Wrap generated client with error handling |
| 反模式 | 危害 | 解决方案 |
|---|---|---|
| 将生成代码提交至Git仓库 | 产生合并冲突、代码过期 | 添加到.gitignore,在CI/构建阶段生成 |
| 未固定生成器CLI版本 | 输出结果不一致 | 在package.json中固定生成器版本 |
| 手动编辑生成的文件 | 重新生成后修改内容丢失 | 扩展或封装生成的代码 |
| 生成前未验证规范 | 生成无效的类型 | 先使用@redocly/cli验证规范 |
| 团队内使用不同的生成器 | 类型定义不一致 | 标准化为单一生成器 |
| 从远程规范生成且未缓存 | 构建缓慢、依赖网络 | 本地缓存规范或使用Schema Registry |
| 规范变更后未更新生成代码 | 类型与运行时不匹配 | 在CI中规范变更时自动运行生成 |
| 生成代码中缺少错误处理 | 用户体验差 | 封装生成的客户端,添加错误处理逻辑 |
Quick Troubleshooting
快速故障排查
| Issue | Possible Cause | Solution |
|---|---|---|
| Generation fails | Invalid OpenAPI spec | Validate with |
| Type errors after generation | Spec doesn't match API | Verify spec matches actual responses |
| Missing types | Spec incomplete or refs broken | Check all $refs resolve, add missing schemas |
| Wrong HTTP client generated | Generator config mismatch | Check -g flag or generator setting |
| Circular reference errors | Self-referencing schemas | Use discriminators or flatten schema |
| Slow generation | Large spec file | Use spec splitting or partial generation |
| Auth not working | Security scheme not configured | Add securityWorker or token config |
| "Cannot find module" errors | Generation didn't complete | Check for generation errors, rerun |
| Type conflicts | Multiple generators running | Use single generator, remove others |
| 问题 | 可能原因 | 解决方案 |
|---|---|---|
| 生成失败 | OpenAPI规范无效 | 使用 |
| 生成后出现类型错误 | 规范与实际API不匹配 | 验证规范是否与真实响应一致 |
| 缺少部分类型 | 规范不完整或引用断裂 | 检查所有$refs是否解析正常,补充缺失的schema |
| 生成的HTTP客户端不符合预期 | 生成器配置错误 | 检查-g参数或生成器设置 |
| 循环引用错误 | Schema存在自引用 | 使用鉴别器或扁平化Schema |
| 生成速度缓慢 | 规范文件过大 | 使用规范拆分或部分生成功能 |
| 认证不生效 | 安全方案未配置 | 添加securityWorker或令牌配置 |
| “找不到模块”错误 | 生成未完成 | 检查生成过程中的错误,重新运行生成 |
| 类型冲突 | 同时运行多个生成器 | 使用单一生成器,移除其他生成器 |
Reference Documentation
参考文档
- openapi-typescript
- openapi-generator
- swagger-typescript-api
- trpc-openapi
- openapi-typescript
- openapi-generator
- swagger-typescript-api
- trpc-openapi