DrillLab
第 91 / 105 道91 / 105 · #316

什么是 CRUD

What is CRUD

先自己答,再往下看Answer it yourself first

一句话:Create / Read / Update / Delete —— 数据操作的四种基本类型。 REST 把它们映射到 HTTP 方法。

操作方法路径成功状态码
CreatePOST/orders201 Created
Read(列表)GET/orders200
Read(单个)GET/orders/:id200,没有则 404
Update(整体)PUT/orders/:id200
Update(部分)PATCH/orders/:id200
DeleteDELETE/orders/:id204 No Content

两个高频追问:

① PUT vs PATCH。PUT整体替换—— 没传的字段应该被清空;PATCH局部更新—— 只改传了的字段。实践中很多人把 PUT 当 PATCH 用, 这是错的,但要知道现实如此。

② 幂等性。同一个请求发多次,结果一样就叫幂等。

  • GET / PUT /DELETE ——幂等
  • POST ——不幂等(发两次会创建两条)
  • PATCH ——看实现{ n: 5 } 幂等,{ n: { $inc: 1 } } 不幂等)

为什么重要:客户端重试、 网关超时重发时, 幂等的接口是安全的,POST 需要幂等键(idempotency key)来防重复下单。

再一个追问:「删一个不存在的资源返回什么?」——可以是 204 也可以是 404。 返 204 更符合幂等语义 (「删完了」这个结果达成了); 返 404 信息更明确。关键是团队内一致, 并且写进接口文档。

In one line: Create / Read / Update / Delete — the four basic things you do to data. REST maps them onto HTTP methods.

OperationMethodPathStatus on success
CreatePOST/orders201 Created
Read (list)GET/orders200
Read (one)GET/orders/:id200, or 404 if it is not there
Update (whole)PUT/orders/:id200
Update (partial)PATCH/orders/:id200
DeleteDELETE/orders/:id204 No Content

Two follow-ups they almost always ask:

① PUT vs PATCH. PUT is a full replacement — fields you leave out should be cleared. PATCH is a partial update — only the fields you send change. Plenty of real code uses PUT as if it were PATCH, which is wrong, but know that it happens.

② Idempotency. Send the same request more than once, get the same result — that is idempotent.

  • GET / PUT / DELETE idempotent
  • POSTnot idempotent (send it twice and you get two records)
  • PATCHdepends on the payload ({ n: 5 } is idempotent, { n: { $inc: 1 } } is not)

Why it matters: when a client retries or a gateway resends after a timeout, an idempotent endpoint is safe. POST needs an idempotency key to stop the same order being placed twice.

One more follow-up: “What do you return when deleting something that does not exist?” — 204 or 404, both defensible. 204 fits the idempotent reading (the outcome you asked for is true); 404 tells the caller more. What matters is that the team agrees and it is in the API docs.