How to make an API request in Node.js?
© https://nodejs.org/en/

How to make an API request in Node.js?

3 ways to make HTTP requests in Node.js

ByMario Kandut

honey pot logo

Europe’s developer-focused job platform

Let companies apply to you

Developer-focused, salary and tech stack upfront.

Just one profile, no job applications!

This article is based on Node v16.14.0.

Making HTTP requests is a core functionality for modern language and a daily task for a developer. One task you’ll encounter often in Node.js is making HTTP requests to an external API from a server.

💰 The Pragmatic Programmer: journey to mastery. 💰 One of the best books in software development, sold over 200,000 times.

Let's take a look at three options on how to make an HTTP request, there are many more available.

3 Ways to Make HTTP Requests in Node.js

1. HTTP – the default

The default HTTP module is the built-in way to make HTTP requests in Node.js. The module can just be required without installing it, which is a big benefit if you don't want to add more dependencies to your project.

The HTTP module unfortunately also has a few downsides. You’re required to receive response data in chunks, rather than just providing a callback function to be executed when the data is fully received, and you have to parse the data manually. Yes, if the data is JSON formatted it is very simple json(), but still, it's an extra step. Currently, the module supports HTTP by default and needs to be required for https, so const http = require('http'); or const https=require('https');.

Let's look at a code example to request a list of todos from a placeholder API.

const https = require('https');
const options = {
  hostname: 'jsonplaceholder.typicode.com',
  port: 443,
  path: '/todos',
  method: 'GET',
};

const req = https.request(options, res => {
  console.log(`statusCode: ${res.statusCode}`);

  res.on('data', d => {
    process.stdout.write(d);
  });
});

req.on('error', error => {
  console.error(error);
});

2. Fetch (node-fetch)

node-fetch is a lightweight module that enables us to use fetch() in Node. The package is very similar to window.fetch() in native JavaScript, but has a few differences (see node-fetch docs).

Let's look at an example:

Create a project folder.

mkdir node-api-fetch

Initialize project with npm init -y to be able to install node packages.

cd node-api-fetch
npm init -y

Install node-fetch to make fetch requests.

npm install node-fetch

Create an index.js file.

touch index.js

Add code.

// import node-fetch
const fetch = require('node-fetch');
// set url as constant
const URL = 'https://jsonplaceholder.typicode.com/todos';

fetch(URL)
  .then(response => response.json())
  .then(json => console.log(json))
  .catch(err => console.error(err));

The res.body in node-fetch is a readable stream, so decoding can be handled independently, which is very convenient. The downside is that it only supports res.text(), res.json(), res.blob(), res.arraybuffer(), and res.buffer(). There is no caching built-in and no server-side cookie store, so Set-Cookie headers have to extracted manually.

3. Axios

Axios is a Promise based HTTP client. It can be used in the browser (frontend, SPA, etc.) and in Node.js. Using Promises is a way to deal with asynchronous code. Have a look at Understanding Promises in Node.js for more details on Promises in Node.js.

Let's look at an example:

Create a project folder.

mkdir node-api-axios

Initialize project with npm init -y to be able to install node packages.

cd node-api-axios
npm init -y

Install axios to make fetch requests.

npm install axios

Create an index.js file.

touch index.js

Add code.

// import node-fetch
const axios = require('axios');
// set url as constant
const URL = 'https://jsonplaceholder.typicode.com/todos';

axios
  .get(URL)
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.log(error);
  });

A convenient feature of Axios is that JSON gets parsed by default. There are many other options Axios provides, please have a look at the official Axios Docs.

TL;DR

  • Node.js has a built-in module to make API requests http
  • The concept of handling asynchronous code has to be understood to make API requests.
  • There are many utilities available to make API requests convenient.
  • The module node-fetch implements the Fetch-API for Node.js.
  • Axios is another utility module and automatically parses JSON data.

Thanks for reading and if you have any questions, use the comment function or send me a message @mariokandut.

If you want to know more about Node, have a look at these Node Tutorials.

References (and Big thanks):

Sam Agnew, Nodejs.dev, node-fetch, MDN - Fetch API, Axios

More node articles:

Getting started with Webpack

How to list/debug npm packages?

How to specify a Node.js version

How to create a web server in Node.js

How to dynamically load ESM in CJS

How to convert a CJS module to an ESM

How to create a CJS module

How to stream to an HTTP response

How to handle binary data in Node.js?

How to use streams to ETL data?

How to connect streams with pipeline?

How to handle stream errors?

How to connect streams with pipe?

What Is a Node.js Stream?

Handling Errors in Node (asynchronous)

Handling Errors in Node.js (synchronous)

Introduction to errors in Node.js

Callback to promise-based functions

ETL: Load Data to Destination with Node.js

ETL: Transform Data with Node.js

ETL: Extract Data with Node.js

Event Emitters in Node.js

How to set up SSL locally with Node.js?

How to use async/await in Node.js

What is an API proxy?

How to make an API request in Node.js?

How does the Event Loop work in Node.js

How to wait for multiple Promises?

How to organize Node.js code

Understanding Promises in Node.js

How does the Node.js module system work?

Set up and test a .env file in Node

How to Use Environment Variables in Node

How to clean up node modules?

Restart a Node.js app automatically

How to update a Node dependency - NPM?

What are NPM scripts?

How to uninstall npm packages?

How to install npm packages?

How to create a package.json file?

What Is the Node.js ETL Pipeline?

What is data brokering in Node.js?

How to read and write JSON Files with Node.js?

What is package-lock.json?

How to install Node.js locally with nvm?

How to update Node.js?

How to check unused npm packages?

What is the Node.js fs module?

What is Semantic versioning?

The Basics of Package.json explained

How to patch an NPM dependency

What is NPM audit?

Beginner`s guide to NPM

Getting started with Node.js

Scroll to top ↑