Calling API from NodeJS API using Axios

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 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 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 made by John Potter, I have done a comparison between Request, GOT, Axios and Superagent some of the popular packages for calling APIs here. The results are as below:

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:

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. 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.

Following shows the folder structure for the project:

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

As always the JSONPlaceholder 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';
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.

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 Git Repository

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.

Learner, developer, coder and an exceptional omelet lover. Knows how to flip arrays or omelet or arrays of omelet.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store