LESSON 78 · ADVANCED4 min read

Project: Tested & Deployed API

Build a small JSON API, test its routes and validation, containerize it, and automate the release checks.

ES2024 / Node.js 20+Free to readModule 17 of 19
YOUR NEXT SMALL WINS

By the end, you’ll be able to…

  • Implement a dependency-injected HTTP API with validation and a health endpoint.
  • Test successful routes, validation failures, and patches with node:test.
  • Package the service in Docker and verify it through a GitHub Actions workflow.

01Scope and build order

Build a task API with GET /health, GET /tasks, POST /tasks, and PATCH /tasks/:id. It uses node:http, node:test, and an in-memory store. Every response is JSON with an x-request-id header.

Keep five files under src: store.js, validate.js, http.js, app.js, and server.js, plus test/api.test.js. Build in that order; each file has one job. Contributors run npm ci, npm test, and docker build.

package.jsonJSON
{  "name": "tasks-api",  "version": "1.0.0",  "private": true,  "type": "module",  "engines": { "node": ">=22" },  "scripts": {    "dev": "node --watch src/server.js",    "start": "node src/server.js",    "test": "node --test",    "lint": "eslint .",    "check": "npm run lint && npm test"  },  "devDependencies": {    "@eslint/js": "^9.0.0",    "eslint": "^9.0.0"  }}

02A store behind a seam

The store owns mutable state and exposes list, find, create, and update. A Map keeps insertion order, so listing is predictable; each new task gets a short id and a done flag.

createApp receives the store instead of importing a singleton. Each test passes a fresh store, so tasks never leak between tests. Production keeps one store for the process lifetime.

src/store.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

03Validate at the edge

Validation returns a message or null, keeping HTTP concerns out of the rules. New tasks need a title between three and 120 characters. Patches may change title or done, but must provide one.

Check types before trimming. A number is not a title, and an array is an object but not a valid body. These guards stop malformed input before the store sees it.

src/validate.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

04HTTP plumbing

Three helpers keep the handler readable. send writes JSON and the request id. readJson reads a size-limited body and turns parse failures into a 400. HttpError carries a trusted status.

Without a limit, a client can stream an enormous body into memory; sixteen kilobytes is plenty. A typed error keeps expected client mistakes separate from server failures.

src/http.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

05Routes and request ids

The handler accepts or creates a request id, routes by method and path, and logs a structured line when the response finishes. The id returns in a header for bug reports.

A 404 is a normal outcome, not an exception. Only unexpected failures become 500 responses, and those log details while hiding internals from the client.

src/app.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

06Start, stop, and test

The entry point creates the store, starts the server, and handles SIGTERM by draining connections. A ten-second timeout forces exit if a request refuses to finish.

Tests should use the real HTTP stack without a fixed port. Listen on port zero, read the assigned port from server.address(), and close in a finally block. This catches routing mistakes a direct call would miss.

src/server.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

07Route and validation tests

The helper starts a fresh app and server for each test. Cases cover health, task creation, a rejected short title, a patch, a missing task, and the store boundary. Assertions check status, body fields, and headers.

Send an explicit JSON content type with fetch. Parse the response once and assert named fields rather than the whole serialized string, which would fail on key ordering.

test/api.test.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

08Package and containerize

Package scripts are the interface for people and CI. The Dockerfile builds in a throwaway stage, then copies only the manifest and source into a small runtime image. The container runs as node with a health check.

Build with docker build -t tasks-api:local ., run with docker run --rm -p 3000:3000 tasks-api:local, then request /health. A .dockerignore excludes node_modules, .git, and .env while keeping test available to the build stage.

DockerfileDockerfile
FROM node:22-alpine AS buildWORKDIR /appCOPY package*.json ./RUN npm ciCOPY src ./srcCOPY test ./testRUN npm testFROM node:22-alpine AS runtimeENV NODE_ENV=productionWORKDIR /appCOPY package*.json ./RUN npm ci --omit=devCOPY --from=build /app/src ./srcUSER nodeEXPOSE 3000HEALTHCHECK --interval=30s --timeout=3s CMD wget -qO- http://127.0.0.1:3000/health || exit 1CMD ["node", "src/server.js"]

09A shared lint configuration

The project reuses a flat ESLint configuration. Recommended rules catch accidental globals and unused bindings, scoped to JavaScript source files.

Commit the config so editors and CI apply the same rules.

eslint.config.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

10Automate and review

The workflow grants read-only repository access, installs from the lockfile, and runs the same commands as a developer. It builds the image only after linting and tests pass.

