REST API最佳实践
1. 使用名词表示资源
URL标识资源,而非动作。使用复数名词。
✅ GET /users /products/42
❌ GET /getUser /fetchProduct
❌ GET /getUser /fetchProduct
2. HTTP方法语义
为每种操作选择正确的HTTP动词。
GET /users — 获取所有用户
POST /users — 创建用户
GET /users/1 — 获取用户#1
PUT /users/1 — 替换用户#1
PATCH /users/1 — 部分更新
DELETE /users/1 — 删除用户#1
POST /users — 创建用户
GET /users/1 — 获取用户#1
PUT /users/1 — 替换用户#1
PATCH /users/1 — 部分更新
DELETE /users/1 — 删除用户#1
3. 一致的HTTP状态码
200 OK — 成功(GET/PUT/PATCH)
201 Created — 资源已创建(POST)
204 No Content — 成功,无响应体(DELETE)
400 Bad Request — 请求参数无效
401 Unauthorized — 未认证/认证失效
403 Forbidden — 无操作权限
404 Not Found — 资源不存在
422 Unprocessable — 数据验证失败
500 Server Error — 服务器内部错误
201 Created — 资源已创建(POST)
204 No Content — 成功,无响应体(DELETE)
400 Bad Request — 请求参数无效
401 Unauthorized — 未认证/认证失效
403 Forbidden — 无操作权限
404 Not Found — 资源不存在
422 Unprocessable — 数据验证失败
500 Server Error — 服务器内部错误
4. API版本控制
对API进行版本化,避免破坏性变更。
✅ /api/v1/users
✅ Accept: application/vnd.myapi.v2+json
✅ Accept: application/vnd.myapi.v2+json
5. 分页、过滤、排序
GET /users?page=2&limit=20
GET /products?sort=price&order=asc
GET /orders?status=pending&userId=42
GET /products?sort=price&order=asc
GET /orders?status=pending&userId=42
6. 使用JSON作为请求/响应格式
始终设置Content-Type: application/json。错误响应统一包含code、message和details字段。