api-documentation-generator

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

API Documentation Generator

API文档生成工具

Overview

概述

Automatically generate clear, comprehensive API documentation from your codebase. This skill helps you create professional documentation that includes endpoint descriptions, request/response examples, authentication details, error handling, and usage guidelines.
Perfect for REST APIs, GraphQL APIs, and WebSocket APIs.
从你的代码库自动生成清晰、全面的API文档。该技能可帮助你创建专业的文档,包括端点描述、请求/响应示例、认证细节、错误处理和使用指南。
适用于REST API、GraphQL API和WebSocket API。

When to Use This Skill

适用场景

  • Use when you need to document a new API
  • Use when updating existing API documentation
  • Use when your API lacks clear documentation
  • Use when onboarding new developers to your API
  • Use when preparing API documentation for external users
  • Use when creating OpenAPI/Swagger specifications
  • 当你需要为新API编写文档时使用
  • 当你需要更新现有API文档时使用
  • 当你的API缺乏清晰文档时使用
  • 当你需要让新开发者快速上手你的API时使用
  • 当你需要为外部用户准备API文档时使用
  • 当你需要创建OpenAPI/Swagger规范时使用

How It Works

工作流程

Step 1: Analyze the API Structure

步骤1:分析API结构

First, I'll examine your API codebase to understand:
  • Available endpoints and routes
  • HTTP methods (GET, POST, PUT, DELETE, etc.)
  • Request parameters and body structure
  • Response formats and status codes
  • Authentication and authorization requirements
  • Error handling patterns
首先,我会检查你的API代码库,以了解:
  • 可用的端点和路由
  • HTTP方法(GET、POST、PUT、DELETE等)
  • 请求参数和请求体结构
  • 响应格式和状态码
  • 认证和授权要求
  • 错误处理模式

Step 2: Generate Endpoint Documentation

步骤2:生成端点文档

For each endpoint, I'll create documentation including:
Endpoint Details:
  • HTTP method and URL path
  • Brief description of what it does
  • Authentication requirements
  • Rate limiting information (if applicable)
Request Specification:
  • Path parameters
  • Query parameters
  • Request headers
  • Request body schema (with types and validation rules)
Response Specification:
  • Success response (status code + body structure)
  • Error responses (all possible error codes)
  • Response headers
Code Examples:
  • cURL command
  • JavaScript/TypeScript (fetch/axios)
  • Python (requests)
  • Other languages as needed
对于每个端点,我会创建包含以下内容的文档:
端点详情:
  • HTTP方法和URL路径
  • 功能简要描述
  • 认证要求
  • 速率限制信息(如适用)
请求规范:
  • 路径参数
  • 查询参数
  • 请求头
  • 请求体 schema(包含类型和验证规则)
响应规范:
  • 成功响应(状态码 + 响应体结构)
  • 错误响应(所有可能的错误码)
  • 响应头
代码示例:
  • cURL命令
  • JavaScript/TypeScript(fetch/axios)
  • Python(requests)
  • 其他按需提供的语言示例

Step 3: Add Usage Guidelines

步骤3:添加使用指南

I'll include:
  • Getting started guide
  • Authentication setup
  • Common use cases
  • Best practices
  • Rate limiting details
  • Pagination patterns
  • Filtering and sorting options
我会包含以下内容:
  • 快速入门指南
  • 认证设置说明
  • 常见使用场景
  • 最佳实践
  • 速率限制详情
  • 分页模式
  • 过滤和排序选项

Step 4: Document Error Handling

步骤4:文档化错误处理

Clear error documentation including:
  • All possible error codes
  • Error message formats
  • Troubleshooting guide
  • Common error scenarios and solutions
清晰的错误文档包括:
  • 所有可能的错误码
  • 错误消息格式
  • 故障排除指南
  • 常见错误场景及解决方案

Step 5: Create Interactive Examples

步骤5:创建交互式示例

Where possible, I'll provide:
  • Postman collection
  • OpenAPI/Swagger specification
  • Interactive code examples
  • Sample responses
在可能的情况下,我会提供:
  • Postman集合
  • OpenAPI/Swagger规范
  • 交互式代码示例
  • 示例响应

Examples

示例

Example 1: REST API Endpoint Documentation

示例1:REST API端点文档

markdown
undefined
markdown
undefined

Create User

创建用户