Before finishing, verify: tests cover health, creation, validation, and not-found paths; no secret is committed; environment variables are documented; the image runs as non-root; SIGTERM drains requests; and a previous tag is available for rollback. After deploy, check /health and one real route.

.github/workflows/ci.ymlYAML
name: cion:  push:    branches: [main]  pull_request:permissions:  contents: readjobs:  verify:    runs-on: ubuntu-latest    steps:      - uses: actions/checkout@v4      - uses: actions/setup-node@v4        with:          node-version: 22          cache: npm      - run: npm ci      - run: npm run lint      - run: npm test      - run: docker build -t tasks-api:${{ github.sha }} .
LET IT CLICK

The ideas worth keeping.

  • Small modules with injected dependencies make an API testable without a database or a fixed port.
  • Validation at the HTTP boundary turns malformed input into clear 400 responses.
  • A tested, non-root container plus a read-only CI workflow makes deployment repeatable and reviewable.
TURN UNDERSTANDING INTO SOMETHING YOU CAN DO

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.

01

Exercise 1: Add a read-by-id route

Add a readTask helper that returns 200 with store.find(id) or 404 with Task not found, then call it for GET /tasks/:id. Add a test that requests an unknown id and asserts 404.

your_turn_1.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.jsJavaScript
// Add this helper to src/app.js, then call it for GET /tasks/:id.function readTask({ store, send, res, requestId, id }) {  const task = store.find(id);  if (!task) return send(res, 404, { error: 'Task not found' }, requestId);  return send(res, 200, task, requestId);}// In test/api.test.js:test('GET /tasks/:id returns 404 for an unknown id', async () => {  await withApi(async (base) => {    const response = await fetch(`${base}/tasks/missing`);    assert.equal(response.status, 404);  });});

The helper returns a 404 when the store finds no record, so an absent id is a normal response rather than an exception. The test exercises the real handler and confirms the status.

02

Exercise 2: Filter the task list

Add a listTasks helper that supports GET /tasks?done=true and ?done=false by filtering store.list(). With no query parameter, return every task. Add a test that creates two tasks, patches one to done, and verifies the filtered response contains only that task.

your_turn_2.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.jsJavaScript
// Add this helper to src/app.js, then call it from the GET /tasks branch.function listTasks({ store, send, res, requestId, done }) {  const tasks = store.list().filter((task) =>    done === null ? true : String(task.done) === done,  );  return send(res, 200, tasks, requestId);}// A focused test can seed the store directly:test('GET /tasks?done=true returns completed tasks', async () => {  await withApi(async (base) => {    const first = await fetch(`${base}/tasks`, {      method: 'POST',      headers: { 'content-type': 'application/json' },      body: JSON.stringify({ title: 'First task' }),    }).then((response) => response.json());    await fetch(`${base}/tasks`, {      method: 'POST',      headers: { 'content-type': 'application/json' },      body: JSON.stringify({ title: 'Second task' }),    });    await fetch(`${base}/tasks/${first.id}`, {      method: 'PATCH',      headers: { 'content-type': 'application/json' },      body: JSON.stringify({ done: true }),    });    const response = await fetch(`${base}/tasks?done=true`);    const tasks = await response.json();    assert.equal(tasks.length, 1);    assert.equal(tasks[0].id, first.id);  });});

The filter compares string representations because query parameters are always strings. Once listTasks is wired into GET /tasks, the test verifies creation, patching, and filtering through the real API.

A SMALL QUESTION. A USEFUL NEXT STEP.

What stayed with you?

Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.

A LITTLE ACTIVE RECALL0 / 3 answered
01Why does createApp accept a store instead of creating one internally?
02What is the purpose of returning x-request-id on every response?
03Why does the Dockerfile use two stages?
⚡CODING CHALLENGE
🔒Required to Mark Lesson Complete

Exercise 1: Add a read-by-id route

Add a readTask helper that returns 200 with store.find(id) or 404 with Task not found, then call it for GET /tasks/:id. Add a test that requests an unknown id and asserts 404.

main.jsJavaScript
Ctrl + ↵
Execution Console
Click "Run & Verify" (or press Ctrl + Enter) to test your code against the challenge.

Keep exploring.

The official references behind this lesson, when you want a second angle or the full details.

MODULE 17 · PRACTICAL SELF-CHECK

Pause. Put the pieces together.

You’ve reached the end of Testing, Tooling & Deployment. Before moving on, use this task to check what you can do independently.

Take the Bookstore API through tests, CI, a Docker build, and a documented deployment verification.

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 module

One lesson closer.

Reading is a start. Trying it yourself makes the connection.

Solve the hands-on coding challenge in the knowledge section to verify your code and unlock lesson completion.