实战

用 Claude Code 生成 API 文档:OpenAPI/Swagger 自动化完全指南

用 Claude Code 自动生成 API 文档完整教程:从代码直接生成 OpenAPI 3.0 规范、Swagger UI 配置、Markdown 文档、SDK 代码示例,以及集成到 CI/CD 流水线保持文档同步更新的工作流。

2026/3/153分钟 阅读ClaudeEagle

写 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 规范

相关文章推荐

实战Claude Code 自动生成 OpenAPI 文档:从代码到 Swagger UI 一键完成Claude Code 自动生成 OpenAPI(Swagger)文档完整教程:从现有代码逆向生成 OpenAPI 3.1 规范、为 FastAPI/Express/Gin 添加完整的 schema 注释、让 Claude 补全缺失的请求/响应 schema 定义、生成带真实示例值的 Swagger 文档、将 OpenAPI Spec 转为各语言客户端 SDK(openapi-generator)、保持文档与代码同步的 CI/CD 方案,以及从 Postman Collection 迁移到 OpenAPI 的方法。2026/3/20实战用 Claude Code 自动生成技术文档:README、API 文档、架构说明一键搞定Claude Code 自动生成技术文档完整指南:从代码库生成 README、基于源码生成 OpenAPI 文档、Mermaid 架构图、CHANGELOG、贡献指南,以及 Hooks 自动更新文档工作流。2026/3/16实战Claude Code Plugins 开发指南:封装 Skills、Agents、Hooks 和 MCP ServersClaude Code Plugins 适合把团队工作流从 .claude 本地配置升级为可共享扩展。插件通过 .claude-plugin/plugin.json 描述元数据,skills 使用命名空间避免冲突,可用 --plugin-dir 本地测试。2026/6/8实战Claude Code GitLab CI/CD 完整指南:@claude 创建 MR、Bedrock/Vertex 企业部署Claude Code GitLab CI/CD 官方文档中文整理:beta 状态、工作原理、最小 .gitlab-ci.yml、masked CI/CD variables、issue/MR 评论触发、AI_FLOW_INPUT/AI_FLOW_CONTEXT、GitLab MCP server、Bedrock/Vertex AI 企业认证和安全建议。2026/5/20实战Claude Code GitHub Actions v1 完整指南:@claude 自动开发、PR 审查和 CI 集成Claude Code GitHub Actions 官方文档中文整理:它能做什么、快速安装 /install-github-app、手动配置 GitHub App 和 ANTHROPIC_API_KEY、v1 相比 beta 的破坏性变更、@claude 评论触发、自动 PR 审查、Skills 调用、Daily Report 自动化、权限安全、成本控制和可直接复制的 workflow 模板。2026/5/15实战Claude Code 并行 Worktree 实战:同时跑 4 个 AI 任务的工作流设计Claude Code Worktree 4 种并行工作流模式:功能开发+Bug修复同时进行(3个终端并行、时间节省分析);并行代码审查(PR Worktree审查+继续开发);大规模重构+主线开发(破坏性变更的隔离策略);Subagent 隔离自动并行(4个维度同时分析节省 75% 时间)。不应该并行的场景(有依赖/需共享上下文/单一简单任务)。5 个实用技巧(命名规范、.worktreeinclude、状态监控脚本、PR Worktree 直接推送)。2026/5/13