Building a RESTful API with Node.js and Express

Hi there fellow coders! Are you ready to dive into the world of Node.js and Express to build a RESTful API? Because I sure am! In this tutorial, we are going to explore the basics of building a RESTful API with Node.js and Express step by step. We will cover everything from setting up the environment to deploying our API live. So strap in, grab a cup of coffee, and let's get started!

What is a RESTful API?

Before we get started with building our API, let's first understand what a RESTful API is. A RESTful API is an architectural style for building web services that uses HTTP methods like GET, POST, PUT, and DELETE. RESTful APIs are called so because they follow the REST architectural pattern, where resources are identified by URIs, and interactions are done through representations of the resource's state.

In simpler terms, a RESTful API is a way to build web services that can be easily consumed by other applications. RESTful APIs use common HTTP methods for CRUD operations over resources. Each resource has its unique URI, and we interact with those resources using HTTP methods.

Setting Up the Environment

To get started with building our API, we need to have Node.js and Express installed. Node.js is a platform built on Chrome's JavaScript runtime for building scalable network applications, and Express is a fast, unopinionated, minimalist web framework for Node.js.

Let's start by installing Node.js on our local environment. You can download Node.js from its official website https://nodejs.org/en/. Once you have downloaded and installed Node.js, you can check its version by running the following command in your terminal.

node -v

If Node.js is installed correctly, this command should print out the version of Node.js installed on your machine.

Next, we need to install Express. To do that, we will create a new project directory and initialize a new NPM project. Open up your terminal and run the following commands to create a new project directory and initialize an empty NPM project.

mkdir my-api
cd my-api
npm init -y

The npm init -y command initializes a new NPM project with all the default settings. Once the NPM project is initialized, we can install Express using NPM. Run the following command to install Express.

npm install express

Creating the Server

Now that we have our environment set up, we can start with building our API. Let's create a new file called index.js in our project directory and add the following code to it.

const express = require('express');

const app = express();
const port = process.env.PORT || 3000;

app.listen(port, () => {
  console.log(`Listening on port ${port}...`);
});

In the above code, we are importing the express module and initializing a new Express application. We are also setting the port number for our application to 3000 or the environment variable PORT if it is present. Finally, we are starting our server with the app.listen() method, which listens on the specified port number and logs a message to the console when the server is started.

Let's run our server by executing the following command in our terminal.

node index.js

If everything is set up correctly, you should see a message in your terminal saying "Listening on port 3000...". Congratulations, you have successfully created your first Express server!

Handling GET Requests

Now that we have our server up and running, let's start handling some requests. The first request we will handle is the GET request to retrieve a list of items from our API.

Let's add a new endpoint to our server that handles GET requests to the root URL /.

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

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

In the above code, we are defining an array of items and creating a new endpoint that handles GET requests to the root URL /. When the server receives a GET request to this URL, it responds with a JSON representation of the items array.

Let's run our server again with the node index.js command and open up a web browser. Navigate to http://localhost:3000/, and you should see a list of items displayed on the page.

Congratulations! You have successfully created an endpoint that handles GET requests and retrieves a list of items from our API.

Handling POST Requests

Now that we can retrieve a list of items from our API, let's add an endpoint that allows us to add new items to the list using a POST request.

let nextItemId = 4;

app.use(express.json());

app.post('/', (req, res) => {
  const { name } = req.body;

  if (!name) {
    return res.status(400).send('Name is required');
  }

  const item = {
    id: nextItemId++,
    name,
  };

  items.push(item);

  res.json(item);
});

In the above code, we are creating a new endpoint that handles POST requests to the root URL /. We are also using the express.json() middleware to parse JSON request bodies.

When the server receives a POST request to this URL, it creates a new item object and adds it to the list of items. It then responds with a JSON representation of the newly created item.

We are also checking if the name field is present in the request body. If it is not present, we are responding with a 400 Bad Request error.

Let's add a new item to our list using a tool like curl or Postman. Send a POST request to http://localhost:3000/ with the following JSON body.

{
  "name": "Item 4"
}

If the request is successful, you should get a response with the newly created item.

{
  "id": 4,
  "name": "Item 4"
}

Congratulations! You have successfully created an endpoint that handles POST requests and adds new items to our API.

Handling PUT Requests

