31
How to make an API request in Node.js?
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.
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);
});
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.
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.
- 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.
31