Calling HTTP APIs from Node.js application

September 14, 2018
by Rahil Shaikh
  • http in node.js

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.

callapi.js
const got = require('got');

const server = 'YOUR-API-SERVER';
let fixedHeaders = {
    'json': true,
    'Content-Type': 'application/json; charset=utf-8',
    'user-agent': 'ciphertrick-server'
}

module.exports = function(path, method, body = {}, newheaders ={}){
    const url = server + path;
    let headers = Object.assign(fixedHeaders, newheaders);
    const options = {
        body: JSON.stringify(body),
        headers: headers
    }
    return got[method](url, options).then((data)=>{
        if(typeof data.body === 'string'){ //expecting data to be json object
            return JSON.parse(data.body);
        }
        return data.body;
    })
    .catch((err)=>{
        logger.error(`[request Handler]`, err);
    });
}

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.

explorer.js
const callapi = require('./callapi');


module.exports.getUsers = async function(){
    try {
        const user = await callapi(`/user`, 'get', {}, {});
    } catch(e){
        console.log(e);
    }
};

module.exports.addUser = async function(user){
    try {
        const user = await callapi(`/user`, 'post', user, {});
    } catch(e){
        console.log(e);
    }
};

That’s how simple it is.

Conculsion

This article showed how easy it is to call an HTTP API from node.js using the got module. To add the toppings our wrapper function callapi makes it much simpler.
 

About

Engineer. Blogger. Thinker. Loves programming and working with emerging tech. We can also talk on Football, Gaming, World Politics, Monetary Systems.

Free PDF

Subscribe and get AngularJS Tips PDF. We never spam!
First Name:
Email:

Leave a Comment