Official Blog of Azilen

The Techie Explorations

Basic API Creation with Node.JS

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

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:

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

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

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

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:

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

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.

Leave a reply