Skip to content

Basic API Creation with Node.JS

Featured Image

To create a project with node.js either for mobile applications to access data or for various clients based websites which requires accessing data; it requires building a basic API. These projects, mostly built with express.js and a mango database. In this article we will understand the basic of Node.js, express middleware and API creation/Restful web services using Node.js with one basic example.

What is an API?

API (Application Programming interface) is a set of programming instructions and standards for accessing a web based software application.

Many software companies allow third party apps to integrate with their services. So they don’t provide direct access to their databases or business logic directly. They provide one interface from which they can easily access the database, without any efforts from scratch.

For example, now a day’s many applications allow signing up from Facebook account. Once you authenticate, with the help of the Facebook API, they collect your personal information, Friends details, or post any things. Also, many Mobile Applications are getting data from the server. For that purpose they are creating Restful service and gets result from the service.

Node.js is a good choice when we need some scalable app with lesser effort and fast development. There are many frameworks available which easily creates Controllers automatically based on Models defined. Let’s understand what is node.js?

What is Node.js?

Node.js is a software platform for scalable server-side and networking applications. Node.js application is written in JavaScript and can be run within the Node.js runtime on different platforms like windows, Mac OS X and Linux without any changes.

Node.js applications are designed to maximize throughout and efficiency of the app with the help of non-blocking I/O asynchronous events. Node.js applications run single-threaded, although Node uses multiple threads for file and network events. Node.js contains a built-in HTTP server library, and making it possible to run a web server without Apache or any server.

Many companies like PayPal, Linkedin, Yahoo, and Microsoft is using Node.js in their product development. PayPal has created their own framework called KankenJS using Node, which is used in development all their new web applications.

If Node.js is new for you, in this article we will see how to install node.js, develop and run an application with the help of Node.js.

Installation & Development

You can download the NodeJS installer from here.

Creating an HTTP server which responds to client query is very easy to build with node.js.

Just write below code in a file and save as server.js

var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello Node.js\n');
}).listen(80, "127.0.0.1");
console.log('Server running at http://127.0.0.1:80/');

To run the server, execute a file with the node program from the command line.

C:\> node server.js

So whenever you access http://127.0.0.1 from the browser and through any HTTP Client, it will respond with “Hello Node”.

Express.js

Express.js works as middleware and provides light-weight application framework to help to organize server side web applications.

Express.js is a very popular module which provides various feature like robust routing, Dynamic view helpers, Focus on high performance, view rendering, session support and High test coverage.

The same code written earlier can be written as below in express.js:

var express = require('express');
var app = express();app.get('/', function(req, res){ res.send('hello world');});
app.listen(80);

Let’s Create One Simple Application with Node.js

Let’s see an example of User Management, which allows creating, updating, removing or to get the user information from the database. These are the basic operations, which are used by most of the applications in which there are involvement of the users.

Note: In this example we are using MongoDB as a Database. So make sure that MongoDB process is running while executing this code.

Check below the URL endpoint which we are creating for achieving this:

Method URL Action
GET /user Retrieves all users.
GET /user/[id] Retrieve user specified by id.
POST /user Add a new user.
PUT /user/[id] Update user specified by id.
DELETE /user/[id] Delete user specified by id.

For creating this functionality code is divided into three files:

Filename Purpose
App.js We will define all the routes.
UserController.js Defines all the Business Logic to perform user related operations
Model.js Defines the Database schema for User Entity

App.JS

var express = require('express');
var userController = require('./usercontroller.js');
var mongoose = require(' mongoose');

// Initializing express Object
var app = express();

app.configure(function () {
app.use(express.logger('dev'));
app.use(express.bodyParser());
});

// Connecting to Database
mongoose.connect(mongodb://localhost/myDb);

// Start writing Routes here.
app.get('/user', userController.getAllUsers);

app.get('/user/:id', userController.getUserById);

app.post('/user', userController.addUser);

app.put('/user/:id', userController.updateUser);

app.delete('/user/:id', userController.deleteUserById);

// Starts Listening on port 9000
app.listen(9000);
console.log ('Server listening on port : 9000');

In this file we have done the following things:

  • Initializing Express object.
  • Configuring App: It is used to define the various application level configurations for the app.
  • Connecting to a Database.
  • Defining Routes: It is used to define various routes for performing various operations.
  • Start Listening: Open server port. Various operations and communication can be done through this port.

Model.JS

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;

/* By default each Schema contains _id property as a unique field*/

var userSchema = new Schema({
emailId: String,
firstName: String,
lastName: String,
password: String
});

exports.userModel = mongoose.model('User', userSchema);

Mongoose is a node module for performing and simplifying various Mongo database related operations. Mongoose is MongoDB Object modeling module for Node.js

In this file we have done the following things:

  • Defining Schema for the User with email, password, first name and last name field.
  • Creating Model from the Schema.

UserController.JS

var UserModel = require('./model.js').userModel;

// No User Inputs required.
exports.getAllUsers = function(req, res) {

var responseObj = new Object();
responseObj.result = false;

UserModel.find(function(err, users){
if(err){
responseObj.error = err;
}else{
responseObj.result = true;
responseObj.users = users;
}
res.send(responseObj);
});
}

// you need to call
exports.getUserById = function(req, res) {

var responseObj = new Object();
responseObj.result = false;

var id = req.params.id;

var searchQuery = { '_id' : id }; //format for search query

UserModel.findOne(searchQuery, function(err, user){
if(err){
responseObj.error = err;
}else{
responseObj.result = true;
responseObj.user = user;
}
res.send(responseObj);
});
}

exports.addUser = function(req, res){
var responseObj = new Object();
responseObj.result = false;

//In Post request, we can retrieve data by req.body object.

var userModelObj = new UserModel();
userModelObj.emailId = req.body.emailId;
userModelObj.firstName = req.body.firstName;
userModelObj.lastName = req.body.lastName;
userModelObj.password = req.body.password;

userModelObj.save(function(err){
if(err){
responseObj.error = err;
}else{
responseObj.result = true;
}
res.send(responseObj);
});

}

exports.updateUser = function(req, res){

var responseObj = new Object();
responseObj.result = false;

var id = req.params.id;

var searchQuery = { '_id' : id }; //format for search query

UserModel.findOne(searchQuery, function(err, user){
if(err || user == null){
responseObj.error = err;
res.send(responseObj);

}else{
user.emailId = req.body.emailId;
user.firstName = req.body.firstName;
user.lastName = req.body.lastName;
user.password = req.body.password;

user.save(function(err){
if(err){
responseObj.error = err;
}else{
responseObj.result = true;
}
res.send(responseObj);
});
}

});

}

exports.deleteUserById = function(req, res){

var responseObj = new Object();
responseObj.result = false;

var id = req.params.id;

var searchQuery = { '_id' : id }; //format for search query

UserModel.remove(searchQuery, function(err){
if(err){
responseObj.error = err;
}else{
responseObj.result = true;
}
res.send(responseObj);

});
}

This file contains the business logic for performing user related operations. You can read various mongoose operations from the following link http://mongoosejs.com/docs/guide.html.In this file we have done the following things:

  • Defining Business Logic for the various operations.
  • Communication with MongoDB using Mongoose.

To run the server, we required to call below command on command prompt:

node server.js

If the server is started successfully, then we can see this message on command prompt:

Server listening on port: 9000

How to Run this Code:

GET /user

Now make a GET request to http://127.0.0.1:9000/user then we will get a list of all the users which are in the Database. For other POST, PUT & DELETE type of request, you can make use of any tool which allows creating HTTPRequest. For example, you can use “Poster” add on for the Firefox.

GET /user/:id

When we make calls like this http://127.0.0.1:9000/user/1, then it will return the user with matching userId.

POST /user

When we make call http://127.0.0.1:9000/user with a POST Type request, it will add new user information to the Database. With a Post request, we required to send some data and the type of data. In data part we send the user information in JSON format and set the content type as application/json and data will be like this:

{
“emailId”: “demo@example.com”,
“firstName”: “ABC”,
“lastName”: “XYZ”,
“password”: “123456”
}

PUT /user/:id

When we make call http://127.0.0.1:9000/user/1 with a PUT Type request, it will update user information in database with matching user id. So, here whatever data passed it will be assigned to user with having userId 1.

DELETE /user/:id

When we make call http://127.0.0.1:9000/user/1 with a DELETE Type request, it will remove user information from the database.

Benefit of using Node.js

  • Easy Development: Node runs on the JavaScript language. So, the web developer needs to learn only one language. So we can reuse the same code on both sides of the stack.
  • High Performance & Scalability: Due to its non-blocking I/O architecture, we can achieve great performance with handling a big number of users.
  • Ideal for Data-Heavy: Due to its non-blocking I/O architecture, it is best for the applications which required much database access than the operation which require computation. If your application required much computation, then Node.JS is not an ideal solution because it runs on single thread. So such operation can block other requests from clients.
  • Open Source Community: Node.js has a great open source community which has produced many good modules to extend our application functionality with no effort. There are many modules available like PayPal Integration, Android/iOS Push Notifications API. For the entire module, there is one central repository available. You can access it from here.

Applications

  • Real Time Applications: There are many applications which require live connections with the server. In other technologies like PHP, for each connection, it creates a new thread for handling operations for it. So, the number for live connection can be limited by the memory available to the server. While in node.js, all the connection is handled by the same thread. So, the server can handle many connections at the same time. For example, online games, chat programs etc.
  • Backend APIs: Various big brands are using Node.js as a backend for their API which is accessed by mobile devices due to its fast, lightweight and scalable architecture.
  • Websites: Because of its scalability and performance more and more people are stared using Node.js. There are various MVC Frameworks available in the market, which helps developers to create website with lesser efforts and front-end and backend can be done by JavaScript.
  • Data Driven Applications: Node’s evented I/O model helps from various locking and concurrency issues which is possible in various multithreaded Async I/O Operations.

Conclusion

In this article, we have discussed Node.js with some basic theory, the benefits of it and a simple example of API creation. With lots benefits of Node.js, there are some pitfalls of it. So, we have to choose it properly as per our requirement. Node runs on a single thread, so if the application is data-centric then Node will be a good choice. But, if the application operation requires more CPU-Cycle usages, then it might not be a good option as most of the time thread will be blocked in processing.

Related Insights