Calling API from NodeJS API using Axios
Tags: typescript, node, express, axios
Published: 2023-05-17 16:57:59

---
title: Calling API from NodeJS API using Axios
published: true
date: 2021-05-13 17:55:39 UTC
tags: typescript,nodejs,expressjs,axios
canonical_url: https://zakimohammed.medium.com/calling-api-from-nodejs-api-using-axios-c7ff5cd32a81
---

![Unsplash](https://cdn-images-1.medium.com/max/800/1*wTpO69mvp10VFP-SBsxmng.jpeg)

I found Axios a great library to make calls to a third party API, it’s easy to understand, demands lesser coding, Promise me to return the data, works perfectly with a async/await style, get along with TypeScript.

As per decade old coding advice “Don’t invent the wheel”. When we are building a car we will primarily focus on building a car and not on wheels duh!. We will choose best out of many wheels for our car from many different options available to us. Pretty lame, but will set the base for this article.

In NodeJS, to make an API call or order cheese burger (kidding) from the outside world we use [HTTPS](https://nodejs.org/api/http.html)/ [HTTPS](https://nodejs.org/api/https.html) modules. There is no down side to it, but we have to do the heavy lifting by our own. Big fat code will make a call to your third party API which you have to test and maintain. Why not hire a ninja for this one who does the job without leaving any trace. We are talking about [Axios](https://www.npmjs.com/package/axios) here.

Axios a “Promise based HTTP client for the browser and node.js” as per the package’s introduction. Personally, I found Axios a great library to make calls to a third party API, it’s easy to understand, demands lesser coding, Promise me to return the data, works perfectly with a async/await style, get along with TypeScript. But it’s always better to compare what other options we have, so before started using Axios for my project I have done some research of 200 days (chuckles). What I found that there are other players too, some of which even compete Axios in some way. Lets have a close look at it.

With the help of [npmtrends](https://www.npmtrends.com/) made by [John Potter](https://twitter.com/johnmpotter), I have done a comparison between Request, GOT, Axios and Superagent some of the popular packages for calling APIs [here](https://www.npmtrends.com/axios-vs-got-vs-request-vs-superagent). The results are as below:

![](https://cdn-images-1.medium.com/max/1024/0*0D-jaPtMZQ2x-fP2.jpg)

There is a close competition going between GOT and Axios as shown, while the GOT remains trending then Axios, but Axios holds more stars as shown below:

![](https://cdn-images-1.medium.com/max/1024/0*dKYAr4K9DGBEelOq.jpg)

Apart from that “Why to ignore request?” as it has already gained a huge success is the fear of deprecation. Have a look at this article [here](https://medium.com/better-programming/request-has-been-deprecated-a76415b4910b). The request package was deprecated since Feb 11th 2020. Still pretty trendy and stable, but for my project I was looking for some package to relay on for a longer period of time. So Axios I choose you!

### Axios in Action

Enough research stuff, lets see Axios in action. In this article will create an ExpressJS API along with TypeScript. So for the setup of the project, refer my previous article [here](https://codeomelet.com/posts/getting-started-with-nodejs-express-using-typescript).

Following shows the folder structure for the project:

```
src/
|-- models/
    |-- post.ts
|-- routes/
    |-- posts.ts
server.ts
```

As always the [JSONPlaceholder](https://jsonplaceholder.typicode.com/) API will serve as a third party API for us to understand the Axios calls. Let’s jump directly to routes/posts.ts file from where we are doing CRUD calls to JSONPlaceholder API.

### Setting up Axios

```
import axios, { AxiosRequestConfig } from 'axios';

const apiPath = '[https://jsonplaceholder.typicode.com/posts'](https://jsonplaceholder.typicode.com/posts');
const config: AxiosRequestConfig = {
    httpsAgent: new https.Agent({
        rejectUnauthorized: false
    })
};
```

Here we have to make httpsAgent’s rejectUnauthorized to false in order to avoid “Error: unable to verify the first certificate” error, please refer [here](https://stackoverflow.com/a/53585725/4989054).

Moving ahead a simplest form of GET call looks like below:

```
const response = await axios.get(apiPath, config);
const posts: Post[] = response.data;
```

No further questions asked and you get your posts array filled with data coming from your remote API. Let’s complete the CRUD operations with JSONPlaceholder API to conclude this topic.

### Read Posts [GET]

```
// get all posts
router.get('/', async (req: Request, res: Response) => {
    const response = await axios.get(apiPath, config);
    res.json(response.data);
});
```

### Read Single Post [GET]

```
// get posts by id
router.get('/:id', async (req: Request, res: Response) => {
    const response = await axios.get(`${apiPath}/${req.params.id}`, config);
    res.json(response.data);
});
```

### Create Post [POST]

```
// create posts
router.post('/', async (req: Request, res: Response) => {
    const response = await axios.post(apiPath, req.body, config);
    res.json(response.data);
});
```

### Update Post [PUT]

```
// update post by id
router.put('/:id', async (req: Request, res: Response) => {
    const response = await axios.put(`${apiPath}/${req.params.id}`, ({
        id: +req.params.id,
        userId: req.body.userId,
        title: req.body.title,
        body: req.body.body
    }), config);
    res.json(response.data);
});
```

### Delete Post [DELETE]

```
// delete posts by id
router.delete('/:id', async (req: Request, res: Response) => {
    const response = await axios.delete(`${apiPath}/${req.params.id}`, config);
    res.json(response.data);
});
```

Told ya! A single line of code doing all the different calls for you, what more we can ask for. I have used Axios in my projects and written unit tests around it; worked like a charm (will write about Unit Testing Axios using JEST in the near future).

### Git Repository

Check out the git repository for this project or download the code.

[Download Code](https://github.com/ZakiMohammed/nodets-axios/archive/master.zip)[Git Repository](https://github.com/ZakiMohammed/nodets-axios)

### Summary

It is always good to do a thorough research before settling on any NPM package. A good research result in better sleep for long running projects. With many stars Axios also holds many issues, but with active support from the package and for many common operations like above we can happily rely on it.

Hope this article helps.

_Originally published at_ [_https://codeomelet.com_](https://codeomelet.com/posts/calling-api-from-nodejs-api-using-axios)_._