Lets Develop a simple backend REST API in Node and Express
Karibu dear friends and family. Its been long since i last put something up here, i am really sorry about that. So enough of the remarks, our object of discussion today is simple, we are going to build a REST API in less than 10 mins, how cool is that.
Just a disclaimer before we start, i tried as much as possible to simplify all the steps in this tutorial but hmm basic familiarity with javascript will be awesome. If you are not a javascript developer you may find some of the concepts here a bit weird but take heart 💙 its just the same thing with what you are used to.
Lets taxi to the runway….
We will start with basic definitions just to get you to pace you know:
Nodejs : Ok i want to be efficient as possible here, so i am not going to waste your time talking about node, if you want to know about node in its entirety please do visit this post.
REST : This is an acronym for a Representational State Transfer. Need more info check this post out.
API : There are a couple of thoughts on what this really is but well let me tell you what I know an API is an Application Programming Interface 😂.
Guess with that out of the way we can start building our API.
Runway Entry Procedure…
We are going to build a student details API, which is generally a module within a larger system, it may be for a school, university or whatever institution that deals with students. Before you get your hopes high please note that this is not a real world API but just a demonstration to help you grasp the concepts of node and express.
To get started we need Node, if you don’t have it already please visit this link to get that setup and after we get that done we need to create a new folder called students-api or whatever you want to call it, this is the directory that will house all our source code. Use the terminal to change directory into the one we just created now and type the following command in the terminal.
npm initthis will create a new nodejs project, all you need to do now is to just press Enter or Return till the setup is done.
After now that we have a proper node project setup, there is something called the node package manager, this is a tool we are going to use to download more node packages like express and Joi, lucky enough its installed when you setup node. Back to the terminal let us install express and start writing code.
npm install expressIf you need to know more about express, i suggested you visit their docs, this is quite an extensively used module.
Some Side Notes
The construction of any API is hinged on the four basic types of HTTP requests and these are better known as CRUD (Create, Read, Update and Delete). These are important as the whole concept of an API is a client requesting some service from a server. These four basic requests in our context can be summarised as :
Create POST \api\students creates a new student
Read GET \api\students\:id returns a record which matches the id
Update PUT \api\students\:id updates the record which matches the id
Delete DELETE \api\students\:id deletes the record that matches the id
Our API is going to demonstrate all these requests in action.
I think we are ready to take off now…
Using the prefered text editor (personally i would advise you to use VS CODE) , go ahead and create a file called index.js and add the following lines of code in it.
let express = require('express');let app = express();
app.use(express.json());
Ok please donot leave me now, i know to some this is new but let me explain it and you will realise that its not as complicated as it seems.
The first and second lines are an equivalent of the import statement in Java, we are just telling our compiler that we will need to use some stuff defined in those two modules.
The 3rd line skipping the space, is actually creating an express instance called app and this is what we are going to be using extensively in this tutorial and finally the last line is what we call middleware, don’t worry about it now just know that it allows us to read the content passed in the body of a request.
Ok since we are not going to be setting up any database, we are going to setup a simple array data structure that is going to store our student details.
const students = [
{ id : "1", name : "Tinashe Makuti"},
{ id : "2", name : "John Doe"},
{ id : "3", name : "Some Name"}
];Ok nice so just pretend to have a database now.
The first end point we want to create is the one that handles get requests.
app.get('/api/students/:id', (req, res) => {
const student = students.find(s =>s.id===parseInt(req.params.id)); if(!student) return res.status(404).send("Student not found"); res.send(student);});
In the above code we use one of the inbuilt array data structure methods find to check if a student with the passed id exists in the students array. If not our server responds with a 404 resource not found status and if found we get a response with that object.
That should be enough for our get request, now before we can start testing our endpoint, let us create on that will enable us to create some resources. This is done by the post request.
app.post('/api/students/', (req, res) => {
const student = {
id : req.body.id,
name : req.body.name
}; students.push(student);
res.send(student);
});
Ladies and gents, this end point will receive data from a client requesting that new a student be created, we create a new json object called student and assign the id to the one in the body of the received request, the same is done for the name. After that we use the basic push method to add the object to the array.
Lets Prepare for Landing…
If you have reached this point congrats because you are almost a master in API development, we are not going to create the remaining two endpoints for updating and deleting, i will leave that as a home work.
For us to start our server we need to tell express to listen to a certain port, in most production environments there is an environment variable set for the port.
const port = process.env.PORT || 6000;In the above line we are assigning the variable set in the environment to the port, if its not found we give it a default value of 6000.
app.listen(port, () => {
console.log(`Server running on ${port}`);
} After Landing Checklist
Now that we got this baby on the ground, we can begin testing our API to see if it works. I suggest you get a tool called POSTMAN it makes it quite easy to test API’s but well if you can’t you can still use your browser.
http://localhost:5000/api/students/1Visit the above in your browser and you should get a response as shown below:

This marks the end of our tutorial fam, i know its quite a bit long, but i believe you got something out of it.
If you have any comments or problems please let me know, i will try to respond as soon as possible.
Asante Sana