Creating REST API using Nodejs and consuming in Angularjs

Cover image

In most of the applications we need to talk to some kind of database. While AngularJS is a client side library which is capable only at the client side or at browser, now to connect to our database which usually resides at our server we need NodeJS.

NodeJS is an awesome light weight, non-blocking platform to have at your server which is perfect for data-intensive real-time applications.

We will create a simple inventory manager app which will communicate to database

Database: products-demo Collection: products Fields: SKU, Product Name, Price

Our learning path will be like following

  • Install NodeJS and MongoDB
  • Create and configure web server to communicate to database (NodeJS + Express)
  • Craft the client side app (AngularJS)

Install NodeJS, NPM and MongoDB

Create ReST API

  • To create a NodeJS application we first need to create 2 files named:

1. package.json (Defines the architecture and dependency of the nodejs app)

"name": "ReST-API",
"version": "1.0.0",
"description": "A simple RESTFul API created using nodejs that talks to Mongodb database",
"main": "index.js",
"author": "codenx",
"license": "ISC",
"dependencies": {
"body-parser": "^1.13.3",
"express": "^4.13.3",
"mongoose": "^4.1.3",
"node-restful": "^0.2.2"
"main": "server.js"

2. server.js (This will create a basic webserver similar to Apache)

// Dependencies
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
// MongoDB
mongoose.connect(process.env.OPENSHIFT_MONGODB_DB_URL || 'mongodb://localhost/products-demo');
// mongoose.connection.on('error', function(){});
// Express
var app = express();
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({ extended: true }));
// Routes
app.use('/api', require('./routes/api'));
// Start server
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080
, ip = process.env.OPENSHIFT_NODEJS_IP || "";
app.listen(port, ip, function() {
console.log('Express server listening on %d', port);

Now we created our server, lets open command line and navigate to the project folder (C:\creating-rest-api-using-nodejs-and-consuming-in-angularjs) Enter the following commands

npm install node server

npm install – Install all required modules defined in package.json file

  • body-parser – Required to parse the JSON data from the client
  • express – Webserver similar to Apache
  • mongoose – Handy module to talk to MongoDB database
  • node-restful – This module automatically create REST API from specified model

node server – Run our NodeJS app

At this point we should see the message Server is running on port 3000 Create the following 2 files

  • models/product.js – Define the database schema
app.controller('ProductsCtrl', function($scope, Product, ngProgress, toaster) {
$scope.product = new Product();
var refresh = function() {
$scope.products = Product.query();
$scope.product ="";
$scope.add = function(product) {,function(product){
$scope.update = function(product) {
$scope.remove = function(product) {
$scope.edit = function(id) {
$scope.product = Product.get({ id: id });
$scope.deselect = function() {
$scope.product = "";

routes/api.js – Defines the API routes (data providers)

// Dependencies
var express = require('express');
var router = express.Router();
var Product = require('../models/product');
Product.methods(['get', 'put', 'post', 'delete']);
Product.register(router, '/products');
// Return router
module.exports = router;

Now that our API is ready. You can test it using Chrome Postman extension

The next step is to create our client using AngularJS To call our ReST API we need the help of angular-resource which will make our task easy and fun. In this application I’ve added some animations too. For this application we will create a factory named Product to interact with our ReST API which in turn interacts with our database. We will call this factory from products.js file with different methods like get, post, put, delete. The file public/index.html is the starting point of our application. From here everything starts. This page renders the view.

<html ng-app="myApp">
<title>Simple demonstration of AngularJS with ReSTful API - AngularCode</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/ngProgress.css">
<link rel="stylesheet" href="css/toaster.css">
[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
display: none !important;
<body ng-cloak>
<div class="container" ng-controller="ProductsCtrl">
<form name="Codenx" novalidate>
<table class="table">
<td><input class="form-control" ng-model="" required="" placeholder="Product Name"></td>
<td><input class="form-control" ng-model="product.sku" placeholder="Stock Control Unit"></td>
<td><input class="form-control" ng-model="product.price" placeholder="Should be a number"></td>
<td><button class="btn btn-primary" ng-click="add(product)" ng-if="!product._id" type="submit" ng-disabled="!Codenx.$valid">Add Product</button>
<div class="btn-group">
<button class="btn btn-info" ng-click="update(product)" ng-if="product._id" type="submit">Update</button>
<button class="btn" ng-click="deselect()" ng-if="product._id">Clear</button>
<tr ng-repeat="product in products">
<div class="btn-group">
<button class="btn btn-danger" ng-click="remove(product)">Remove</button>
<button class="btn btn-warning" ng-click="edit(product._id)">Edit</button>
<div data-loading></div>
<toaster-container toaster-options="{'time-out': 3000, 'close-button':true, 'animation-class': 'toast-top-center'}"></toaster-container>
<script src="js/angular.min.js"></script>
<script src="js/angular-resource.min.js"></script>
<script src="js/angular-animate.min.js"></script>
<script src="js/ngProgress.min.js"></script>
<script src="js/toaster.js"></script>
<script src="app/app.js"></script>
<script src="app/products.js"></script>

We have 2 controller where we define the business logic and the angular app resides here


var app = angular.module('myApp', ['ngResource', 'ngProgress', 'ngAnimate', 'toaster']);
app.config(function ($httpProvider) {
// Handle http server errors
app.factory('myHttpInterceptor', function ($q,toaster) {
return {
responseError: function (response) {
toaster.error("Error: ",;
toaster.error("Error: ",;
return $q.reject(response);
// Showing loading indicator on top while data is requested from database
app.directive('loading', ['$http', 'ngProgress', function ($http, ngProgress)
return {
restrict: 'A',
link: function (scope, elm, attrs)
scope.isLoading = function () {
return $http.pendingRequests.length > 0;
scope.$watch(scope.isLoading, function (v)
// Create a resource factory to access products table from database
app.factory('Product', function($resource) {
return $resource('/api/products/:id', { id: '@_id' }, {
update: { // We need to define this method manually as it is not provided with ng-resource
method: 'PUT'


This is the ProductsCtrl where we handle all user interactivity

// Dependencies
var restful = require('node-restful');
var mongoose = restful.mongoose;
// Schema
var productSchema = new mongoose.Schema({
name: String,
sku: String,
price: Number
// Return model
module.exports = restful.model('Products', productSchema);
Subscribe my updates via Email