A cheat sheet for JavaScript's Axios
Tags: javascript, programming, codenewbie, computerscience
Published: 2021-06-30 09:32:08

*Originally Posted on [realpythonproject.com](https://www.realpythonproject.com/a-cheat-sheet-for-javascripts-axios/)*

<p><em>Connect with me on </em><a href="https://www.linkedin.com/in/rahulbanerjee2699/" rel="noreferrer noopener" target="_blank"><em>LinkedIn</em></a><em>, </em><a href="https://twitter.com/rahulbanerjee99" rel="noreferrer noopener" target="_blank"><em>Twitter</em></a></p>

Since quite a few people found [my previous article](https://www.realpythonproject.com/a-cheat-sheet-for-javascripts-fetch-api/) 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
```bash
npm install axios
```
### Importing Axios
```javascript
const axios = require('axios')
```

### Making a get request

#### With Promises (without async/await)
```javascript
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

```javascript
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
```javascript
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
```javascript
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
```javascript
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](https://thecatapi.com/)

#### Loading env variables stored in .env files
We will need to install 'dotenv' using npm
```bash
npm install dotenv
```
The below code snippet reads the environment  variable
```javascript
require("dotenv").config();
const CAT_API_KEY = process.env.API_KEY;
```
Let's try making a request to the API
```javascript
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
```javascript
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
```javascript
const getData = async (url, headers) => {
  try {
    const res = await axios.get(url, {
      headers: headers,
    });
  } catch (err) {
    console.log(err);
  }
};
```

### Making a Post Request
```javascript
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
```javascript
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) 
};
```