API 文档往往是最难保持更新的部分。Claude Code 能从现有代码 自动生成和维护 OpenAPI 规范,让文档永远和代码保持同步。
从现有代码逆向生成 OpenAPI
你:读取 src/api/ 目录下的所有路由文件,
根据代码逆向生成完整的 OpenAPI 3.1 规范文档。
要求:
- 提取所有 HTTP 方法、路径、请求参数
- 推断请求 Body 和响应的 JSON Schema
- 为每个接口添加中文描述(从函数名/注释推断)
- 包含认证方式(从代码中识别)
- 生成真实的示例值(example 字段)
- 保存到 docs/openapi.yaml
Claude:[分析路由文件后生成]
生成的 OpenAPI 3.1 结构示例:
yaml
openapi: "3.1.0"
info:
title: Task Manager API
version: "1.0.0"
description: 任务管理系统 REST API
servers:
- url: https://api.example.com/v1
description: 生产环境
- url: http://localhost:8000/v1
description: 本地开发
security:
- BearerAuth: []
paths:
/tasks:
get:
summary: 获取任务列表
description: 返回当前用户的所有任务,支持按状态筛选
tags: [任务管理]
parameters:
- name: status
in: query
description: 按状态筛选
schema:
type: string
enum: [todo, in_progress, done]
example: todo
responses:
"200":
description: 成功
content:
application/json:
schema:
type: array
items:
$ref: "#/components/schemas/Task"
example:
- id: "task-001"
title: "完成报告"
status: "in_progress"
components:
schemas:
Task:
type: object
required: [id, title, status]
properties:
id:
type: string
format: uuid
example: "550e8400-e29b-41d4-a716-446655440000"
title:
type: string
maxLength: 200
example: "完成季度报告"
status:
type: string
enum: [todo, in_progress, done]
created_at:
type: string
format: date-time
example: "2026-03-20T10:30:00Z"
securitySchemes:
BearerAuth:
type: http
scheme: bearer
bearerFormat: JWT为 FastAPI 补全 Schema 注释
FastAPI 从 Pydantic 模型自动生成文档,让 Claude 补全缺失部分:
你:这些 Pydantic 模型缺少文档字段描述(description)和示例值(example),
帮我补全,让 Swagger UI 显示清晰:
class TaskCreate(BaseModel):
title: str
description: str | None = None
due_date: datetime | None = None
priority: int = 3
Claude:
from pydantic import BaseModel, Field
from datetime import datetime
class TaskCreate(BaseModel):
title: str = Field(
...,
description="任务标题",
min_length=1,
max_length=200,
example="完成 Q1 技术报告"
)
description: str | None = Field(
None,
description="任务详细描述(可选)",
example="需要包含技术选型分析和实施计划"
)
due_date: datetime | None = Field(
None,
description="截止日期(ISO 8601 格式,可选)",
example="2026-03-31T18:00:00Z"
)
priority: int = Field(
3,
description="优先级,1(最高)到 5(最低)",
ge=1, le=5,
example=2
)
Express/Node.js 生成 OpenAPI
你:为这个 Express Router 生成 JSDoc 注释,
格式兼容 swagger-jsdoc 自动生成 OpenAPI 文档
router.get('/users/:id', authenticate, async (req, res) => {
const user = await UserService.findById(req.params.id);
res.json(user);
});
Claude:
/**
* @swagger
* /users/{id}:
* get:
* summary: 根据 ID 获取用户
* description: 返回指定 ID 的用户详细信息
* tags: [用户管理]
* security:
* - BearerAuth: []
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: string
* format: uuid
* description: 用户 UUID
* example: "550e8400-e29b-41d4-a716-446655440000"
* responses:
* 200:
* description: 成功
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/User'
* 401:
* description: 未认证
* 404:
* description: 用户不存在
*/
router.get('/users/:id', authenticate, async (req, res) => {
生成客户端 SDK
OpenAPI Spec 生成后,用 openapi-generator 一键生成各语言 SDK:
bash
# 安装
npm install -g @openapitools/openapi-generator-cli
# 生成 TypeScript 客户端
openapi-generator-cli generate -i docs/openapi.yaml -g typescript-axios -o sdk/typescript --additional-properties=supportsES6=true
# 生成 Python 客户端
openapi-generator-cli generate -i docs/openapi.yaml -g python -o sdk/python
# 让 Claude 帮你验证生成的 SDK 是否正确
claude "检查 sdk/typescript 目录,确认生成的 API 客户端与 openapi.yaml 是否一致"CI/CD 文档同步
yaml
# .github/workflows/docs-sync.yml
# 每次合并到 main 时自动更新 OpenAPI 文档
- name: Sync API Docs
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
# 检测 API 路由文件是否有变更
CHANGED=$(git diff HEAD~1 --name-only | grep -E "src/api|routes" || true)
if [ -n "$CHANGED" ]; then
claude -p "
以下 API 文件有变更:$CHANGED
请更新 docs/openapi.yaml 中对应的接口定义,
保持其他部分不变,输出完整的更新后的 YAML
" --output-format text > docs/openapi.yaml
git add docs/openapi.yaml
git commit -m "docs: auto-update OpenAPI spec"
fi来源:Claude Code 官方文档 - docs.anthropic.com/en/docs/claude-code