RESTful API 教程
REST 是什么、它约束了什么,以及一个最小可用的 REST 请求长什么样。
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 的区别
| Style | Addressing | Action | Typical payload |
|---|---|---|---|
| REST | Resource noun: /users/42 | HTTP verb | JSON |
| RPC | Verb in the path: /getUser?id=42 | Any method name | JSON / XML |
| SOAP | Single endpoint: /ws | Envelope element | XML 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".
学习路线
- Concepts — resources, representations, statelessness
- HTTP methods — verbs, safety and idempotency
- URL design — nouns, nesting, filtering, versioning
- Request & response — headers, status codes, error shape
- Practice — pagination, idempotency, rate limiting, debugging
REST 是什么
REST(Representational State Transfer,表述性状态转移)由 Roy Fielding 在 2000 年的博士论文中提出。它不是协议、不是标准,而是一组架构约束:满足这些约束的接口风格就叫 RESTful。HTTP 本身只是承载它的传输层,真正决定「像不像 REST」的是接口设计。
一个最小的 REST 请求
客户端向一个「资源地址」发起请求,服务端返回该资源的当前表述(通常是 JSON),并用状态码说明结果。整个过程不依赖之前的任何一次请求。
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"}六条架构约束
- 客户端-服务端 —— 界面与数据存储各自独立演进
- 无状态 —— 每个请求自带全部上下文
- 可缓存 —— 响应要声明能否缓存
- 统一接口 —— 资源、表述、自描述消息、HATEOAS
- 分层系统 —— 网关、代理对客户端透明
- 按需代码(可选)—— 服务端可下发可执行代码
和 RPC / SOAP 的区别
| 风格 | 寻址 | 动作 | 典型载荷 |
|---|---|---|---|
| REST | 资源名词:/users/42 | HTTP 方法 | JSON |
| RPC | 路径里带动词:/getUser?id=42 | 任意方法名 | JSON / XML |
| SOAP | 单端点:/ws | 信封元素 | 仅 XML |
REST 的收益不在「更高级」,而在于:URL 可被缓存、可被浏览器/网关理解、可被任何人用 curl 复现。设计接口时优先问「这是什么资源」,而不是「要调用哪个函数」。
学习路线
- 概念 —— 资源、表述、无状态
- HTTP 方法 —— 语义、安全性与幂等
- URL 设计 —— 名词、层级、过滤、版本
- 请求与响应 —— 头、状态码、错误结构
- 实践 —— 分页、幂等、限流、调试