Next, let's add an endpoint that allows us to update an item using a PUT request. We will use the item's id to identify the item we want to update.

app.put('/:id', (req, res) => {
  const { id } = req.params;
  const { name } = req.body;

  const index = items.findIndex((item) => item.id == id);

  if (index === -1) {
    return res.status(404).send('Item not found');
  }

  if (!name) {
    return res.status(400).send('Name is required');
  }

  const item = {
    ...items[index],
    name,
  };

  items[index] = item;

  res.json(item);
});

In the above code, we are creating a new endpoint that handles PUT requests to an item's URL, where :id is the item's id. We are also checking if the name field is present in the request body.

When the server receives a PUT request to this URL, it finds the item with the specified id and updates its name field. It then responds with a JSON representation of the updated item.

We are also checking if the item exists in the list of items. If it does not exist, we are responding with a 404 Not Found error.

Let's update an item using a tool like curl or Postman. Send a PUT request to http://localhost:3000/1 with the following JSON body.

{
  "name": "Updated Item 1"
}

If the request is successful, you should get a response with the updated item.

{
  "id": 1,
  "name": "Updated Item 1"
}

Congratulations! You have successfully created an endpoint that handles PUT requests and updates items in our API.

Handling DELETE Requests

Finally, let's add an endpoint that allows us to delete an item using a DELETE request. We will use the item's id to identify the item we want to delete.

app.delete('/:id', (req, res) => {
  const { id } = req.params;

  const index = items.findIndex((item) => item.id == id);

  if (index === -1) {
    return res.status(404).send('Item not found');
  }

  items.splice(index, 1);

  res.sendStatus(204);
});

In the above code, we are creating a new endpoint that handles DELETE requests to an item's URL, where :id is the item's id.

When the server receives a DELETE request to this URL, it finds the item with the specified id and removes it from the list of items. It then responds with a 204 No Content status code, indicating that the request was successful but there is no response body.

We are also checking if the item exists in the list of items. If it does not exist, we are responding with a 404 Not Found error.

Let's delete an item using a tool like curl or Postman. Send a DELETE request to http://localhost:3000/1.

If the request is successful, you should get a response with a 204 No Content status code.

Congratulations! You have successfully created an endpoint that handles DELETE requests and deletes items from our API.

Wrapping Up

In this tutorial, we have covered the basics of building a RESTful API with Node.js and Express. We started by setting up our environment by installing Node.js and Express. We then created a simple Express server that listens on a specified port number.

We then added endpoints to our server that handle GET, POST, PUT, and DELETE requests. We created an endpoint that retrieves a list of items from our API using a GET request, an endpoint that adds new items to our API using a POST request, an endpoint that updates existing items in our API using a PUT request, and an endpoint that deletes items from our API using a DELETE request.

We hope this tutorial has given you a good understanding of how to build a RESTful API with Node.js and Express. Keep practicing, and happy coding!

Additional Resources

databasemigration.dev - database data migration, data movement, CDC change data capture, WAL log exporting
explainability.dev - techniques related to explaining ML models and complex distributed systems
quick-home-cooking-recipes.com - quick healthy cooking recipes
moderncli.com - modern command line programs, often written in rust
sitereliabilityengineer.dev - site reliability engineering SRE
eventtrigger.dev - A site for triggering events when certain conditions are met, similar to zapier
cloudtraining.dev - learning cloud computing in gcp, azure, aws. Including certification, infrastructure, networking
rust.community - A community for rust programmers
persona6.app - persona 6
cloudblueprints.dev - A site for templates for reusable cloud infrastructure, similar to terraform and amazon cdk
mlstartups.com - machine learning startups, large language model startups
nftsale.app - buying, selling and trading nfts
anthos.video - running kubernetes across clouds and on prem
networksimulation.dev - network optimization graph problems
witcher4.app - the witcher 4 PC game
mlwriting.com - machine learning writing, copywriting, creative writing
devsecops.review - A site reviewing different devops features
modelshop.dev - buying and selling machine learning models and weights
erlang.cloud - Erlang and Elixir in the cloud
learngcp.dev - learning Google cloud


Written by AI researcher, Haskell Ruska, PhD (haskellr@mit.edu). Scientific Journal of AI 2023, Peer Reviewed