Step-by-step example of a basic REST API for managing “books” using Express.js.
1️⃣ Setup Project
mkdir express-api
cd express-api
npm init -y
npm install express
2️⃣ Create server.js
const express = require("express");
const app = express();
const PORT = 3000;
// Middleware to parse JSON bodies
app.use(express.json());
// In-memory data store
let books = [
{ id: 1, title: "Clean Code", author: "Robert C. Martin" },
{ id: 2, title: "You Don’t Know JS", author: "Kyle Simpson" }
];
// --- Routes ---
// GET all books
app.get("/books", (req, res) => {
res.json(books);
});
// GET a book by ID
app.get("/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" });
res.json(book);
});
// POST 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);
});
// PUT - 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).json({ message: "Book not found" });
const { title, author } = req.body;
book.title = title || book.title;
book.author = author || book.author;
res.json(book);
});
// DELETE a book
app.delete("/books/:id", (req, res) => {
books = books.filter(b => b.id !== parseInt(req.params.id));
res.json({ message: "Book deleted" });
});
// Start server
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
3️⃣ Test the API
- GET all books:
GET http://localhost:3000/books - GET one book:
GET http://localhost:3000/books/1 - POST a new book:
POST http://localhost:3000/books
Body:
{
"title": "JavaScript: The Good Parts",
"author": "Douglas Crockford"
}
- PUT update a book:
PUT http://localhost:3000/books/1
Body:
{
"title": "Clean Code (Updated)"
}
- DELETE a book:
DELETE http://localhost:3000/books/2
✅ Key Points
express.json()middleware allows parsing JSON request bodies.- REST endpoints: GET, POST, PUT, DELETE.
- Using an in-memory array for simplicity (replace with DB in real apps).
- Handles basic status codes and error messages.