5 Ways to Make HTTP Requests in Node.js (Creating REST API)

5 Ways to Make HTTP Requests in Node.js (Creating REST API)
1007 Views
4.4
(157)

In Node.js, there are several ways to make HTTP requests. You can use the built-in HTTP and HTTPS modules that come with Node.js, the Fetch API that’s part of Node, or third-party packages like Axios, Got, SuperAgent, and node-fetch that you add to make things easier. can.

In this guide, we’ll take a closer look at the built-in HTTPS module and the Fetch API. We’ll also examine some popular npm packages like Axios, Got, SuperAgent, and node-fetch, which help make HTTP requests easier.

Let’s get into it!

Prerequisites

  1. Node.js: You need to have Node.js version 14 or later installed on your computer, which could be set up directly or inside a Docker container.
  2. npm Skills: Be familiar with basic npm commands like npm init, and know how to install new packages using npm install <module-name>.
  3. Running JavaScript: Know how to run JavaScript files using the node <filename> command to check out what each script does.
  4. JavaScript Knowledge: Understand JavaScript concepts like callbacks, promises, and async/await for handling asynchronous operations.

Example RESTful API

For our examples, we’ll use the JSONPlaceholder API to fetch and display data about 10 users, showing each user’s username and ID on the console. You can find all the example code in a GitHub repository linked in this guide.

Methods for Making HTTP Requests in Node.js

We’ll explore five different ways to send GET requests to the JSONPlaceholder API, starting with the built-in HTTP(S) module in Node.js as our first example.

5 Ways to Make HTTP Requests in Node.js

Standard Node.js HTTP(S) Module

The default HTTP module in the standard library is first on our hit parade. You don’t need to install any external dependencies with this module. However, it is not very user-friendly compared to other solutions.

In the following code, a GET request will be sent to NASA’s API and the URL for that day’s astronomy picture and explanation will be printed: JavaScript

const https = require('https');

https.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY', (resp) => {
  let data = '';

  // A chunk of data has been received.
  resp.on('data', (chunk) => {
    data += chunk;
  });

  // The whole response has been received. Print out the result.
  resp.on('end', () => {
    console.log(JSON.parse(data).explanation);
  });

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

The majority of HTTP and HTTPS modules have fairly low-level functionality. To receive the response data in chunks, you should not provide a callback function to execute after all the data is received. Additionally, you must manually parse the response data. In a JSON format, this is fairly trivial, but it still requires additional steps.

We’ll also need the HTTP module if the API we’re using communicates over HTTPS since this module doesn’t support HTTPS by default.

Although it might take a little more work, it’s a great utility for those who don’t want to add a lot of dependencies or access low-level features to their codebase.

Node-Fetch

In Node.js, node-fetch translates the browser library window.fetch as a lightweight module. Unlike HTTP, you must install this from npm as a dependency.

Run the following commands from the directory you want your code to reside in: JavaScript

npm install [email protected]

As this library uses promises, we can use async/await syntax with it as well: JavaScript

const fetch = require('node-fetch');

(async () => {
  try {

    const response = await fetch('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY')
    const json = await response.json()

    console.log(json.url);
    console.log(json.explanation);
  } catch (error) {
    console.log(error.response.body);
  }
})();

In this library, the response is converted to JSON via a built-in function, but it doesn’t do it automatically as it does in some of the libraries below. For browser users who are familiar with the Fetch API, this is great.

Axios

Node.js and the browser both support Axios, a Promise-based HTTP client. Promises are very useful when dealing with code that requires a complex chain of events. There are several solutions to the problem of writing asynchronous code, and Promises are one of them. Swift and other languages can also benefit from them.

You can install Axios from npm by entering the following command: JavaScript

npm install [email protected]

The code below notes the URL and explains the day’s astronomical image.JavaScript

const axios = require('axios');

axios.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY')
  .then(response => {
    console.log(response.data.url);
    console.log(response.data.explanation);
  })
  .catch(error => {
    console.log(error);
  });

Axios also parses JSON answers by default. That’s completely convenient! You can see that error handling is completed. We now use promises, thus .catch() is necessary.

Axios supports many concurrent queries. For example, if you wish to capture an astronomical image of two days simultaneously:JavaScript

var axios = require('axios');

axios.all([
  axios.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&date=2017-08-03'),
  axios.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&date=2017-08-02')
]).then(axios.spread((response1, response2) => {
  console.log(response1.data.url);
  console.log(response2.data.url);
})).catch(error => {
  console.log(error);
});

Asynchronous code may quickly become overly difficult and unpleasant to work with, and the way Axios approaches this issue may make your life simpler in the long term.

SuperAgent

SuperAgent, like Axios, is a popular package for making AJAX queries in the browser but also supports Node.js. Install SuperAgent using the following command:JavaScript

npm install [email protected]

SuperAgent has additional methods, such as query(), for adding arguments to requests. In earlier instances, we manually added them to the URL, but observe how SuperAgent provides a method to do so:JavaScript

const superagent = require('superagent');

superagent.get('https://api.nasa.gov/planetary/apod')
.query({ api_key: 'DEMO_KEY', date: '2017-08-02' })
.end((err, res) => {
  if (err) { return console.log(err); }
  console.log(res.body.url);
  console.log(res.body.explanation);
});

You don’t have to parse the JSON answer manually, which is a nice feature.

Got

Got is another option for a lightweight library. It may also be used in Codexcoach Functions.

Again, install Got with npm:JavaScript

npm install [email protected]

Got, like Axios, operates with promises. The following code will work as the other examples do:JavaScript

const got = require('got');

got('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY', { json: true }).then(response => {
  console.log(response.body.url);
  console.log(response.body.explanation);
}).catch(error => {
  console.log(error.response.body);
});

Got is ideal if you want a smaller library that is less “bloated” than something like Request.

How useful was this blog?

Click on a star to rate it!

Average rating 4.4 / 5. Vote count: 157

No votes so far! Be the first to rate this blog.

By Dhruv Lakkad

Hello, my name is Dhruv. I am located in Gujarat. I have 1.5+ years of experience in Node.js & Next.js web development areas. Currently, I am working on the CodexCoach site. So keep reading Node.js & Next.js related blogs and enhance your NodeJS & NextJS web development skills by reading my guides. Thank you!

Leave a comment

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