HTTP Patch Request
Unlike PUT Request, PATCH does partial update e.g. Fields that need to be updated by the client, only that field is updated without modifying the other field.
So in the previous example, we have to send only the name and email field in the request body.
{
"first_name":"Geeky", // field that to be updated
"email":"hello@geeky.com", // field that to be updated
}
Example: The following code demonstrates the PATCH request method
let PatchRequest = () => {
// sending PUT request with fetch API in javascript
fetch("https://reqres.in/api/users/2", {
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
method: "PATCH",
// Fields that to be updated are passed
body: JSON.stringify({
email: "hello@geeky.com",
first_name: "Geeky"
})
})
.then(function (response) {
// console.log(response);
return response.json();
})
.then(function (data) {
console.log(data);
});
};
PatchRequest();
Output:
In the above example, we have made a PATCH request to the server, with a payload attached to the body. If we want to update the email and first_name, with a PATCH request then we have to send only the fields that have to be updated e.g first_name and email.
Difference Between PUT and PATCH Request
When working with APIs, figuring out the right way to update resources can be tricky. Both PUT and PATCH requests are used for this purpose, but they have distinct functionalities. This guide will break down the key differences between these two methods, helping you choose the most appropriate approach for your needs.