Getting data from RESTful API in Node

There are many websites and servers on the internet that provide various RESTful API which we can use in order to get a certain type of data such as motivational quotes, weather reports, etc. 

For example, to make an application that shows the weather on the basis of the user’s location, we have to use some API that sends the information about the weather of the location we request for.

Also read: Build a CRUD API in Node.js

Consuming RESTful API

Getting data from RESTful API in Node.js varies from method to method. Each method returns a different type of response containing different properties and methods for an API so it is essential to learn the various methods for consuming RESTful API so that you can choose them according to the project requirement.

We have a separate tutorial on RESTful API using Node.js and Express.js.

Methods for Getting Data from the NodeJS RESTful API

Let’s now get started with learning the different NodeJS methods for using the Restful API

fetch()

The fetch method is popular in client-side JavaScript to fetch data from APIs. In Node.js it is required to install v17.5 or above in order to use the fetch() method. 

Use the below command in the terminal to check for the Node.js version installed on your system.

node -v

You can download the setup file of Node.js latest version from the Node.js Official Website.

The fetch() method in Node.js is an experimental feature so you can use it by using the –experimental-fetch parameter.

node fileName –experimental-fetch

where the fileName is the file you want to execute

Syntax:

fetch(url)

where the url is the address of an API

This method returns a response object containing the following methods and properties.

  • text() – returns the response as a string
  • json() – parser the response into a JSON string
  • status – return the status code
  • statusText – return the status message
  • ok – return true if the request is successfully completed
  • url – the value of the final URL 
  • header – contains response header

Example:

const url = 'https://api.adviceslip.com/advice';

fetch(url)
    .then((response) => response.json())
    .then((data) => {
      console.log(data);
});

Output:

Fetch Method Example

axios()

For using the method, we have to use the Axios module. Axios module can be installed by npm using the below command.

npm i axios

This method takes an URL as an argument in order to send the get request.

Syntax:

axios(url)

where the url is the address of an API

This method returns a response object containing the following properties.

  • data – the actual data
  • status – return the status code
  • statusText – return the status message
  • header – contains response header
  • config – the request configuration
  • request – the request object

Example:

const axios = require('axios');

const url = 'https://api.adviceslip.com/advice';

(async () => {
        const response = await axios(url);
        console.log(response.data);
})();

Output: 

Axios Method Example

https.request()

This method can be used to send the HTTPS request to the API in order to fetch the data. For using this method it is required to import the HTTPS module. The HTTPS is a built-in module used to send an HTTPS request to a secure web server.

This method takes a URL as an argument and a callback which makes it asynchronous in nature. 

Syntax:

https.request(url, callback)

where the url is the address of an API

This method returns the data stream containing data in chunks which can be finalized using the stream’s event.

We have a separate tutorial on Node.js Events if you want to learn about them.

Example:

const https = require('https');

const url = 'https://api.adviceslip.com/advice';

const request = https.request(url, (response) => {
    let data = '';
    response.on('data', (chunk) => {
        data = data + chunk.toString();
    });
  
    response.on('end', () => {
        const body = JSON.parse(data);
        console.log(body);
    });
})
  
request.on('error', (error) => {
    console.log('An error', error);
});
  
request.end() 

Output: 

Https Method Example

Summary

The APIs are the best way to use the methods and data of the other websites and servers in your project in order to get different types of information such as weather reports, sport news, movie release date, etc. For consuming RESTful API we can use many different methods such as fetch(), axios(), request(), etc which return a slightly different response for an API. Hope this tutorial helps you to learn the methods of consuming the RESTful API in Node.js.

Reference

Aditya Gupta
Aditya Gupta
Articles: 109