写 API 文档是开发中最容易被忽视但又最重要的工作。Claude Code 可以从代码直接生成完整的 OpenAPI 规范、Swagger 文档、使用示例,大幅降低文档维护成本。
方式一:从代码生成 OpenAPI YAML
bash
# 在项目目录启动 Claude Code
cd your-api-project
claude输入:
Read all the API route files in src/routes/ and generate a complete
OpenAPI 3.0 specification in YAML format.
Include for each endpoint:
- HTTP method and path
- Summary and description
- Request body schema with field descriptions
- Response schemas for 200, 400, 401, 404, 500
- Authentication requirements (Bearer token)
- Request/response examples
Save to docs/openapi.yaml
方式二:从注释生成文档
先让 Claude 给代码加注释,再生成文档:
Step 1: Add JSDoc/docstring comments to all API handlers in src/handlers/
Format for each handler:
- @route HTTP_METHOD /path
- @summary One-line description
- @param {type} name - description
- @returns {type} - description
- @throws {401} - Unauthorized
- @throws {404} - Resource not found
Step 2: After commenting, generate OpenAPI YAML from these comments.
典型生成结果
yaml
openapi: 3.0.3
info:
title: My API
version: 1.0.0
description: Auto-generated by Claude Code
paths:
/users/{id}:
get:
summary: Get user by ID
parameters:
- name: id
in: path
required: true
schema:
type: string
responses:
'200':
description: User found
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'404':
description: User not found
security:
- bearerAuth: []生成 Markdown 文档
Generate a developer-friendly Markdown API reference from src/routes/.
Format:
# API Reference
## Authentication
## Endpoints (grouped by resource)
### GET /users
**Description**: ...
**Request**: (table of params)
**Response**: (JSON example)
**Example**: curl command
Save to docs/API.md
为每个端点生成多语言示例
For each endpoint in docs/openapi.yaml, generate code examples in:
1. curl
2. Python (requests)
3. JavaScript (fetch)
4. TypeScript (axios)
Add these examples to the openapi.yaml under each endpoint's
x-code-samples field.
自动检测文档和代码是否同步
Compare the current API implementation (src/routes/) with docs/openapi.yaml.
List:
1. New endpoints not in docs
2. Removed endpoints still in docs
3. Changed request/response schemas
4. Missing error responses
Generate a diff report.
集成到 CI/CD(GitHub Actions)
yaml
# .github/workflows/docs.yml
name: Update API Docs
on:
push:
paths: ['src/routes/**', 'src/handlers/**']
jobs:
update-docs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: npm install -g @anthropic-ai/claude-code
- run: |
claude -p "Update docs/openapi.yaml to reflect changes in src/routes/. Preserve existing descriptions, only update schemas and paths."
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
- name: Commit updated docs
run: |
git config user.name 'Docs Bot'
git config user.email 'docs@ci'
git add docs/
git diff --staged --quiet || git commit -m 'docs: auto-update API reference'
git push配置 Swagger UI
python
# FastAPI 自动渲染(内置支持)
from fastapi import FastAPI
app = FastAPI(
title="My API",
description="Auto-generated docs",
version="1.0.0"
)
# 访问 /docs 即可看到 Swagger UI
# 访问 /redoc 看到 ReDoc 风格bash
# 独立 Swagger UI(静态部署)
npx swagger-ui-serve docs/openapi.yaml三个最佳实践
1. 让 Claude 保留已有描述:更新文档时告诉 Claude preserve existing descriptions,避免把手工写好的描述覆盖掉。
2. 先生成再人工润色:Claude 生成的文档结构正确但描述可能偏技术,人工补充业务背景和使用场景。
3. 和代码一起 Code Review:把文档变更和代码变更放同一个 PR,确保两者同步。
来源:Anthropic 官方文档 + OpenAPI 规范