REST API 设计原则:构建直观易用的 API
良好的 API 设计能减少消费者的使用障碍,加速集成。
资源命名
# 错误:基于动词的 URL
GET /getUsers
POST /createUser
PUT /updateUser/1
GET /deleteUser/1
# 正确:基于名词的资源 + HTTP 动词
GET /users 列出用户
POST /users 创建用户
GET /users/1 获取用户
PUT /users/1 替换用户
PATCH /users/1 部分更新
DELETE /users/1 删除用户
# 嵌套资源表示关系
GET /users/1/orders 用户的订单
POST /users/1/orders 为用户创建订单
GET /users/1/orders/5 特定订单

HTTP 状态码
2xx 成功:
200 OK - GET/PUT/PATCH 成功
201 Created - POST 创建资源
204 No Content - DELETE 成功(无响应体)
4xx 客户端错误:
400 Bad Request - 无效输入/格式错误请求
401 Unauthorized - 未认证
403 Forbidden - 已认证但无权限
404 Not Found - 资源不存在
409 Conflict - 资源冲突(如重复)
422 Unprocessable Entity - 验证失败
5xx 服务器错误:
500 Internal Server Error - 服务器内部错误
503 Service Unavailable - 临时不可用
错误响应格式
{
"error": {
"code": "VALIDATION_FAILED",
"message": "请求验证失败",
"details": [
{
"field": "email",
"code": "INVALID_FORMAT",
"message": "邮箱必须是有效的邮箱地址"
},
{
"field": "age",
"code": "MIN_VALUE",
"message": "年龄必须至少为 18"
}
],
"requestId": "req_abc123",
"timestamp": "2025-01-01T00:00:00Z"
}
}

过滤、排序、分页
# 过滤
GET /users?status=active&role=admin
# 排序
GET /users?sort=createdAt:desc,name:asc
# 分页(基于游标 - 大数据集推荐)
GET /users?limit=20&cursor=eyJpZCI6MTB9
# 分页(基于偏移 - 更简单)
GET /users?limit=20&offset=40
# 字段选择(稀疏字段集)
GET /users?fields=id,name,email
分页响应
{
"data": [...],
"pagination": {
"total": 1000,
"limit": 20,
"offset": 40,
"nextCursor": "eyJpZCI6NjB9",
"hasMore": true
}
}

版本管理
# URL 版本(最常见)
GET /v1/users
GET /v2/users
# 头部版本
GET /users
Accept: application/vnd.myapi.v2+json
# 查询参数(REST 中避免使用)
GET /users?version=2
幂等性
# 幂等键用于安全重试
POST /payments
Idempotency-Key: pay_unique_client_key_123
# 服务器存储结果,重复请求返回相同响应
HATEOAS 链接
{
"id": 1,
"name": "Alice",
"links": {
"self": "/users/1",
"orders": "/users/1/orders",
"profile": "/users/1/profile"
}
}
一致且设计良好的 API 能将集成时间从数周缩短至数小时。