DEV Community

Cover image for Creating a Simple REST API - Part 2
Noopur Sharma
Noopur Sharma

Posted on • Edited on

Creating a Simple REST API - Part 2

Hello JuxtaCoders!
Welcome to the second part of the REST API series. I hope the first part was helpful in some way. To get a better understanding of this part, you should have a basic knowledge of JavaScript, Node.js, basic shell/terminal commands and how to setup npm, etc. on your device. If there are topics on which I should make separate in-depth articles, please let me know in the comments.


In this part, we'll get an introduction to Express.js

A basic http server in NodeJs looks like following :

const http = require('http');

const server = http.createServer((req, res) => {
    if(req.url === '/'){
        res.write("Hello World!");
        res.end();
    }
    if(req.url === '/api/customers'){
        res.write(JSON.stringify([1,2,3]));
        res.end();
    }
});

server.listen(3000);
console.log("Listening on http://localhost:3000");
Enter fullscreen mode Exit fullscreen mode

The problem here, however, is in the route handlers. For a web application, there can be multiple routes and it can get tedious to write so many ' if ' statements.

To resolve this, we use express framework.

To set up express, we first create a folder and initialize our packages.json file in it.

> mkdir REST API
> cd REST API
> npm init --yes
Enter fullscreen mode Exit fullscreen mode

Now that we have our folder ready with the packages.json file, we can install express :

> npm install express
Enter fullscreen mode Exit fullscreen mode

Now we can import express to our file and use it.


Another module that we should install is 'nodemon'. This is short for node-monitor. Basically, when we execute a .js file, we use the following statement :

> node index.js
Enter fullscreen mode Exit fullscreen mode

But, with this, whenever we make any change in our file, we have to restart the server. This can be very tedious. Instead, if we use nodemon, we don't have to manually restart the server. Nodemon will do it for us.

To install nodemon :

> npm install -g nodemon
Enter fullscreen mode Exit fullscreen mode

We simply have to run our file using the following command :

> nodemon index.js
Enter fullscreen mode Exit fullscreen mode

Now, we won't have to repeatedly restart our server.


If we see our http server we've created in NodeJs, we see the use of a hard coded Port = 3000. While this may work in our own system, it may not work in a production environment. This is because, when we host an application on a hosting environment, a port is dynamically assigned to our application. In most cases the port that we've exclusively chosen will not be available in a dynamic environment. For this we use the following way to set up a port :

const port = process.env.PORT || 3000;
Enter fullscreen mode Exit fullscreen mode

This means that if the application is running on some external process, the port should be equal to the environment variable PORT of that process, otherwise, we've set it to 3000.

If we don't want to give a constant value to our port variable in our code, we can assign the environment variable PORT a value in the terminal :

> set PORT = 5000
Enter fullscreen mode Exit fullscreen mode

Now let's see how we create Route Handlers in express :

const express = require('express');
const app = express();

app.get('/', (req, res) => {
    res.send('Hello World!');
});

const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}...`));
Enter fullscreen mode Exit fullscreen mode

This is what a simple http server using express looks like.

First we import the express module. Then we get an express object in a variable 'app'. This object contains all the important properties and methods of the express module. By convention, we call it an express app.

This object will contain all our http methods (like get, put, post, delete, etc.). We can directly use them to describe what kind of request we want from the user.

If we want to define a route handler for a get request to the homepage, we use the get() method of our express app. This method takes two arguments. The first is the path of the request. In case we want to make this handler for the homepage, our path is '/'. The next argument is the call back function. Here we describe how does our server respond to the request. For instance, we simply send a response displaying 'Hello World' on the screen.

We can create similar route handlers for all types of http requests and path names.


In the above example if we want to add a route to get the list of courses, we can use the following statement :

app.get('/api/courses', (req,res) => {
    res.send([1,2,3]);
});
Enter fullscreen mode Exit fullscreen mode

Whenever the user makes a url request of http://localhost:3000/api/courses the response is an array of numbers [1,2,3].

Now let's see how we parse the url to give specific responses based on the id that a client requests :

app.get('/api/courses/:id', (req, res) => {
    res.send(req.params.id);
});
Enter fullscreen mode Exit fullscreen mode

Here the path contains :id, which means here we are putting a placeholder that'll take whatever id the user requests. In our response we use the .params object of request, that'll contain the id.

We can use the params object for multiple parameters in the request as well :

app.get('/api/courses/:year/:month', (req, res) => {
    res.send(req.params);
});

//Responds with an object containing values of the properties "year" and "month"
//as requested by the client
//eg. http://localhost:3000/api/courses/2021/July -->
// { year : 2021, month : "July"}
Enter fullscreen mode Exit fullscreen mode

We can parse the queries out of the request using the .query object of request :

app.get('/api/courses/:year/:month', (req, res) => {
    res.send(req.query );
});

//Responds with an object containing key-value pairs of the query
//as requested by the client
//eg. http://localhost:3000/api/courses/2021/July?sortBy=name -->
// { sortBy : "name"}
Enter fullscreen mode Exit fullscreen mode

That's all for now!! I hope this was helpful. In the next part, I'll provide a explanation of how to use what we've seen so far and create a REST API using Express.

If there are any suggestions, feel free to share:)

Until next time... Happy Coding!

Top comments (0)