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


Sometimes, Application requires to call Remote or external API from a nodejs Application.

It covers following items

  • How to call remote REST API from nodejs application
  • How to get data from http get request data
  • How to make http get and post 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 requst of type GET/POST/DELETE/PATCH

  • http/https inbuilt
  • axios
  • fetch

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

For calling any rest API, We need followings

  • REST API URL
  • Request type 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 a inbuilt module, can be used as server and client

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

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

  • First import using require 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.