rest-api
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseREST API
REST API
Representational State Transfer (REST) is the architectural style for distributed hypermedia systems. It relies on stateless, client-server, cacheable communications protocols (mostly HTTP).
Representational State Transfer(REST)是分布式超媒体系统的架构风格,它依赖于无状态、客户端-服务器、可缓存的通信协议(主要是HTTP)。
When to Use
适用场景
- Public APIs: The universal standard; easiest for 3rd parties to consume.
- Simple Resource Access: Perfect for CRUD (Create, Read, Update, Delete) operations.
- Caching: When you need to leverage HTTP caching (CDNs, Browsers).
- 公开API:通用标准,第三方最容易使用。
- 简单资源访问:非常适合CRUD(创建、读取、更新、删除)操作。
- 缓存需求:当你需要利用HTTP缓存(CDN、浏览器)时。
Quick Start
快速入门
typescript
// Express.js Example
app.get("/users/:id", async (req, res) => {
const user = await db.find(req.params.id);
if (!user) return res.status(404).json({ error: "Not Found" });
// HATEOAS (Hypermedia As The Engine Of Application State) - optional but "True REST"
res.json({
...user,
links: {
self: `/users/${user.id}`,
orders: `/users/${user.id}/orders`,
},
});
});typescript
// Express.js Example
app.get("/users/:id", async (req, res) => {
const user = await db.find(req.params.id);
if (!user) return res.status(404).json({ error: "Not Found" });
// HATEOAS (Hypermedia As The Engine Of Application State) - optional but "True REST"
res.json({
...user,
links: {
self: `/users/${user.id}`,
orders: `/users/${user.id}/orders`,
},
});
});Core Concepts
核心概念
Resources
资源
Everything is a resource identified by a URI ().
/users/123所有事物都是通过URI()标识的资源。
/users/123HTTP Verbs
HTTP 动词
Use verbs to define actions, not URIs.
- (List)
GET /orders - (Create)
POST /orders - (Update partial)
PATCH /orders/1 - (Remove)
DELETE /orders/1
使用动词定义操作,而非URI。
- (列表)
GET /orders - (创建)
POST /orders - (部分更新)
PATCH /orders/1 - (删除)
DELETE /orders/1
Statelessness
无状态性
Each request must contain all information necessary to understand the request. The server accepts no session state.
每个请求必须包含理解该请求所需的全部信息,服务器不保存会话状态。
Common Patterns
常见模式
Filtering, Sorting, Pagination
过滤、排序、分页
Standard query params: .
?sort=-created_at&limit=10&page=2&status=active标准查询参数:。
?sort=-created_at&limit=10&page=2&status=activeVersioning
版本控制
- URI Versioning: (Most common).
/v1/users - Header Versioning: .
Accept: application/vnd.myapi.v1+json
- URI版本控制:(最常用)。
/v1/users - 请求头版本控制:。
Accept: application/vnd.myapi.v1+json
Best Practices
最佳实践
Do:
- Use proper HTTP Status Codes (200 OK, 201 Created, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 500 Server Error).
- Use Snake Case () in JSON responses (standard convention) or camelCase if consistent with JS ecosystem.
user_id - Implement Rate Limiting to protect resources.
Don't:
- Don't use GET for state-changing operations.
- Don't return 200 OK for errors (e.g., with status 200).
{ "error": "failed" } - Don't expose database IDs if possible (use UUIDs).
建议做:
- 使用正确的HTTP状态码(200 OK、201 Created、400 Bad Request、401 Unauthorized、403 Forbidden、404 Not Found、500 Server Error)。
- 在JSON响应中使用蛇形命名法(,标准约定),如果与JS生态系统一致也可使用驼峰命名法。
user_id - 实现速率限制以保护资源。
建议不要做:
- 不要使用GET执行会改变状态的操作。
- 错误时不要返回200 OK(例如,返回却使用200状态码)。
{ "error": "failed" } - 尽可能不要暴露数据库ID(使用UUID)。
Troubleshooting
故障排除
| Error | Cause | Solution |
|---|---|---|
| Sending POST to a GET-only endpoint. | Check HTTP verb. |
| Sending XML when JSON expected. | Set |
| Browser blocking cross-origin request. | Set |
| 错误 | 原因 | 解决方案 |
|---|---|---|
| 向仅支持GET的端点发送POST请求 | 检查HTTP动词 |
| 当期望JSON时发送了XML格式数据 | 设置 |
| 浏览器阻止跨域请求 | 在服务器上设置 |