Difference Between PUT and PATCH in REST API
PUT is used to replace the entire resource with a new one.
PATCH is used to modify an existing resource by updating only certain fields.
1. PUT Request
Purpose: Replace the entire resource with the updated content.
Characteristics:
Replaces the entire resource.
If the resource does not exist, it creates a new one.
The client must send a complete resource representation in the request.
Example:
Let's say we have a user profile resource with this data:
json
Copy code
{
"id": 1,
"name": "John Doe",
"email": "john.doe@example.com",
"age": 30
}
PUT Request to /users/1:
http
Copy code
PUT /users/1
Content-Type: application/json
{
"id": 1,
"name": "Jane Doe",
"email": "jane.doe@example.com",
"age": 28
}
Effect: The entire user profile is replaced with this new content. Even if only the name and age were updated, the whole object must be sent, and all fields will be replaced.
Response:
http
Copy code
200 OK
{
"id": 1,
"name": "Jane Doe",
"email": "jane.doe@example.com",
"age": 28
}
2. PATCH Request
Purpose: Update only certain fields of the resource, leaving others unchanged.
Characteristics:
Partially updates a resource.
The client sends only the fields that need to be updated.
Efficient for small updates, as it doesn't require the full resource.
Example:
Using the same user profile resource:
json
Copy code
{
"id": 1,
"name": "John Doe",
"email": "john.doe@example.com",
"age": 30
}
PATCH Request to /users/1:
http
Copy code
PATCH /users/1
Content-Type: application/json
{
"age": 31
}
Effect: Only the age field is updated, while the rest of the resource remains unchanged.
Response:
http
Copy code
200 OK
{
"id": 1,
"name": "John Doe",
"email": "john.doe@example.com",
"age": 31
}
Summary:
PUT replaces the entire resource (overwrites all fields).
PATCH modifies only the specified fields without affecting the other fields.
Use PUT when you need to completely replace a resource and PATCH when you only want to update specific parts of a resource. #RESTAPI, #PUTvsPATCH, #APIRequests, #PUTRequest, #PATCHRequest, #APIDifference, #APITutorial, #RESTAPIExample, #JSON, #WebDevelopment, #APIUpdate, #ResourceUpdate, #HTTPEndpoints, #BackendDevelopment, #APIDesign, #HTTPMethods, #SoftwareDevelopment, #Programming, #WebServices, #PartialUpdate, #FullResourceUpdate
On this page of the site you can watch the video online Difference Between PUT and PATCH in REST API with a duration of hours minute second in good quality, which was uploaded by the user Mr.Expert 24 September 2024, share the link with friends and acquaintances, this video has already been watched 48 times on youtube and it was liked by 1 viewers. Enjoy your viewing!