mcpField
A
API Designer

API Designer

github.com/daffy0208开发39202 次安装45 周前更新
代码仓库

关于 API Designer

API Designer 是面向开发者的 API 设计技能,涵盖 REST 与 GraphQL。内容涉及端点规范、安全、性能、版本管理和文档实践。

主要功能

  1. 01REST 端点与 HTTP 方法指南
  2. 02GraphQL 架构与分页模式
  3. 03认证与速率限制指南
  4. 04版本管理与兼容性实践
  5. 05OpenAPI 文档建议

适用场景

  1. 01规划 REST 资源结构
  2. 02选择 REST 或 GraphQL
  3. 03制定 API 认证与限流规则
  4. 04准备 API 版本迁移指南

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/daffy0208/ai-dev-standards --skill api-designer

安装后在 Claude Code 中输入/api-designer确认已加载。

附带文件manifest.yamlREADME.md

详细介绍

API 设计师

设计稳健、可扩展且对开发者友好的 API。

核心原则

1. 开发者体验优先
  • 命名规范清晰且可预测
  • 提供完善的文档
  • 提供有帮助的错误消息
  • 各端点采用一致的模式
2. 面向演进进行设计
  • 从一开始就制定版本策略
  • 保持向后兼容
  • 制定弃用流程
  • 为破坏性变更提供迁移指南
3. 默认安全
  • 身份验证和授权
  • 速率限制和流量控制
  • 输入验证和清理
  • 仅使用 HTTPS,不得例外
4. 性能至关重要
  • 高效的查询和索引
  • 缓存策略
  • 为大型数据集提供分页
  • 压缩(gzip、brotli)

REST API 设计

资源命名规范
✅ Good (Nouns, plural, hierarchical):
GET    /users                  # List all users
GET    /users/123              # Get specific user
POST   /users                  # Create user
PUT    /users/123              # Replace user
PATCH  /users/123              # Update user
DELETE /users/123              # Delete user
GET    /users/123/posts        # User's posts (nested)
GET    /users/123/posts/456    # Specific post

❌ Bad (Verbs, inconsistent, unclear):
GET /getUsers
POST /createUser
GET /user-list
GET /UserData?id=123
HTTP 方法及语义
方法用途幂等安全请求正文响应正文
GET检索数据是是否是
POST创建资源否否是是(已创建)
PUT替换资源是否是是(可选)
PATCH部分更新否否是是(可选)
DELETE删除资源是否否否(204)或是

幂等:多个相同请求的效果与单个请求相同 安全:请求不会修改服务端状态

HTTP 状态码

成功(2xx):

  • 200 OK - GET、PUT、PATCH、DELETE 请求成功
  • 201 Created - POST 请求成功,并包含 Location 标头
  • 204 No Content - 请求成功,无响应正文(通常用于 DELETE)

客户端错误(4xx):

  • 400 Bad Request - 语法无效或验证错误
  • 401 Unauthorized - 需要身份验证或身份验证失败
  • 403 Forbidden - 已通过身份验证,但权限不足
  • 404 Not Found - 资源不存在
  • 409 Conflict - 请求与当前状态冲突
  • 422 Unprocessable Entity - 验证错误(语义错误)
  • 429 Too Many Requests - 超出速率限制

服务端错误(5xx):

  • 500 Internal Server Error - 通用服务端错误
  • 502 Bad Gateway - 上游服务错误
  • 503 Service Unavailable - 服务暂时不可用
  • 504 Gateway Timeout - 上游请求超时
响应格式规范

成功响应:

{
  "data": {
    "id": "123",
    "type": "user",
    "attributes": {
      "name": "John Doe",
      "email": "[email protected]",
      "created_at": "2025-01-15T10:30:00Z"
    }
  }
}

错误响应:

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Request validation failed",
    "details": [
      {
        "field": "email",
        "code": "REQUIRED",
        "message": "Email is required"
      },
      {
        "field": "age",
        "code": "OUT_OF_RANGE",
        "message": "Age must be between 18 and 120"
      }
    ],
    "request_id": "req_abc123",
    "documentation_url": "https://api.example.com/docs/errors/validation"
  }
}

带分页的列表响应:

{
  "data": [...],
  "pagination": {
    "cursor": "eyJpZCI6MTIzfQ==",
    "has_more": true,
    "total_count": 1000
  },
  "links": {
    "next": "/users?cursor=eyJpZCI6MTIzfQ==&limit=20",
    "prev": "/users?cursor=eyJpZCI6MTAwfQ==&limit=20"
  }
}
分页策略

基于游标(推荐):

GET /users?cursor=abc123&limit=20

Pros: Consistent results, efficient, handles real-time data
Cons: Can't jump to arbitrary page
Use when: Large datasets, real-time data, performance critical

基于偏移量:

GET /users?page=1&per_page=20
GET /users?offset=0&limit=20

Pros: Simple, can jump to any page
Cons: Inconsistent with concurrent writes, inefficient at scale
Use when: Small datasets, admin interfaces, simple use cases
筛选、排序和搜索

筛选:

GET /users?status=active&role=admin&created_after=2025-01-01

排序:

GET /users?sort=-created_at,name  # Descending created_at, then ascending name

搜索:

GET /users?q=john&fields=name,email  # Search across specified fields
身份验证与授权

JWT Bearer Token(推荐用于 SPA):

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Pros: Stateless, includes user claims, works across domains
Cons: Can't revoke until expiry, larger payload

API 密钥(用于服务间调用):

X-API-Key: sk_live_abc123...

Pros: Simple, easy to rotate, per-service keys
Cons: No user context, must be kept secret

OAuth 2.0(用于第三方访问):

Authorization: Bearer access_token

