Calling HTTP APIs from Node.js application

Most of the times you might have used Node.js for exposing RESTful APIs to user-facing applications. But there are times when you may need to consume some other service over HTTP. This tutorial is going to show you just that in the easiest possible way.

The most popular module to achieve this is request, but we feel that request is bloated. Hence, in this tutorial, we will use a lightweight package called as got, which works using promises and is easy to use.

Let’s start by creating a new Node.js project. Go into your project directory and run

npm init

Answer the questions it asks. This will create a package.json file for you. Next, we will install the got package.

npm i got --save

This will install got and save it as a dependency.

Now instead of directly using got let’s create a wrapper method that will call got methods. This is so, we do not have to do common things again and again.

Here we have a method that takes in path, method, body(post request), newheaders(extra headers you might wanna pass along with fixed headers); constructs a got request and sends it. We are expecting data to be application/json hence handling for the same.

This about it. But let’s create an example file that utilizes the above method to call HTTP endpoints. Please note, these will be just example functions.