Creating a Simple REST App in ExpressJS
Introduction
Express is an open source framework for NodeJS. To understand the requirement of Express let’s look at the following simple example.
Here we look at creating a simple server using NodeJS through its http module.
Creating a Node Server
const http = require('http');const server = http.createServer((req, res) => {
if (req.url === '/') {
res.write('Hello World');
res.end();
}if (req.url === '/students ') {
res.write(JSON.stringify(['Mark', 'Sam', 'Diana']));
res.end();
}
});server.listen(3000);console.log('Listening on port 3000...');
The Drawback
In a real world application we have to include multiple routes inside the callback function that is passed to createServer. Therefore the code become complex. To avoid this issue ExpressJS Framework is used. This makes the code much easier to read and maintain.
Installing express
For installing express to your app and adding it to the dependencies execute to following command within the project folder.
$ npm install express --save
Creating an express Server
Creating a server in express is very simple. In below example a server created and it listens on port 3000.
const express = require('express');
const app = express();
app.listen(3000,() => console.log('Listening on port 3000...'));
Implementing GET Method — Getting all the Resources
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello World');
});
app.get('/students', (req, res) => {
res.send(JSON.stringify(['Mark', 'Sam', 'Diana']));
});
app.listen(3000, () => console.log('Listening on port 3000...'));
Here unlike in the node we do not have to include multiple if statements to handle routes. Express provide us with a structure for handling the routes. Therefore code becomes much cleaner.
Implementing GET Method — Getting a Resource with specific ID
app.get('/students/:id', (req, res) => {
res.send(req.params.id);
});
In the above example we send a parameter with the URL– id. For simplicity we are not considering fetching data from a database. Just a response is send back to the client with the id parameter that was specified.
E.g. –
http://localhost:3000/students/001
Output - 001
Implementing POST Method — Creating a Resource
const express = require('express');
const app = express();app.use(express.json());const students = [{
id: 1,
name: 'Mark'
},
{
id: 2,
name: 'Sam'
},
{
id: 3,
name: 'Diana'
},
];app.get('/students', (req, res) => {
res.send(students);
});app.post('/students', (req, res) => {
const student = {
id: students.length + 1,
name: req.body.name
};students.push(student);
res.send(student);});app.listen(3000, () => console.log(`Listening on port 3000...`));
POST
http://localhost:3000/students

Output –

Implementing PUT Method — Updating a Resource
Let’s consider the same example we used in POST. Now we are defining the put method.
const express = require('express');
const app = express();app.use(express.json());const students = [{
id: 1,
name: 'Mark'
},
{
id: 2,
name: 'Sam'
},
{
id: 3,
name: 'Diana'
},
];app.get('/students', (req, res) => {
res.send(students);
});app.put('/students/:id', (req, res) => {
const student = students.find(c => c.id === parseInt(req.params.id));
if (!student) return res.status(404).send('Student not found.');student.name = req.body.name;
res.send(student);
});app.listen(3000, () => console.log(`Listening on port 3000...`));
Note : 404 — Resource not found.
PUT
http://localhost:3000/students/1

Output — The updated student object is returned. The name Mark has changed to Mathew.

Implementing DELETE Method — Deleting a Resource
In the below example splice method is used remove one object that is located in the given index.
app.delete('/students/:id', (req, res) => {
const student = students.find(c => c.id === parseInt(req.params.id));
if (!student) return res.status(404).send('Student not found.');//Delete
const index = students.indexOf(student);
students.splice(index, 1);res.send(student);});
DELETE
http://localhost:3000/students/2

Output –
The deleted object is returned. The Student Sam is deleted.

References –