How to Build a Simple REST API with Node/Express

Express is a popular unopinionated web framework, written in JavaScript and hosted within the Node.js runtime environment. Because it is a JavaScript framework, so many packages and libraries are available as open-source to minify an Express project workload. it also has huge developer support so that the errors can be easily solved just by Googling it.

Before continuing this tutorial, I am assuming that you are comfortable with JavaScript programing language. Here we are going to create REST API with Node/Express Backend.

1. Install Nodejs

Installing Nodejs on our system may differ with our Operating System.

  • For macOS and Windows users, the below link can be referred to download the Nodejs Installation file.
https://nodejs.org/en/download/
  • For Ubuntu users, Nodejs can be installed with the below commands.
curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -
sudo apt-get install -y nodejs
  • For other operating systems, the installation instructions are available with the link below.
https://nodejs.org/en/download/package-manager/

2. Install Nodemon

Nodemon is a tool that helps develop node.js based applications by automatically restarting the node application when file changes in the directory are detected.

npm i -g nodemon

3. Create a Project Directory

Create a project directory and navigate to it using our Command Prompt/Terminal.

mkdir express-backend
cd express-backend

4. Initialize a Node.js Project

It requires a package.json file inside our project directory to work with Node.js projects. So we need to initialize a Node.js project using the below command.

npm init

5. Install Express

Now inside our project, we need to install Express package.

npm i express --save

6. Install Cors

CORS is a node.js package for providing a Connect/Express middleware that can be used to enable CORS with various options.

npm i cors --save

7. Install Body-Parser

To handle HTTP POST request in Express.js version 4 and above, we need to install the middleware module called body-parser. When we don’t use it, we get the raw request, and your body and headers are not in the root object of the request parameter.

npm i body-parser --save

8. Install Morgan

Morgan is basically a logger, on any requests being made, it generates logs automatically.

npm i morgan --save

9. Configure the Root File (index.js)

When initializing NPM, we selected index.js as our entry point(root file). So the app directs to index.js first and so we need to create and configure it.

9.1 Create index.js

We can create a file named index.js in our project directory using GUI or using our terminal.

touch index.js

9.2 Import all packages installed

Import all the packages we have installed earlier to our index.js file.

const express = require("express");
const app = express();
const cors = require("cors");
const bodyParser = require("body-parser");
const logger = require("morgan");

9.3 Define port number

Now define a port number in which our app needs to be started.

const port = process.env.PORT || 3001;

9.4 Use Logger

Use the logger package we have imported to get the log details of our application if needed.

app.use(logger('dev'));

9.5 Use Cors

Now use cors to enable Cross-Origin Resource Sharing.

app.use(cors());

9.6 Use Body-Parser

Also, use body-parser to handle HTTP POST requests.

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

9.7 Import and use players route

Yes. We did not create any route yet. But in the future steps, it will be made and configure. So just add the below lines in our root file.

const playersRouter = require("./routes/players");
app.use("/players", playersRouter);

9.8 Listen to the port we defined

We already defined a port number and it needs to be used when starting our project. So this port number must listen to our application.

app.listen(port, function() {
  console.log("Runnning on " + port);
});

9.9 Export the app module.

Now export the module app we have created.

module.exports = app;

10. Create a dummy database

Some data needs to sent to the frontend with a GET request. So it needs to create a dummy database. So first create a file named dummyDatabase.js, feed some data and export it.

touch dummyDatabase.js

The above command will generate a file named dummyDatabase.js. Open it and paste the array of objects players in it and export it.

let players = [
  { _id: 1, name: "Sachin", runs: "18426" },
  { _id: 2, name: "Dhoni", runs: "10500" },
  { _id: 3, name: "Virat", runs: "10843" }
];
module.exports = players;

11. Create a Route

We need to create a route file where all the functions of a route are defined. Here we need a list of names to our frontend and so we are going to make a names.js route inside a directory named routes.

mkdir routes
cd routes
touch players.js

11.1 Define router

Import express package and put express.Router() in a variable called router.

const express = require("express");
const router = express.Router();

11.2 Import dummy database

Now import the dummy database file we have created earlier.

let players = require("../dummyDatabase");

11.3 GET the complete list of players

We want to get the complete list of players in our database. So we need to create a router for GET request to /list.

router.get("/list", async (req, res) => {
  try {
    res.status(200).json({
      data: players
    });
  } catch (err) {
    res.status(400).json({
      message: "Some error occured",
      err
    });
  }
});

Now, if we run our project, the below link will return the complete list of players.

http://localhost:3001/players/list

11.4 GET a single-player details

We got the full player list. Now we need each player details. This can be done by passing the id of each player as the API parameter from the frontend.

:id is the player_id passed as the URL parameter. It is used to find a single-player with the _id.

Note:-

The id that we are passing from frontend can be accessed from here as req.params.id and it needs to convert to the number type before comparing with database _id because the _ids in the database are in the form of numbers.

router.get("/list/:id", async (req, res) => {
  let { id } = req.params;
  id = Number(id);
  try {
    let player = players.find(player => player._id === id);
    res.status(200).json({
      data: player
    });
  } catch (err) {
    res.status(400).json({
      message: "Some error occured",
      err
    });
  }
});

So, the below link returns the details of player 3.

 http://localhost:3001/players/3

11.5 Export the module

Now export the router module we have created.

module.exports = router;

12. Running our Backend

So we have created a RESTful API using Nodejs and Express. Now we can run our backend using Nodemon. Nodemon can watch the changes we are adding to our project and update the live server itself.

nodemon index.js

13. Testing the APIs

So our server is running on port 3001. The recommended method of testing our APIs is with Postman and it can be downloaded using the link below.

https://www.getpostman.com/downloads/

But here, our backend only dealing with GET requests without headers. So we can simply test it within our browser.

13.1 GET the complete list of players

The API URL below will show the complete list of players as JSON.

http://localhost:3001/players/list

This will return the data of players from our Express backend without a specific format. I am using the JSON formatter extension in my chrome browser to format the JSON data.

13.2 GET the single player details

To get the details of a single player, we need to pass the id with our API URL. So the below URL will return the single-player( _id: 2) details.

http://localhost:3001/players/list/2

GitHub

The complete project here I made is uploaded in GitHub for reference.

https://github.com/techomoro/SimpleExpressBackend

Have a nice code!

One thought on “How to Build a Simple REST API with Node/Express

  1. HII. I love your tutorial. I further developed two simple routes in the Project based on this.( A simple nodejs express API) But I am struggling wirh post and delete req /. any help is appreciated.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.