Introduction
REST APIs are the backbone of many modern applications—powering everything from social media to online stores. But how do you build one?
In this beginner-friendly tutorial, we’ll show you how to create a simple REST API using Node.js and Express that performs CRUD operations on a list of books (Create, Read, Update, Delete). No database is required—we’ll use a local array to simulate data.
If you're new to backend development, this guide is a hands-on way to learn RESTful principles by building something real.
📦 Tools We'll Use
- Node.js – JavaScript runtime
- Express.js – Minimal backend framework
- Postman or browser – For testing API requests
- No database – In-memory simulation using arrays
🔧 Step 1: Initialize Your Project
First, let’s set up a Node.js project.
mkdir book-api
cd book-api
npm init -y
📘 What’s Happening?
This creates a package.json
file that stores your project dependencies.
📥 Step 2: Install Express
Install Express for routing and HTTP handling.
npm install express
📄 Step 3: Set Up Entry File
Create your main file named index.js
.
// index.js
const express = require('express');
const app = express();
const PORT = 3000;
app.use(express.json());
app.listen(PORT, () => {
console.log(`API server is running at http://localhost:${PORT}`);
});
🔍 Breakdown
- The server listens on port 3000.
express.json()
middleware lets us handle JSON request bodies.
📚 Step 4: Create Sample Book Data
Right under app.use(...)
, add some example books.
let books = [
{ id: 1, title: 'Clean Code', author: 'Robert C. Martin' },
{ id: 2, title: 'The Pragmatic Programmer', author: 'Andrew Hunt' }
];
These are the "book records" our API will manage.
📖 Step 5: GET All Books
Create your first API route to return all books.
app.get('/books', (req, res) => {
res.json(books);
});
🧪 Test It
Go to http://localhost:3000/books
in your browser or Postman. You’ll see the list of books in JSON format.
🔍 Step 6: GET a Book by ID
Let users fetch a single book by its ID.
app.get('/books/:id', (req, res) => {
const id = parseInt(req.params.id);
const book = books.find(b => b.id === id);
if (!book) return res.status(404).json({ message: 'Book not found' });
res.json(book);
});
🆕 Step 7: POST – Add a New Book
Now let’s allow users to add a new 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);
});
🧪 Example POST JSON
{
"title": "You Don’t Know JS",
"author": "Kyle Simpson"
}
✏️ Step 8: PUT – Update a Book
Allow users to update a book’s information.
app.put('/books/:id', (req, res) => {
const id = parseInt(req.params.id);
const { title, author } = req.body;
const book = books.find(b => b.id === id);
if (!book) return res.status(404).json({ message: 'Book not found' });
book.title = title;
book.author = author;
res.json(book);
});
❌ Step 9: DELETE – Remove a Book
Let users remove a book by its ID.
app.delete('/books/:id', (req, res) => {
const id = parseInt(req.params.id);
books = books.filter(b => b.id !== id);
res.json({ message: 'Book removed successfully' });
});
🧪 API Testing Checklist
Use Postman or browser to test:
GET /books
– List all booksGET /books/:id
– Get a book by IDPOST /books
– Add a new bookPUT /books/:id
– Update an existing bookDELETE /books/:id
– Remove a book
💡 Best Practices
- Use meaningful HTTP status codes (200, 201, 404, etc.)
- Validate input with tools like
express-validator
- In real apps, use a database like MongoDB or PostgreSQL
- Replace auto-increment IDs with UUIDs for more secure IDs
🌐 SEO Tie-In
Clean backend APIs enhance site performance, user experience, and speed—all of which contribute to better SEO rankings. A well-built API helps with structured data, dynamic rendering, and content updates, which search engines love.
🎯 Conclusion
Well done! You just built a fully functional REST API with Express and Node.js to manage book data.
This project teaches you:
- How to handle routes and HTTP methods
- How to simulate backend data
- The building blocks of full-stack applications
🚀 Want more? Connect this to a frontend with React or deploy it to the cloud. Explore our Backend & APIs tutorials to keep building.
0 Comments