🚀 快速安装

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

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

💡 提示:需要 Node.js 和 NPM

API 设计

何时使用此技能

  • 设计新的 REST API
  • 创建 GraphQL 模式
  • 重构 API 端点
  • 记录 API 规范
  • API 版本控制策略
  • 定义数据模型和关系

指示

步骤 1:定义 API 需求

  • 识别资源和实体
  • 定义实体之间的关系
  • 指定操作(增删改查、自定义动作)
  • 规划认证/授权
  • 考虑分页、过滤、排序

步骤 2:设计 REST API

资源命名

  • 使用名词,而非动词:/users 而不是 /getUsers
  • 使用复数名称:/users/{id}
  • 逻辑嵌套资源:/users/{id}/posts
  • 保持 URL 简短且直观

HTTP 方法

  • GET:检索资源(幂等)
  • POST:创建新资源
  • PUT:替换整个资源
  • PATCH:部分更新
  • DELETE:移除资源(幂等)

响应码

  • 200 OK:成功,包含响应体
  • 201 Created:资源创建成功
  • 204 No Content:成功,无响应体
  • 400 Bad Request:无效输入
  • 401 Unauthorized:需要认证
  • 403 Forbidden:无权限
  • 404 Not Found:资源不存在
  • 409 Conflict:资源冲突
  • 422 Unprocessable Entity:验证失败
  • 500 Internal Server Error:服务器错误

REST 端点示例

GET    /api/v1/users           # 列出用户
GET    /api/v1/users/{id}      # 获取用户
POST   /api/v1/users           # 创建用户
PUT    /api/v1/users/{id}      # 更新用户
PATCH  /api/v1/users/{id}      # 部分更新
DELETE /api/v1/users/{id}      # 删除用户

步骤 3:请求/响应格式

请求示例

POST /api/v1/users
Content-Type: application/json

{
  "name": "张三",
  "email": "zhangsan@example.com",
  "role": "admin"
}

响应示例

HTTP/1.1 201 Created
Content-Type: application/json
Location: /api/v1/users/123

{
  "id": 123,
  "name": "张三",
  "email": "zhangsan@example.com",
  "role": "admin",
  "created_at": "2024-01-15T10:30:00Z",
  "updated_at": "2024-01-15T10:30:00Z"
}

步骤 4:错误处理

错误响应格式

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "提供的输入无效",
    "details": [
      {
        "field": "email",
        "message": "邮箱格式无效"
      }
    ]
  }
}

步骤 5:分页

查询参数

GET /api/v1/users?page=2&limit=20&sort=-created_at&filter=role:admin

包含分页信息的响应

{
  "data": [...],
  "pagination": {
    "page": 2,
    "limit": 20,
    "total": 100,
    "pages": 5
  },
  "links": {
    "self": "/api/v1/users?page=2&limit=20",
    "first": "/api/v1/users?page=1&limit=20",
    "prev": "/api/v1/users?page=1&limit=20",
    "next": "/api/v1/users?page=3&limit=20",
    "last": "/api/v1/users?page=5&limit=20"
  }
}

步骤 6:认证

选项

  • JWT(JSON Web 令牌)
  • OAuth 2.0
  • API 密钥
  • 基于会话

使用 JWT 的示例

GET /api/v1/users
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

步骤 7:版本控制

URL 版本控制(推荐):

/api/v1/users
/api/v2/users

标头版本控制

GET /api/users
Accept: application/vnd.api+json; version=1

步骤 8:文档

创建 OpenAPI 3.0 规范:

openapi: 3.0.0
info:
  title: 用户管理 API
  version: 1.0.0
  description: 用于管理用户的 API
servers:
  - url: https://api.example.com/v1
paths:
  /users:
    get:
      summary: 列出用户
      parameters:
        - name: page
          in: query
          schema:
            type: integer
            default: 1
        - name: limit
          in: query
          schema:
            type: integer
            default: 20
      responses:
        '200':
          description: 成功响应
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/User'
    post:
      summary: 创建用户
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UserCreate'
      responses:
        '201':
          description: 用户已创建
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: integer
        name:
          type: string
        email:
          type: string
          format: email
        created_at:
          type: string
          format: date-time
    UserCreate:
      type: object
      required:
        - name
        - email
      properties:
        name:
          type: string
        email:
          type: string
          format: email

最佳实践

  1. 一致性:使用一致的命名、结构和模式
  2. 版本控制:从一开始就对 API 进行版本控制
  3. 安全性:实施认证和授权
  4. 验证:在服务器端验证所有输入
  5. 速率限制:防止滥用
  6. 缓存:使用 ETag 和 Cache-Control 标头
  7. CORS:为 Web 客户端正确配置
  8. 文档:使文档与代码保持同步
  9. 测试:彻底测试所有端点
  10. 监控:记录请求并跟踪性能

常见模式

过滤

GET /api/v1/users?role=admin&status=active

排序

GET /api/v1/users?sort=-created_at,name

字段选择

GET /api/v1/users?fields=id,name,email

批量操作

POST /api/v1/users/batch
{
  "operations": [
    {"action": "create", "data": {...}},
    {"action": "update", "id": 123, "data": {...}}
  ]
}

GraphQL 替代方案

如果 REST 不合适,可以考虑 GraphQL:

type User {
  id: ID!
  name: String!
  email: String!
  posts: [Post!]!
  createdAt: DateTime!
}

type Query {
  users(page: Int, limit: Int): [User!]!
  user(id: ID!): User
}

type Mutation {
  createUser(input: CreateUserInput!): User!
  updateUser(id: ID!, input: UpdateUserInput!): User!
  deleteUser(id: ID!): Boolean!
}

参考资料

示例

示例 1:基本用法

示例 2:高级用法

📄 原始文档

完整文档(英文):

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

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

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