Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to make REST API call from Express Application

                At times our application might depend on other 3rd party REST APIs. In that case we might require to make either GET or POST requests from our express application.

               Here I am going to use node module called “request” HTTP client to make 3rd party API calls. There are so many other node modules which will provide functionality what we want. But, I have chosen “request” node module based on the usage stats. I always prefer to look at the usage stats of any node module before picking it to use. This shows the developer community adoption.

                 For the demonstration purpose  I am going to use express application which we created in the last article. In this example I am using “Elastic search” to get the product information. We need to make REST API call to the search server to get the product information. The GET request to the search server from the express is given below.

//Add required modules here
var express = require('express');
var request = require('request');
var app = express(); 
//http://localhost:3000/_getproduct/8821264 
app.get('/_getproduct/:id', function(req, res) { 
       if (!req.params.id) { 
           res.status(500); 
           res.send({"Error": "Looks like you are not senging the product id to get the product details."}); 
           console.log("Looks like you are not senging the product id to get the product detsails."); 
       } 
      request.get({ url: "http://localhost:9200/productcatalog/product/" + req.params.id },      function(error, response, body) { 
              if (!error && response.statusCode == 200) { 
                  res.json(body); 
                 } 
             }); 
     }); 

The explanation to the above code is given below.

In the coming article we will see how to connect to mongo db from Node.js. Till then, Stay Tune!!!




This post first appeared on Smart Techie | My Thoughts, My Work, My Ideas, please read the originial post: here

Share the post

How to make REST API call from Express Application

×

Subscribe to Smart Techie | My Thoughts, My Work, My Ideas

Get updates delivered right to your inbox!

Thank you for your subscription

×