DEV Community

loading...

How to make an API request in Node.js?

Mario
Software Engineer from Vienna, Austria. Building things, mainly in JavaScript.
Originally published at mariokandut.com on ・7 min read

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.

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);
});
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

cd node-api-fetch
npm init -y
Enter fullscreen mode Exit fullscreen mode

Install node-fetch to make fetch requests.

npm install node-fetch
Enter fullscreen mode Exit fullscreen mode

Create an index.js file.

touch index.js
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

cd node-api-axios
npm init -y
Enter fullscreen mode Exit fullscreen mode

Install axios to make fetch requests.

npm install axios
Enter fullscreen mode Exit fullscreen mode

Create an index.js file.

touch index.js
Enter fullscreen mode Exit fullscreen mode

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);
  });
Enter fullscreen mode Exit fullscreen mode

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

Discussion (0)