How to Consume RESTful APIs on the Frontend Using Axios

Rumaisa NavedRumaisa Naved
5 min read

Introduction

In this article, we'll learn how to use Axios to consume RESTful APIs on the frontend. We’ll cover different HTTP methods, handling API responses and errors, setting up Axios in a project, using interceptors, and following best practices.

Understanding HTTP Methods in RESTful APIs

When working with APIs, we use various HTTP methods to interact with data. Let’s explore each method:

  1. GET Method

    Used to retrieve data from an API.

  2. POST Method

    Used to send data to the API and create a new resource.

  3. PUT Method

    Used to update an entire resource.

  4. DELETE Method

    Used to delete a resource.

  5. PATCH Method

    Used to update part of a resource.

Setting Up Axios in a Frontend Project

First, install Axios in your project.

npm i axios

Now, you’re ready to use Axios in your project.

Understanding API Response Status Codes

When consuming an API, it's crucial to handle responses properly. Some common status codes include:

  • 200 – OK (Request was successful)

  • 201 – Created (Resource created successfully)

  • 401 – Unauthorized (Invalid credentials)

  • 403 – Forbidden (No permission to access resource)

  • 404 – Not Found (Resource does not exist)

  • 500 – Internal Server Error (Server issue)

Handling API Responses and Errors

Axios provides built-in error handling mechanisms. Below is a generic error handler function:

const handleCreateUser = async (e) => {
    e.preventDefault();
    const userData = {
      email: data.email,
      password: data.password
    };
    try {
        // all the status codes in the range of 200 to 299 will fall here 
        const res = await axios.post("https://reqres.in/api/login", userData);
        console.log(res.data); // data returned by the server
        console.log(res.status); // 200 
        console.log(res.statusText); // ok 
    } catch (error) {
        // all the status codes above 299 will fall here including 3xx, 4xx and 5xx 
        if (error.response) {
            // if there's some response from API but has error 
            console.log(error.response.data);
            console.log(error.response.status);
        } else if (error.request) {
            // The request was made but no response was received 
            condasole.log(error.request);
        } else {
            console.log('Error', error.message);
        }
    }
  };

Making API Requests Using Axios

  1. GET Method

async function getCharacters() {
     try {
         const response = await axios.get(
             "https://finalspaceapi.com/api/v0/character/?limit=2"
          );
         console.log(response.data);
        // If using React, update state with the response data
        // setCharacters(response.data);     
     } catch (error) {
          if (error.response) {
               console.log(error.response.data); // The error message sent by the server 
          } else if (error.request) {
                // The request was made, but no response was received
               console.log(error.request);
          } else {
               // Something else happened while setting up the request
               console.log(`Error: ${error.message}.`);
          }
     }
}
getCharacters();
  1. POST Method

    As we're using the POST method, we need to include headers in the request to inform the server that we're sending JSON data. Headers are required whenever we send a request body, and they are most commonly used in POST, PUT, and PATCH requests.

const handleUserLogin = async (e) => {
    e.preventDefault();
    const userData = {
      email: data.email,
      password: data.password
    };
    const headers = {"Content-type" : "application/json"};
    try {
        const response = axios.post("https://reqres.in/api/login", userData, { headers });
        console.log(response.data); 
        if (response.status === 200) {
            console.log("User logged in successfully.");
        }
    } catch (error) {
           if (error.response) {
               if (error.response.status === 401) {
                    console.log("Not authorized");
                } else if (error.response.status === 404) {
                    console.log("User not found.");
                }
          } else if (error.request) {
               console.log(`No response received: ${error.request}.`);
          } else {
               console.log(`Error: ${error.message}.`);
          }
    }
  };
  1. PUT Method

const handleUpdateUser = async (e) => {
    e.preventDefault();
    const userData = {
      email: data.email,
      password: data.password
    };
    const headers = {"Content-type" : "application/json"};
    try {
        const response = axios.put("https://reqres.in/api/update", userData, { headers });
        if (response.status === 200) {
            console.log("User updated successfully.");
        }
    } catch (error) {
           if (error.response) {
               console.log(error.response);
          } else if (error.request) {
               console.log(error.request);
          } else {
               console.log(`Error: ${error}.`);
          }
    }
  };
  1. DELETE Method

const deleteUser = async () => {
            try {
                const response = await axios.delete(
                    'https://reqres.in/api/delete-user',
                );
                if (response.status === 200) {
                    console.log("User deleted successfully!");
                }
            } catch (error) {
                if (error.response) {
                    console.log(error.response);
                } else if (error.request) {
                    console.log(error.request);
                } else {
                    console.log("Failed to delete user");
                }
            }
        };
deleteUser();

Note: Don't copy and paste the same code, as the API URLs used are fake and won't work when you run the project.

Working with Axios Interceptors

Interceptors allow modifying requests and responses globally before they reach the application.

  1. Request Interceptor

Used to add headers or modify requests before they are sent.

// Add a request interceptor 
axios.interceptors.request.use(
    (config) => {
        // Do something before request is sent 
        console.log("Request sent:", config);
        return config;
    },
    // Do something with request error
    (error) => Promise.reject(error)
);
  1. Response Interceptor

    Used to handle global errors and perform actions based on response status codes.

// Add a response interceptor
axios.interceptors.response.use(
    (response) => response,
    (error) => {
        if (error.response.status === 401) {
            // redirect the user to the login page in case of 401 error 
            console.log("Unauthorized! Redirecting to login...");
        }
        // Do something with response error
        return Promise.reject(error);
    }
);

Common Mistakes to Avoid When Using Axios

The API Integration can become exhausting when not used properly. Here are some mistakes which you should avoid.

  • Not handling errors properly.

  • Forgetting to set headers.

  • Repetitive code.

  • Not using interceptors.

Best Practices for Using Axios

  • Always use async/await for better readability.

  • Use Axios interceptors to handle authentication and error responses globally.

  • Properly handle API response status codes.

  • Avoid unnecessary API calls by implementing caching or debouncing where applicable.

Conclusion

In this guide, we explored how to consume RESTful APIs using Axios, different HTTP methods, handling responses, error handling, and best practices. In the next article, we’ll learn how to integrate APIs in a React application.

Stay connected for more insightful articles! - Rumaisa Naveed

4
Subscribe to my newsletter

Read articles from Rumaisa Naved directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Rumaisa Naved
Rumaisa Naved

I talk about coding, tech and some personal growth topics as well. I hope you guys will love and enjoy reading as much as I do.