1. Home
  2. Linux
  3. Ubuntu
  4. How to Create a Node.js Restful API Using Express.js on Ubuntu 16.04 LTS

How to Create a Node.js Restful API Using Express.js on Ubuntu 16.04 LTS

How to Create a Node.js Restful API Using Express.js on Ubuntu 16.04 LTS
How to Create a Node.js Restful API Using Express.js on Ubuntu 16.04 LTS

In this tutorial, you will learn how to set up a complete RESTful API, which will serve HTTP requests using Node.js and Express while reverse proxying it with NGINX; all on Ubuntu 16.04 LTS.
You will be utilizing an application called Postman, a very well-known API development tool, to test your API and make sure that it is fully functional. ‘Node.js’ is a fast, cross-platform JavaScript framework based on Chrome’s V8 engine. It is used in both desktop as well as server applications and is famous for its single-threaded event loop handling.
You will be using Node.js as the backend for our RESTful API, bundled with Express.js, the web application framework built for Node.js. Express.js is released as free and open software. Express is server-side that is written in JavaScript and is designed for building APIs, which makes it perfect for our project. On the other hand, Postman is a very-powerful HTTP client with API development in mind. It features all of the tools you could possibly want for API development.

Installing Postman

First, you want to head over to Postman’s website to download and install Postman for your main PC (Not your server). All installation instructions will be on their website.

Installing Node.js

To begin, you will first need to install Node.js so that you can begin developing our API. You will be downloading and installing Node.js from the official website.

curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
 sudo apt-get install -y nodejs

In addition, you will also want to grab the necessary build tools, which will be helpful in compiling modules.

sudo apt-get install build-essential

For this tutorial, we will be using the LTS version of Node.js, which is version 8.9.3.

Initializing our Node.js project

You will need to initialize a new Node.js project, which will contain an application. To do that, create a new directory.

mkdir expressapi

Change to the new directory. Once inside, run ‘npm init’ and complete all of the required prompts. Keep note of the ‘entry point’ of your application; you will be creating this file later. Once you are finished, you will see a ‘package.json’ file in your current directory. It acts as a description of your project, and lists all of the dependencies needed to function.

Setting up Express.js

Now configure Express.js and its dependencies.

npm install express

The installation process will begin. It will take a few minutes for everything to finish downloading.

Starting your main file

Next, create your main starting file for your API. This is where you will use the ‘entry point’ you saw in the ‘package.json’ file. For the sake of this tutorial, we will use the default naming scheme, ‘index.js’.

touch index.js

Open it in the nano text editor.

nano index.js

In your main file, you want to first call all of your main packages and register your routes.

