Skip to main content

PUT Request

Overview

Explore how to perform a PUT request in JavaScript using the Fetch API. A PUT request is typically used to update existing data on a server. This code snippet provides a practical approach to using the Fetch API for sending PUT requests, making it easier to interact with web services for data updates.

Code

function updateData(apiUrl, updatedData) {
fetch(apiUrl, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(updatedData),
})
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then((data) => {
console.log("Data updated:", data);
})
.catch((error) => {
console.error("Fetch error:", error);
});
}

Example Usage

// Example data to update
const dataToUpdate = {
name: "Jane Doe",
email: "janedoe@example.com",
};

// Calling the function with URL and data to update
updateData("https://api.example.com/data/123", dataToUpdate);

Code Description

The updateData function is a JavaScript utility for making HTTP PUT requests using the Fetch API. It is designed to update data on a server. Here's a breakdown of its functionality:

Function Parameters:

  • apiUrl: The URL of the resource to be updated. It should include the resource ID.
  • updatedData: An object representing the new data for updating the resource.

Fetch API Configuration:

  • Initiates a PUT request to apiUrl.
  • Sets the request headers to indicate that the content type is application/json.
  • Stringifies updatedData and includes it in the request body.

Response Handling:

  • Checks if the response status is OK. Throws an error for non-OK responses.
  • Parses the response body as JSON for successful responses.

Data Processing:

  • Handles the response data, such as logging the updated data to the console.

Error Handling:

  • Catches and logs any errors during the fetch process, including network issues or request configuration problems.

This function can be used in various parts of a web application that require sending updated data to a server, such as in user profile updates or content modifications.

References