rest-api

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

REST 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/123
)标识的资源。

HTTP Verbs

HTTP 动词

Use verbs to define actions, not URIs.
  • GET /orders
    (List)
  • POST /orders
    (Create)
  • PATCH /orders/1
    (Update partial)
  • DELETE /orders/1
    (Remove)
使用动词定义操作,而非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=active

Versioning

版本控制

  • URI Versioning:
    /v1/users
    (Most common).
  • 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 (
    user_id
    ) in JSON responses (standard convention) or camelCase if consistent with JS ecosystem.
  • 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.,
    { "error": "failed" }
    with status 200).
  • 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响应中使用蛇形命名法
    user_id
    ,标准约定),如果与JS生态系统一致也可使用驼峰命名法。
  • 实现速率限制以保护资源。
建议不要做
  • 不要使用GET执行会改变状态的操作。
  • 错误时不要返回200 OK(例如,返回
    { "error": "failed" }
    却使用200状态码)。
  • 尽可能不要暴露数据库ID(使用UUID)。

Troubleshooting

故障排除

ErrorCauseSolution
405 Method Not Allowed
Sending POST to a GET-only endpoint.Check HTTP verb.
415 Unsupported Media Type
Sending XML when JSON expected.Set
Content-Type: application/json
.
CORS Error
Browser blocking cross-origin request.Set
Access-Control-Allow-Origin
headers on server.
错误原因解决方案
405 Method Not Allowed
向仅支持GET的端点发送POST请求检查HTTP动词
415 Unsupported Media Type
当期望JSON时发送了XML格式数据设置
Content-Type: application/json
请求头
CORS Error
浏览器阻止跨域请求在服务器上设置
Access-Control-Allow-Origin
响应头

References

参考资料