Node.js Rest Service Calls

In many instances, an application may need to make a call to a REST service to retrieve relevant information. The Node.js request package offers support for this sort of task.

Begin by creating a Node.js application using Handlebars as the template engine. You can either use your IDE or follow this tutorial to do this from the command line.

Once you have created a skeleton project, head over to OMDB to request an API key. You will get an email that will contain an API key. Then type npm install request to install the request package. Once you have the email, create a keys.js file in the routes folder.


The keys.js file is used to hold API keys. Since API keys are like passwords, it’s generally a bad idea to push them to a public repository. By placing them in a file, you can import the keys into a project and then add them to .gitignore to keep them save. Here is what the keys.js file should look like.

exports.omdb_api = 'Your API Key';


The index.js is used for HTTP GET and POST requests to our application. You can view this tutorial to get an idea of how MVC works in Node.js with Express. We are going to mainly focus on the POST portion of this file.

var express = require('express');
var router = express.Router();
var key = require('./keys.js').omdb_api;
var request = require('request');

var movie = [];

/* GET home page. */
router.get('/', function (req, res) {
    res.render('index', { title: 'Rest Example', movie: movie });
});'/', function(req, res){
    var query = req.body.query;
    var url = '' + key + '&t=' + query + '&y=&plot=short&r=json';

    //Clear out movie
    movie = [];

    request(url, function(error, response, body){
        //Check for HTTP Status OK
        if (response.statusCode === 200){
            //Convert the body to a JSON object
            var json = JSON.parse(body);

            //Check if it has an error
                movie = json.Error;
            } else {
                //Otherwise, add our movie information to movie
                    title: json.Title,
                    year: json.Year,
                    imdb: json.Ratings[0].Value,
                    tomatoes: json.Ratings[1].Value,
                    country: json.Country,
                    plot: json.Plot,
                    actors: json.Actors
        } else {
            //We had something other than HTTP OK
            //Push an error to movie and just pass the body
            movie.push({Error: body});
        //Render the index page
        res.render('index', {title: 'Rest Example', movie: movie[0]});

module.exports = router;

We begin on line 3, where we import our keys.js file and grab it’s omdb_api variable. This variable holds our API key and will be used to create our URL for our web request. On line 6, we create a movie variable and initialize it to an empty array.

Our POST handler is located on line 13. One line 14, we grab the name of the movie the user wishes to inspect from the req.body.query variable. On line 15, we assemble our url by adding our API key and movie name to the url string.

Line 20 uses the request package to make a call to the OMBD API. It takes two parameters, a url and a call back function. The callback function can have 3 parameters: error, response, and body. We are interested in response and body in this case. Our first job is to check the HTTP status code from response.statusCode. If everything is OK, the response will be 200 (for HTTP OK). Assuming all went well, we can convert the body variable into a JSON object so that we can access the properties of the response.

If the user happens to enter a move that doesn’t exist, the json will have an Error property. We will just assign this to the movie variable is that’s the case. Otherwise, we can create a new object containing title, year, imdb, tomatoes, country, plot, and actors (lines 31-38) and push it to movies. Finally we can return the reponse body back to the view and render the index page (line 47).


We need to add our Jquery and Bootstrap libraries to our layout.hbs file so that they are available to our pages.


This page renders the results our request.
The main take away is that we use the {{#if [value]}} markup so that the template engine can decide if it wants to render the error or movie information.


When everything is complete you will get a site that looks like the one shown in the screenshots below.

You can view the full source at my GitHub page here.

Create Node.jS & Handlebars & Express.js Project from command line

It’s trivial to create an empty Node.js project using express generator using the command line. You can follow the guide found at this link for the official express generator example or just keep reading.

Begin by opening up your terminal and navigate to any folder on your file system. Keep in mind that the project will be created as a sub-directory of the folder you choose. If you haven’t installed express generator then execute the following command.

npm install express-generator -g

This command will install express generator on your system. Once the installation is complete, you can create an express project with the handlebars view engine using this command.

express --hbs [application name]

Replace [application name] with the name of your application. For example express -hbs myhbsproject. The script will create a folder in the current directory that has the same name as your application. You should see terminal output that looks similar to the screen shot.
If you look closely, the script tells you the next two steps. First you need to install the dependencies.

cd [application name]
npm install

Once again, npm will do the job of downloading all required project dependencies.
Finally, you can run the project by issuing the next command in the terminal.

DEBUG=[application name]:* npm start

You will see this output in the terminal.
When the server is running, you can open up your web browser and point it at http://localhost:3000/ to see the default homepage.

Folder Structure

For those people who are curious, you will get the following folder structure when using express generator to create a project.
The public folder is for files such as client side javascript, css, and images that can be referenced by a web page. You should put your server js in the routes folder. All handlebar template files should get placed in the views folder.

You can view the YouTube video here.

Node.js & Spotify

Spotify provides APIs that allow developers to write client applications. This tutorial will demonstrate how to use Node.js to create a simple web application that queries Spotify for information about a particular song. Start by creating a Node.js application with a folder structure that resembles the one shown in this screenshot. You can view a tutorial one how to do this at this link or use your IDE.
Folder_Structure You will want to have the following dependencies in your package.json file.

  "name": "spotifynode",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  "dependencies": {
    "body-parser": "~1.17.1",
    "cookie-parser": "~1.4.3",
    "debug": "~2.6.3",
    "express": "~4.15.2",
    "hbs": "~4.0.1",
    "morgan": "~1.8.1",
    "node-spotify-api": "^1.0.5",
    "serve-favicon": "~2.4.2"

Spotify requires developers to create application keys in order to use their APIs. Follow the guide provided here in order to create a developer account with Spotify. Once you have created an application, you will need to retain the application id and secret.

Start by creating a keys.js file in the routes folder. It should look like the following example.


exports.spotifyKeys = {
    id: 'Spotify Id Here',
    secret: 'Spotify Secret Here'

The next thing to do is to write the server side code that handles HTTP GET and POST requests. Here is the code for index.js.


var express = require('express');
var router = express.Router();

//Import the Spotify API
var Spotify = require('node-spotify-api');

//Import our Keys File
var keys = require('./keys');

//Create a Spotify Client
var spotify = new Spotify(keys.spotifyKeys);

//Store the results of a request to spotify
var results = [];

/* GET home page. */
router.get('/', function (req, res) {
    res.render('index', {title: 'Spotify', results: results});
});'/', function (req, res) {
    //Get the type of Query from the User
    var type = req.body.param_type;

    //Get the query from the user
    var query = req.body.param_query;

    //Clear out old results
    results = [];

    //Make a request to Spotify{type: type, query: query})
        .then(function (spotRes) {

            //Store the artist, song, preview link, and album in the results array
                results.push({artist: ea.artists[0].name,
                              preview: ea.external_urls.spotify,
            //Render the homepage and return results to the view
            res.render('index', {title: 'Spotify', results: results});
        .catch(function (err) {
            throw err;

module.exports = router;

This code sets up two handlers for GET and POST requests. More details about how to do this can be found in this post. We begin on line 5 by importing the Spotify API into our script. Then we pull in the keys.js file we created earlier so that we can authenticate with Spotify. The next line creates a spotify object and we pass our creditionals to its constructor.

The next point of interest is the found on line 32. The function takes in two arguments, type and query. The type argument specifies the type of query and the query is the actual search criteria that we are going to send to the API. The spotify library will make correct rest calls to the Spotify API and it will return a response.

Inside of the body of the promise function, we push some information about the song to the results array so that we can display it to the view. In this case, we are going to grab the artist, song, a preview url, and the song’s album. We then return it to the view for display in a table.


We can use Handlebars to markup a template page that will get returned to the browser from the server.


When run, the application will look like the following screenshots.

You can view the source from my GitHub page at this link.

Node.js Handlebars Twitter

Twitter provides REST APIS that make it incredibly easy to access information from Twitter. When combined with Node.js, it becomes a trivial task to create a web application that connects to Twitter and displays the latest tweets for a User.

In order to begin, you will need to register at Twitter’s developers page. The details page will give you several tokens that you will need to connect to Twitter: consumer_key, consumer_secret, access_token_key, and access_token_secret. Keep this information handy as you will need it for later.

Now we can create the project. I use Intellij’s node.js plugin to create my project, but you will want to create a project structure that is similar to the one shown in the following screenshot. You can view a tutorial one how to do this at this link or use your IDE or you may find the directions at Express.js to be useful as well.
Once you have created your project (making sure you have express.js and handlebars.js), you will need to add Twitter. Open up the terminal and navigate to your project’s directory. Then type

npm install twitter

At this point you are ready to begin developing.

Create a keys.js file in your routes folder. Then populate it with the following code. You will use the consumer_key, consumer_secret, access_token_key, and access_token_secret properties that you obtained earlier on Twitter’s developer’s page and replace the values in this file accordinly.

exports.twitterKeys = {
    consumer_key: '[your consumer key here]',
    consumer_secret: '[your consumer secret here]',
    access_token_key: '[your access_token_key here]',
    access_token_secret: '[your acess_token_secret here]',

The next job is to write the index.js file that handles HTTP GET and POST requests. (You can view this tutorial for more information). The code is very short as we are only handling a GET and POST request.

//Pull in our libraries
var express = require('express');
var router = express.Router();
var Twitter = require('twitter');

//Get our access keys
var keys = require('./keys.js');

//Create twitter client
var twitter = new Twitter(keys.twitterKeys);

//Store our tweets
var tweets = [];

/* GET home page. */
router.get('/', function (req, res) {
    res.render('index', {title: 'Node Twitter', tweets: tweets});
});'/', function (req, res) {
    //Get the user name and number of tweets from the form
    var user = req.body.user_name;
    var numTweets = req.body.tweets;

    //Clear out old tweets
    tweets = [];

    //Hit Twitter for the information
    twitter.get('statuses/user_timeline', {screen_name: user, count: numTweets})
        .then(function (tw) {
            //Loop through the results
            for (var i = 0; i < tw.length; i++) {
                tweets.push({timestamp: tw[i]['created_at'], tweet: tw[i]['text']});
            //Render the index page with the tweets
            res.render('index', {title: 'Node Twitter', tweets: tweets});
        .catch(function (error) {
            throw error;

module.exports = router;

The magic of retrieving tweets is done with the twitter.get(). This function takes a rest endpoint (see here for a list) along with a map of arguments that end up becoming URL parameters in the request. Since we are getting the user’s tweets, we are going to hit the statuses/user_timeline endpoint. The screen_name argument is the users Twitter name and count is the number of tweets that are getting returned.

The Twitter api returns a massive JSON response that holds just about every detail we could ever want to know about a Tweet. We are only interested in when the tweet was created and the text of the tweet. So we loop through the tw (the response object) and just grab those two properties and push them into our tweets array. When we have finished, we will pass tweets back to the view and render the index page.

Our final job is to define our html templates. Since we are using Bootstrap and jQuery, we will need to add these libraries to layout.hbs.
Next we need to write our index.hbs template. Here is the source.
Line 25 starts with {{#if tweets}}. This is a conditional rendering tag that only renders the code between 25-42 if there are tweets to display. Without it, we would write out the table between lines 26-41 when there are no tweets, which would not make a lot of sense.

Once we have tweets, the #if condition will be true and the page will write out a table of tweets. The code on line 34-39 will write out a table row for each tweet that is contained. When we are finished, we will get this output.

You can get the code out my GitHub page here or view the video tutorial on my YouTube channel.

%d bloggers like this: