Lompat ke konten

Pelajaran 130 ยท Projects

Final project: build and package a bookshop API

Build a small bookshop API with Node.js, SQLite, input validation, automated tests and Docker, with SQL checkpoints, clear milestones and a rubric.

Fern Alley Books is a fictional independent bookshop. The staff want one program that their website and counter screen can both ask: which books exist, which are in stock, and can this customer order two copies? You will build that program as a small HTTP API.

At the end, you will have a Node.js service that lists books, accepts orders safely, rejects bad requests with useful errors, has automated tests and runs in a Docker container without losing its data. The shop, people and data are invented.

The SQL checkpoints here use the site's bookstore sample database, with the tables authors, books, customers and orders. Each run starts with fresh data. A checkpoint only compares query results. The site cannot grade your API, tests or container, so you build and run those on your own computer.

What you need first

This project combines the tutorials of the Back-End Developer path:

  • JavaScript for functions, modules, errors and promises.
  • Git for a history you can trust.
  • Node.js for servers, files and tests.
  • SQL for queries, constraints and transactions.
  • REST API design for predictable routes and responses.
  • Docker for images, containers and volumes.

Install Node.js 24, Git and Docker on your computer. You can finish this project with Node's built-in modules, including node:http, node:sqlite and node:test. Check the documentation for your exact Node version, since node:sqlite is a newer module.

The brief

  1. GET /health returns status 200 when the service can query its database.
  2. GET /books returns books with author names. It accepts an optional genre and a page number, with three books per page and a stable order.
  3. GET /books/{id} returns one book, or 404.
  4. POST /orders accepts JSON with customerId, bookId and quantity. All are integers, and quantity is from 1 to 5.
  5. A successful order returns 201, saves the order and lowers the stock. Both changes happen, or neither does.
  6. Errors use one JSON shape, such as {"error": {"code": "out_of_stock", "message": "Not enough copies."}}.
  7. All SQL values are passed as parameters.
  8. Automated tests cover successes and failures with a separate test database.
  9. The service runs in Docker as a non-root user, and orders survive replacing the container.
  10. A README documents every route, and Git holds no secrets or database files.

Milestones

1. Write the API contract

Before any code, write a table in your README: method, path, accepted input, success response and possible errors. Decide the codes. A sensible choice is 400 for malformed JSON or an invalid page, 404 for a missing book, 409 for too little stock, 413 for a body that is too large, 415 for the wrong content type and 422 for well-formed JSON with invalid values or an unknown customer or book. Other choices can work if you apply them consistently.

Why: a written contract turns vague ideas into things you can test.

Hint: write one example request and response for each route, including one failure.

Done when: another person could write a client from your table, and your first commit contains it.

2. Create the database

Copy the structure of the four tables into a schema.sql file and add a few invented rows in a separate seed file. Add rules to the database itself, such as CHECK (stock >= 0) and CHECK (quantity BETWEEN 1 AND 5) in your new schema. Turn on foreign key checks for each connection. Seed only an empty database, so a restart never repeats or erases data. Read the database path from an environment variable.

Why: validation in code gives friendly messages, while constraints protect the data even when your code has a bug.

Hint: in your own project, store money as whole cents. The sample data uses decimal numbers to keep lessons simple.

Done when: deleting the local database file and starting again rebuilds the same starting data.

3. Read the catalog

Keep database functions in one module and HTTP handling in another. Parse the address with the URL class, validate genre and page, then run a parameterized query. Develop the query first.

Checkpoint 1. Build the query behind one page of the catalog.

SQL Page two of the catalog ยท database: bookstore

Your task: Return the second page of all books, three per page. Pages are ordered by price from lowest to highest, then by book id. Return exactly the columns id, title, author, price and stock, where author is the author's name.

Hint

Join authors, then skip the three rows of page one.

Press Run (or Ctrl + Enter) to see the result here.

✅ Correct. Your result matches. ❌ Not yet. Check the output and try again. The answer could not be checked. Please try again.

Expected result


        

One possible solution

SELECT b.id, b.title, a.name AS author, b.price, b.stock
FROM books AS b
JOIN authors AS a ON a.id = b.author_id
ORDER BY b.price, b.id
LIMIT 3 OFFSET 3;

In your code, the page size is fixed and the offset is (page - 1) * 3. Set a maximum page number too. A placeholder can hold a value, but not a column name or a sort direction. If you later let clients choose the order, map their choice to a fixed list of allowed SQL text.

