RESTful API 概念

资源、表述、无状态、统一接口四个核心概念,以及 Richardson 成熟度模型。

Beginner
Key PointsREST 把一切抽象成资源:URL 是资源的名字,JSON 是资源某一时刻的表述,客户端通过统一的方法操作这些表述。

资源(Resource)

A resource is a named entity: a user, an order, a collection of orders. The URL only identifies it; operations are expressed by the HTTP method. /users/42 is the name of user 42 — reading, updating and deleting all reuse that name.

Text
/users            集合资源(所有用户)
/users/42         单个资源(42 号用户)
/users/42/orders  子集合(42 号用户的订单)

表述(Representation)

The server never ships the resource itself, only a representation of it at a point in time. One resource may have many representations — JSON, XML, CSV, HTML — and the client asks for one with Accept.

JSON
{
  "id": 42,
  "name": "Alice",
  "email": "alice@example.com",
  "_links": {
    "self":   {"href": "/users/42"},
    "orders": {"href": "/users/42/orders"}
  }
}

无状态(Stateless)

The server keeps no client state between requests: each request carries its own identity (Authorization) and all parameters. Any instance can serve any request, so scaling is just adding machines; the cost is repeating that context every time.

Text
有状态(不推荐):GET /next-page          ← 依赖服务端记住「你上次看到第几页」
无状态(推荐):    GET /users?page=3&size=20  ← 翻页信息由客户端携带

统一接口(Uniform Interface)

  • Resource identification — URLs name things, not actions
  • Manipulation through representations — the client edits the JSON, then sends it back
  • Self-descriptive messages — Content-Type and status codes carry the meaning
  • HATEOAS — responses link to the next possible actions

Richardson 成熟度模型

LevelWhat it doesExample
L0One endpoint, one verb (tunnel)POST /api with an action field
L1Resources, but still one verbPOST /users/42
L2HTTP verbs + status codesGET/PUT/DELETE /users/42
L3HATEOAS: hypermedia drives the clientResponse carries _links
Most so-called RESTful APIs sit at L2, which is already practical: correct verbs, accurate status codes, noun URLs. Do not force L3 links unless clients genuinely discover capabilities from them.

Friends & Partners