REST API in Express.js
Hello in this tutorial, we will build a REST API in a Node.js environment running on an Express.js server.
1. Introduction
RESTful API stands for the standard web service interface used by the applications to communicate with each other. This API conforms to the REST architectural style and constraints. It is scalable, stateless, cacheable, and has a uniform interface. It utilizes HTTP requests and the four most common HTTP methods are POST, PUT, GET, and DELETE. Express.js on the other hand is the most popular Node.js web framework that provides a robust set of features to develop web and mobile applications. It offers features like –
- Set up middleware to respond to HTTP requests
- Defines the routing table to perform different actions based on HTTP methods
- Allows to render HTML pages dynamically
1.1 Setting up Node.js
To set up Node.js on windows you will need to download the installer from this link. Click on the installer (also include the NPM package manager) for your platform and run the installer to start with the Node.js setup wizard. Follow the wizard steps and click on Finish when it is done. If everything goes well you can navigate to the command prompt to verify if the installation was successful as shown in Fig. 1.
2. REST API in Express.js
To set up the application, we will need to navigate to a path where our project will reside. For programming stuff, I am using Visual Studio Code as my preferred IDE. You’re free to choose the IDE of your choice.
2.1 Setting up dependencies
Navigate to the project directory and run npm init -y
to create a package.json
file. This file holds the metadata relevant to the project and is used for managing the project dependencies, script, version, etc. Add the following code to the file wherein we will specify the required dependencies.
package.json
{ "name": "expressjs-restapi", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node index.js" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "body-parser": "^1.19.0", "express": "^4.17.1" }, "devDependencies": { "nodemon": "^2.0.7", "underscore": "^1.13.1" } }
To download the dependencies navigate to the directory path containing the file and use the npm install
command. If everything goes well the dependencies will be loaded inside the node_modules
folder and you are good to go with the further steps.
2.2 Creating the controller file
Create a controller file in the src/api
folder. This file will expose endpoints that will be responsible to entertain the request from the client. As an improvement, you can enhance this tutorial to interact with the database and perform the CRUD operations with the help of a model object. For simplicity, we are keeping the controller file as simple and you are free to modify it as per your wish.
routes.js
const express = require('express'); const router = express.Router(); const _ = require('underscore'); let employees = [ {"id":1,"full_name":"Sarine Heatherington","email":"sheatherington0@goo.ne.jp","gender":"Polygender","mobile":"870-915-1187"}, {"id":2,"full_name":"Anatollo Dudding","email":"adudding1@tinyurl.com","gender":"Polygender","mobile":"229-523-4940"}, {"id":3,"full_name":"Mordy Flux","email":"mflux2@csmonitor.com","gender":"Male","mobile":"905-446-7491"}, {"id":4,"full_name":"Larina Mallebone","email":"lmallebone3@smh.com.au","gender":"Male","mobile":"938-933-8220"}, {"id":5,"full_name":"Neal Doidge","email":"ndoidge4@state.gov","gender":"Male","mobile":"344-976-2688"} ]; // create and save a new employee // http://localhost:4001/api/create // note - provide the json request body /* { "full_name": "Cierra Vega", "email": "cierra.vega@automation.com", "gender": "female", "mobile": "603-367-2819" } */ router.post('/create', (req, res) => { // skipping request body validations for brevity let empId = employees[employees.length - 1].id + 1; employees.push({ id: empId, full_name: req.body.full_name, email: req.body.email, gender: req.body.gender, mobile: req.body.mobile }); res.status(201).json({info: `Entity ${empId} created successfully`}); }); // get all employees // http://localhost:4001/api/findAll router.get('/findAll', (req, res) => { res.status(200).json({info: employees}); }); // get a single employee // http://localhost:4001/api/findById?id=1 router.get('/findById', (req, res) => { if (_.isEmpty(req.query.id)) { res.status(400).json({info: 'Id cannot be null'}); } let data = employees.filter(function (emp) { if (emp.id == req.query.id) { return true; } }); if (_.isEmpty(data)) { res.status(404).json({info: 'Entity not found'}); } else { res.status(200).json({info: data}); } }); // other HTTP methods like PUT, DELETE are skipped for brevity. // you can add them on your own. // routes module.exports = router;
2.3 Creating an index file
Create an index file that will act as an entry point for our server. The file will contain the code to define the routes to the application endpoints.
index.js
const express = require('express'); const bodyParser = require('body-parser'); const app = express(); // Parse requests of Content-Type - application/json app.use(bodyParser.json()); // Application routes app.use('/api', require('./src/api/routes')); const PORT = process.env.port || 4001; app.listen(PORT, () => { console.log(`Server started on port ${PORT}`); });
3. Run the Application
To run the application navigate to the project directory and enter the following command as shown in Fig. 4. If everything goes well the application will be started successfully on port number 4001
.
4. Project Demo
When the application is started, open the Postman tool to hit the application endpoints. You are free to choose any tool of your choice.
Application endpoints
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 | // create a new employee HTTP POST url - http://localhost:4001/api/create // note - provide the json request body // { // "full_name": "Cierra Vega", // "email": "cierra.vega@automation.com", // "gender": "female", // "mobile": "603-367-2819" // } // get all employees HTTP GET url - http://localhost:4001/api/findAll // get a single employee HTTP GET url - http://localhost:4001/api/findById?id=1 |
Similarly, you can create other endpoints. That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!
5. Summary
In this tutorial, we learned –
- Introduction to RESTful API and Express.js
- Steps to setup Node.js
- Sample programming stuff to create RESTful endpoints via Express.js
You can download the source code of this tutorial from the Downloads section.
6. Download the Project
This was a programming tutorial to create RESTful API endpoints in a node.js environment.
You can download the full source code of this example here: REST API in Express.js