designing-apis
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDesigning 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 skill for Express, FastAPI code)
api-patterns - Authentication implementation (use skill for JWT, sessions)
auth-security - API testing strategies (use skill)
testing-strategies - API deployment and infrastructure (use skill)
deploying-applications
适用于以下场景:
- 设计新的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 /createUserNest 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方法语义
| Method | Idempotent | Safe | Use For | Success Status |
|---|---|---|---|---|
| GET | Yes | Yes | Read resource | 200 OK |
| POST | No | No | Create resource | 201 Created |
| PUT | Yes | No | Replace entire resource | 200 OK, 204 No Content |
| PATCH | No | No | Update specific fields | 200 OK, 204 No Content |
| DELETE | Yes | No | Remove resource | 204 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
决策矩阵
| Factor | REST | GraphQL | WebSocket | Message Queue |
|---|---|---|---|---|
| Public API | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐ | ⭐ |
| Complex Data | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐ | ⭐⭐ |
| Caching | ⭐⭐⭐⭐⭐ | ⭐⭐ | ⭐ | ⭐ |
| Real-time | ⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
| Simplicity | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐ |
| 考量因素 | REST | GraphQL | WebSocket | 消息队列 |
|---|---|---|---|---|
| 公开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/usersPros: 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: (not recommended)
?version=1
- 基于Header:
Accept-Version: v1 - 基于媒体类型:
Accept: application/vnd.example.v1+json - 基于查询参数:(不推荐)
?version=1
Breaking Change Management
破坏性变更管理
Timeline:
- Month 0: Announce deprecation
- Months 1-3: Migration period
- Months 4-6: Deprecation warnings
- 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
时间线:
- 第0个月:宣布废弃
- 第1-3个月:迁移过渡期
- 第4-6个月:返回废弃警告
- 第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+jsonFor 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
策略选型
| Scenario | Strategy | Why |
|---|---|---|
| Small datasets (<1000) | Offset-based | Simple, page numbers |
| Large datasets (>10K) | Cursor-based | Efficient, handles writes |
| Sorted data | Keyset | Consistent results |
| Real-time feeds | Cursor-based | Handles new items |
| 场景 | 策略 | 原因 |
|---|---|---|
| 小型数据集(<1000条) | 基于偏移量 | 简单易用,支持页码 |
| 大型数据集(>10K条) | 基于游标 | 性能高效,支持写入操作 |
| 排序后的数据 | 基于键集 | 结果一致性高 |
| 实时信息流 | 基于游标 | 适配新增内容 |
Offset-Based (Simple)
基于偏移量(简单易用)
http
GET /users?limit=20&offset=40Response includes: , , ,
limitoffsettotalcurrentPagehttp
GET /users?limit=20&offset=40响应包含:、、、
limitoffsettotalcurrentPageCursor-Based (Scalable)
基于游标(可扩展)
http
GET /users?limit=20&cursor=eyJpZCI6MTIzfQ==Cursor is base64-encoded JSON with position information.
Response includes: ,
nextCursorhasNextFor implementation details, see references/pagination-patterns.md
http
GET /users?limit=20&cursor=eyJpZCI6MTIzfQ==游标是经过base64编码的JSON,包含位置信息。
响应包含:、
nextCursorhasNext实现细节请参考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: 1672531200When exceeded (429):
http
Retry-After: 3600http
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 73
X-RateLimit-Reset: 1672531200超出限制时(返回429):
http
Retry-After: 3600Strategies
限流策略
- 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):
- Redirect user to authorization server
- User grants permission
- Exchange code for access token
- Use token for API requests
Client Credentials Flow (Service-to-Service):
- Authenticate with client ID and secret
- Receive access token
- Use token for API requests
授权码流程(Web应用):
- 将用户重定向到授权服务器
- 用户授予权限
- 用授权码换取访问令牌
- 使用令牌调用API
客户端凭证流程(服务间通信):
- 使用客户端ID和密钥认证
- 获取访问令牌
- 使用令牌调用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_abc123xyz456Best 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: stringFor 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: stringAsyncAPI示例请查看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
分页策略选型
| Scenario | Strategy |
|---|---|
| Small datasets | Offset-based |
| Large datasets | Cursor-based |
| Sorted data | Keyset |
| Real-time feeds | Cursor-based |
| 场景 | 策略 |
|---|---|
| 小型数据集 | 基于偏移量 |
| 大型数据集 | 基于游标 |
| 排序后的数据 | 基于键集 |
| 实时信息流 | 基于游标 |
Versioning Strategy Selection
版本控制策略选型
| Factor | URL Path | Header | Media Type |
|---|---|---|---|
| Visibility | ⭐⭐⭐⭐⭐ | ⭐⭐ | ⭐⭐ |
| Simplicity | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐ |
| Best For | Most APIs | Internal APIs | Content 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规范