Rest Api:何时使用Post、PUT、PATCH 和 Delete

Rest Api: When to use Post, PUT, PATCH and Delete

我正在处理 restful api,我需要更新资源(即包含 10 个字段的客户详细信息记录)。

在添加请求时,我发送了一个包含完整记录的 Post 请求。 根据更新请求,我发送了一个包含 10 个字段的完整记录的 PUT 请求。 在验证请求时,我发送了一个只有两个字段的 PUT 请求,即 recordId 和 versionNo。 在删除请求时,我发送了一个包含 HttpOptions 中两个字段的 DELETE 请求。

我有几个问题:

REST 响应

A RESTful API 必须 始终使用 HTTP 代码响应客户端请求:

Success and error responses are a vital part to define how an API is used correctly.

请参阅 this 指南以解决所有 RESTful 相关问题。


PATCH/PUT

来自Wikipedia

The main difference between the PUT and PATCH method is that the PUT method uses the request URI to supply a modified version of the requested resource which replaces the original version of the resource whereas the PATCH method supplies a set of instructions to modify the resource. If the PATCH document is larger than the size of the new version of the resource sent by the PUT method then the PUT method is preferred.

还有:

Using the PUT method consumes more bandwidth as compared to the PATCH method when only a few changes need to be applied to a resource. But when the PATCH method is used, it usually involves fetching the resource from the server, comparing the original and new files, creating and sending a diff file. On the server side, the server has to read the diff file and make the modifications. This involves a lot of overhead compared to the PUT method.[11] On the other hand, the PUT method requires a GET to be performed before the PUT and it is difficult to ensure that the resource is not modified between the GET and PUT requests.

所以我将使用 PATCH 来验证资源。


删除

通常,对于 DELETE 请求,客户端指定资源的 id 并将其作为 路径变量 传递在 URL:

curl -X DELETE http://example.com/resource/{id}

但是您也可以根据请求传递正文。这种可能性由 MDN Mozilla Web DOCS 声明:

Request has body - May

Successful response has body - May

Should I use PATCH in case of Verify (or anyother action where just recordId and versionNo send to server to change some fields) or it is OK to use PUT.

在RESTful API设计中,PUT请求通常用于添加或替换整个资源,而PATCH应该只用于更新现有资源。 PUT 请求称为 "idempotent" - 无论您发送多少次 PUT 响应,您都应该得到相同的结果。 PATCH 不是幂等的。

示例:

PATCH /Cars/vauxhall-astra/engine --> 此请求将仅用于更新我现有的 vauxhall astra

的引擎

PUT /Cars/renault-clio --> 此请求将创建一个新的 Renault Clio,或者,如果它已经存在,则使用我的请求中指定的数据替换整个 Clio。一个Clio在我请求成功后就会保证存在,不管之前是否存在

Although, it a restful api but specific application which would be used by an angular application, So should I return data in response of POST/PUT requests.

完全取决于您,从 POST/PUT 返回数据很好 - 特别是如果它可以让您不必发出额外的 GET api 请求。始终确保您只从响应中返回所需的数据。

To make uniformity, should I send data in body of delete request as I need recordId and versionNo to delete a record.

同样,这完全取决于您。无论您使用查询参数(例如 DELETE cars?id=123)还是请求主体只是您的偏好,REST 中都没有这方面的规则。

尽管其他人已经在我之前详细回答了这个问题,但我仍然发布这个只是为了提供一个所有这些 HTTP 方法之间的方便的简短区别

1.HTTP Post:It 用于创建一个项目

2.HTTP Put:It 用于更新项目

3.HTTP Patch:It 用于部分更新项目

4.HTTP Delete:It用于删除一个项目