HTTP PUT Request
PUT is a method of modifying resources where the client sends data that updates the entire resource. PUT is similar to POST in that it can create resources, but it does so when there is a defined URL wherein PUT replaces the entire resource if it exists or creates new if it does not exist.
For example, When you want to update the Candidate name and email, you have to send all the parameters of the Candidate including those not to be updated in the request body, otherwise, it will simply replace the entire resource with the name and email.
{
id: 8,
email: "lindsay.ferguson@reqres.in",
// field to be updated
first_name: "Lindsay",
// field to be updated
last_name: "Ferguson",
avatar: "https://reqres.in/img/faces/8-image.jpg"
}
let us take an example to understand PUT requests by sending only the fields that we want to update.
Example: The following code demonstrates the PUT request method
let PutRequest = () => {
// Sending PUT request with fetch API in javascript
fetch("https://reqres.in/api/users/2", {
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
method: "PUT",
// Sending only the fields that to be updated
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);
});
};
PutRequest();
Output:
In the above example, we have made a PUT request to the server, with a payload attached to the body. If we want to update the name and email, with a PUT request we have to send all the other fields such id, avatarlast_name, to the server, otherwise, it replaces the data with the payload passed as we can see in the above example.
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.
Contact Us