Creates a new user account.
Endpoint:
POST /api/v1/users
Authentication: Required (Bearer token)
Request Body: ```json { "email": "user@example.com", // Required: Valid email address "password": "SecurePass123!", // Required: Min 8 chars, 1 uppercase, 1 number "name": "John Doe", // Required: 2-50 characters "role": "user" // Optional: "user" or "admin" (default: "user") } ```
Success Response (201 Created): ```json { "id": "usr_1234567890", "email": "user@example.com", "name": "John Doe", "role": "user", "createdAt": "2026-01-20T10:30:00Z", "emailVerified": false } ```
Error Responses:
  • 400 Bad Request
    - Invalid input data ```json { "error": "VALIDATION_ERROR", "message": "Invalid email format", "field": "email" } ```
  • 409 Conflict
    - Email already exists ```json { "error": "EMAIL_EXISTS", "message": "An account with this email already exists" } ```
  • 401 Unauthorized
    - Missing or invalid authentication token
Example Request (cURL): ```bash curl -X POST https://api.example.com/api/v1/users
-H "Authorization: Bearer YOUR_TOKEN"
-H "Content-Type: application/json"
-d '{ "email": "user@example.com", "password": "SecurePass123!", "name": "John Doe" }' ```
Example Request (JavaScript): ```javascript const response = await fetch('https://api.example.com/api/v1/users', { method: 'POST', headers: { 'Authorization':
Bearer ${token}
, 'Content-Type': 'application/json' }, body: JSON.stringify({ email: 'user@example.com', password: 'SecurePass123!', name: 'John Doe' }) });
const user = await response.json(); console.log(user); ```
Example Request (Python): ```python import requests
response = requests.post( 'https://api.example.com/api/v1/users', headers={ 'Authorization': f'Bearer {token}', 'Content-Type': 'application/json' }, json={ 'email': 'user@example.com', 'password': 'SecurePass123!', 'name': 'John Doe' } )
user = response.json() print(user) ```
undefined
创建新的用户账户。
端点:
POST /api/v1/users
认证: 必填(Bearer令牌)
请求体: ```json { "email": "user@example.com", // 必填:有效的电子邮件地址 "password": "SecurePass123!", // 必填:至少8个字符,包含1个大写字母和1个数字 "name": "John Doe", // 必填:2-50个字符 "role": "user" // 可选:"user"或"admin"(默认值:"user") } ```
成功响应(201 Created): ```json { "id": "usr_1234567890", "email": "user@example.com", "name": "John Doe", "role": "user", "createdAt": "2026-01-20T10:30:00Z", "emailVerified": false } ```
错误响应:
  • 400 Bad Request
    - 输入数据无效 ```json { "error": "VALIDATION_ERROR", "message": "Invalid email format", "field": "email" } ```
  • 409 Conflict
    - 电子邮件已存在 ```json { "error": "EMAIL_EXISTS", "message": "An account with this email already exists" } ```
  • 401 Unauthorized
    - 缺少或无效的认证令牌
示例请求(cURL): ```bash curl -X POST https://api.example.com/api/v1/users
-H "Authorization: Bearer YOUR_TOKEN"
-H "Content-Type: application/json"
-d '{ "email": "user@example.com", "password": "SecurePass123!", "name": "John Doe" }' ```
示例请求(JavaScript): ```javascript const response = await fetch('https://api.example.com/api/v1/users', { method: 'POST', headers: { 'Authorization':
Bearer ${token}
, 'Content-Type': 'application/json' }, body: JSON.stringify({ email: 'user@example.com', password: 'SecurePass123!', name: 'John Doe' }) });
const user = await response.json(); console.log(user); ```
示例请求(Python): ```python import requests
response = requests.post( 'https://api.example.com/api/v1/users', headers={ 'Authorization': f'Bearer {token}', 'Content-Type': 'application/json' }, json={ 'email': 'user@example.com', 'password': 'SecurePass123!', 'name': 'John Doe' } )
user = response.json() print(user) ```
undefined

Example 2: GraphQL API Documentation

示例2:GraphQL API文档

markdown
undefined
markdown
undefined

User Query

用户查询

Fetch user information by ID.
Query: ```graphql query GetUser($id: ID!) { user(id: $id) { id email name role createdAt posts { id title publishedAt } } } ```
Variables: ```json { "id": "usr_1234567890" } ```
Response: ```json { "data": { "user": { "id": "usr_1234567890", "email": "user@example.com", "name": "John Doe", "role": "user", "createdAt": "2026-01-20T10:30:00Z", "posts": [ { "id": "post_123", "title": "My First Post", "publishedAt": "2026-01-21T14:00:00Z" } ] } } } ```
Errors: ```json { "errors": [ { "message": "User not found", "extensions": { "code": "USER_NOT_FOUND", "userId": "usr_1234567890" } } ] } ```
undefined
通过ID获取用户信息。
查询语句: ```graphql query GetUser($id: ID!) { user(id: $id) { id email name role createdAt posts { id title publishedAt } } } ```
变量: ```json { "id": "usr_1234567890" } ```
响应: ```json { "data": { "user": { "id": "usr_1234567890", "email": "user@example.com", "name": "John Doe", "role": "user", "createdAt": "2026-01-20T10:30:00Z", "posts": [ { "id": "post_123", "title": "My First Post", "publishedAt": "2026-01-21T14:00:00Z" } ] } } } ```
错误: ```json { "errors": [ { "message": "User not found", "extensions": { "code": "USER_NOT_FOUND", "userId": "usr_1234567890" } } ] } ```
undefined

