The image is taken from Wikipedia.

How to Build a simple REST API: Introduction to NodeJS and Express.

Bilguun Batbold
Quick Code

--

Have you ever wanted to learn more about the Back-End development process? If you have had experience building Front-End apps, here is a good place to start. You will find how you can use the same technology stack to build servers. If you already have experience with developing APIs using other frameworks, you will learn here how much faster and easier it is to develop and deploy using NodeJS and Express.

Essentially, Node is a Javascript runtime environment built on the same engine as Chrome engine, the fastest JS engine yet. The non-blocking or asynchronous nature of Node makes it ideal for building I/O intensive applications.

Getting Started

To get started, head over to https://nodejs.org/en/ to download the latest stable version of NodeJS. Once you have installed the application on your machine, check your installed versions:

node -vnpm -v

Initialize The App

There are multiple ways of initializing an app, but in this tutorial, I will be using the simplest way.
Let’s first create a new folder myapp and create a new file index.js:

$ mkdir myapp
$ cd myapp
$ touch index.js

To initialise, run the following command:

$ npm init --yes

The yes flag is used to enter default values for all the questions asked. The command output will be something like this:

{"name": "myapp","version": "1.0.0","description": "","main": "index.js","scripts": {"test": "echo \"Error: no test specified\" && exit 1"},"keywords": [],"author": "","license": "ISC"}

As you can see from the output, the main point of entry is index.js . These are just names, and you should not be bothered too much with it.

Install dependencies

Let’s install express and some useful modules that I usually work with.

npm i express morgan debug multer serve-index

There are other useful modules which will not be used in this tutorial, but I will list them down below for your reference. Some installed modules are not used in this tutorial but the GitHub gist provided references them. Include them to avoid compilation errors.

Let’s open up the index.js file we created and add the following code:

const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log('Server is up and running on port ', port);
})

Running And Configuring The App

Congrats! You’ve created your first express server! It will listen to a port from an environment variable (if available) or 3000. Let’s run the app like so:

$ node index.js
Server is up and running on port 3000

Debug Module

While we are at it, let’s introduce a debug module. As you can see, the current console.log just prints a simple line. This may be acceptable for simple applications, but when you app scales, it is good to have some distinction between various logs.
Edit the index.js :

const express = require('express');
const app = express();
const debug = require('debug')('myapp:server');
const port = process.env.PORT || 3000;app.listen(port, () => {
debug('Server is up and running on port ', port);
})

What it does is we get the debug function and pass in the module name myapp:server . DEBUG environment variable is then used to toggle different namespaces. Let’s try it out:

You can see here that you get a much more visual output. This helps tremendously when reviewing your logs. You can set to show all logs or only certain namespaces.

The app will now be accessible at http://localhost:3000, but when u try to access it u will get Cannot GET / . This is because we have not set up any event listener on the server. So let’s create some event listeners.

The server will receive a request, process the request and return a response. The requests have 4 main types: GET to retrieve data, POST often used to create entity, PUT often used to update entity and DELETE often used to delete an entity. Let’s create a simple get request:

app.get('/', function(req,res) {
return res.send("hello from my app express server!")
})

If you access http://localhost:3000, you will now get a response!

Let’s now implement some additional functions so that we can test it.

So we have implemented all 4 main methods. I have put in the comments what each of the methods does. Now we can use Postman to check all these methods work.

Code Refactoring

So this gets the job done, we now have can get users, update their data or delete them. However, this is not scalable at all. In real life applications, there are multiple routes and it is not ideal to put all these in the single index.js file. Let’s do some refactoring to make life easier for all of us.

Go back to the main folder and do the following:

$ mkdir routes
$ cd routes
$ touch user.route.js

Copy the following code into the newly created file. Here we create a router (mini-app), define the events and export it to be used elsewhere.

The index.js then simplifies into the above code. This makes it much simpler to organize and maintain the codebase. While it may not seem important, in the long run, it is always good to think about scalability or maintainability.

HTTP Logging Module

Before we finish this tutorial, remember we installed morgan ? That is an HTTP logger middleware for NodeJS. Essentially, it helps us log all the requests. I have already included it in the code preview above. Let’s run the application and make some requests, you should see something like:

node index.js
GET /users/ 200 57 - 16.789 ms
POST /users/ 200 85 - 0.739 ms
PUT /users/1 200 85 - 0.590 ms
DELETE /users/last 200 27 - 0.412 ms

There are a lot more options on how you wish the logging to be done. Feel free to view the full documentation.

I have put down this simple tutorial to consolidate my own learning and to also help others in the process. If anyone finds these useful, feel free to share this or let me know should there be an error / bad practice/implementations.

I will be creating another tutorial on NodeJS to include authentication, authorization, connecting our server to MySQL / MongoDB, Unit / Integration Testing and finally deployment.

Have fun coding!

--

--