Let's think about it this way for a moment
This lesson is meant to combine the knowledge from Express Intro, Express Routing, Async & Promises, and API Intro/GET/POST into broader hands-on practice. Each task builds on the last, using route parameters, async functions, and an in-memory array as the data store, and you'll write out an entire CRUD flow yourself. Testing your logic this carefully before hooking up a database in a real project makes connecting a database later much easier. Send requests for each task through Postman or the browser and confirm the results.
Exercises
Task 1: Build an Express app and return the in-memory array 'books' (id, title, author) via a GET /books route. Task 2: Add a GET /books/:id route that returns a 404 status with an error message if no book matches the id. Task 3: Create a POST /books route using the express.json() middleware, and push a new book from the request body into the array — make the id auto-increment. Task 4: Write a delay() helper function that wraps setTimeout in a Promise, and use async/await to add a 500ms delay in the GET /books/:id route to simulate 'searching a database'.
Code Example
const express = require('express');
const app = express();
app.use(express.json());
let books = [
{ id: 1, title: 'Node.js Basics', author: 'Aung' },
{ id: 2, title: 'Express Guide', author: 'Su' }
];
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// Task 1
app.get('/books', (req, res) => {
res.json(books);
});
// Task 2 + 4: param + async delay
app.get('/books/:id', async (req, res) => {
await delay(500); // simulate database lookup
const book = books.find((b) => b.id === Number(req.params.id));
if (!book) {
return res.status(404).json({ error: 'Book not found' });
}
res.json(book);
});
// Task 3
app.post('/books', (req, res) => {
const { title, author } = req.body;
if (!title || !author) {
return res.status(400).json({ error: 'title and author required' });
}
const newBook = { id: books.length + 1, title, author };
books.push(newBook);
res.status(201).json(newBook);
});
app.listen(3000, () => console.log('API running on port 3000'));GET /books returns the book list as a JSON array; GET /books/:id waits 500ms before returning a single book (or a 404); and POST /books adds a new book to the array when you send a body.5-Minute Try
In 5 minutes, write a new DELETE /books/:id route and try using array.filter() to remove a book from the array by id.
A Quick Warning
If you don't wrap error-prone code in an async route handler with try/catch, the server can crash — in production, pair it with an error-handling middleware.