RESTful URL

URL 用名词、层级表达从属、查询参数表达过滤与分页、版本号放哪里。

Beginner
Key PointsURL 只标识资源:路径用复数名词、层级表达从属,过滤/排序/分页一律走查询参数。

用名词,不用动词

The method already expresses the action, so a verb in the path is redundant. The test: read the URL aloud — it should name a thing, not an operation.

BadGood
GET /getUsersGET /users
POST /createUserPOST /users
POST /users/42/deleteDELETE /users/42
GET /users/42/getOrdersGET /users/42/orders

层级表达从属

Express ownership through nesting, but keep it at most two levels deep; anything deeper deserves its own top-level address.

Text
GET  /users/42/orders            42 号用户的订单
GET  /users/42/orders/7          42 号用户的 7 号订单
GET  /orders/7                   更好:订单本身有全局 id 时直接访问

过滤、排序、分页走查询参数

These are view parameters over a collection, not new resources. Putting them in the path explodes the URL space and breaks caching.

Text
GET /orders?status=paid&minTotal=100
GET /orders?sort=-createdAt,total
GET /orders?page=3&size=20
GET /orders?cursor=eyJpZCI6OTAwMX0

版本号放哪里

OptionExampleTrade-off
Path/v1/usersSimplest, easy to route and cache
HeaderAccept: application/vnd.api.v2+jsonClean URLs, harder to test by hand
Query/users?version=2Easy but pollutes caching keys
Bump the version only for breaking changes; adding fields or optional parameters is not one. A published version must be maintained for a long time — avoid adding one unless you must.

命名规范清单

  • 集合用复数:/users、/orders
  • 一律小写,多个单词用连字符:/order-items
  • 不要在 URL 里出现文件扩展名:用 Accept 协商
  • 不要在 URL 里放自增 id 之外的含义,如 /users/me 只作为别名
  • 结尾不加斜杠,全站统一

Friends & Partners