Checkpoint 2. The counter screen also needs a summary for each genre.

SQL Stock by genre ยท database: bookstore

Your task: For each genre, return genre, titles (number of books), in_stock_titles (books with stock above 0) and copies (total stock). Order by copies from highest to lowest, then by genre A to Z.

Hint

A CASE expression inside SUM counts only the rows that meet a condition.

Press Run (or Ctrl + Enter) to see the result here.

✅ Correct. Your result matches. ❌ Not yet. Check the output and try again. The answer could not be checked. Please try again.

Expected result


        

One possible solution

SELECT genre,
       COUNT(*) AS titles,
       SUM(CASE WHEN stock > 0 THEN 1 ELSE 0 END) AS in_stock_titles,
       SUM(stock) AS copies
FROM books
GROUP BY genre
ORDER BY copies DESC, genre;

Done when: both read routes work with curl or another HTTP client, including an unknown id and an invalid page.

4. Accept orders with validation and a transaction

Check requests in layers. First check the content type. Read the body with a size limit, such as 4 KB, and stop once it is exceeded. Parse it inside try. Confirm that the result is a plain object, not null or an array. Use Number.isInteger and range checks, and decide whether to reject unknown fields. Do not silently turn the string "2" into a number.

Checkpoint 3. Think through the database rules with a batch of imagined requests before you write the route.

SQL Decide each order request ยท database: bookstore

Your task: The query starts with a table requests of imagined orders, each checked on its own against current stock. Return request_id and decision for each. Use the first rule that applies: bad_quantity (quantity below 1 or above 5), unknown_book (no such book), out_of_stock (quantity is greater than stock), otherwise accept. Order by request_id. Keep the WITH part unchanged.

Hint

An inner join drops unknown books. CASE checks its conditions from top to bottom.

Press Run (or Ctrl + Enter) to see the result here.

✅ Correct. Your result matches. ❌ Not yet. Check the output and try again. The answer could not be checked. Please try again.

Expected result


        

One possible solution

WITH requests(request_id, book_id, quantity) AS (
  VALUES (1, 1, 2), (2, 3, 1), (3, 99, 1), (4, 2, 4), (5, 7, 4), (6, 5, 0), (7, 5, 6), (8, 99, 9)
)
SELECT r.request_id,
       CASE
         WHEN r.quantity < 1 OR r.quantity > 5 THEN 'bad_quantity'
         WHEN b.id IS NULL THEN 'unknown_book'
         WHEN r.quantity > b.stock THEN 'out_of_stock'
         ELSE 'accept'
       END AS decision
FROM requests AS r
LEFT JOIN books AS b ON b.id = r.book_id
ORDER BY r.request_id;

To place a real order, start a transaction, lower the stock only if enough remains, then insert the order. Here is the core idea, to adapt in your own project:

JavaScript
db.exec('BEGIN IMMEDIATE');
try {
  const update = db
    .prepare('UPDATE books SET stock = stock - ? WHERE id = ? AND stock >= ?')
    .run(quantity, bookId, quantity);
  if (update.changes !== 1) {
    throw new OrderError('out_of_stock');
  }
  db.prepare(
    'INSERT INTO orders (customer_id, book_id, quantity, ordered_on) VALUES (?, ?, ?, ?)',
  ).run(customerId, bookId, quantity, orderedOn);
  db.exec('COMMIT');
} catch (error) {
  db.exec('ROLLBACK');
  throw error;
}

OrderError is a small error class that you define. Check that the book and customer exist so you can report the right error. Keep the whole transaction synchronous, with no await inside it.

Why: if inserting the order fails after the stock changed, the rollback restores the stock. The condition in UPDATE also stops stock from going below zero.

Hint: log unexpected errors on the server, but send the client only a general 500 message.

Done when: each failure in your contract leaves both tables unchanged.

5. Test the behavior

Export a function that creates the server from a database object, and call listen in a separate start file. Each test can then create a fresh in-memory database, listen on port 0, send requests with fetch and close both afterward. Use node:test and node:assert/strict.

Test at least: a valid order, the last copy, one copy too many, a wrong type, broken JSON, an oversized body, an unknown customer and a text value containing quote characters. After every rejected order, assert that stock and order count did not change. Force the insert to fail in one test, for example with a temporary trigger, to prove the rollback works.

