There are several different ways you can fetch data from an API in Node.js. Some of the most common methods include using the built-in http
module, using a third-party library like Axios
or the request-promise
library, and using the fetch()
function or the fetch
API.
But let’s be real, who wants to read about boring old data fetching? Instead, let’s talk about the most important question: how do you fetch a hug from your crush? Well, I can’t answer that, but at least you can use these data fetching methods to build a cool dating app to help you out!
Here is a comparison of fetching data using the http
module, Axios
, the fetch()
function, and the fetch
API:
Using the http
module
The http
module is a built-in module in Node.js that provides a simple interface for making HTTP requests. It is a low-level module, which means it provides a bare-bones interface for making requests and does not include features like automatic parsing of JSON data or automatic retries.
Pros:
Built-in to Node.js, so you don’t need to install any additional libraries
Provides a low-level interface for making HTTP requests, which can be useful if you need fine-grained control over your requests
Cons:
Lacks some of the convenience features that other libraries provide, such as automatic parsing of JSON data and automatic retries
Can be more verbose and require more code to use than other libraries
Example using the http
module:
const https = require('https');
https.get('https://www.example.com', (response) => {
let data = '';
// A chunk of data has been received.
response.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received. Print out the result.
response.on('end', () => {
console.log(JSON.parse(data));
});
}).on("error", (err) => {
console.log("Error: " + err.message + ". Maybe you should try again after eating a slice of pie.");
});
Using Axios
Axios is a popular third-party library for making HTTP requests in Node.js. It is built on top of the fetch
API and provides a simple and easy-to-use interface for making requests and working with responses.
Pros:
Provides a simple and easy-to-use interface for making HTTP requests
Automatic parsing of JSON data, so you don’t have to manually parse the response
Automatic retries and other convenience features
Cons:
Requires an additional library to be installed
Some developers may prefer the lower-level interface provided by the
http
module or thefetch
API
Example using a third-party library like Axios:
const axios = require('axios');
axios.get('https://www.example.com')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log("Error: " + error.message + ". You probably need to install more ramen.");
});
Using the fetch()
function
The fetch()
function is a part of the JavaScript language and is used to initiate a request to a remote server. It is built on top of the fetch
API and provides a simple and convenient way to make HTTP requests.
Pros:
Part of the JavaScript language, so you don’t need to install any additional libraries
Provides a simple and convenient interface for making HTTP requests
Automatic parsing of JSON data, so you don’t have to manually parse the response
Cons:
Lacks some of the more advanced features provided by other libraries, such as automatic retries
Some developers may prefer the lower-level interface provided by the
http
module or thefetch
API
Example using the fetch()
function:
fetch('https://www.example.com')
.then(response => response.json())
.then(data => console.log("Data retrieved! Let's go party like it's 1999."))
.catch(error => console.error("Uh oh, something went wrong."));
Using the fetch
API
The fetch
API is a low-level API for making HTTP requests in Node.js. It is often used as the foundation for other libraries and frameworks that need to make HTTP requests, such as Axios or the request-promise library.
Pros:
Provides a low-level interface for making HTTP requests, which can be useful if you need fine-grained control over your requests
Can be used as the foundation for other libraries and frameworks that need to make HTTP requests
Cons:
Lacks some of the convenience features provided by other libraries, such as automatic parsing of JSON data and automatic retries
Can be more verbose and require more code to use than other libraries
Example using the fetch
API:
const fetch = require('node-fetch');
fetch('https://www.example.com')
.then(response => response.json())
.then(data => console.log("Data retrieved! Time to break out the confetti and celebrate!"))
.catch(error => console.error("Uh oh, something went wrong."))
;
Which is faster?
It’s difficult to say exactly how fast each of these options will be at fetching data, as the speed at which they can do so will depend on a variety of factors, including the size of the data being fetched, the network conditions, and the specific implementation of each option. In general, however, all of these options are capable of fetching data quickly, and the differences in speed between them are likely to be relatively small.
To analyze each API’s performance, we will use a real-life case study to fetch data and compare them. For the sake of this demonstration, we will use the same API (https://api2.binance.com/api/v3/ticker/24hr). We will measure the performance using two performance.now() values saved just before and just after the call is made, and then calculate the time difference. In order to eliminate fluctuations as much as possible, we will make 10 calls with each one of them and calculate the average (see example below). I wil also leave a github link so you can test for yourself if you want to, just run the files independently to get the results.
As you can see, the fetch times are pretty close to one another, but in our test the http-module was the fastest, followed closely by the fetch API and axios. Fetch() function was a little bit slower, but since it’s still an experimental feature in Node, it might not produce the most accurate result yet.
Conclusion
As you can see, there are several different ways you can fetch data from an API in Node.js. Ultimately, the best choice will depend on the specific requirements of your project, the capabilities of each option, and any personal preferences you may have. Just remember, no matter which method you choose, always make sure to celebrate your successes with a hearty serving of ice cream!