HTTP 方法

GET/POST/PUT/PATCH/DELETE 的语义、安全性与幂等性,以及幂等键的用法。

Beginner
Key Points方法决定语义:GET 只读、POST 创建、PUT 整体替换、PATCH 局部更新、DELETE 删除;除 POST 外都应幂等。

五个方法

MethodMeaningSafeIdempotentTypical status
GETRead a resourceYesYes200 / 404
POSTCreate under a collectionNoNo201 + Location
PUTReplace the whole resourceNoYes200 / 204
PATCHPartially updateNoUsually200 / 204
DELETERemove the resourceNoYes204 / 404

安全与幂等

Safe means it does not change server state; idempotent means one call and N calls leave the same result. These properties decide what browsers, proxies and retry logic may do: GET can be prefetched, PUT/DELETE retried automatically, POST cannot.

Text
PUT    /users/42  {"name": "Alice"}     # 调 3 次,结果一样 —— 幂等
DELETE /users/42                        # 第一次 204,之后 404,但状态一致 —— 幂等
POST   /users     {"name": "Alice"}     # 调 3 次建 3 个用户 —— 不幂等

PUT 与 PATCH 怎么选

  • PUT — the body is the complete new state; omitted fields are cleared
  • PATCH — the body carries only the changes; use a diff or JSON Merge Patch
  • When in doubt, PATCH for forms that submit a subset of fields
Text
PUT   /users/42   {"name": "Alice", "email": "a@x.com", "age": 30}
PATCH /users/42   {"email": "a@x.com"}

让 POST 也幂等:幂等键

Retried payments or orders would double-charge. The client sends a unique Idempotency-Key header; the server remembers whether it has seen that key and replays the first result instead of re-executing.

Text
POST /payments HTTP/1.1
Idempotency-Key: 3f2a9c10-8b7e-4a1d-9c2f-1e5b7d0a6c33
Content-Type: application/json

{"orderId": 9001, "amount": 19900}
Persist the key (Redis or a unique index) with a TTL such as 24 hours. Keeping it in memory fails as soon as you run more than one instance.

常见误用

  • 用 GET 做删除或修改 —— 爬虫和预取会真的删数据
  • 用 POST 做查询 —— 失去缓存与可收藏的 URL
  • 用 PUT 只传部分字段 —— 没传的字段被清空
  • 用 DELETE 返回 200 加一段 JSON —— 用 204 更干净

Friends & Partners