Why: a status code alone does not show that your data is safe.

Hint: tests must not depend on the order in which they run.

Done when: node --test passes repeatedly from a clean clone.

Checkpoint 4. A sales report helps you check what your orders recorded.

SQL Copies sold, including unsold books ยท database: bookstore

Your task: Return id, title and sold (total ordered quantity, 0 when never ordered) for every book in the genres Fiction and Mystery. Order by sold from highest to lowest, then by id.

Hint

Keep books without orders, and replace their empty total with zero.

Press Run (or Ctrl + Enter) to see the result here.

✅ Correct. Your result matches. ❌ Not yet. Check the output and try again. The answer could not be checked. Please try again.

Expected result


        

One possible solution

SELECT b.id, b.title, COALESCE(SUM(o.quantity), 0) AS sold
FROM books AS b
LEFT JOIN orders AS o ON o.book_id = b.id
WHERE b.genre IN ('Fiction', 'Mystery')
GROUP BY b.id, b.title
ORDER BY sold DESC, b.id;

6. Package it with Docker

Inside a container, listen on 0.0.0.0. When you publish the port, bind it to your own computer. This Dockerfile assumes your source is in src and your schema and seed files are there too. It also assumes you have no third-party packages. If you add some, copy package.json and the lock file, then run npm ci --omit=dev.

DOCKERFILE
FROM node:24-alpine
WORKDIR /app
COPY package.json ./
COPY src ./src
RUN mkdir data && chown node:node data
ENV DB_PATH=/app/data/shop.db HOST=0.0.0.0 PORT=3000
USER node
EXPOSE 3000
CMD ["node", "src/start.js"]
Terminal
docker build -t fern-books:1 .
docker run --rm --name fern -p 127.0.0.1:3000:3000 -v fern-data:/app/data fern-books:1

Add a .dockerignore that excludes .git, node_modules, .env files and databases. Handle SIGTERM by closing the server, then the database.

Why: the image holds the program, and the named volume holds data that must outlive a container.

Hint: place an order, stop the container, start a new one and read the stock again.

Done when: the health route works from your computer and the order is still there after replacement.

This project has no login, so anyone who reaches it can place an order for any customer. Keep it on your own computer. A public service would need authentication, authorization, rate limits, HTTPS and backups.

Check your work

Criterion What good looks like
API design Routes, status codes and error shape match the README
Validation Wrong types, bad ranges, broken and oversized bodies are rejected
Data safety Parameters everywhere, constraints enabled, failed orders change nothing
Tests Isolated, repeatable, and checking database state as well as responses
Code structure Database rules and HTTP handling are separate and readable
Docker Non-root user, small build context, data survives, clean shutdown
Git Focused commits, no secrets or database files, setup works from a clone

Common mistakes

Do not build SQL by joining client text into the query. Use parameters for values, even after validation. For identifiers such as sort columns, choose from your own fixed list.

Do not assume that retrying POST /orders is safe. If a response gets lost, a second request can create a second order. Document this limit, or add idempotency keys as an extension.

Take it further

  • Accept an idempotency key and store it with a unique constraint.
  • Let one order contain several books while keeping a single transaction.
  • Describe the API with an OpenAPI document.
  • Run your tests and an image build automatically on each push.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why put the stock update and order insert in one transaction?

    A transaction prevents a half-finished order. It does not replace validation.
  2. 2. A client sends valid JSON in which quantity is the string "2". Under the contract suggested here, what should happen?

    The contract asks for an integer. This is a client mistake, not a server failure.
  3. 3. What can a SQL placeholder safely stand for?

    Parameters carry values. Table names, columns and keywords are part of the statement itself.
  4. 4. Why do tests use a fresh database?

    Known starting data makes results repeatable and independent of test order.
  5. 5. Where should the container's order data live?

    A volume remains when you remove and replace the container.

Summary

  • Write the API contract before the code, then test against it.
  • Combine friendly validation with database constraints and parameterized queries.
  • Make each order one transaction and prove that failures change nothing.
  • Give every test its own database and a free port.
  • Run the container as a non-root user and keep data in a volume.
  • State your limits honestly, including the missing login and unsafe retries.

Back to the path: Back-End Developer learning path

Pantau kemajuanmu

Buat akun gratis untuk menandai pelajaran yang selesai dan melanjutkan dari tempat terakhirmu di perangkat mana pun.