This Express app follows REST principles by using HTTP methods and clear URLs to manage books. It shows how clients can get, add, update, and delete books easily.
import express from 'express';
const app = express();
app.use(express.json());
// Sample data
let books = [{ id: 1, title: 'Learn REST' }];
// Get all books
app.get('/books', (req, res) => {
res.json(books);
});
// Add a new book
app.post('/books', (req, res) => {
const newBook = { id: books.length + 1, title: req.body.title };
books.push(newBook);
res.status(201).json(newBook);
});
// Update a book
app.put('/books/:id', (req, res) => {
const id = Number(req.params.id);
const book = books.find(b => b.id === id);
if (!book) return res.status(404).send('Book not found');
book.title = req.body.title;
res.json(book);
});
// Delete a book
app.delete('/books/:id', (req, res) => {
const id = Number(req.params.id);
books = books.filter(b => b.id !== id);
res.status(204).send();
});
app.listen(3000, () => console.log('Server running on http://localhost:3000'));