RESTful API 教程

REST 是什么、它约束了什么,以及一个最小可用的 REST 请求长什么样。

Beginner
Key PointsREST 是一种架构风格而不是协议:用 URL 标识资源,用 HTTP 方法表达动作,用状态码表达结果,服务端不保存会话。

REST 是什么

REST (Representational State Transfer) was defined by Roy Fielding in his 2000 dissertation. It is not a protocol or a standard but a set of architectural constraints; an API that honours them is called RESTful. HTTP is only the transport — what makes an API RESTful is how it is designed.

一个最小的 REST 请求

The client requests a resource address, the server returns the current representation (usually JSON) plus a status code describing the outcome. Nothing depends on earlier requests.

Text
GET /api/users/42 HTTP/1.1
Host: api.example.com
Accept: application/json

HTTP/1.1 200 OK
Content-Type: application/json

{"id": 42, "name": "Alice", "email": "alice@example.com"}

六条架构约束

  • Client–Server — the UI and the data store evolve independently
  • Stateless — every request carries all the context it needs
  • Cacheable — responses declare whether they may be cached
  • Uniform interface — resources, representations, self-descriptive messages, HATEOAS
  • Layered system — gateways and proxies are invisible to the client
  • Code on demand (optional) — the server may ship executable code

和 RPC / SOAP 的区别

StyleAddressingActionTypical payload
RESTResource noun: /users/42HTTP verbJSON
RPCVerb in the path: /getUser?id=42Any method nameJSON / XML
SOAPSingle endpoint: /wsEnvelope elementXML only
The payoff of REST is not sophistication but leverage: URLs can be cached, understood by browsers and gateways, and reproduced by anyone with curl. Design by asking "what resource is this", not "which function do I call".

学习路线

  1. Concepts — resources, representations, statelessness
  2. HTTP methods — verbs, safety and idempotency
  3. URL design — nouns, nesting, filtering, versioning
  4. Request & response — headers, status codes, error shape
  5. Practice — pagination, idempotency, rate limiting, debugging

Friends & Partners