Example 3: Authentication Documentation

示例3:认证文档

markdown
undefined
markdown
undefined

Authentication

认证

All API requests require authentication using Bearer tokens.
所有API请求都需要使用Bearer令牌进行认证。

Getting a Token

获取令牌

Endpoint:
POST /api/v1/auth/login
Request: ```json { "email": "user@example.com", "password": "your-password" } ```
Response: ```json { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "expiresIn": 3600, "refreshToken": "refresh_token_here" } ```
端点:
POST /api/v1/auth/login
请求: ```json { "email": "user@example.com", "password": "your-password" } ```
响应: ```json { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "expiresIn": 3600, "refreshToken": "refresh_token_here" } ```

Using the Token

使用令牌

Include the token in the Authorization header:
``` Authorization: Bearer YOUR_TOKEN ```
在Authorization头中包含令牌:
``` Authorization: Bearer YOUR_TOKEN ```

Token Expiration

令牌过期

Tokens expire after 1 hour. Use the refresh token to get a new access token:
Endpoint:
POST /api/v1/auth/refresh
Request: ```json { "refreshToken": "refresh_token_here" } ```
undefined
令牌1小时后过期。使用刷新令牌获取新的访问令牌:
端点:
POST /api/v1/auth/refresh
请求: ```json { "refreshToken": "refresh_token_here" } ```
undefined

Best Practices

最佳实践

✅ Do This

✅ 推荐做法

  • Be Consistent - Use the same format for all endpoints
  • Include Examples - Provide working code examples in multiple languages
  • Document Errors - List all possible error codes and their meanings
  • Show Real Data - Use realistic example data, not "foo" and "bar"
  • Explain Parameters - Describe what each parameter does and its constraints
  • Version Your API - Include version numbers in URLs (/api/v1/)
  • Add Timestamps - Show when documentation was last updated
  • Link Related Endpoints - Help users discover related functionality
  • Include Rate Limits - Document any rate limiting policies
  • Provide Postman Collection - Make it easy to test your API
  • 保持一致 - 对所有端点使用相同的格式
  • 包含示例 - 提供多种语言的可运行代码示例
  • 文档化错误 - 列出所有可能的错误码及其含义
  • 使用真实数据 - 使用贴近实际的示例数据,而非"foo"和"bar"
  • 解释参数 - 描述每个参数的作用及其约束
  • API版本化 - 在URL中包含版本号(/api/v1/)
  • 添加时间戳 - 显示文档最后更新的时间
  • 关联相关端点 - 帮助用户发现相关功能
  • 包含速率限制 - 文档化任何速率限制策略
  • 提供Postman集合 - 让用户可以轻松测试你的API

❌ Don't Do This

❌ 不推荐做法

  • Don't Skip Error Cases - Users need to know what can go wrong
  • Don't Use Vague Descriptions - "Gets data" is not helpful
  • Don't Forget Authentication - Always document auth requirements
  • Don't Ignore Edge Cases - Document pagination, filtering, sorting
  • Don't Leave Examples Broken - Test all code examples
  • Don't Use Outdated Info - Keep documentation in sync with code
  • Don't Overcomplicate - Keep it simple and scannable
  • Don't Forget Response Headers - Document important headers
  • 不要跳过错误场景 - 用户需要知道可能出现的问题
  • 不要使用模糊描述 - "获取数据"这类描述毫无帮助
  • 不要忘记认证 - 务必文档化认证要求
  • 不要忽略边缘情况 - 文档化分页、过滤、排序等功能
  • 不要保留无效示例 - 测试所有代码示例
  • 不要使用过时信息 - 保持文档与代码同步
  • 不要过度复杂化 - 保持文档简洁易读
  • 不要忘记响应头 - 文档化重要的响应头

Documentation Structure

文档结构

Recommended Sections