Pros: Delegated auth, scoped permissions, industry standard
Cons: Complex setup, requires OAuth server

Basic Auth(仅用于内部/管理员工具):

Authorization: Basic base64(username:password)

Pros: Simple, built-in to HTTP
Cons: Credentials in every request, must use HTTPS
速率限制

标准标头:

X-RateLimit-Limit: 1000          # Max requests per window
X-RateLimit-Remaining: 999       # Requests left
X-RateLimit-Reset: 1640995200    # Unix timestamp when limit resets
Retry-After: 60                  # Seconds to wait (on 429)

常见策略:

  • 固定窗口:每小时 1000 个请求
  • 滑动窗口:每个滚动小时 1000 个请求
  • 令牌桶:允许突发流量,并按一定速率补充令牌
  • 按用户、IP 或 API 密钥限制
版本策略

URL 版本控制(推荐):

/v1/users
/v2/users

Pros: Explicit, easy to route, clear in logs
Cons: URL pollution, harder to evolve incrementally

标头版本控制:

Accept: application/vnd.myapp.v2+json
API-Version: 2

Pros: Clean URLs, follows REST principles
Cons: Less visible, harder to test in browser

最佳实践:

  • 从 v1 开始,而不是 v0
  • 仅在存在破坏性变更时递增版本
  • 同时支持 N 和 N-1 版本
  • 提供迁移指南
  • 提前 6-12 个月宣布弃用

GraphQL API 设计

Schema 设计
type User {
  id: ID!
  name: String!
  email: String!
  posts(first: Int, after: String): PostConnection!
  createdAt: DateTime!
}

type PostConnection {
  edges: [PostEdge!]!
  pageInfo: PageInfo!
}

type PostEdge {
  node: Post!
  cursor: String!
}

type PageInfo {
  hasNextPage: Boolean!
  endCursor: String
}

type Query {
  user(id: ID!): User
  users(first: Int, after: String): UserConnection!
}

type Mutation {
  createUser(input: CreateUserInput!): CreateUserPayload!
  updateUser(id: ID!, input: UpdateUserInput!): UpdateUserPayload!
}

input CreateUserInput {
  name: String!
  email: String!
}

type CreateUserPayload {
  user: User
  errors: [Error!]
}
GraphQL 最佳实践

1. 使用 Relay Connection 模式进行分页:

query {
  users(first: 10, after: "cursor") {
    edges {
      node {
        id
        name
      }
      cursor
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}

2. 为变更操作使用输入类型:

# ✅ Good: Input type + payload
mutation {
  createUser(input: { name: "John", email: "[email protected]" }) {
    user {
      id
      name
    }
    errors {
      field
      message
    }
  }
}

# ❌ Bad: Flat arguments
mutation {
  createUser(name: "John", email: "[email protected]") {
    id
    name
  }
}

3. 错误处理:

type Mutation {
  createUser(input: CreateUserInput!): CreateUserPayload!
}

type CreateUserPayload {
  user: User # Null if errors
  errors: [Error!] # Field-level errors
}

type Error {
  field: String!
  code: String!
  message: String!
}
REST 与 GraphQL 的选择

在以下情况下使用 REST:

  • 简单的 CRUD 操作
  • 缓存至关重要(HTTP 缓存)
  • 面向第三方的公共 API
  • 文件上传/下载
  • 团队不熟悉 GraphQL

在以下情况下使用 GraphQL:

  • 客户端需要灵活查询
  • 减少过度获取/获取不足
  • 快速迭代前端
  • 复杂的嵌套数据关系
  • 强类型和架构带来的优势

API 文档

OpenAPI/Swagger 规范
openapi: 3.0.0
info:
  title: User Management API
  version: 1.0.0
  description: API for managing users and posts
servers:
  - url: https://api.example.com/v1
paths:
  /users:
    get:
      summary: List users
      parameters:
        - name: page
          in: query
          schema:
            type: integer
            default: 1
        - name: per_page
          in: query
          schema:
            type: integer
            default: 20
            maximum: 100
      responses:
        '200':
          description: Success
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UserList'
        '401':
          $ref: '#/components/responses/Unauthorized'
    post:
      summary: Create user
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateUserInput'
      responses:
        '201':
          description: User created
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: string
        name:
          type: string
        email:
          type: string
          format: email
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
文档最佳实践
  • ✅ 包含请求/响应示例
  • ✅ 记录所有错误代码
  • ✅ 提供身份验证指南
  • ✅ 交互式 API 试用平台(Swagger UI、GraphQL Playground)
  • ✅ 提供多种语言的代码示例
  • ✅ 速率限制信息
  • ✅ API 更新的变更日志

安全检查清单

  • 仅使用 HTTPS(将 HTTP 重定向至 HTTPS)
  • 受保护的端点必须进行身份验证
  • 授权检查(用户只能访问自己的数据)
  • 输入验证(架构验证、清理)
  • 按用户/IP 限制速率
  • CORS 配置(将来源加入白名单)
  • 防止 SQL 注入(使用参数化查询)
  • URL 中不包含敏感数据(使用标头/请求体)
  • 对敏感操作进行审计日志记录
  • API 密钥可轮换和撤销

相关资源

相关技能:

  • frontend-builder - 用于从前端调用 API
  • deployment-advisor - 用于 API 托管决策
  • performance-optimizer - 用于 API 性能调优

相关模式:

  • META/DECISION-FRAMEWORK.md - REST 与 GraphQL 的选择
  • STANDARDS/architecture-patterns/api-gateway-pattern.md - API 网关架构(创建后提供)

相关操作手册:

  • PLAYBOOKS/deploy-api.md - API 部署流程(创建后提供)
  • PLAYBOOKS/version-api.md - API 版本管理工作流(创建后提供)

评论

支持 Markdown