designing-apis

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Designing APIs

API设计

Design well-structured, scalable APIs using REST, GraphQL, or event-driven patterns. Focus on resource design, versioning, error handling, pagination, rate limiting, and security.
使用REST、GraphQL或事件驱动模式设计结构合理、可扩展的API。重点关注资源设计、版本控制、错误处理、分页、限流和安全机制。

When to Use This Skill

何时使用此技能

Use when:
  • Designing a new REST, GraphQL, or event-driven API
  • Establishing API design standards for a team or organization
  • Choosing between REST, GraphQL, WebSockets, or message queues
  • Planning API versioning and breaking change management
  • Defining error response formats and HTTP status code usage
  • Implementing pagination, filtering, and rate limiting patterns
  • Designing OAuth2 flows or API key authentication
  • Creating OpenAPI or AsyncAPI specifications
Do NOT use for:
  • Implementation code (use
    api-patterns
    skill for Express, FastAPI code)
  • Authentication implementation (use
    auth-security
    skill for JWT, sessions)
  • API testing strategies (use
    testing-strategies
    skill)
  • API deployment and infrastructure (use
    deploying-applications
    skill)
适用于以下场景:
  • 设计新的REST、GraphQL或事件驱动型API
  • 为团队或组织制定API设计标准
  • 在REST、GraphQL、WebSocket或消息队列之间做选型
  • 规划API版本控制和破坏性变更管理
  • 定义错误响应格式和HTTP状态码的使用规范
  • 实现分页、过滤和限流模式
  • 设计OAuth2流程或API密钥认证机制
  • 创建OpenAPI或AsyncAPI规范
不适用于以下场景:
  • 实现代码(如需Express、FastAPI代码实现,请使用
    api-patterns
    技能)
  • 认证功能实现(如需JWT、会话管理,请使用
    auth-security
    技能)
  • API测试策略(请使用
    testing-strategies
    技能)
  • API部署与基础设施(请使用
    deploying-applications
    技能)

Core Design Principles

核心设计原则

Resource-Oriented Design (REST)

面向资源的设计(REST)

Use nouns for resources, not verbs in URLs:
✓ GET    /users              List users
✓ GET    /users/123          Get user 123
✓ POST   /users              Create user
✓ PATCH  /users/123          Update user 123
✓ DELETE /users/123          Delete user 123

✗ GET    /getUsers
✗ POST   /createUser
Nest resources for relationships (limit depth to 2-3 levels):
✓ GET /users/123/posts
✓ GET /users/123/posts/456/comments
✗ GET /users/123/posts/456/comments/789/replies  (too deep)
For complete REST patterns, see references/rest-design.md
URL中使用名词表示资源,而非动词:
✓ GET    /users              列出用户
✓ GET    /users/123          获取用户123的信息
✓ POST   /users              创建用户
✓ PATCH  /users/123          更新用户123的信息
✓ DELETE /users/123          删除用户123

✗ GET    /getUsers
✗ POST   /createUser
通过嵌套资源表示关联关系(限制深度为2-3层):
✓ GET /users/123/posts
✓ GET /users/123/posts/456/comments
✗ GET /users/123/posts/456/comments/789/replies  (层级过深)
完整的REST模式请参考references/rest-design.md

HTTP Method Semantics

HTTP方法语义

MethodIdempotentSafeUse ForSuccess Status
GETYesYesRead resource200 OK
POSTNoNoCreate resource201 Created
PUTYesNoReplace entire resource200 OK, 204 No Content
PATCHNoNoUpdate specific fields200 OK, 204 No Content
DELETEYesNoRemove resource204 No Content, 200 OK
Idempotent means multiple identical requests have the same effect as one request.
方法幂等性安全性适用场景成功状态码
GET读取资源200 OK
POST创建资源201 Created
PUT替换整个资源200 OK、204 No Content
PATCH更新特定字段200 OK、204 No Content
DELETE删除资源204 No Content、200 OK
幂等性指多次相同请求的效果与单次请求一致。

HTTP Status Codes

HTTP状态码

Success (2xx):
  • 200 OK, 201 Created, 204 No Content
Client Errors (4xx):
  • 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found
  • 409 Conflict, 422 Unprocessable Entity, 429 Too Many Requests
Server Errors (5xx):
  • 500 Internal Server Error, 503 Service Unavailable
For complete status code guide, see references/rest-design.md
成功(2xx):
  • 200 OK、201 Created、204 No Content
