The Comprehensive Guide to Create a RESTful API using Node.js and Express.js

M. Ilham Margatama
5 min readFeb 14, 2023
Photo by Douglas Lopes on Unsplash

Hello again, I want to share my API development step with you. I’ll make it one by one starting from creating the server, adding the routes, protecting the routes, optimizing the development process, etc.

Introduction

An API (Application Programming Interface) allows different software systems to communicate with each other. A RESTful API is a type of API that adheres to a set of architectural constraints, such as using HTTP methods for communication and data transfer.

Node.js is a powerful, open-source, server-side runtime environment built on JavaScript. It allows developers to build scalable network applications using JavaScript on the server side. Express.js is a popular and widely-used Node.js framework for building web applications and APIs.

Prerequisites

Before you start, make sure you have Node.js and npm (Node Package Manager) installed on your system. You can download the latest version of Node.js from the official website (https://nodejs.org/en/download/). npm is automatically installed when you install Node.js. Or you can use NVM instead. Check my last story about Managing Node Version.

Step 1: Create a new project and install dependencies

To create a new Node.js project, open your terminal or command prompt and run the following command:

$ mkdir node-express-api
$ cd node-express-api

This will create a folder with a name node-express-api then you navigate to the folder.

Next, run the following command to initialize the project with a package.json file:

$ npm init -y

The -y flag will accept the default options and generate a package.json file with the default settings.

Now, install the Express.js framework by running the following command:

$ npm install express

Step 2: Set up the Express.js framework

Create a new file named app.js in the node-express-api directory and add the following code to it:

const express = require('express');
const app = express();
app.listen(3000, () => {
console.log('Server started on port 3000');
});

The code above sets up the Express.js framework and starts a server on port 3000. You can test the server by running the following command:

$ node app.js

If everything is set up correctly, you should see the following message in the terminal:

Server started on port 3000

Step 3: Define routes

Routes are the endpoints that define the structure of your API. In this step, you will define the routes for your API.

Add the following code to the app.js file:

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

The code above creates a GET route that listens to the root endpoint ('/') and sends a response with the message 'Hello World!'.

Step 4: Test the API

To test the API, open your web browser and navigate to http://localhost:3000. You should see the message Hello World! displayed in the browser.

Step 5: Add more routes

You can add more routes to your API by using the app.get(), app.post(), app.put(), and app.delete() methods, which correspond to the four HTTP methods (GET, POST, PUT, and DELETE, respectively).

For example, add the following code to add a GET route for retrieving a list of items:

const items = [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' }
];

app.get('/items', (req, res) => {
res.json(items);
});

Then press CTRL+C in the terminal to close the current server. Start it again with node app.js. This will restart your server to apply the current code. After restarting the server you can check the new routes.

And the following code to add a GET route for retrieving a specific item:

app.get('/items/:id', (req, res) => {
const item = items.find(item => item.id === parseInt(req.params.id));
if (!item) return res.status(404).send('Item not found');
res.json(item);
});

In the code above, the req.params.id is used to retrieve the value of the :id parameter in the URL. Don’t forget to restart your server after adding new code. I’ll create a new story to optimize the development of an API next week. For now, check the new route.

Final code,

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

const items = [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' }
];

app.listen(3000, () => {
console.log('Server started on port 3000');
});

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

app.get('/items', (req, res) => {
res.json(items);
});

app.get('/items/:id', (req, res) => {
const item = items.find(item => item.id === parseInt(req.params.id));
if (!item) return res.status(404).send('Item not found');
res.json(item);
});

Conclusion

In this article, you learned how to create a RESTful API with Node.js and Express.js. You started by installing a new Node.js project and the Express.js library. Then you created an Express.js application and added several routes to handle different HTTP methods. Now you can build your RESTful APIs with Node.js and Express.js, or use this as a starting point for your projects.

--

--