Setup a simple api using node js and express

Today we are going to explore a rather simple but very useful feature that we can build using Node.js.

What is an api?

Simple put an api is an application interface that allows accessing certain functionality and resources. The one we are exploring today will be a web api which means that is will be accessible using web protocols such as http/https.

You can use it for sharing and updating information across different applications. You can use this to listen or trigger web hooks.

How to set it up

1) First you will need to install node. Instructions for this can quickly become outdated but the idea is to fetch the latest package from their official site and then install using

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

2) Next install build tools. This will be necessary for compiling.

sudo apt-get install build-essential

3) Now that we have node we can initialize our project by creating a directory and executing

npm init

4) Next you will want to install express

npm install express

5) Create a file index.js and paste this content

var express = require('express');        
var app = express();                 
var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = 3000;  
const router = express.Router();
router.get('/', function(req, res) {
     res.json({
      	message: 'Success!' 
     });   
});

app.use('/path/to/api', router);
app.listen(port);
console.log('Listening on port ' + port);

6. You can start the application by running

node index.js

7. Test that your application is running by visiting

http://your-domain-or-ip:3000/path/to/api

You should see the "Success" message in the response.

That is the very basics of it. Next step would be to setup proper routes using nginx. You might also be interested in process management tools which would allow you to keep the api running in the background. We would suggest using pm2 for this. We will explore this deeper in a later post. Depending on what you are building authentication might be a must in order to limit the usage of your resources.