推荐章节

  1. Introduction
    • What the API does
    • Base URL
    • API version
    • Support contact
  2. Authentication
    • How to authenticate
    • Token management
    • Security best practices
  3. Quick Start
    • Simple example to get started
    • Common use case walkthrough
  4. Endpoints
    • Organized by resource
    • Full details for each endpoint
  5. Data Models
    • Schema definitions
    • Field descriptions
    • Validation rules
  6. Error Handling
    • Error code reference
    • Error response format
    • Troubleshooting guide
  7. Rate Limiting
    • Limits and quotas
    • Headers to check
    • Handling rate limit errors
  8. Changelog
    • API version history
    • Breaking changes
    • Deprecation notices
  9. SDKs and Tools
    • Official client libraries
    • Postman collection
    • OpenAPI specification
  1. 介绍
    • API的功能
    • 基础URL
    • API版本
    • 支持联系方式
  2. 认证
    • 认证方式
    • 令牌管理
    • 安全最佳实践
  3. 快速入门
    • 简单的入门示例
    • 常见使用场景演练
  4. 端点
    • 按资源组织
    • 每个端点的完整细节
  5. 数据模型
    • Schema定义
    • 字段描述
    • 验证规则
  6. 错误处理
    • 错误码参考
    • 错误响应格式
    • 故障排除指南
  7. 速率限制
    • 限制和配额
    • 需检查的响应头
    • 处理速率限制错误
  8. 更新日志
    • API版本历史
    • 破坏性变更
    • 弃用通知
  9. SDK与工具
    • 官方客户端库
    • Postman集合
    • OpenAPI规范

Common Pitfalls

常见问题

Problem: Documentation Gets Out of Sync

问题:文档与代码不同步

Symptoms: Examples don't work, parameters are wrong, endpoints return different data Solution:
  • Generate docs from code comments/annotations
  • Use tools like Swagger/OpenAPI
  • Add API tests that validate documentation
  • Review docs with every API change
症状: 示例无法运行、参数错误、端点返回数据不符 解决方案:
  • 从代码注释/注解生成文档
  • 使用Swagger/OpenAPI等工具
  • 添加验证文档的API测试
  • 每次API变更时都审核文档

Problem: Missing Error Documentation

问题:缺少错误文档

Symptoms: Users don't know how to handle errors, support tickets increase Solution:
  • Document every possible error code
  • Provide clear error messages
  • Include troubleshooting steps
  • Show example error responses
症状: 用户不知道如何处理错误,支持工单增加 解决方案:
  • 文档化所有可能的错误码
  • 提供清晰的错误消息
  • 包含故障排除步骤
  • 展示示例错误响应

Problem: Examples Don't Work

问题:示例无法运行

Symptoms: Users can't get started, frustration increases Solution:
  • Test every code example
  • Use real, working endpoints
  • Include complete examples (not fragments)
  • Provide a sandbox environment
症状: 用户无法入门,挫败感增加 解决方案:
  • 测试所有代码示例
  • 使用真实可运行的端点
  • 提供完整示例(而非片段)
  • 提供沙箱环境

Problem: Unclear Parameter Requirements

问题:参数要求不明确

Symptoms: Users send invalid requests, validation errors Solution:
  • Mark required vs optional clearly
  • Document data types and formats
  • Show validation rules
  • Provide example values
症状: 用户发送无效请求,出现验证错误 解决方案:
  • 明确标记必填和可选参数
  • 文档化数据类型和格式
  • 展示验证规则
  • 提供示例值

Tools and Formats

工具与格式

OpenAPI/Swagger

OpenAPI/Swagger

Generate interactive documentation:
yaml
openapi: 3.0.0
info:
  title: My API
  version: 1.0.0
paths:
  /users:
    post:
      summary: Create a new user
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateUserRequest'
生成交互式文档:
yaml
openapi: 3.0.0
info:
  title: My API
  version: 1.0.0
paths:
  /users:
    post:
      summary: Create a new user
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateUserRequest'

Postman Collection

Postman集合

Export collection for easy testing:
json
{
  "info": {
    "name": "My API",
    "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
  },
  "item": [
    {
      "name": "Create User",
      "request": {
        "method": "POST",
        "url": "{{baseUrl}}/api/v1/users"
      }
    }
  ]
}
导出集合以便轻松测试:
json
{
  "info": {
    "name": "My API",
    "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
  },
  "item": [
    {
      "name": "Create User",
      "request": {
        "method": "POST",
        "url": "{{baseUrl}}/api/v1/users"
      }
    }
  ]
}

Related Skills

相关技能

  • @doc-coauthoring
    - For collaborative documentation writing
  • @copywriting
    - For clear, user-friendly descriptions
  • @test-driven-development
    - For ensuring API behavior matches docs
  • @systematic-debugging
    - For troubleshooting API issues
  • @doc-coauthoring
    - 用于协作文档编写
  • @copywriting
    - 用于撰写清晰、对用户友好的描述
  • @test-driven-development
    - 用于确保API行为与文档一致
  • @systematic-debugging
    - 用于排查API问题

Additional Resources

额外资源


Pro Tip: Keep your API documentation as close to your code as possible. Use tools that generate docs from code comments to ensure they stay in sync!

专业提示: 让你的API文档尽可能贴近代码。使用从代码注释生成文档的工具,确保文档与代码保持同步!