Building a REST API with Node and Express

Learn how to build a robust REST API using Node.js and Express. Step-by-step guide covering setup, routing, CRUD operations, and best practices.


Back to Home

Table of content

Introduction

Building a REST API has become an essential skill for web developers, as APIs act as the backbone that connects front-end and back-end systems. Node.js, combined with the Express framework, offers a fast and flexible way to create scalable REST APIs. In this guide, we’ll walk you through the process of setting up a REST API from scratch using Node and Express.

Why Use Node and Express?

  • Non-blocking, event-driven architecture: Node.js is highly efficient for I/O-heavy operations.
  • Lightweight and fast: Express minimizes boilerplate and makes routing simple.
  • Large ecosystem: Plenty of packages on npm make adding features easy.

Setting Up the Project

  1. Install Node.js from the official website.
  2. Create a new folder for your project and initialize it:
    mkdir node-rest-api
    cd node-rest-api
    npm init -y
  3. Install Express:
    npm install express

Creating Your First Express Server

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

app.use(express.json());

app.get('/', (req, res) => {
  res.send('Welcome to the Node.js REST API!');
});

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

Run node index.js to start your server.

Defining RESTful Routes

A REST API typically supports CRUD (Create, Read, Update, Delete) operations. Let’s build a basic API for managing a list of books.

Sample Data

let books = [
  { id: 1, title: 'The Pragmatic Programmer', author: 'Andrew Hunt' },
  { id: 2, title: 'Clean Code', author: 'Robert C. Martin' }
];

Setting Up CRUD Endpoints

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

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

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

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

// Delete a book
app.delete('/books/:id', (req, res) => {
  books = books.filter(b => b.id !== parseInt(req.params.id));
  res.status(204).send();
});

Best Practices

  • Use middleware for logging, authentication, and error handling.
  • Validate incoming data (use libraries like joi or express-validator).
  • Handle errors gracefully and return meaningful HTTP status codes.
  • Structure your project with separate folders for routes, controllers, and models as it grows.

Conclusion

In this article, we’ve built a simple REST API with Node.js and Express, and covered the foundations of setting up routes and handling CRUD operations. This foundation prepares you for more advanced topics like integrating with databases (MongoDB, PostgreSQL), authentication, and deploying your API. Happy coding!

Backend
Express
JavaScript
Node.js
REST API
Web Development