Project: Bookstore REST API
Build a complete Express API with CRUD routes, validation, atomic JSON persistence, consistent errors, and a README.
By the end, you’ll be able to…
- Structure an Express project so the app, server, and repository can be tested separately.
- Implement validated CRUD endpoints with correct status codes and one error format.
- Verify persistence, document the API, and review it against a production-minded checklist.
01Project brief and package setup
Build an Express API that stores books in a JSON file and exposes list, read, create, update, and delete endpoints. Each book has an id, title, author, and optional year. The API validates input, returns consistent JSON, survives restarts, and includes a health endpoint and a short README.
Create the project in this order: initialise package.json, install Express, add data/books.json containing [], write the repository, build the app, then add the listener. Keeping the app separate from app.listen lets a test import the app without opening a port.
{ "name": "bookstore-api", "version": "1.0.0", "private": true, "type": "module", "scripts": { "start": "node src/server.js", "dev": "node --watch src/server.js" }, "dependencies": { "express": "^5.1.0" }}npm install then npm run dev starts the API on port 3000.
02Build the JSON repository
src/store.js is the only module that touches the file. It reads and validates the array, writes through a temporary file, and exports one function per operation. Routes never import node:fs; they ask the repository for data. That boundary is what makes a later move to SQLite or Postgres a contained change.
Create data/books.json with [] before the first run. If the file contains valid JSON that is not an array, readAll normalizes it to an empty list; malformed JSON throws rather than silently resetting the file. This store inherits Node's single-process model, so a production database would add transactions and row-level locking.
03Add list, read, and create routes
src/app.js creates the Express app, installs express.json with a size limit, and defines validation. The validator returns an array of field errors rather than throwing immediately, so a client can fix every problem in one request. HttpError carries the status and code that the central handler will use.
04Finish update, delete, and error handling
PATCH validates only the fields that are present and merges them into the existing record. DELETE returns 204 when a record is removed and 404 when the id is unknown. A catch-all 404 and a four-parameter error handler finish the stack, and Express 5 forwards rejected async handlers automatically.
A validation failure returns 400 with a details array, while a missing record returns 404 with only a code and message. Clients should branch on error.code, not on wording, so messages can change without breaking integrations.
05Start and stop the server
src/server.js owns the port and the process lifecycle. Read PORT from the environment, log the actual address, and close the server on SIGINT or SIGTERM. Do not call app.listen from app.js, or importing the app in a test will leave a port open.
Set PORT in the environment when deploying, and keep the default for local work. A startup log that prints the real port saves time when a hosting platform assigns one dynamically.
06Document and review the API
Write a README that another developer can follow without reading the source: install, run, endpoint table, request example, error shape, and the storage limitation. State that the JSON file is for learning and single-process use; concurrent production traffic needs a database with transactions.
Review the API before calling it finished. Check every endpoint with valid and invalid input, confirm that 201 and 204 responses have the right bodies, restart the server to prove persistence, and verify that unknown routes and thrown errors keep the same error shape. Confirm that no secret or stack trace appears in a response.
# Bookstore API## Run npm install npm startThe API listens on http://localhost:3000 (override with `PORT`).## Endpoints| Method | Path | Purpose || --- | --- | --- || GET | /health | Health check || GET | /api/books | List books || GET | /api/books/:id | Get one book || POST | /api/books | Create a book || PATCH | /api/books/:id | Update a book || DELETE | /api/books/:id | Delete a book |Errors use `{ "error": { "code", "message", "details" } }`.Data lives in `data/books.json`; this store is for learning and single-process use, not concurrent production traffic.A README another developer can use to install, run, and exercise the API.
The ideas worth keeping.
- Keep the app, server, and repository separate so each piece can be tested and replaced.
- Validate before writing, return 201/204 correctly, and use one error envelope for every failure.
- Prove persistence with a restart, document the API, and state the limits of the JSON store.
Make it yours.
Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.
Exercise 1: Add search and pagination
Extend GET /api/books with q, limit, and offset query parameters. Filter by title or author, validate that limit is between 1 and 50, and return { data, total }.
Explore a worked solution
app.get("/api/books", async (request, response, next) => { const q = typeof request.query.q === "string" ? request.query.q.trim().toLowerCase() : ""; const limit = Number(request.query.limit ?? 20); const offset = Number(request.query.offset ?? 0); if (!Number.isInteger(limit) || limit < 1 || limit > 50 || !Number.isInteger(offset) || offset < 0) { return next(new HttpError(400, "VALIDATION_ERROR", "Invalid pagination parameters.")); } const books = await listBooks(); const matches = q ? books.filter((book) => `${book.title} ${book.author}`.toLowerCase().includes(q)) : books; response.json({ data: matches.slice(offset, offset + limit), total: matches.length });});The filter runs before pagination so total describes the full match set. Converting query strings to numbers and validating them prevents slice from receiving nonsense, and the response keeps the collection's data key while adding metadata.
Exercise 2: Make the health check verify storage
Change /health so it reads the repository and returns 200 with the book count, or 503 with a generic error if storage cannot be read.
Explore a worked solution
app.get("/health", async (request, response) => { try { const books = await listBooks(); response.json({ status: "ok", books: books.length }); } catch (error) { console.error(error); response.status(503).json({ error: { code: "STORAGE_UNAVAILABLE", message: "Storage is unavailable." }, }); }});A health endpoint that only returns ok cannot detect a broken data layer. Reading the repository proves the process can serve requests, while the generic 503 body avoids exposing file paths or parse errors.
What stayed with you?
Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.
Exercise 1: Add search and pagination
Extend GET /api/books with q, limit, and offset query parameters. Filter by title or author, validate that limit is between 1 and 50, and return { data, total }.
Keep exploring.
The official references behind this lesson, when you want a second angle or the full details.
Pause. Put the pieces together.
You’ve reached the end of Node.js, Express & REST APIs. Before moving on, use this task to check what you can do independently.
Ship a validated Bookstore API with CRUD routes, consistent errors, persistence, a health endpoint, and a README a teammate can follow.
Try it in your own environment and write down the result. This is a self-check; reading completion does not evaluate your code.
Review this moduleOne lesson closer.
Reading is a start. Trying it yourself makes the connection.