You are currently viewing Handling HTTP PUT Requests with Axios

Handling HTTP PUT Requests with Axios

When developing web applications, interacting with APIs to update data is a crucial task. HTTP PUT requests are commonly used for this purpose, allowing you to send data to a server to update an existing resource. PUT requests are integral to many functionalities, such as updating user information, modifying product details, and changing settings.

Axios, a popular JavaScript library, simplifies the process of making HTTP PUT requests by providing a promise-based interface. This makes it easy to handle asynchronous operations in JavaScript. In this comprehensive guide, we’ll explore how to use Axios to make PUT requests, handle responses and errors, and configure requests to suit different use cases.

Understanding HTTP PUT Requests

An HTTP PUT request is a method used to send data to a server to create or update a resource. When a PUT request is made, the server processes the data sent in the body of the request and returns a response. PUT requests are idempotent, meaning that multiple identical requests will have the same effect as a single request.

Use Cases for PUT Requests

PUT requests are used in various scenarios, such as:

  • Updating User Information: Modifying user details such as name, email, or password.
  • Editing Product Details: Updating information about a product, including price, description, and availability.
  • Changing Settings: Modifying configuration settings for an application or service.
  • Replacing Resources: Fully replacing an existing resource with new data.

Setting Up Axios in Your Project

To start using Axios for making PUT requests, you need to set it up in your project. You can install Axios via npm/yarn or include it via a CDN.

Installing Axios via npm/yarn

If you’re using npm or yarn, you can install Axios with a simple command.

Using npm:

npm install axios

Using yarn:

yarn add axios

After installation, you can import Axios in your JavaScript files:

import axios from 'axios';

Setting Up Axios via CDN

If you prefer to include Axios via a Content Delivery Network (CDN), you can add the following script tag to your HTML file:

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

This approach is useful for quick setups or for use in environments where a package manager is not available. When included via CDN, Axios is available globally as axios.

Making Simple PUT Requests

Once Axios is set up in your project, making a PUT request is straightforward. Here is a basic example.

Using npm/yarn:

import axios from 'axios';

// Function to send data to an API
const updateData = async () => {

  try {
  
    const response = await axios.put('https://jsonplaceholder.typicode.com/posts/1', {
      id: 1,
      title: 'updated title',
      body: 'updated body',
      userId: 1
    });
	
    console.log('Response data:', response.data);
	
  } catch (error) {
    console.error('Error updating data:', error);
  }
  
};

// Call the function to send data
updateData();

Using CDN:

<script>

  // Function to send data to an API
  const updateData = async () => {
  
    try {
	
      const response = await axios.put('https://jsonplaceholder.typicode.com/posts/1', {
        id: 1,
        title: 'updated title',
        body: 'updated body',
        userId: 1
      });
	  
      console.log('Response data:', response.data);
	  
    } catch (error) {
      console.error('Error updating data:', error);
    }
	
  };

  // Call the function to send data
  updateData();
  
</script>

In this example, we define a function updateData that sends a PUT request to the URL https://jsonplaceholder.typicode.com/posts/1 with a JSON payload containing id, title, body, and userId fields. The axios.put method is used to send the PUT request. The first argument is the URL endpoint, and the second argument is the data payload to be sent. The await keyword ensures that the function waits for the request to complete before continuing. The response data is logged to the console if the request is successful, and any errors are caught and logged.

Handling Responses and Errors

When you make a request with Axios, the response object contains several properties, including data, status, statusText, headers, and config. These properties provide detailed information about the response, allowing you to handle it appropriately.

Here’s an example of how to handle responses and errors in Axios:

Using npm/yarn:

import axios from 'axios';

// Function to send data and handle responses and errors
const updateData = async () => {

  try {
  
    const response = await axios.put('https://jsonplaceholder.typicode.com/posts/1', {
      id: 1,
      title: 'updated title',
      body: 'updated body',
      userId: 1
    });
	
    console.log('Data:', response.data);
    console.log('Status:', response.status);
	
  } catch (error) {
  
    if (error.response) {
	
      // Server responded with a status other than 2xx
      console.error('Error response data:', error.response.data);
      console.error('Error response status:', error.response.status);
	  
    } else if (error.request) {
	
      // No response received from server
      console.error('Error request:', error.request);
	  
    } else {
	
      // Other errors
      console.error('Error message:', error.message);
	  
    }
  }
};

// Call the function to send data
updateData();

Using CDN:

<script>

  // Function to send data and handle responses and errors
  const updateData = async () => {
  
    try {
      const response = await axios.put('https://jsonplaceholder.typicode.com/posts/1', {
        id: 1,
        title: 'updated title',
        body: 'updated body',
        userId: 1
      });
	  
      console.log('Data:', response.data);
      console.log('Status:', response.status);
	  
    } catch (error) {
	
      if (error.response) {
	  
        // Server responded with a status other than 2xx
        console.error('Error response data:', error.response.data);
        console.error('Error response status:', error.response.status);
		
      } else if (error.request) {
	  
        // No response received from server
        console.error('Error request:', error.request);
		
      } else {
	  
        // Other errors
        console.error('Error message:', error.message);
		
      }
    }
  };

  // Call the function to send data
  updateData();
  
