api-design
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAPI Design
API设计
When to use this skill
何时使用此技能
- Designing new REST APIs
- Creating GraphQL schemas
- Refactoring API endpoints
- Documenting API specifications
- API versioning strategies
- Defining data models and relationships
- 设计新的REST API
- 创建GraphQL schema
- 重构API端点
- 编写API规范
- API版本管理策略
- 定义数据模型与实体关系
Instructions
操作指南
Step 1: Define API requirements
步骤1:定义API需求
- Identify resources and entities
- Define relationships between entities
- Specify operations (CRUD, custom actions)
- Plan authentication/authorization
- Consider pagination, filtering, sorting
- 识别资源与实体
- 定义实体间的关系
- 指定操作类型(CRUD、自定义操作)
- 规划认证/授权机制
- 考虑分页、过滤、排序功能
Step 2: Design REST API
步骤2:设计REST API
Resource naming:
- Use nouns, not verbs: not
/users/getUsers - Use plural names:
/users/{id} - Nest resources logically:
/users/{id}/posts - Keep URLs short and intuitive
HTTP methods:
- : Retrieve resources (idempotent)
GET - : Create new resources
POST - : Replace entire resource
PUT - : Partial update
PATCH - : Remove resources (idempotent)
DELETE
Response codes:
- : Success with response body
200 OK - : Resource created successfully
201 Created - : Success with no response body
204 No Content - : Invalid input
400 Bad Request - : Authentication required
401 Unauthorized - : No permission
403 Forbidden - : Resource doesn't exist
404 Not Found - : Resource conflict
409 Conflict - : Validation failed
422 Unprocessable Entity - : Server error
500 Internal Server Error
Example REST endpoint:
GET /api/v1/users # List users
GET /api/v1/users/{id} # Get user
POST /api/v1/users # Create user
PUT /api/v1/users/{id} # Update user
PATCH /api/v1/users/{id} # Partial update
DELETE /api/v1/users/{id} # Delete user资源命名规则:
- 使用名词而非动词:而非
/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} # 删除用户Step 3: Request/Response format
步骤3:请求/响应格式
Request example:
json
POST /api/v1/users
Content-Type: application/json
{
"name": "John Doe",
"email": "john@example.com",
"role": "admin"
}Response example:
json
HTTP/1.1 201 Created
Content-Type: application/json
Location: /api/v1/users/123
{
"id": 123,
"name": "John Doe",
"email": "john@example.com",
"role": "admin",
"created_at": "2024-01-15T10:30:00Z",
"updated_at": "2024-01-15T10:30:00Z"
}请求示例:
json
POST /api/v1/users
Content-Type: application/json
{
"name": "John Doe",
"email": "john@example.com",
"role": "admin"
}响应示例:
json
HTTP/1.1 201 Created
Content-Type: application/json
Location: /api/v1/users/123
{
"id": 123,
"name": "John Doe",
"email": "john@example.com",
"role": "admin",
"created_at": "2024-01-15T10:30:00Z",
"updated_at": "2024-01-15T10:30:00Z"
}Step 4: Error handling
步骤4:错误处理
Error response format:
json
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid input provided",
"details": [
{
"field": "email",
"message": "Invalid email format"
}
]
}
}错误响应格式:
json
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid input provided",
"details": [
{
"field": "email",
"message": "Invalid email format"
}
]
}
}Step 5: Pagination
步骤5:分页功能
Query parameters:
GET /api/v1/users?page=2&limit=20&sort=-created_at&filter=role:adminResponse with pagination:
json
{
"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"
}
}查询参数示例:
GET /api/v1/users?page=2&limit=20&sort=-created_at&filter=role:admin带分页的响应示例:
json
{
"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"
}
}Step 6: Authentication
步骤6:认证机制
Options:
- JWT (JSON Web Tokens)
- OAuth 2.0
- API Keys
- Session-based
Example with JWT:
GET /api/v1/users
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...可选方案:
- JWT (JSON Web Tokens)
- OAuth 2.0
- API密钥
- 基于会话的认证
JWT示例:
GET /api/v1/users
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...Step 7: Versioning
步骤7:版本管理
URL versioning (recommended):
/api/v1/users
/api/v2/usersHeader versioning:
GET /api/users
Accept: application/vnd.api+json; version=1URL版本管理(推荐):
/api/v1/users
/api/v2/users请求头版本管理:
GET /api/users
Accept: application/vnd.api+json; version=1Step 8: Documentation
步骤8:文档编写
Create OpenAPI 3.0 specification:
yaml
openapi: 3.0.0
info:
title: User Management API
version: 1.0.0
description: API for managing users
servers:
- url: https://api.example.com/v1
paths:
/users:
get:
summary: List users
parameters:
- name: page
in: query
schema:
type: integer
default: 1
- name: limit
in: query
schema:
type: integer
default: 20
responses:
'200':
description: Successful response
content:
application/json:
schema:
type: object
properties:
data:
type: array
items:
$ref: '#/components/schemas/User'
post:
summary: Create user
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/UserCreate'
responses:
'201':
description: User created
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创建OpenAPI 3.0规范:
yaml
openapi: 3.0.0
info:
title: User Management API
version: 1.0.0
description: API for managing users
servers:
- url: https://api.example.com/v1
paths:
/users:
get:
summary: List users
parameters:
- name: page
in: query
schema:
type: integer
default: 1
- name: limit
in: query
schema:
type: integer
default: 20
responses:
'200':
description: Successful response
content:
application/json:
schema:
type: object
properties:
data:
type: array
items:
$ref: '#/components/schemas/User'
post:
summary: Create user
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/UserCreate'
responses:
'201':
description: User created
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: emailBest practices
最佳实践
- Consistency: Use consistent naming, structure, and patterns
- Versioning: Always version your APIs from the start
- Security: Implement authentication and authorization
- Validation: Validate all inputs on the server side
- Rate limiting: Protect against abuse
- Caching: Use ETags and Cache-Control headers
- CORS: Configure properly for web clients
- Documentation: Keep docs up-to-date with code
- Testing: Test all endpoints thoroughly
- Monitoring: Log requests and track performance
- 一致性:使用统一的命名、结构和模式
- 版本管理:从项目初期就为API添加版本管理
- 安全性:实现认证与授权机制
- 输入验证:在服务端验证所有输入内容
- 请求限流:防止API被滥用
- 缓存策略:使用ETag和Cache-Control请求头
- CORS配置:为Web客户端正确配置跨域资源共享
- 文档维护:保持文档与代码同步更新
- 测试覆盖:全面测试所有API端点
- 监控追踪:记录请求并跟踪性能指标
Common patterns
常见模式
Filtering:
GET /api/v1/users?role=admin&status=activeSorting:
GET /api/v1/users?sort=-created_at,nameField selection:
GET /api/v1/users?fields=id,name,emailBatch operations:
POST /api/v1/users/batch
{
"operations": [
{"action": "create", "data": {...}},
{"action": "update", "id": 123, "data": {...}}
]
}过滤功能:
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 alternative
GraphQL替代方案
If REST doesn't fit, consider GraphQL:
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!
}如果REST不符合需求,可以考虑使用GraphQL:
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!
}References
参考资料
Examples
示例
Example 1: Basic usage
示例1:基础用法
<!-- Add example content here -->
<!-- 在此添加示例内容 -->
Example 2: Advanced usage
示例2:高级用法
<!-- Add advanced example content here -->
<!-- 在此添加高级示例内容 -->