You could earn up to $300 by adding new articles!

Get Started Now

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

Published on: Fri, May 25, 2018 at 11:26 am EST

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, on Ubuntu 16.04 LTS. We will be utilizing an application called Postman, a very well-known API development tool, to test our API and make sure that it is fully functional and working properly. Node.js is a fast, cross-platform JavaScript framework based on Chrome's V8 engine. It is used in both desktop and server applications and is famous for its single-threaded event loop handling. We will be using Node.js as the backend for our RESTful API, bundled with Express.js, our web application framework built for Node.js. Express.js is released as free and open software. Express is server-side, 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, and download and install Postman for your main PC (Not your server). All installation instructions will be on their website.

Installing Node.js

To begin, we will first need to install Node.js so we can begin developing our API. We 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

We 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 our project, and lists all of the dependencies needed to function.

Setting up Express.js

Now we will configure Express.js and it's dependencies.

npm install express

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

Starting our main file

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

touch index.js

Then, open it in the nano text editor.

nano index.js

In our main file, we want to first call all of our main packages and register our routes.

var express = require('express');        
var app = express();                 
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
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);
app.listen(port);
console.log('Listening on port ' + port);

Basically what we are doing here is initializing our app, and setting up a basic router for our API. Note that we set our application's port to 8080. We will need this number for when we configure our RESTful API. Now we are ready to go ahead and test our 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".

`http://your-server-ip:3000/api` 

You will see "'API is online'".

API routes

To handle routes, we will be using the Express router. If you don't know what a router is, it's 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 we will set up our 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 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 what 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 as capitalized.

Introduction to NGINX

NGINX is a well-known open-source software used for web serving, reverse proxies, streaming, and more. We will be utilizing NGINX to reverse proxy our API, to allow us to run it on port 80, because 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 wait for the installation to complete.

sudo apt-get install nginx

Next, we will want to create our site file that NGINX will use to reverse proxy our 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 
                $remote_addr;
                proxy_set_header 
                X-Forwarded-For 
                $proxy_add_x_forwarded_for;
                proxy_set_header Host 
                $http_host;
                proxy_set_header 
                X-NginX-Proxy true; proxy_pass 
                http://127.0.0.1:8080/;
                proxy_redirect off;
                proxy_http_version 1.1;
                proxy_set_header Upgrade 
                $http_upgrade;
                proxy_set_header Connection 
                "upgrade";
                proxy_redirect off;
                proxy_set_header 
               X-Forwarded-Proto $scheme;
       }
}

Using the same port we ran our application on earlier, we are telling Nginx to redirect all requests from our IP address on port 80 to our API running on port 8080.

Next, enable the reverse proxy by symlinking our 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 we have finished our NGINX configuration, we will start NGINX, then start our 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

We have now completed our 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.

Want to contribute ?

You could earn up to $300 by adding new articles!

Get started in the SSD Cloud!