A cheat sheet for JavaScript's Axios
Rahul Banerjee
Posted on June 30, 2021
Originally Posted on realpythonproject.com
Connect with me on LinkedIn, Twitter
Since quite a few people found my previous article helpful, I decided to make a similar cheatsheet for axios.
Axios is used to make requests and to consume APIs.
I will be working in NodeJS environment.
Installing Axios
npm install axios
Importing Axios
const axios = require('axios')
Making a get request
With Promises (without async/await)
const axios = require("axios");
const url = "https://jsonplaceholder.typicode.com/todos/1";
axios.get(url)
.then((response) => response)
.then((responseObject) => console.log(responseObject.data))
.catch((err) => console.log(err));
With async/await
Under the hood, we are still using promises. Async/await makes the code look much more cleaner
const axios = require("axios");
const getData = async (url) => {
const res = await axios.get(url);
const json = await res.data;
console.log(json);
};
const url = "https://jsonplaceholder.typicode.com/todos/1";
getData(url);
Making multiple request simultaneously
const axios = require("axios");
const getData = async (url, id) => {
console.log("Making request to id ", id);
const res = await axios.get(url + id);
const json = await res.data;
console.log(json);
return json;
};
const url = "https://jsonplaceholder.typicode.com/posts/";
const ids = [1, 2, 3, 4, 5, 6, 7];
axios
.all(ids.map((id) => getData(url, id)))
.then(
(res) => console.log(res) // Array of all the json data
//[ {userId:1} , {userId:2} , {userId:3}...........]
)
.catch((err) => console.log(err));
Passing Parameters
Adding it to the URL
const getData = async (url) => {
const res = await axios.get(url);
const json = await res.data;
console.log(json);
};
const url = "https://jsonplaceholder.typicode.com/posts?userId=1";
getData(url);
Creating a params object
const getData = async (url,params) => {
const res = await axios.get(url,{
params: params
});
const json = await res.data;
console.log(json);
};
const url = "https://jsonplaceholder.typicode.com/posts";
const params = {
userId: 1
}
getData(url,params);
Passing a headers object
This is useful when the API you are consuming requires authentication. We will be working with the Cats as a Service API
Loading env variables stored in .env files
We will need to install 'dotenv' using npm
npm install dotenv
The below code snippet reads the environment variable
require("dotenv").config();
const CAT_API_KEY = process.env.API_KEY;
Let's try making a request to the API
const getData = async (url,headers) => {
const res = await axios.get(url,{
headers: headers
});
const json = await res.data;
console.log(json);
};
const url =
"https://api.thecatapi.com/v1/breeds";
const headers = {
"x-api-key": CAT_API_KEY,
};
getData(url,headers);
We simply create an object when making the request and store the headers object inside it.
Handling Errors
Let's try to make a request to the Cat's API but to a non-existing endpoint.
Handling with then..catch
axios
.get(url, {
headers: headers,
})
.then((res) => res)
.then((responseObject) => console.log(responseObject.data))
.catch((err) => console.log(err));
Handling with async/await and try...catch
const getData = async (url, headers) => {
try {
const res = await axios.get(url, {
headers: headers,
});
} catch (err) {
console.log(err);
}
};
Making a Post Request
const postData = async (url, data) => {
const res = await axios.post(url, {
...data,
});
const json = await res.data;
console.log(json);
};
const url = "https://jsonplaceholder.typicode.com/posts";
const data = {
title: "test Data",
body: "this is a test post request",
userId: 120,
};
postData(url, data);
Response Object
const getData = async (url) => {
const res = await axios.get(url);
const json = await res.data
console.log(json); // The JSON data
console.log(res.status) // 200
console.log(res.statusText) // OK
/**
* The below provide more info about your request
* such as url, request type, redirects, protocols etc
*/
console.log(res.headers)
console.log(res.config)
console.log(res.request)
};
Posted on June 30, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.