var express = require('express');       
var app = express();                
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
var port = process.env.PORT || 8080; 
const router = express.router();
router.get('/', function(req, res) {
    res.json({ message: 'API is Online!' });  
app.use('/api', router);
console.log('Listening on port ' + port);

Basically what you are doing here is initializing your app and setting up a basic router for your API.
Note that we have set our application’s port to 8080. You will need this number for when you configure our RESTful API. Now you are ready to go ahead and test your API.

Testing our API with Postman

In the project directory, run the following.

node <filename>.js

This will start the API, where ‘<filename>’ is the start file you specified in the ‘package.json’ file. Then, open Postman on your PC/Mac, and click the ‘New’ button in the top right corner, then click ‘Request’. When there, you should see a bar that says ‘GET’ next to it. Here we will enter our request URL. Simply enter the following in the request URL section and click ‘Send’.
You will see a n=message stating that ‘API is online’.

API routes

To handle routes, use the Express router. If you don’t know what a router is, it is essentially how application endpoints respond to client requests. Here are the routes we will be setting up as an example:

  • /api/numbers – Shows all numbers from 1-10.
  • /api/letters – Shows all letters from A-Z.

Now set up your first route middleware structure, like so.

router.use(function(req, res, next) {
   console.log('We've got something.');
   next() //calls next middleware in the application.
router.route('/numbers/:number').get((req, res) => {
     res.json({result: req.params.number + 1})

In this example, we have set up a situation where a user can request the sum of a number + 1 by providing the word form of it, using the ‘GET’ method. We use the ‘router.route()’ function to point to the number we want to send back as a result. Parameters are named with a ‘:’ in front of them. We access these parameter(s) via ‘req.params’.
Here’s an example with letters.

   router.route('/letters/:letter').get((req, res) => {
     res.json({result: req.params.letter.toUpperCase()})

We use the same method as above, but we send back the letter capitalized.

Introduction to NGINX

NGINX is a well-known open-source software used for web serving, reverse proxies, streaming, and more. You can utilize NGINX to reverse proxy your API to allow us to run it on port 80, as Node.js does not allow connections on ports less than 1024 without root access. This can come in handy when linking your domain to your server.

Setting up NGINX

To begin installing NGINX, you will need to run the following in your terminal and then wait for the installation to complete.

sudo apt-get install nginx

Next, create your site file that NGINX will use to reverse proxy your app.

sudo nano /etc/nginx/sites-available-api.js

Populate the file with the following, then CTRL + O to save it.

server {
          listen 80;
          location / {
                proxy_set_header X-Real-IP
                proxy_set_header Host
                X-NginX-Proxy true; proxy_pass
                proxy_redirect off;
                proxy_http_version 1.1;
                proxy_set_header Upgrade
                proxy_set_header Connection
                proxy_redirect off;
               X-Forwarded-Proto $scheme;

Using the same port you ran your application on earlier, you can tell Nginx to redirect all requests from your IP address on port 80 to your API running on port 8080.
Next, enable the reverse proxy by ‘symlinking’ your newly created file to the sites-available folder.

sudo ln -s /etc/nginx/sites-available/api /etc/nginx/sites-available

This will ensure that NGINX will reverse proxy our API.

First run with NGINX

Once you have finished your NGINX configuration; start NGINX, then start your API.
First, restart NGINX.

sudo systemctl restart nginx

Then, change back to your API directory, and start it.
node <filename>.js

The application will run on port 80. Simply run the test from above with Postman to ensure everything is working properly.

Keeping our API running
In a production environment, you want to make sure that you have a process manager for your Node applications, to ensure that they stay running forever in the background.
In this tutorial, we will be using a process manager called PM2 (Process Manager 2) which is a process manager for Node.js applications that will keep them alive forever with minimal downtime. PM2 comes with many useful management tools such as stopping, reloading, pausing, and more.

To install PM2, type the following and wait for it to install.

sudo npm install pm2 -g

Once it is installed, all you have to do is make sure you are in the project directory, type the following and the application will be started.

pm2 start <filename>.js


Managing our application with PM2

As mentioned earlier, PM2 has some useful tools that you can use to better manage your application.

  • pm2 stop – As the name suggests, this allows you to stop the currently running application, and kill its process. If your application is producing an unexpected result, then stopping it will come in handy.
  • pm2 list – The list function allows you to see all of the currently running applications via PM2, mapped by their names. If you need to quickly check your application’s uptime, you should use this tool.
  • pm2 restart – If your application freezes for some reason, and you would like to reload it, pm2 restart does just that. It will kill the application process and start it again under a different process.
  • pm2 monit – PM2’s built-in monitor tool allows you to view a graph of your application’s specific details, such as CPU/RAM usage, in a user-friendly ncurses-style graph. This is useful if you would like a visual picture of your application’s load.

Final remarks

You have now completed your task of creating a RESTful API, utilizing Node.js, Express, and reverse proxying it with NGINX. Feel free to expand on this tutorial. You can do many great things with your new API, such as add authentication methods, a database, better route and error handling, and much, much more.
If you have a domain, with an ‘A’ record already set up to your IP address, then you will be able to access your API from your domain. If you want to learn more about Express.js, visit their website at http://expressjs.com. To learn more about NGINX and reverse proxying, visit http://nginx.com. To read more about PM2, visit their page at http://pm2.keymetrics.io.

Updated on December 23, 2018

Was this article helpful?

Related Articles

Leave a Comment

[apsl-login-lite login_text='Please login with a social account']