Skip to content
DeveloperMemos

Building a Simple REST API with Node.js and Express

Node.js, Express, REST API2 min read

Building a RESTful API is a common task in modern web development, and Node.js provides an excellent platform for creating backend servers. In this tutorial, we will use Node.js along with the Express framework to build a simple REST API. We'll go step by step, covering the essential concepts and demonstrating their usage with practical examples.

Prerequisites

Before proceeding, make sure you have the following installed on your system:

  • Node.js (version 12 or above)
  • npm (Node Package Manager)

Setting Up the Project

First, let's create a new directory for our project and navigate into it using the command line:

1mkdir simple-rest-api
2cd simple-rest-api

Next, initialize a new Node.js project by running the following command:

1npm init -y

This will generate a package.json file, which allows us to manage our project dependencies. Now, let's install Express by executing the following command:

1npm install express

Creating the Server

With the project set up and the necessary packages installed, let's create a new file called server.js and open it in your preferred code editor. Paste the following code into server.js:

1const express = require('express');
2const app = express();
3const port = 3000;
4
5app.listen(port, () => {
6 console.log(`Server is listening on port ${port}`);
7});

This code imports the express module, creates an Express application, and starts a server listening on port 3000. To run the server, execute the following command:

1node server.js

If everything goes well, you should see the message "Server is listening on port 3000" in the console.

Handling Routes

Now that we have a server up and running, let's define some routes to handle different HTTP requests. In the server.js file, modify the code as follows:

1// ...
2
3app.get('/', (req, res) => {
4 res.send('Hello, world!');
5});
6
7app.post('/api/data', (req, res) => {
8 // Handle POST request
9});
10
11app.put('/api/data/:id', (req, res) => {
12 // Handle PUT request
13});
14
15app.delete('/api/data/:id', (req, res) => {
16 // Handle DELETE request
17});

In this code, we've defined three routes: a GET route for the root path ("/"), a POST route for creating data, and PUT and DELETE routes for updating and deleting data, respectively. Each route handler receives a req (request) and res (response) object, allowing us to interact with the incoming request and send a response back to the client.

Interacting with Data

To demonstrate how to interact with data, we'll use an in-memory array as our data source. Add the following code at the top of the server.js file:

1let data = [];
2
3// ...

Now, let's implement the route handlers to perform CRUD operations on our data array:

1app.get('/api/data', (req, res) => {
2 res.json(data);
3});
4
5app.post('/api/data', (req, res) => {
6 const newItem = req.body;
7 data.push(newItem);
8 res.status(201).json(newItem);
9});
10
11app.put('/api/data/:id', (req, res) => {
12 const itemId = req.params.id;
13 // Find the item in the array and update it
14 res.sendStatus(204);
15});
16
17app.delete('/api/data/:id', (req, res) => {
18 const itemId = req.params.id;
19 // Find the item in the array and remove it
20 res.sendStatus(204);
21});

In the example above, the GET route returns the entire data array as a JSON response. The POST route adds a new item to the data array, while the PUT and DELETE routes update and delete items from the array based on their ID.

Congratulations!

You've successfully built a simple REST API using Node.js and Express. We covered the basics of setting up a server, defining routes, and interacting with data. This serves as a solid foundation for building more complex RESTful APIs. You can further enhance this API by integrating it with a database, implementing authentication and authorization mechanisms, and adding validation and error handling.

I hope this tutorial has provided you with a good starting point for building your own REST API with Node.js and Express. Happy coding!