JavaScript

How to make HTTP requests in JavaScript using Axios | Explained with Examples

Axios is strictly a promise-based JavaScript library that can be included in your project by either using the node package manager (npm) or CDN-hosted Axios. It is used to make XMLHttpRequest from the browser as well as HTTP requests for projects created with NodeJS. Since it can work with both node projects and for browsers, it is often referred to as an isomorphic module.

It is an HTTP client, which means we can use its GET, POST, and DELETE methods to interact with APIs

Setting up Axios in your project

If you are working with the node package manage then you can download Axios by typing in the following command in the terminal of your code editor:

$ npm install axios

If you are working with vanilla JavaScript, then you can include the CDN hosted Axios in your HTML file using the following line:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">

</script>

Also to test out Axios, we will be using the mock API provided by Req | Res. And the URL of the API is “https://reqres.in/api/users”.

Since it is a tutorial for showing you how to work with Axios to make HTTP requests, therefore, we will not manipulate with HTML elements. We only have the following lines in the HTML webpage:

<center>

<div id="demoID">Axios HTTP Requests</div>

</center>

Get Request with Axios

To make GET requests to the API using API we use the following syntax:

axios.get(URL).then(response => {}).catch(error =>());

Let’s use this syntax to make a get request to the req | res user’s API:

axios.get("https://reqres.in/api/users").then((response) => {
      const users = response.data.data;
      console.log(`GET users`, users);
    }).catch((error) =>console.error(error));

But we want to wrap this get method in a function, So use the following lines of code:

const getUsers = () => {
axios
    .get("https://reqres.in/api/users")
    .then((response) => {
      const users = response.data.data;
      console.log(`GET users`, users);
    })
    .catch((error) =>console.error(error));
};

Now, all we have to do is call the function getUesrs() with the following line of code:

getUsers();

By running the HTML file, you will see the following results:

If we expand this entry then we will be able to see the response of the API much more clearly:

We made a successful GET request using Axios and printed out the response to the console.

Post Request with Axios

To make a post request with Axios, you need to use the following syntax:

axios.post(URL).then((response) => { }).catch((error));

To make a post request to the Req|Res API, we use the following lines of code that will create a new user:

const createUser = (user) => {
axios
    .post("https://reqres.in/api/users", user)
    .then((response) => {
      const addedUser = response.data;
console.log(`POST: user is added`, addedUser);
    })
    .catch((error) =>console.error(error));
};

To invoke this POST request, we need to call this function createUser(), but before we do that we need to check the API on what type of JSON does it accept for a new user creation. So, on Req|Req website we can see the following JSON format for the POST request:

It takes a “name” key-value pair and a “job” key-value pair. Let’s call the createUser() function with appropriate JSON inside it:

createUser({

name: "John Doe",

job: "Auditor",

});

Run the file and you will see the following result on your browser’s console:

That is it, we were able to send a POST request to an API using Axios.

Delete Request with Axios

To make delete requests with axios to the API you have to use the following syntax

axios.delete(URL).then((response) => {}).catch((error) => ());

To make delete request to the req|res API, use the following lines of code:

const deleteUser = (id) => {
axios
    .delete(`https://reqres.in/api/users/${id}`)
    .then((response) => {
console.log(`DELETE: user is removed`, id);
    })
    .catch((error) =>console.error(error));
};

All we have to do is to invoke the function deleteUser using the following line:

deleteUser(2);

Run the file and observe the result on the browser’s console:

There you go, we have successfully made a DELETE request to an API using Axios.

Conclusion

Axios is an HTTP client which can be included in your node projects by using the node package manager or in your vanilla javascript project by using the CDN-hosted Axios. Axios is used to make XMLHttpRequests to an API, and it is strictly a promise-based library. In this post, we learned how to interact with an external API using Axios and make different GET, POST and DELETE requests to the API.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.