客户端错误(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、503 Service Unavailable
完整的状态码指南请参考references/rest-design.md

API Style Selection

API风格选型

Decision Matrix

决策矩阵

FactorRESTGraphQLWebSocketMessage Queue
Public API⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
Complex Data⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
Caching⭐⭐⭐⭐⭐⭐⭐
Real-time⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
Simplicity⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
考量因素RESTGraphQLWebSocket消息队列
公开API⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
复杂数据场景⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
缓存支持⭐⭐⭐⭐⭐⭐⭐
实时性⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
易用性⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐

Quick Selection

快速选型指南

  • Public API, CRUD operations → REST
  • Complex data, flexible queries → GraphQL
  • Real-time, bidirectional → WebSockets
  • Event-driven, microservices → Message Queue
For detailed protocol selection, see references/protocol-selection.md
  • 公开API、CRUD操作 → REST
  • 复杂数据、灵活查询 → GraphQL
  • 实时双向通信 → WebSocket
  • 事件驱动、微服务 → 消息队列
详细的协议选型请参考references/protocol-selection.md

API Versioning

API版本控制

URL Path Versioning (Recommended)

URL路径版本控制(推荐)

https://api.example.com/v1/users
https://api.example.com/v2/users
Pros: Explicit, easy to implement and test Cons: Maintenance overhead
https://api.example.com/v1/users
https://api.example.com/v2/users
优点:明确清晰,易于实现和测试 缺点:存在维护开销

Alternative Strategies

替代方案

  • Header-Based:
    Accept-Version: v1
  • Media Type:
    Accept: application/vnd.example.v1+json
  • Query Parameter:
    ?version=1
    (not recommended)
  • 基于Header:
    Accept-Version: v1
  • 基于媒体类型:
    Accept: application/vnd.example.v1+json
  • 基于查询参数:
    ?version=1
    (不推荐)

Breaking Change Management

破坏性变更管理

Timeline:
  1. Month 0: Announce deprecation
  2. Months 1-3: Migration period
  3. Months 4-6: Deprecation warnings
  4. Month 6: Sunset (return 410 Gone)
Include deprecation headers:
http
Deprecation: true
Sunset: Sat, 31 Dec 2025 23:59:59 GMT
Link: </api/v2/users>; rel="successor-version"
For complete versioning guide, see references/versioning-strategies.md
时间线:
  1. 第0个月:宣布废弃
  2. 第1-3个月:迁移过渡期
  3. 第4-6个月:返回废弃警告
  4. 第6个月:停止服务(返回410 Gone)
返回废弃相关Header:
http
Deprecation: true
Sunset: Sat, 31 Dec 2025 23:59:59 GMT
Link: </api/v2/users>; rel="successor-version"
完整的版本控制指南请参考references/versioning-strategies.md

Error Response Standards

错误响应标准

RFC 7807 Problem Details (Recommended)

RFC 7807问题详情格式(推荐)

json
{
  "type": "https://api.example.com/errors/validation",
  "title": "Validation Error",
  "status": 400,
  "detail": "One or more fields failed validation",
  "errors": [
    {
      "field": "email",
      "message": "Must be a valid email address",
      "code": "INVALID_EMAIL"
    }
  ]
}
Content-Type:
application/problem+json
For complete error patterns, see references/error-handling.md
json
{
  "type": "https://api.example.com/errors/validation",
  "title": "验证错误",
  "status": 400,
  "detail": "一个或多个字段验证失败",
  "errors": [
    {
      "field": "email",
      "message": "必须是有效的邮箱地址",
      "code": "INVALID_EMAIL"
    }
  ]
}
Content-Type:
application/problem+json
完整的错误处理模式请参考references/error-handling.md

Pagination Patterns

分页模式

Strategy Selection

策略选型

ScenarioStrategyWhy
Small datasets (<1000)Offset-basedSimple, page numbers
Large datasets (>10K)Cursor-basedEfficient, handles writes
Sorted dataKeysetConsistent results
Real-time feedsCursor-basedHandles new items
场景策略原因
小型数据集(<1000条)基于偏移量简单易用,支持页码
大型数据集(>10K条)基于游标性能高效,支持写入操作
排序后的数据基于键集结果一致性高
实时信息流基于游标适配新增内容

Offset-Based (Simple)

基于偏移量(简单易用)

http
GET /users?limit=20&offset=40
Response includes:
limit
,
offset
,
total
,
currentPage
http
GET /users?limit=20&offset=40
响应包含:
limit
offset
total
currentPage

Cursor-Based (Scalable)

基于游标(可扩展)

http
GET /users?limit=20&cursor=eyJpZCI6MTIzfQ==
Cursor is base64-encoded JSON with position information. Response includes:
nextCursor
,
hasNext
For implementation details, see references/pagination-patterns.md
http
GET /users?limit=20&cursor=eyJpZCI6MTIzfQ==
游标是经过base64编码的JSON,包含位置信息。 响应包含:
nextCursor
hasNext
实现细节请参考references/pagination-patterns.md

Rate Limiting

限流机制

Token Bucket Algorithm

令牌桶算法

  • Each user has bucket with tokens
  • Each request consumes 1 token
  • Tokens refill at constant rate
  • Empty bucket rejects request
  • 每个用户拥有一个令牌桶
  • 每次请求消耗1个令牌
  • 令牌以固定速率补充
  • 令牌桶为空时拒绝请求

Rate Limit Headers

限流相关Header

http
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 73
X-RateLimit-Reset: 1672531200
When exceeded (429):
http
Retry-After: 3600
http
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 73
X-RateLimit-Reset: 1672531200
超出限制时(返回429):
http
Retry-After: 3600

Strategies

限流策略

  • Per User: 100 requests/hour
  • Per API Key: 1000 requests/hour
  • Per IP: 50 requests/hour (unauthenticated)
  • Tiered: Free (100/hr), Pro (1000/hr), Enterprise (10000/hr)
For implementation patterns, see references/rate-limiting.md
  • 按用户:100次请求/小时
  • 按API密钥:1000次请求/小时
  • 按IP:50次请求/小时(未认证用户)
  • 分级策略:免费版(100次/小时)、专业版(1000次/小时)、企业版(10000次/小时)
实现模式请参考references/rate-limiting.md

API Security Design

API安全设计

OAuth 2.0 Flows

OAuth 2.0流程

Authorization Code Flow (Web Apps):
  1. Redirect user to authorization server
  2. User grants permission
  3. Exchange code for access token
  4. Use token for API requests
Client Credentials Flow (Service-to-Service):
  1. Authenticate with client ID and secret
  2. Receive access token
  3. Use token for API requests
授权码流程(Web应用):
  1. 将用户重定向到授权服务器
  2. 用户授予权限
  3. 用授权码换取访问令牌
  4. 使用令牌调用API
客户端凭证流程(服务间通信):
  1. 使用客户端ID和密钥认证
  2. 获取访问令牌
  3. 使用令牌调用API

Scope-Based Authorization

基于范围的授权

Define granular permissions:
read:users    - Read user data
write:users   - Create/update users
delete:users  - Delete users
admin:*       - Full admin access
定义细粒度权限:
read:users    - 读取用户数据
write:users   - 创建/更新用户
delete:users  - 删除用户
admin:*       - 完整管理员权限

API Key Management

API密钥管理

Use header-based keys:
http
X-API-Key: sk_live_abc123xyz456
Best practices:
  • Prefix with environment:
    sk_live_*
    ,
    sk_test_*
  • Store hashed keys only
  • Support key rotation
  • Track last-used timestamp
For complete security patterns, see references/authentication.md
使用基于Header的密钥:
http
X-API-Key: sk_live_abc123xyz456
最佳实践:
  • 按环境添加前缀:
    sk_live_*
    sk_test_*
  • 仅存储哈希后的密钥
  • 支持密钥轮换
  • 跟踪最后使用时间戳
完整的安全模式请参考references/authentication.md

OpenAPI Specification

OpenAPI规范

Basic Structure

基本结构

yaml
openapi: 3.1.0
info:
  title: User Management API
  version: 2.0.0

paths:
  /users:
    get:
      summary: List users
      parameters:
        - name: limit
          in: query
          schema:
            type: integer
      responses:
        '200':
          description: Success
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UserList'
OpenAPI enables:
  • Code generation (server stubs, client SDKs)
  • Validation (request/response checking)
  • Mock servers (testing against spec)
  • Documentation (interactive docs)
For complete OpenAPI examples, see examples/openapi/
yaml
openapi: 3.1.0
info:
  title: 用户管理API
  version: 2.0.0

paths:
  /users:
    get:
      summary: 列出用户
      parameters:
        - name: limit
          in: query
          schema:
            type: integer
      responses:
        '200':
          description: 成功
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UserList'
OpenAPI支持:
  • 代码生成(服务端桩代码、客户端SDK)
  • 验证(请求/响应校验)
  • 模拟服务器(基于规范测试)
  • 文档(交互式文档)
完整的OpenAPI示例请查看examples/openapi/

AsyncAPI Specification

AsyncAPI规范

Event-Driven APIs

事件驱动API

AsyncAPI defines message-based APIs (WebSockets, Kafka, MQTT):
yaml
asyncapi: 3.0.0
info:
  title: Order Events API

channels:
  orders/created:
    address: orders.created
    messages:
      orderCreated:
        payload:
          type: object
          properties:
            orderId:
              type: string
For AsyncAPI examples, see examples/asyncapi/
AsyncAPI定义基于消息的API(WebSocket、Kafka、MQTT):
yaml
asyncapi: 3.0.0
info:
  title: 订单事件API

channels:
  orders/created:
    address: orders.created
    messages:
      orderCreated:
        payload:
          type: object
          properties:
            orderId:
              type: string
AsyncAPI示例请查看examples/asyncapi/

GraphQL Design

GraphQL设计

Schema Structure

架构结构

graphql
type User {
  id: ID!
  username: String!
  posts(limit: Int): [Post!]!
}

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

type Mutation {
  createUser(input: CreateUserInput!): User!
}
graphql
type User {
  id: ID!
  username: String!
  posts(limit: Int): [Post!]!
}

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

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

N+1 Problem Solution

N+1问题解决方案

Use DataLoader to batch requests:
javascript
const userLoader = new DataLoader(async (userIds) => {
  // Single query for all users
  const users = await db.users.findByIds(userIds);
  return userIds.map(id => users.find(u => u.id === id));
});
For GraphQL patterns, see references/graphql-design.md
使用DataLoader批量处理请求:
javascript
const userLoader = new DataLoader(async (userIds) => {
  // 一次性查询所有用户
  const users = await db.users.findByIds(userIds);
  return userIds.map(id => users.find(u => u.id === id));
});
GraphQL设计模式请参考references/graphql-design.md

Quick Reference Tables

快速参考表格

Pagination Strategy Selection

分页策略选型

ScenarioStrategy
Small datasetsOffset-based
Large datasetsCursor-based
Sorted dataKeyset
Real-time feedsCursor-based
场景策略
小型数据集基于偏移量
大型数据集基于游标
排序后的数据基于键集
实时信息流基于游标

Versioning Strategy Selection

版本控制策略选型

FactorURL PathHeaderMedia Type
Visibility⭐⭐⭐⭐⭐⭐⭐⭐⭐
Simplicity⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
Best ForMost APIsInternal APIsContent negotiation
考量因素URL路径Header媒体类型
可见性⭐⭐⭐⭐⭐⭐⭐⭐⭐
易用性⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
最佳适用场景大多数API内部API内容协商

Integration with Other Skills

与其他技能的集成

  • api-patterns: Implement API designs in Express, FastAPI, Go
  • auth-security: Implement OAuth2, JWT, session management
  • database-design: Design database schemas for API resources
  • testing-strategies: API testing (integration, contract, load)
  • deploying-applications: Deploy and scale APIs
  • observability: Monitor API performance and errors
  • api-patterns:在Express、FastAPI、Go中实现API设计
  • auth-security:实现OAuth2、JWT、会话管理
  • database-design:为API资源设计数据库架构
  • testing-strategies:API测试(集成测试、契约测试、负载测试)
  • deploying-applications:部署和扩展API
  • observability:监控API性能和错误

Additional Resources

附加资源

Detailed guidance:
  • references/rest-design.md - RESTful patterns and best practices
  • references/graphql-design.md - GraphQL schema and resolver patterns
  • references/versioning-strategies.md - Comprehensive versioning guide
  • references/error-handling.md - RFC 7807 implementation details
  • references/pagination-patterns.md - Pagination implementation patterns
  • references/rate-limiting.md - Rate limiting algorithms and strategies
  • references/authentication.md - OAuth2, API keys, scopes
  • references/protocol-selection.md - Choosing the right API style
Working examples:
  • examples/openapi/ - Complete OpenAPI 3.1 specifications
  • examples/asyncapi/ - Event-driven API specifications
  • examples/graphql/ - GraphQL schemas and patterns
Validation and tooling:
  • scripts/validate-openapi.sh - Validate OpenAPI specifications
详细指南:
  • references/rest-design.md - RESTful模式与最佳实践
  • references/graphql-design.md - GraphQL架构与解析器模式
  • references/versioning-strategies.md - 全面的版本控制指南
  • references/error-handling.md - RFC 7807实现细节
  • references/pagination-patterns.md - 分页实现模式
  • references/rate-limiting.md - 限流算法与策略
  • references/authentication.md - OAuth2、API密钥、权限范围
  • references/protocol-selection.md - 选择合适的API风格
实战示例:
  • examples/openapi/ - 完整的OpenAPI 3.1规范
  • examples/asyncapi/ - 事件驱动API规范
  • examples/graphql/ - GraphQL架构与模式
验证与工具:
  • scripts/validate-openapi.sh - 验证OpenAPI规范