📜  put vs patch (1)

📅  最后修改于: 2023-12-03 15:03:53.860000             🧑  作者: Mango

Put vs Patch

When it comes to updating data in a RESTful API, there are two HTTP methods that are commonly used: PUT and PATCH. Both of these methods have the same objective of updating data, however, there are some significant differences between them.

PUT Method

The PUT method is used to update a resource on the server. If the resource does not exist, a new resource will be created. This method is idempotent, meaning if the same request is made multiple times, the result will be the same.

Usage

The PUT method is typically used to replace or edit an entire resource. For example, if you have a user resource and want to update the user's name, you would send a PUT request to the user's endpoint with the updated information.

Example
PUT /users/1 HTTP/1.1
Host: example.com
Content-Type: application/json

{
    "name": "John Doe",
    "email": "johndoe@example.com"
}
PATCH Method

The PATCH method is used to update only the specified fields of a resource on the server. This method is not idempotent, meaning if the same request is made multiple times, the result may not be the same.

Usage

The PATCH method is typically used to make partial updates to a resource. For example, if you have a user resource and want to update only the user's email, you would send a PATCH request to the user's endpoint with the updated information.

Example
PATCH /users/1 HTTP/1.1
Host: example.com
Content-Type: application/json

{
    "email": "newemail@example.com"
}
Conclusion

In conclusion, the main difference between PUT and PATCH is that PUT replaces or edits an entire resource, while PATCH makes partial updates to a resource. When designing a RESTful API, it is important to choose the appropriate method for updating resources depending on the needs of your application.