How to use Node.js and Express to make API request.

As we can notice that the current software industry is using latest microservies architecture for their application development, we need some way to make external api request to fetch data.

Making request to fetch data from Node.js can be achieved using a Node.js module named as 'request'. We can download it using node package manager 'npm'.

Let's start by building a simple application using Node.js and Express.js. The application will fetch exchange data from an external service https://openexchangerates.org.

Express is an node.js framework for building web application.

Step 1: Open your command prompt and navigate to folder of your choice. Create a new empty folder for your project.

mkdir exchangeapi

cd exchangeapi

 

Step 2:  Next is to initialize a node project using 'npm init' command.

Continue by choosing the defaults. Once done you should find a 'package.json' file which is used to manage depedency for node.js application or we can directly create a package.json file and paste the code mentioned below and skip step 3:

{
  "name": "exchangeapi",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.17.2",
    "express": "^4.15.3",
    "morgan": "^1.8.2",
    "request": "^2.81.0"
  }
}

Next run npm install for installing the above depedencies.

Step 3: Now we need to install the dependencies for the project which are listed below:

  1. express: Framework for web application.
  2. request: Module for api request.
  3. morgan: Module used for logging.
  4. body-parser: Module used for parsing request data.

npm install express morgan request body-parser --save 

 

'--save' is used to save the depedencies inside the package.json file. 

Step 4: Create two files server.js and config.js.

Add the below code to server.js file:

var express = require('express'); 

var bodyParser =  require('body-parser'); // used to handle request parameter

var morgan = require('morgan'); // package used for logging

var config = require('./config'); // config file

var app = express();

// allows form parameter binding to req object and extended true basically allows you to parse full objects 
app.use(bodyParser.urlencoded({extended:true}));
// allows to handle json request parameter
app.use(bodyParser.json());
// used for logging
app.use(morgan('dev'));

app.use(express.static(__dirname + '/public')); // serves static file from public folder

var api = require('./app/routes/controller')(app,express);

app.use('/api', api); // end point will be accessed by appending api to the end point

app.listen(config.port,function(err){

  if(err){
    console.log("error");
  }else{
    console.log("server listening on port "+ config.port);   
  }

});

The above code is simple and commented. Next paste the below code to config.js.

/**
 * @description
 * configuraton for the exchange api end point
 *
 */
module.exports = {
"basepath":"https://openexchangerates.org/api/",
"apikey":"xxxxxxxxxxxxxxxxxxxxxxxx",   
"port":process.env.PORT || 3000  
}

 

In the above script at line no 8 , replace your api key to access the exchange data , follow the given below link to free signup and get the api key.

https://openexchangerates.org/signup/free

Step 5: Next create a folder app and within app folder create another folder routes which will contain our code to interact with external api.

Step 6: As per the above image, create two files named controller.js and services.js  where we will write code to interact with the external api.

controller.js :

'use strict'
//used to import service module
var util = require('./service');

module.exports = function(app,express){
    
    var api = express.Router();

      /**
       * @name latest
       * @description
       *  end point to get latest exchange rate with USD as base currency
       */    

      api.get('/latest',function(req,res){
            var result = util.getLatest(function(err,response,data){
            if(!err){
              res.send(data);   
            }
           });           
        });

      /**
       * @name currencies
       * @description
       *  end point to get list of currencies available
       */  

      api.get('/currencies',function(req,res){
            var result = util.getCurrencies(function(err,response,data){
            if(!err){
              res.send(data);   
            }
           });
        });

      /**
       * @name history
       * @description
       *  end point to get history data given a date ass parameter
       */ 

      api.get('/history',function(req,res){
           var dateString = req.query.date;
           var result = util.getHistorical(dateString,function(err,response,data){
            if(!err){
              res.send(data);   
            }
           });
        });

    return api;

}

In the above controller.js file we expose three different end points 

  1. api/latest
  2. api/currencies
  3. api/history

Line 3 includes service.js for making call to exchange api

service.js :

'use strict'

//module used to make http request
var request = require('request'); 
//configuration object
var config = require('./../../config');


/**
 * @name getHistorical
 * @description
 *  service function to get historical data
 * @param date format(yyyy-mm--dd)
 * @param cb a callback function
 */
var getHistorical = function getHistorical(date,cb){

  var dateString = date.concat(".json");
  var url = config.basepath.concat('historical/').concat(dateString).concat("?app_id=").concat(config.apikey);
  request(url, function (error, response, body) {
    cb(error,response,body); //callback function
  });
   
}
/**
 * @name getCurrencies
 * @description
 *  service function to get list of currencies data
 * @param cb a callback function
 */

var getCurrencies = function getCurrencies(cb){

  var url = config.basepath.concat('/').concat('currencies.json').concat("?app_id=").concat(config.apikey);
  request(url, function (error, response, body) {
    cb(error,response,body); // callback function 
  });

}
/**
 * @name getLatest
 * @description
 *  service function to get latest exchange rate wiith base currency set as USD
 * @param cb a callback function
 */
var getLatest = function getLatest(cb){
  var url = config.basepath.concat('/').concat('latest.json').concat("?app_id=").concat(config.apikey);
  request(url, function (error, response, body) {
    cb(error,response,body); // callback function
  });

}

/**
 * @description
 * Service object to expose required functions
 */

var serviceObject = {
  "getLatest":getLatest,  
  "getHistorical":getHistorical,
  "getCurrencies":getCurrencies
}

/**
 * @description
 * used to expose the methods
 */
module.exports = serviceObject

This is the main file which uses request module of node.js for making external api request, we use callback to handle the response from the request, usage can be found from line 20 -22, 35-36, 48-49.

Once done with the above sample, run the application from root of the code by running 

node server.js

Once application is up, access the end point to view the results for e.g.

http://localhost:3000/api/latest