NodeJS: How to make HTTP request

neotam Avatar

NodeJS: How to make HTTP request
Posted on :
,

When it comes to modern era of Web with microservices and service oriented architecture applications depend on the web API calls. Thankfully NodeJS offers the many different ways to request a resource through web API call or HTTP request.

Some examples of web APIs

  • Getting live game score
  • Transcript Service
  • OpenAPI API for AI models
  • Finance API: Getting stocks, quotes, balance sheet etc

Before you jump into making API call, make sure Node and NPM are installed

There are multiple ways to make a HTTP request in Node JS as follows

To demonstrate the making HTTP request using these different approaches, we will use the api https://api.stackexchange.com/docs/sites. Where, authentication is not required for this endpoint till the finite about of requests

API URL: https://api.stackexchange.com/2.3/sites

HTTP module

HTTP is the built-in node module which operates at quite low level. By default http module can’t handle the SSL for such a case we must use https.
Unlike other libraries we will be discussing draw back of http is that it is not quite user friendly

Let’s make HTTP GET request to the stackexchange and display the sites, users and launch date etc

const https = require('https');
const zlib = require('zlib'); 

const options = {
    hostname: 'api.stackexchange.com',
    port: 443,
    path: '/2.3/sites',
    method: 'GET'
};

// Sending the request
const req = https.request(options, (res) => {
    let buffer = []; 

    var gunzip = zlib.createGunzip(); 
    res.pipe(gunzip); 

    // Receiving Data 
    gunzip.on('data', (chunk) => {
        console.log('received data', chunk);
        buffer.push(chunk.toString()); 
    });

    // Ending the response 
    gunzip.on('end', () => {
        console.log('\n\n Finished receving response');
        console.log('Response:', JSON.parse(buffer.join(''))); 
    });

}).on("error", (err) => {
    console.log("Error: ", err)
}).end()

As it is shown in the above example, http or https offers the low level API to work with HTTP protocol. We need to receive the chunks of data and buffer it, then assemble it after finished the response on ‘end’ event. Converting data into the JSON also needs to be taken care of manually while other libraries implicitly handle the JSON. Since the stackexchange responds to HTTP request with compressed (gzip) data, we are obligated to decompress it first using the zlib module

Read more about the API for node http module

Using Fetch

Install node-fetch

node i node-fetch

Example:

import fetch from 'node-fetch';


fetch('https://api.stackexchange.com/2.3/sites', {
    method: 'GET',
    headers: {
        'Content-type': 'application/json; charset=UTF-8',
    },
})
    // Response JSON
    .then((response) => response.json())

    // Log Response 
    .then((json) => console.log(json))
    .catch(err => console.log(err))

As you can see in the above code, node-fetch is clever enough to handle the compression and json and it works with both http and https. It is an effort by the Node-fetch offers the same kind of API as fetch in the browser.

Axios

Axios is based on Promises and it works in both browser and NodeJS environments. Promise is a great help to deal with asynchronous code and callback chains.

Install the axios using npm

npm i axios

Making HTTP request API call using “axios”

const axios = require('axios')

// GET HTTP REQUEST
axios.get('https://api.stackexchange.com/2.3/sites')

.then(res => console.log(res.data))
.catch(err => console.log(err))

Wow! it is remarkably simple to make HTTP request using AXIOS module. Unlike built in HTTP module of Node, Axios takes care of compression and JSON implicitly.

Using superagent

SuperAgent is yet another library which is used to make AJAX requests in the browser which also works in the NodeJS.

Install superagent

npm i superagent 

SuperAgent provides the elegant API to chain the request with query parameters

Example:


const superagent = require('superagent');

superagent.get('https://api.stackexchange.com/2.3/sites')
    .query({ filter: 'default' })
    .end((err, res) => {
        if (err) { return console.log(err); }
        console.log(res.body);
    });

Just like Axios, superagent make developer life easier by taking care of all grunt work such as JSON, HTTPs, and compression

Using Got

Got is the lightweight library to make HTTP requests

install Got using npm

npm install got

Got also works with Promises making it easier to work with asynchronous code just like Axios

// const got = require('got');
import got from 'got';

got('https://api.stackexchange.com/2.3/sites', { json: true }).then(resp => {
  console.log(resp.body);
}).catch(error => {
  console.log(error);
});

The library Got is effective if you want less foot print and simpler API

Conclusion

This article does not exhaustive in covering all possible libraries and ways to make simple HTTP request. Such that feel free to explore and when it comes to picking one of the way to make HTTP request go with HTTP library if you enjoy dealing with low level stuff other wise go with Axios or Superagent that offer the compact API and make life easier to make HTTP request

Happy HTTP 🕸️. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *