NodeJS uses Google’s V8 engine to bring JavaScript to the server side. JavaScript is a programming language that supports event based programming (just look at the OnClick() in browser environments) and has functions as first class members. This makes it a perfect fit for event-callback constructs that are a cornerstone of asynchronous programming.

The following image shows usage of JavaScript/NodeJS over the last 12 months:

This is how website use NodeJS in different segments of the industry:

When starting the process of building an API, the priority is to make it as efficient as possible in terms of performance — whether that is overall performance or routing performance. If you have selected NodeJS as the platform for your API, then it’s a wise choice.

NodeJS, being asynchronous in nature, provides very good performance, especially if CPU consumption is to be kept low in the API. For more details on this, read this article:-

One of the most popular use-cases for NodeJS is to write RESTful APIs. Its non-blocking I/O model combined with JavaScript make it a great choice for wrapping other data sources such as databases or web services and exposing them via a JSON interface. This article is a quick guide to setup a RESTful API using ExpressJS and NodeJS.

To know more about both good and bad use cases of NodeJS, you can check out this post:-

If CPU consumption will be high (for example, suppose the API has database queries that take time for execution, then every time the query is executed, CPU consumption goes up. This can be problematic in NodeJS, as node runs on a single thread and a single CPU core) then I recommend using a platform other than NodeJS. Possible alternatives are Django or Ruby on Rails in such a case.

In this article I will be discussing

How to setup and install npm and NodeJS on the system. How to create package.json to list the details and dependencies of an API. How to install dependencies required for an API Importing the dependencies in an API, and their corresponding usage. Routing implementation for all the calls to an API Additional tips for enhancement of an API.

Setup and Installing npm and NodeJS on your system

To work with NodeJS, npm and Node need to be installed on the system. To install npm, download the pre-build installers according to the respective platform using the following link:-

Create package.json to list the details and dependencies of API

Coming to the point of making an efficiently structured NodeJS API, let’s start by creating a directory <directory>, and I am naming my directory <node-api>.

Creating <node-api> on Desktop

Now go to the <node-api> folder using the cd node-api/ command. Before writing the API, create the package.json file using npm. This file holds metadata relevant to the project. This file is used to give information to npm that allows it to identify the project as well as handle the project’s dependencies.

To know more about package.json, visit the following link:-

package.json can be created using npm init command on terminal and then the following instructions can be executed.

Install dependencies required for API

Now that package.json has been created, let’s see what packages we need to setup a basic NodeJS API. To do this, three packages are required for this API, namely : Express.js, helmet and body-parser.

Express.js is a minimalistic and flexible NodeJS framework that provides a robust set of features to develop web and mobile applications. It facilitates the rapid development of Node based web applications.

helmet helps secure Express.js apps by setting various HTTP headers.

body-parser handles incoming request bodies in the middleware before your handlers, available under the req.body property.

npm packages can be installed using the following commands. For example, to install express: npm install express

This command will fetch the latest version of Express.js from npm registry and install it into the current folder using the folder name node-modules/. Keep in mind that the above command will install Express.js locally to the folder. It will not be available outside this folder. To install any package globally on the system, pass one extra parameter -g to the same command: npm install express -g

As I described earlier, package.json is used to inform npm about project-dependencies. To do this, use the command:

npm install express — save

Using — save as an extra parameter, npm will save that package under dependencies along with the version number inside package.json.

No dependencies are listed in package.json till then but after running the command given above, the file package.json looks like:

Similarly helmet and body-parser can also be installed. Now, create a file called <app.js> which will serve as our server file.

Importing the dependencies in API and their corresponding usage

app.js requires that all of the modules be installed using npm.

Now let’s define a port for our app to listen to and make an object on Express.js to listen to the server. This can be achieved by adding the following code to our app.js:

var app = express();

var port = 3000;

app.listen(port, function() {

console.log(‘ — — — — — — — — — — SERVER INITIALIZED — — — — — — — — — — ‘);

});

Now save the file and test whether the server is working or not by running it on the terminal by using the node command: node app.js

It will print — — — — — — — — — — SERVER INITIALIZED — — — — — — — — — onto terminal if everything is fine. Otherwise, it will throw an error.

Now we are going to use helmet to disguise our NodeJS app as a PHP app. In addition to this we are going to use json method of body-parser to parse json data received in requests to the server. Now the code file looks like:

Since we have now created a basic server that works, but only prints a string onto terminal when we run the server.

Routing Implementation for all the calls to API

Let’s continue building the API. I’ll discuss routing for different API calls and how to create functions in NodeJS using the Express framework. First, create two folders named ‘models’ and ‘routes’. The models folder will contain files and functions that will process the data received in the requests. The routes folder will contain files that define routes to the functions defined in models with the same file names.

Then define Express middleware inside app.js to identify (from the request) which function in the API it refers to. The file app.js looks like this after the addition of the routing middleware.

To understand how this code works, let’s first create a file named test.js inside models and write the following code into that file:

function test(req, res) {

console.log(‘This is a test url.’);

return res.send(‘This is a test url.’);

}

exports.test = test;

This is just a sample test function that will print This is a test url onto the terminal when called and send the same string back inside response. The line exports.test = test; enables the function to be accessed from outside this file.

Now, create a file with same name inside routes to make a path for the test function created above, inside models/test.js. After creating the file add the following code to routes/test.js :

var requestHandlers = require(“../models/test”);

var handle = {}

handle[“test”] = requestHandlers.test;

exports.handle = handle;

Here, we require the file models/test.js so that all the functions exported inside that file are available here. Then, we create a blank object handle and assign the exported test function to key named “test” and then export the handle object so that it can be accessed outside this file. This means that we can now access the models/test.js using routes/test.js from anywhere in our API.

You might be wondering why can’t we just access models/test.js when we have exported the function inside it — why is there any need of routes/test.js?

We can access models/test.js directly, but the reason behind creating an additional route is to add consistency and generalisation. This type of routing helps users who are going to call the functions of the API. The user will only need to know the name of the file in which the function is present. Now if you will run the server using node app.js and open any browser and type http://localhost:3000/test/test it will call the test function inside models/test.js and will produce results as described earlier.

As you can see that the function works fine as it prints “This is a test url.” onto terminal as well as sends it as response to the browser. Now let’s understand the piece of middleware code. As I said, the user only needs to know the filename and the function name.

On line 13, I store the url called into str which is equal to /test/test in this case. Line 15, makes str = ‘test/test’. On line 16, n = 4 as the name indexOf suggests. On line 17, resstr = ‘test’. On line 18, pkg_path = ‘./routes/test’. On line 19, func_path = ‘test’.

Now, when all the information such as filename and function name are extracted from the url called, the route package is imported using require, on line 20. This means that the object handle, that we exported inside routes/test.js is now available here.

If everything goes correctly then it jumps directly to the if statement on line 24. Here it is checked that the variable pkg is not empty and type of the function name extracted above is a function inside the routes file using pkg.handle[func_path] === ‘function’. This is done by passing the function name inside variable func_path by calling the handle method on the required package inside pkg.

This was just a basic demonstration of what an efficiently structured API can do. Here only a string was returned in the response and nothing was received in the request. But you can do more than that, you can use this API with any database and can receive any type of parameters within the request.

Some Additional Tips for enhancement of API

You can also use validators for validating the data that you are receiving from client side such as the required fields are being received in the request, the fields received are of correct datatype and format.

This can be achieved using the npm package ‘revalidator’ which aids in handling incorrect inputs provided by the users. The data sent in the request can be validated using this package to check whether it meets the requirements to process the data and produce some results before starting the processing of data. To read more visit:

This article gives you a basic idea on how to create a basic RESTful API with appropriate structure for optimal efficiency. It gives insights on how to setup npm and NodeJS on the system along with installation of NodeJS packages using npm, how to create ExpressJS middlewares and the meaning of ‘package.json’ inside any NodeJS project.

Developers are using Node.js because it’s insanely fast — both talking about performance and go-to-market time. And — according to a random answer — because it’s hipster, of course. So, why use NodeJS?

The scope of this article is limited to this because passing parameters into requests and database connections come into another league not in the structure part of the API. Having efficiently structured your API, go along and play with the code more to get a deeper understanding of it.

Thanks for reading!

This is a guest post by Tarun Gupta for zipBoard.