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.
Table of content
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.
mkdir node-rest-api
cd node-rest-api
npm init -y
npm install express
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.
A REST API typically supports CRUD (Create, Read, Update, Delete) operations. Let’s build a basic API for managing a list of books.
let books = [
{ id: 1, title: 'The Pragmatic Programmer', author: 'Andrew Hunt' },
{ id: 2, title: 'Clean Code', author: 'Robert C. Martin' }
];
// 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();
});
joi
or express-validator
).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!