BeginnerCoder
intermediate#Node.js#Express#RESTful API

Building a RESTful API with Node.js and Express

This article was AI-drafted and has not been reviewed yet. Spotted a mistake? Tell us.

Learn how to build a RESTful API using Node.js and Express, and understand the basics of API design.

Introduction to RESTful APIs

A RESTful API (Application Programming Interface) is an architectural style for designing networked applications. It is based on the idea of resources, which are identified by URIs, and can be manipulated using a fixed set of operations.

Step 1: Install Required Packages

First, you need to install the required packages. Run the following command in your terminal:

npm install express body-parser

Step 2: Create a New Express App

Create a new file called app.js and add the following code to it:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();

app.use(bodyParser.json());

const port = 3000;

Step 3: Define API Endpoints

Define API endpoints for creating, reading, updating, and deleting resources. For example, let's say we want to manage a list of books. We can define the following endpoints:

let books = [
  { id: 1, title: 'Book 1', author: 'Author 1' },
  { id: 2, title: 'Book 2', author: 'Author 2' }
];

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

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

app.post('/books', (req, res) => {
  const { title, author } = req.body;
  const newBook = { id: books.length + 1, title, author };
  books.push(newBook);
  res.json(newBook);
});

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

app.delete('/books/:id', (req, res) => {
  const id = req.params.id;
  const index = books.findIndex((book) => book.id === parseInt(id));
  if (index === -1) {
    res.status(404).json({ message: 'Book not found' });
  } else {
    books.splice(index, 1);
    res.json({ message: 'Book deleted' });
  }
});

Step 4: Start the Server

Start the server by running the following command in your terminal:

node app.js

You can now use a tool like curl or a REST client to test your API endpoints.

Keep going with Node.js

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.