🔌 API 文档
OpenAPI/Swagger 自动生成、Zod→JSON Schema、Try It Out 交互式文档——让 API 文档与代码永远同步
📐 OpenAPI 3.0 规范
OpenAPI(原名 Swagger)是 API 文档的行业标准。它用 YAML/JSON 描述 API 的所有细节,然后自动生成交互式文档、SDK、Mock Server。
# openapi.yaml — OpenAPI 3.0 完整示例
openapi: "3.0.3"
info:
title: "My SaaS API"
version: "1.0.0"
description: |
My SaaS 的 REST API 文档。
## 认证
所有 API 请求需要在 Header 中携带 Bearer Token:
```
Authorization: Bearer sk_live_...
```
## 速率限制
- Free: 60 请求/分钟
- Pro: 600 请求/分钟
- Enterprise: 无限制
servers:
- url: https://api.example.com/v1
description: 生产环境
- url: https://api.sandbox.example.com/v1
description: 沙箱环境
security:
- BearerAuth: []
paths:
/users:
get:
summary: 列出所有用户
description: 返回当前工作区下的所有用户列表
operationId: listUsers
tags: [Users]
parameters:
- name: limit
in: query
description: 每页返回数量
required: false
schema:
type: integer
default: 20
maximum: 100
- name: cursor
in: query
description: 分页游标
schema:
type: string
responses:
"200":
description: 成功返回用户列表
content:
application/json:
schema:
type: object
properties:
data:
type: array
items:
$ref: "#/components/schemas/User"
next_cursor:
type: string
"401":
$ref: "#/components/responses/Unauthorized"
/users/{id}:
get:
summary: 获取用户详情
operationId: getUser
tags: [Users]
parameters:
- name: id
in: path
required: true
schema:
type: string
format: uuid
responses:
"200":
description: 用户详情
content:
application/json:
schema:
$ref: "#/components/schemas/User"
"404":
$ref: "#/components/responses/NotFound"
components:
securitySchemes:
BearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
schemas:
User:
type: object
required: [id, email]
properties:
id:
type: string
format: uuid
description: 用户唯一标识
email:
type: string
format: email
description: 邮箱地址
name:
type: string
description: 用户名
role:
type: string
enum: [admin, member, viewer]
description: 角色
created_at:
type: string
format: date-time
description: 创建时间
responses:
Unauthorized:
description: 认证失败
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
NotFound:
description: 资源不存在
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
Error:
type: object
required: [error]
properties:
error:
type: object
required: [code, message]
properties:
code:
type: string
description: 错误码 (e.g., AUTH_FAILED, NOT_FOUND)
message:
type: string
description: 人类可读的错误信息
docs_url:
type: string
description: 错误文档链接
🤖 Zod → JSON Schema → OpenAPI 自动化
手动写 OpenAPI YAML 太痛苦了。用 Zod 定义 TypeScript 类型,自动生成 OpenAPI 文档——代码即文档。
// src/api/schemas.ts — Zod Schema 定义
import { z } from 'zod';
import { extendApi } from '@anatine/zod-openapi';
// 用户 Schema(同时用于验证和文档生成)
export const UserSchema = extendApi(z.object({
id: z.string().uuid().describe('用户唯一标识'),
email: z.string().email().describe('邮箱地址'),
name: z.string().min(1).max(100).describe('用户名'),
role: z.enum(['admin', 'member', viewer']).describe('角色'),
created_at: z.string().datetime().describe('创建时间').optional(),
}), {
description: '用户对象',
example: {
id: '550e8400-e29b-41d4-a716-446655440000',
email: 'user@example.com',
name: 'Alice',
role: 'admin',
created_at: '2024-01-15T08:30:00Z',
},
});
// 创建用户请求
export const CreateUserSchema = UserSchema.pick({
email: true,
name: true,
role: true,
});
// 错误响应
export const ErrorSchema = z.object({
error: z.object({
code: z.string().describe('错误码'),
message: z.string().describe('错误信息'),
docs_url: z.string().url().describe('文档链接').optional(),
}),
});
// src/api/routes.ts — 路由定义
import { generateOpenApi } from '@anatine/zod-openapi';
import { createRoute } from './route-helper';
const routes = [
createRoute('GET', '/users', {
summary: '列出所有用户',
response: z.object({
data: z.array(UserSchema),
next_cursor: z.string().optional(),
}),
}),
createRoute('POST', '/users', {
summary: '创建用户',
body: CreateUserSchema,
response: UserSchema,
}),
createRoute('GET', '/users/:id', {
summary: '获取用户详情',
params: z.object({ id: z.string().uuid() }),
response: UserSchema,
}),
];
// 自动生成 OpenAPI 文档
export const openApiDoc = generateOpenApi(routes, {
title: 'My SaaS API',
version: '1.0.0',
});
🎮 交互式文档:Try It Out
Stripe 文档最强大的功能之一是"Try It Out"——在文档页面直接发送 API 请求并看到响应。这消除了"读文档 → 打开 Postman → 复制粘贴 → 调试"的来回切换。
# 方案 1: Scalar (推荐,开源)
npm install @scalar/api-reference
# 在 Next.js 中使用
import ApiReference from '@scalar/api-reference'
export default function Docs() {
return (
)
}
# 方案 2: Swagger UI (经典)
npm install swagger-ui-express
# Express 中使用
const swaggerUi = require('swagger-ui-express');
const openApiDoc = require('./openapi.json');
app.use('/docs', swaggerUi.serve, swaggerUi.setup(openApiDoc, {
swaggerOptions: {
tryItOutEnabled: true, // 默认开启 Try It Out
persistAuthorization: true, // 记住认证信息
},
}));
# 方案 3: Redoc (只读,最美)
npm install redoc-cli
npx redocly-cli build-docs openapi.yaml -o docs/api.html
# 方案 4: Mintlify (SaaS,内置交互)
# 在 mint.json 中配置 openapi 字段即可
🔑 认证示例文档
# 认证文档的标准结构
## 认证方式
### API Key (推荐用于服务器端)
\`\`\`bash
curl -H "Authorization: Bearer sk_live_abc123" \
https://api.example.com/v1/users
\`\`\`
### OAuth 2.0 (推荐用于客户端应用)
\`\`\`
1. 引导用户访问: https://auth.example.com/authorize?client_id=xxx
2. 用户授权后回调: https://your-app.com/callback?code=yyy
3. 用 code 换 token:
POST https://auth.example.com/token
{ code: "yyy", client_secret: "zzz" }
4. 使用 token 调用 API
\`\`\`
## 安全注意事项
- ❌ 不要在前端代码中暴露 Secret Key
- ✅ 使用 Publishable Key (pk_*) 用于前端
- ✅ Secret Key (sk_*) 仅用于服务器端
- ✅ 设置 API Key 轮换策略
- ✅ 监控异常 API 调用模式
📋 错误码文档
| 错误码 | HTTP 状态 | 含义 | 建议操作 |
AUTH_FAILED | 401 | 认证失败 | 检查 API Key 是否正确 |
AUTH_EXPIRED | 401 | Token 过期 | 刷新 Token |
PERMISSION_DENIED | 403 | 权限不足 | 联系管理员授权 |
NOT_FOUND | 404 | 资源不存在 | 检查 ID 是否正确 |
VALIDATION_ERROR | 422 | 参数验证失败 | 检查请求体格式 |
RATE_LIMITED | 429 | 请求过快 | 等待 Retry-After 秒后重试 |
QUOTA_EXCEEDED | 402 | 配额用尽 | 升级计划或等待下个周期 |
SERVER_ERROR | 500 | 服务器内部错误 | 重试,持续则联系支持 |
💡 Stripe 的错误文档秘诀
Stripe 的错误文档为什么好?因为每个错误码都有:① 精确的触发条件 ② 包含错误码的 JSON 响应示例 ③ 人类可读的 message ④ 修复建议 ⑤ 文档链接。这让开发者不需要搜索就能自己解决问题,节省了大量支持成本。
🔗 相关专题
🔧 文档框架 · 🎓 教程设计 · ✏️ 写作风格 · ✍️ 返回首页