{

Multiple ways to Call REST API from Nodejs Application| Consume REST API


Sometimes, the Application requires calling a Remote or external API from a nodejs Application.

It covers the following items

  • How to call remote REST API from nodejs application
  • How to get data from HTTP to get request data
  • How to make HTTP get and post a request
  • Get HTTP request body in nodejs
  • Process post request in NodeJS

Nodejs is server-side code based on npm libraries.

Consume REST API involves HTTP request of type GET/POST/DELETE/PATCH

  • HTTP/HTTPS inbuilt
  • Axios
  • fetch

It involves sending a request of json data and receiving the HTTP Response with

For calling any rest API, We need the following.

  • REST API URL
  • Request types like GET/POST/DELETE/PATCH
  • HTTP request data type
  • expected response type to handle it
  • content-type and accept request headers
  • Any security or authorization headers

using HTTP/HTTPS client to call remote API

http and HTTPS are inbuilt modules, that can be used as server and client

If the request url is https, We can use the https module, otherwise can use HTTP module Here is a syntax to make an HTTP url request

http.get( options, response callback);
http.post( options, responsecallback);

  • First import using the required keyword
  • call get with Url and returns call back
const http = require('https');
const url = "https://jsonplaceholder.typicode.com/posts";

http.get(url, function (response) {
    let posts = "";

    response.on("data", function (data) {
        posts += data.toString();
    });

    response.on("end", function () {
        console.log(posts.length);
        console.log(posts.toString());
    });

});

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.