DEV Community

Cover image for How to Build a RESTful API with Node.js and Express
Rowsan Ali
Rowsan Ali

Posted on

How to Build a RESTful API with Node.js and Express

In today's world of web development, building RESTful APIs is a fundamental skill. RESTful APIs allow different systems to communicate over HTTP, making them essential for modern web applications. In this blog post, we'll walk through the process of building a RESTful API using Node.js and Express, one of the most popular frameworks for building web applications in JavaScript.

Table of Contents

  1. Introduction to RESTful APIs
  2. Setting Up Your Development Environment
  3. Creating a Basic Express Server
  4. Building the RESTful API
    • GET Request
    • POST Request
    • PUT Request
    • DELETE Request
  5. Adding Middleware
  6. Error Handling
  7. Testing the API
  8. Conclusion

1. Introduction to RESTful APIs

REST (Representational State Transfer) is an architectural style for designing networked applications. A RESTful API is an API that adheres to the principles of REST. It uses HTTP methods (GET, POST, PUT, DELETE) to perform CRUD (Create, Read, Update, Delete) operations on resources, which are typically represented in JSON format.

2. Setting Up Your Development Environment

Before we start coding, let's make sure you have the necessary tools installed:

  • Node.js: Download and install Node.js from nodejs.org.
  • npm: npm is bundled with Node.js, so you don't need to install it separately.
  • Text Editor: You can use any text editor or IDE of your choice. Popular choices include Visual Studio Code, Sublime Text, and Atom.

Once you have Node.js installed, you can check the version by running the following command in your terminal:

node -v
Enter fullscreen mode Exit fullscreen mode

3. Creating a Basic Express Server

First, let's create a new directory for our project and initialize a new Node.js project:

mkdir my-rest-api
cd my-rest-api
npm init -y
Enter fullscreen mode Exit fullscreen mode

This will create a package.json file with default values.

Next, install Express:

npm install express
Enter fullscreen mode Exit fullscreen mode

Now, create a new file named index.js and add the following code to set up a basic Express server:

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

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

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});
Enter fullscreen mode Exit fullscreen mode

To start the server, run:

node index.js
Enter fullscreen mode Exit fullscreen mode

Open your browser and navigate to http://localhost:3000. You should see "Hello World!" displayed on the page.

4. Building the RESTful API

Now that we have a basic Express server running, let's build a simple RESTful API for managing a list of books. We'll use an in-memory array to store the books for simplicity.

4.1 GET Request

Let's start by creating a route to retrieve all books:

let books = [
  { id: 1, title: 'The Great Gatsby', author: 'F. Scott Fitzgerald' },
  { id: 2, title: '1984', author: 'George Orwell' },
];

app.get('/api/books', (req, res) => {
  res.json(books);
});
Enter fullscreen mode Exit fullscreen mode

You can test this by navigating to http://localhost:3000/api/books in your browser or using a tool like Postman.

4.2 POST Request

Next, let's add a route to create a new book:

app.use(express.json());

app.post('/api/books', (req, res) => {
  const book = {
    id: books.length + 1,
    title: req.body.title,
    author: req.body.author,
  };
  books.push(book);
  res.status(201).json(book);
});
Enter fullscreen mode Exit fullscreen mode

You can test this by sending a POST request to http://localhost:3000/api/books with a JSON body like:

{
  "title": "Book name",
  "author": "Author name"
}
Enter fullscreen mode Exit fullscreen mode

4.3 PUT Request

To update an existing book, we'll add a PUT route:

app.put('/api/books/:id', (req, res) => {
  const book = books.find(b => b.id === parseInt(req.params.id));
  if (!book) return res.status(404).json({ message: 'Book not found' });

  book.title = req.body.title;
  book.author = req.body.author;

  res.json(book);
});
Enter fullscreen mode Exit fullscreen mode

You can test this by sending a PUT request to http://localhost:3000/api/books/1 with a JSON body like:

{
  "title": "The Great Gatsby (Updated)",
  "author": "F. Scott Fitzgerald"
}
Enter fullscreen mode Exit fullscreen mode

4.4 DELETE Request

Finally, let's add a route to delete a book:

app.delete('/api/books/:id', (req, res) => {
  const bookIndex = books.findIndex(b => b.id === parseInt(req.params.id));
  if (bookIndex === -1) return res.status(404).json({ message: 'Book not found' });

  books.splice(bookIndex, 1);
  res.status(204).send();
});
Enter fullscreen mode Exit fullscreen mode

You can test this by sending a DELETE request to http://localhost:3000/api/books/1.

5. Adding Middleware

Middleware functions are functions that have access to the request and response objects. They can execute any code, make changes to the request and response objects, end the request-response cycle, or call the next middleware in the stack.

For example, let's add a simple logging middleware:

app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
});
Enter fullscreen mode Exit fullscreen mode

This middleware will log the HTTP method and URL of every request to the console.

6. Error Handling

It's important to handle errors gracefully in your API. Let's add a simple error-handling middleware:

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ message: 'Something went wrong!' });
});
Enter fullscreen mode Exit fullscreen mode

This middleware will catch any errors that occur during request processing and return a 500 status code with an error message.

7. Testing the API

You can test your API using tools like Postman or curl. Here are some example requests:

  • GET all books: GET http://localhost:3000/api/books
  • GET a single book: GET http://localhost:3000/api/books/1
  • POST a new book: POST http://localhost:3000/api/books with a JSON body
  • PUT update a book: PUT http://localhost:3000/api/books/1 with a JSON body
  • DELETE a book: DELETE http://localhost:3000/api/books/1

8. Conclusion

Congratulations! You've just built a simple RESTful API using Node.js and Express. This is just the beginning—there's a lot more you can do, such as adding authentication, connecting to a database, and deploying your API to a cloud platform.

By following this guide, you should now have a solid understanding of how to create a RESTful API with Node.js and Express. Happy coding!

Top comments (1)

Collapse
 
kelvincode1234 profile image
Precious Kelvin Nwaogu

This is amazing and easy to grab