Building a simple REST API with NodeJS and Express.
A large part of the development of web application is related to what is called the back end.
What is back-end or server-side in a web application?
We may think about the back-end as applications that communicate with each other. In web development, backend is a service which sends data to the front-end.
In an application, the back end is used to set up databases, servers, interfaces and operating systems. Backend activity can involve many things like user login, ordering and paying for items, texting, searching, localization services.
Any developer who wants to create Web applications would probably need to have their hands on a backend API.
What is API?
API is an acronym which stands for: Application Programming Interface, Is a programming interface which allows developers to interact with back-end services.
APIs are methods and functions that surround certain operations,
We usually talk about them in the context of Internet network applications, but the API is a more generic term that describes interfaces across all kinds of applications.
REST APIs
Is an architectural style for an API which uses HTTP requests for accessing and using data.
This data can be used for GET, PUT, POST, and DELETE data types, which refers to reading, updating, creating, and deleting operations related to resources.
How to build a simple REST API with NodeJS and ExpressJS
NodeJS
Is an open-source, cross-platform, back-end JavaScript runtime environment that runs on a JavaScript Engine and executes the JavaScript code outside a web browser, which was designed to build scalable network applications
ExpressJS
ExpressJs or simply Express, is a minimal and flexible NodeJS web application framework that provides a robust set of features for web and mobile applications released as free and open-source software
Installation :
Before diving in the tutorial, you should install NodeJS and NPM (Node Package Manager), in case you have already installed, ignore the installation part.
Windows :
Download | Node.js
Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.
nodejs.org
Linux :
1. Firstly execute the command below to install Node
$ sudo apt install nodejs
2. Run the following command to verify the installation by check the version number of Node
$ node -v
3. After successfully installing node, now we need to install npm by executing the command below
$ sudo apt install npm
4. Let’s check the npm version to insure that is installed correctly
$ npm -v
Tutorial :
Part 1 : Set up the server
After successfully installed Node and npm let’s start building our API by setting up the server
1. Make a new directory and open it
$ mkdir myFirstApi$ cd myFirstApi
2. Create new Node project
$ npm init -y
3. Install ExpressJS
$ npm i express --save
4. Open the project using any IDE
If you are using VScode just type the commande below
$ code .
5. Create app.js file and past the following code
const express = require('express');const app = express();const PORT = 3000;app.listen(PORT, (error) => {
const message = error ? `Error occurred, server can't start ${error}` : `Server is Successfully Running on port ${PORT}`;console.log(message);});
6. Install nodemon
Open the terminal in the project folder and write the commande below
$ npm i nodemon --save-dev
Nodemon is a tool that helps you to develop Node.js based applications by automatically restarting the node application when file changes in the directory are detected.
7. Update the package.json file
"main": "app.js",
"scripts": {
"start": "node app.js",
"dev": "nodemon app.js"
},
The main field is a module ID that is the primary entry point to your program.
The scripts property of your package.json file supports a number of built-in scripts with pre-defined lifecycle events as well as arbitrary scripts.
All this can be executed by running npm run <stage> to keep it short.
8. Run the project ( dev mode )
$ npm run dev
Congratulations, now your server is up and running successfully, as we move forward, we will structure the project by making Route, controllers and Services
Part 2 : Structure the project
For a good APIs will definitely have routes, controllers and services.
These files must be well-organized
1. Folder structure
For us, we’re going to use a very simple directory structure,this is the structure which will allow us to organise the code:
├── app.js
├── package.json
├── package-lock.json
├── node_modules
└── src
├── controllers
├── routes
├── services
└── utils
2. Route
Once we have our folder structure in place, we will now create our Route.
Firstly create file under ‘src/routes’ and name it ‘appRoutes.js’ , then copy and paste the code below.
module.exports = routes = (app) => {
app.route('/').get((req, res) => { res.send('Hello world') });
}
After adding the code above open the ‘app.js’ file and import the new file by writing the following code
const appRoutes = require('./src/routes/appRoute');
Next, add this line of code after the declaration of the const app
appRoutes(app);
Now we are finished setting up our Route, your “app.js” should be similar to the following code:
const express = require('express');const appRoutes = require('./src/routes/appRoute');const app = express();
const PORT = 3000;appRoutes(app);app.listen(PORT, (error) => {
const message = error ? `Error occurred, server can't start ${error}`: `Server is Successfully Running on port ${PORT}`;
console.log(message);
});
Once you have completed the previous step, go ahead and open http://localhost:3000/ in your browser
The page should appear with the message “Hello World”
3. Controller
We have set up our route successfully, now we’re going to create our first controller
First of all, create file under “src/controller” and name it “appController.js” , then copy and paste the code below
module.exports.getAll = (req, res) => {
return res.status(200).send('Hello World from controller !!');
};
Go back to the file“src/routes/appRoutes.js” and update the code to the following one.
const controller = require('../controllers/appController');module.exports = routes = (app) => {
app.route('/').get(controller.getAll);
};
Finaly reopen your browser an refresh http://localhost:3000/ link.
The page should appear with the new message “Hello World from controller !!”
4. Services
In this step we are going to create a service, but before starting let’s setting up some data
Create a new repository under “src” and name it “data”, in this folder add new file and name it “appData.js” with the code below
const data = [
{
name: 'Bill Gates',
born: '28-10-1955',
nationality: 'American'
},{
name: 'Steve Jobs',
born: '24-02-1955',
nationality: 'American'
},{
name: 'Mark Zuckerberg',
born: '14-05-1984',
nationality: 'American'
}];module.exports = data;
After setting up the data, we need to install “body-parser” by runnig the following commande line in the terminal
$ npm i body-parser
Then let’s update “src/routes/appRoutes.js” file as shown below
const bodyParser = require('body-parser');const controller = require('../controllers/appController');module.exports = routes = (app) => { app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json()); app.route('/getAll').get(controller.getAll);}
In this step create a new file “appHelper.js” in the folder “src/utils”, and paste the next code on it.
module.exports.findInObject = (dataObj , reqObj) => {if (Object.keys(dataObj).length < Object.keys(reqObj).length) {
return false;
}let res = true;Object.keys(reqObj).map( (field) => {
res = res && !!dataObj[field]
&& reqObj[field].toLowerCase() == dataObj[field].toLowerCase() ;
});return res;};
Now let’s create our service by creating a new file “appService.js” under “src/services”, in this file import “appHelper.js” and create two functions like showen below
Congratulations, now your server is up and running successfully, as we move forward, we will structure the project by making Route, controllers and Servicesconst data = require('../data/appData');
const helper = require('../utils/appHelper');module.exports.getAll = () => {
return { data };
}module.exports.getByField = async (obj) => {const result = await data.filter(field => helper.findInObject(field, obj));
return { data: result };
}
Next update the “appController.js” and “appRoutes.js” like the code to the following one.
- appController.js
const service = require('../services/appService');module.exports.getAll = (req, res) => {const result = service.getAll();if (result.data.length > 0) {
return res.status(200).send(result.data);
}
return res.status(404).send("Data not found");
};module.exports.getByField = async (req, res) => {const result = await service.getByField(req.query);if (result.data.length > 0) {
return res.status(200).send(result.data);
}
return res.status(404).send("Data not found");};
- appRoutes.js
const bodyParser = require('body-parser');const controller = require('../controllers/appController');module.exports = routes = (app) => {app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());app.route('/getAll').get(controller.getAll);
app.route('/get').get(controller.getByField);}
Congratulations, now you have successfly builded your RESTful API.
If you want to test it go ahead and open the links below in your browser