🚀 快速安装

复制以下命令并运行,立即安装此 Skill:

npx @anthropic-ai/skills install supercent-io/skills-template/api-documentation

💡 提示:需要 Node.js 和 NPM

API 文档

何时使用此技能

  • API 开发:添加新端点时
  • 对外发布:公开 API 上线时
  • 团队协作:定义前后端接口时

指示

步骤 1:OpenAPI(Swagger)规范

openapi: 3.0.0
info:
  title: 用户管理 API
  version: 1.0.0
  description: 用于管理用户的 API
  contact:
    email: api@example.com

servers:
  - url: https://api.example.com/v1
    description: 生产环境
  - url: https://staging-api.example.com/v1
    description: 预发布环境

paths:
  /users:
    get:
      summary: 列出所有用户
      description: 检索分页的用户列表
      tags:
        - 用户
      parameters:
        - name: page
          in: query
          schema:
            type: integer
            default: 1
        - name: limit
          in: query
          schema:
            type: integer
            default: 20
            maximum: 100
      responses:
        '200':
          description: 成功响应
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/User'
                  pagination:
                    $ref: '#/components/schemas/Pagination'
        '401':
          $ref: '#/components/responses/Unauthorized'

    post:
      summary: 创建新用户
      tags:
        - 用户
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateUserRequest'
      responses:
        '201':
          description: 用户创建成功
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        '400':
          $ref: '#/components/responses/BadRequest'

components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: string
          format: uuid
        email:
          type: string
          format: email
        name:
          type: string
        createdAt:
          type: string
          format: date-time
      required:
        - id
        - email
        - name

    CreateUserRequest:
      type: object
      properties:
        email:
          type: string
          format: email
        name:
          type: string
          minLength: 2
          maxLength: 50
        password:
          type: string
          minLength: 8
      required:
        - email
        - name
        - password

    Pagination:
      type: object
      properties:
        page:
          type: integer
        limit:
          type: integer
        total:
          type: integer

  responses:
    Unauthorized:
      description: 未授权
      content:
        application/json:
          schema:
            type: object
            properties:
              error:
                type: string
                example: "需要认证"

    BadRequest:
      description: 错误请求
      content:
        application/json:
          schema:
            type: object
            properties:
              error:
                type: string
                example: "输入无效"

  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT

security:
  - bearerAuth: []

步骤 2:从代码生成文档(JSDoc/装饰器)

Express + TypeScript

/**
 * @swagger
 * /api/users:
 *   post:
 *     summary: 创建新用户
 *     tags: [用户]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - email
 *               - name
 *               - password
 *             properties:
 *               email:
 *                 type: string
 *                 format: email
 *               name:
 *                 type: string
 *               password:
 *                 type: string
 *                 minLength: 8
 *     responses:
 *       201:
 *         description: 用户创建成功
 *       400:
 *         description: 输入无效
 */
router.post('/users', async (req, res) => {
  const { email, name, password } = req.body;
  const user = await userService.createUser({ email, name, password });
  res.status(201).json(user);
});

步骤 3:交互式文档

Swagger UI 设置

import swaggerUi from 'swagger-ui-express';
import YAML from 'yamljs';

const swaggerDocument = YAML.load('./openapi.yaml');

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument, {
  customCss: '.swagger-ui .topbar { display: none }',
  customSiteTitle: "我的 API 文档"
}));

步骤 4:示例与指南

## API 文档

### 认证

所有 API 请求都需要使用 JWT 令牌进行认证。

#### 获取令牌
\`\`\`bash
curl -X POST https://api.example.com/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email": "user@example.com", "password": "yourpassword"}'
\`\`\`

响应:
\`\`\`json
{
  "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "refreshToken": "..."
}
\`\`\`

#### 使用令牌
\`\`\`bash
curl -X GET https://api.example.com/v1/users \
  -H "Authorization: Bearer 您的访问令牌"
\`\`\`

### 创建用户

**端点**`POST /v1/users`

**请求体**\`\`\`json
{
  "email": "zhangsan@example.com",
  "name": "张三",
  "password": "SecurePass123!"
}
\`\`\`

**成功响应** (201):
\`\`\`json
{
  "id": "123e4567-e89b-12d3-a456-426614174000",
  "email": "zhangsan@example.com",
  "name": "张三",
  "createdAt": "2025-01-15T10:00:00Z"
}
\`\`\`

**错误响应** (400):
\`\`\`json
{
  "error": "邮箱已存在"
}
\`\`\`

### 速率限制
- 每 IP 每 15 分钟 100 次请求
- 头部:`X-RateLimit-Remaining`

### 分页
\`\`\`
GET /v1/users?page=2&limit=20
\`\`\`

响应包含分页信息:
\`\`\`json
{
  "data": [...],
  "pagination": {
    "page": 2,
    "limit": 20,
    "total": 157,
    "pages": 8
  }
}
\`\`\`

### 错误码
- `400` - 错误请求(验证错误)
- `401` - 未授权(令牌缺失/无效)
- `403` - 禁止访问(权限不足)
- `404` - 未找到
- `409` - 冲突(资源重复)
- `429` - 请求过多(达到速率限制)
- `500` - 内部服务器错误

输出格式

API 文档结构

docs/
├── README.md                    # 概述
├── getting-started.md           # 快速入门指南
├── authentication.md            # 认证指南
├── api-reference/
│   ├── users.md                 # 用户相关端点
│   ├── auth.md                  # 认证相关端点
│   └── products.md              # 产品相关端点
├── guides/
│   ├── pagination.md
│   ├── error-handling.md
│   └── rate-limiting.md
├── examples/
│   ├── curl.md
│   ├── javascript.md
│   └── python.md
└── openapi.yaml                 # OpenAPI 规范

约束条件

必需规则(必须遵守)

  1. 真实示例:提供可运行的代码示例
  2. 错误情况:不仅要记录成功,还要记录失败情况
  3. 保持更新:当 API 变更时更新文档

禁止事项(不得违反)

  1. 示例中使用真实密钥:不要在示例中使用真实的 API 密钥/密码
  2. 描述模糊:避免使用“返回数据”等不明确的描述

最佳实践

  1. 亲自尝试:提供交互式文档(Swagger UI)
  2. 提供 SDK:为主要语言提供 SDK 和示例
  3. 更新日志:记录 API 变更

参考资料

元数据

版本

  • 当前版本:1.0.0
  • 最后更新:2025-01-01
  • 兼容平台:Claude, ChatGPT, Gemini

标签

#API文档 #OpenAPI #Swagger #REST #开发者文档 #文档

示例

示例 1:基本用法

示例 2:高级用法

📄 原始文档

完整文档(英文):

https://skills.sh/supercent-io/skills-template/api-documentation

💡 提示:点击上方链接查看 skills.sh 原始英文文档,方便对照翻译。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。