Skip to main content

How to Use the JavaScript Fetch API to PUT Data

How to Use the JavaScript Fetch API to PUT Data

The Fetch API is a modern JavaScript API used to make HTTP requests and handle responses. One of the common operations is sending data to a server using the PUT method, which is typically used to update existing resources. This article will guide you through the process of using the Fetch API to perform PUT requests and handle responses effectively.


Introduction to the Fetch API

The Fetch API provides a simple and flexible way to make network requests. It supports promises, which makes it easy to handle asynchronous operations. The basic syntax of the Fetch API involves calling the fetch() function and providing the URL and options for the request.

fetch(url, options)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

In the context of a PUT request, you need to specify the method as PUT and include the data you want to send in the request body.


Making a PUT Request with Fetch

To send a PUT request, you need to configure the fetch() function with appropriate options. These options include specifying the method as PUT, setting the request headers, and providing the request body.

const url = 'https://jsonplaceholder.typicode.com/users/1';
const data = {
  name: 'John Doe',
  email: 'john.doe@example.com',
  address: {
    street: '123 Main St',
    city: 'Anytown',
    zip: '12345'
  }
};

fetch(url, {
  method: 'PUT', // Specify the method as PUT
  headers: {
    'Content-Type': 'application/json' // Set the content type to JSON
  },
  body: JSON.stringify(data) // Convert the data object to a JSON string
})
.then(response => {
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  return response.json(); // Parse the JSON from the response
})
.then(data => console.log('Success:', data))
.catch(error => console.error('Error:', error));

In this example:

  • url is the endpoint where the PUT request is sent.
  • data is the object containing the information you want to update.
  • The fetch() function is called with method: 'PUT', indicating that this is a PUT request.
  • Headers are set to 'Content-Type': 'application/json' to indicate that the request body contains JSON data.
  • The body option is used to include the JSON-encoded data in the request.

Real-World Example with JSONPlaceholder API

JSONPlaceholder is a fake online REST API used for testing and prototyping. We'll use it to update a user’s information. In this example, we'll send a PUT request to update user information at https://jsonplaceholder.typicode.com/users/1.

const url = 'https://jsonplaceholder.typicode.com/users/1';
const updatedUser = {
  name: 'John Doe',
  username: 'johndoe',
  email: 'john.doe@example.com',
  address: {
    street: '123 Main St',
    suite: 'Apt. 456',
    city: 'Anytown',
    zipcode: '12345',
    geo: {
      lat: '-37.3159',
      lng: '81.1496'
    }
  },
  phone: '1-770-736-8031 x56442',
  website: 'johndoe.org'
};

fetch(url, {
  method: 'PUT', // Specify the method as PUT
  headers: {
    'Content-Type': 'application/json' // Set the content type to JSON
  },
  body: JSON.stringify(updatedUser) // Convert the data object to a JSON string
})
.then(response => {
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  return response.json(); // Parse the JSON from the response
})
.then(data => {
  console.log('Success:', data);
})
.catch(error => {
  console.error('Error:', error);
});

In this example:

  • The URL https://jsonplaceholder.typicode.com/users/1 is used to identify the resource to update.
  • The updatedUser object contains new values for the user's information.
  • The fetch() function sends a PUT request with the updated data.
  • The response is parsed as JSON, and the updated user data is logged to the console.

Note that JSONPlaceholder will return the updated object, allowing you to verify the update, but the data is not actually saved to a database since it is a mock API.


Handling Responses

Once the request is sent, you need to handle the server's response. The Fetch API returns a promise that resolves to the Response object. You can check if the response was successful using response.ok and then parse the response body accordingly.

fetch(url, {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(data)
})
.then(response => {
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  return response.json(); // Parse the JSON response
})
.then(data => {
  console.log('Success:', data);
})
.catch(error => {
  console.error('Error:', error);
});

In this code:

  • If the response status is not in the range of 200-299, an error is thrown.
  • The response body is parsed as JSON using response.json().
  • The parsed data is logged to the console, or an error message is shown if an exception is caught.

Common Pitfalls and Troubleshooting

While using the Fetch API for PUT requests, you might encounter some common issues. Here are a few troubleshooting tips:

  • Network Errors: Ensure that the URL is correct and that the server is accessible.
  • Content-Type: Verify that the Content-Type header is set correctly based on the data being sent.
  • Response Handling: Check the response status and handle errors appropriately to avoid unexpected issues.
  • Data Formatting: Make sure the data sent in the request body is correctly formatted as JSON.

Conclusion

Using the Fetch API to perform PUT requests is a powerful way to interact with APIs and update resources. By configuring the request method, headers, and body, you can send data to the server and handle the response effectively. Proper error handling and understanding common pitfalls will help you ensure that your PUT requests work smoothly and reliably.

Comments