</script>

In this example, we extend the updateData function to handle different types of errors. The axios.put method is used to make the request, and the response data and status are logged to the console if successful.

The catch block differentiates between three types of errors:

  • Error response: The server responded with a status code other than 2xx.
  • Error request: The request was made, but no response was received.
  • Other errors: Any other errors that might occur, such as network issues.

By handling these different error scenarios, you can ensure that your application responds appropriately to various error conditions.

Configuring PUT Requests

In many cases, you need to configure your PUT requests with custom headers and additional data. Axios allows you to easily add these configurations to your requests.

Using npm/yarn:

import axios from 'axios';

// Function to send data with custom headers
const updateData = async () => {

  try {
  
    const response = await axios.put('https://jsonplaceholder.typicode.com/posts/1', {
      id: 1,
      title: 'updated title',
      body: 'updated body',
      userId: 1
    }, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer token'
      }
    });
	
    console.log('Response data:', response.data);
	
  } catch (error) {
    console.error('Error updating data:', error);
  }
  
};

// Call the function to send data
updateData();

Using CDN:

<script>

  // Function to send data with custom headers
  const updateData = async () => {
  
    try {
	
      const response = await axios.put('https://jsonplaceholder.typicode.com/posts/1', {
        id: 1,
        title: 'updated title',
        body: 'updated body',
        userId: 1
      }, {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer token'
        }
      });
	  
      console.log('Response data:', response.data);
	  
    } catch (error) {
      console.error('Error updating data:', error);
    }
	
  };

  // Call the function to send data
  updateData();
  
</script>

In this example, we define a function updateData that sends a PUT request to the URL https://jsonplaceholder.typicode.com/posts/1 with a JSON payload containing id, title, body, and userId fields. Additionally, custom headers are added using the headers option. The Content-Type header is set to application/json to specify the format of the data being sent, and the Authorization header is set to a bearer token for authentication purposes. The response data is logged to the console if the request is successful, and any errors are caught and logged.

Advanced Usage of PUT Requests

Using Axios Interceptors

Interceptors allow you to run your code or modify the request or response before they are handled by then or catch. This is useful for tasks like adding authorization tokens to requests or logging request and response details.

Using npm/yarn:

import axios from 'axios';

// Add a request interceptor
axios.interceptors.request.use(

  config => {
    console.log('Request made with ', config);
    config.headers.Authorization = 'Bearer token';
    return config;
  },
  
  error => {
    return Promise.reject(error);
  }
  
);

// Add a response interceptor
axios.interceptors.response.use(

  response => {
    console.log('Response received', response);
    return response;
  },
  
  error => {
    console.log('Error response', error.response);
    return Promise.reject(error);
  }
  
);

// Function to make a request
const updateData = async () => {

  try {
  
    const response = await axios.put('https://jsonplaceholder.typicode.com/posts/1', {
      id: 1,
      title: 'updated title',
      body: 'updated body',
      userId: 1
    });
	
    console.log('Response data:', response.data);
	
  } catch (error) {
    console.error('Error updating data:', error);
  }
  
};

// Call the function to send data
updateData();

Using CDN:

<script>

  // Add a request interceptor
  axios.interceptors.request.use(
  
    config => {
      console.log('Request made with ', config);
      config.headers.Authorization = 'Bearer token';
      return config;
    },
	
    error => {
      return Promise.reject(error);
    }
	
  );

  // Add a response interceptor
  axios.interceptors.response.use(
  
    response => {
      console.log('Response received', response);
      return response;
    },
	
    error => {
      console.log('Error response', error.response);
      return Promise.reject(error);
    }
	
  );

  // Function to make a request
  const updateData = async () => {
  
    try {
	
      const response = await axios.put('https://jsonplaceholder.typicode.com/posts/1', {
        id: 1,
        title: 'updated title',
        body: 'updated body',
        userId: 1
      });
	  
      console.log('Response data:', response.data);
	  
    } catch (error) {
      console.error('Error updating data:', error);
    }
	
  };

  // Call the function to send data
  updateData();
  
</script>

In this example, we add request and response interceptors using axios.interceptors.request.use and axios.interceptors.response.use methods. The request interceptor logs the request configuration and adds an authorization header. The response interceptor logs the response details and handles errors. By using interceptors, you can centralize and streamline request and response handling logic, making your code cleaner and more maintainable.

Conclusion

In this article, we explored how to make HTTP PUT requests using Axios. We covered the basics of setting up Axios, making simple PUT requests, handling responses and errors, configuring PUT requests with headers and additional data, and using interceptors for advanced request handling.

The examples and concepts discussed provide a solid foundation for working with Axios in your projects. However, there is much more to explore. I encourage you to experiment further with Axios, integrating it into your applications to handle API interactions efficiently and effectively.

Leave a Reply