Building REST APIs with Nodejs and Express

Lakshan Madhuranga
7 min readApr 30, 2021

Hello Solvers….

Today we have lots of frameworks and technologies to build restful APIs. There are some differences between those technologies.

In here I have explained how we build restful APIs using Nodejs and express. So Nodejs is a very popular technology for build backend services. We have a framework that can use with Node. That is Express. You should have proper knowledge about Javascript and NodeJs, before go through this. We can create Restful APIs using only Node, so why we need a framework like Express. You’ll understand it later in this blog.

What mean by RESTful Services

I think you know about client server architecture. Clients communicate with server through HTTP protocol, actually client send HTTP request to the server. Then clients can access to services provide by server.

After came the REST architecture all the web services converted to the RESTful services. RESTful web services expose API from your application in a secure, uniform, stateless manner to the calling client.

We have standard HTTP methods. We want these methods, when we request to the server. There are 4 main HTTP methods as follows:

POST — For Creating data

GET — For Getting data

PUT — For Updating data

DELETE — For Deleting data

Actually every web application performs these 4 operations. In addition, we might have extra operations. But main and basic operations are these four. We called these operations as CRUD operations.

Why we need Express

Normally we can create a server using Nodejs with the help of http module. And we can specify various incoming request and response using “if” statements like below. But it’s very hard job, because if our app has thousand routes, we want to code thousands of if block there. So you know it’s not maintainable. You can see the below code, it’s not maintainable and readable.

const http = require('http');const Server = http.createServer((req, res) => {  if (req.url === '/'){     res.write('Hello Students');
res.end();
} if (req.url === '/api/students'){ res.write(JSON.stringify([1,2,3]));
res.end();
}});Server.listen(3000);
console.log('Listening on Port 3000...');

Express gives us to proper structure to add more routes to our application. You can get more details about Express via https://www.npmjs.com/package/express

Build your first web server using Express

First you need to create new node project and then you can install Express using the npm i express command. So let’s see how we implement our first web server. In here I have created a javascript file called index.js. And then we can create our server.

const express = require('express');
const app = express();
app.get('/', (req, res) => {res.send('Hello Students..');});app.get('/api/students', (req, res) => {res.send(['S1', 'S2', 'S3']);});app.listen(3000, () => console.log('Listening on Port 3000...'));

First we need to import express to our server file. And then we can create our own routes like above. In my example I have created two APIs. I have talked about handling various request in below, so don’t think about that now.

You can run our server using node your_File_Name command. In my case I can run node index.js like that. So now your server is running in port 3000.

If we type in browser http://localhost:3000/ like this, we can see Hello Students. And also if we type in http://localhost:3000/api/students like this, we can see the array.

So you can see in this implementation hasn’t any “if” blocks like our previous implementation. I think you’ll understand this implementation how easily it can be built.

Tip: Normally, if you implement a new API in your server you need to restart your server to check the result of our new API. So it’s very disturbance for us. We have a solution that problem. We can install nodemon (Node Monitor) in our project using npm i –g nodemon ,if you use mac OS you need to use sudo instead to npm. After installation we can start our server using npm start command. Now, if we done any changes in our code then nodemon automatically restart the server.

Handling Get requests

In here, I have improved our code to get a single student with use student’s id. I haven’t use any database to store data in my implementations. Because I want to explain how the theories and concepts are working in Node and Express. I think you should get proper understanding about basics before go to databases. If you have proper knowledge about basics you can use any database service to your implementations.

const express = require('express');
const app = express();
const Students = [
{ id: 1, name: 'Alise'},
{ id: 2, name: 'Bob'},
];
//Get all students
app.get('/api/students', (req, res) => {
res.send(Students);});//Get a student related to an id
app.get('/api/students/:id', (req, res) => {
const Stu = Students.find(s => s.id === parseInt(req.params.id)); if (!Stu) res.status(404).send('The student with the given ID was not found'); res.send(Stu);
});
app.listen(3000, () => console.log('Listening on Port 3000...'));

In here, I have created Students array, and inside that I have created two objects. We can get all the students using first Get method. And also we can use second Get method to get specific student related their id. If we enter wrong id, this method is shows an error. So you can see results using a browser or postman that we have implemented APIs

Result: student id 1
When use wrong id

Handling POST requests

In here I have improved our code for create a new student. So we can use POST method to implement this API.

const express = require('express');
const app = express();
app.use(express.json());const Students = [
{ id: 1, name: 'Alise'},
{ id: 1, name: 'Bob'},
];
app.post('/api/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...'));

You can see, I have created new object called student, that is used to store the data that user will add newly. Then we can test our API using postman. So let’s see how its work..

You can see our new student has been successfully added to our store.

Handling PUT requests

In here I have implemented, how we update a student who stored in our store. So when we request this we need to specify the id of the student that we want to update.

const express = require('express');
const app = express();
app.use(express.json());const Students = [
{ id: 1, name: 'Alise'},
{ id: 1, name: 'Bob'},
];
app.put('/api/students/:id', (req, res) => {
const student = Students.find(s => s.id === parseInt(req.params.id));
if(!student) res.status(404).send('The student with the given ID was not found'); student.name = req.body.name;
res.send(student);
});app.listen(3000, () => console.log('Listening on Port 3000...'));

So you can check this API using postman like follows. If you request with wrong id then you’ll get an error.

Handling DELETE requests

In here I have implemented delete operation using http DELETE method. So when we request this we need to specify the id of the student that we want to delete.

const express = require('express');
const app = express();
app.use(express.json());const Students = [
{ id: 1, name: 'Alise'},
{ id: 1, name: 'Bob'},
];app.delete('/api/students/:id', (req, res) => { const student = Students.find(s => s.id === parseInt(req.params.id)); if(!student) res.status(404).send('The student with the given ID was not found'); //find the index of the student object that we want to delete
const index = Students.indexOf(student);
//Remove the object
Students.splice(index, 1);
res.send(student);
});app.listen(3000, () => console.log('Listening on Port 3000...'));

Now we can check this API, so let’s check it..

You can see, successfully deleted the student who has id number 1. Now let’s send GET request to get all students then we can check more confidently.

Yeh.. you can see we have only one object. That's mean first object has been deleted successfully.

I think you can get very basic idea about how we develop APIs using Nodejs and Express. I have explained here very basic thing, because I want to show you how easily to develop an APIs using Node and Express.

!!!!

--

--

Lakshan Madhuranga

Undergraduate at university of Kelaniya, and Studies ICT in faculty of computing and technology.