Skip to content

Project: Build and Test a REST API with Node.js and Express (CRUD, API Key, JSON Storage)

NeedMyTools Academy

Sign in free to read the full lesson

Sign in or create a free account

Free forever. No card, no paywall.

This project puts the whole course together. You build souq-api, a REST API for the product list of a small shop. Anyone can read products, but creating, editing and deleting need an API key, which comes from .env as in the previous lesson. Products are saved in a JSON file with a write method that cannot leave a half written file behind, using the file skills from lesson 3. Every input is validated, every answer has the right status code, and five automated tests, written with the test runner built into Node.js, check the API on every change. We also broke the code on purpose so you can see what a failing test looks like. Recorded with Node.js 22.23.4, Express 5.3.0 and curl.

Quick answer

A REST API maps HTTP methods to actions on a resource: GET /api/products lists, GET /api/products/:id reads one, POST creates (201), PATCH /:id updates part of one, and DELETE /:id removes it (204). Build it with Express in a createApp() function that takes its settings, start it from a small server.js that reads .env, protect write routes with middleware that checks an API key header, validate every body, and test it with node --test against a real server on a random port.

60 min read and practice · Content checked on 28 November 2026

In this lesson you will

  • Design REST routes with the right methods and status codes
  • Protect write routes with an API key and validate every input
  • Save data to a JSON file without corrupting it
  • Write automated API tests with node:test and read a failure

The plan: routes, codes and files

REST is a style, not a library. Each kind of thing, here products, gets one URL, and the HTTP method says what to do with it. GET must never change data, so browsers and caches can repeat it safely. POST to the collection creates a product and answers 201 with a Location header pointing to the new item. PATCH changes only the fields you send. DELETE answers 204 No Content, which means success with an empty body. Errors use 400 for bad input, 401 for a missing key and 404 for an unknown id.

The code is split into four files with one job each. store.js loads and saves the JSON file. app.js exports createApp({ dataFile, apiKey }), which builds the Express app but does not start it. server.js reads the environment and calls listen. test/api.test.js creates its own app with a temporary file and a test key. Because createApp receives its settings instead of reading process.env itself, the tests never touch your real data or your real key.

The package.json scripts are the commands you and your host will run: npm start for production, npm run dev for watching files while you work, and npm test. --env-file-if-exists lets the same start command work on your laptop, where .env exists, and on a host that sets real environment variables and has no .env at all. Copy node_modules and package-lock.json from the Express lesson or run npm install express in a new souq-api folder.

Example: package.json, store.js and server.js
package.json
{
  "name": "souq-api",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "start": "node --env-file-if-exists=.env server.js",
    "dev": "node --watch --env-file-if-exists=.env server.js",
    "test": "node --test --test-reporter=spec"
  },
  "dependencies": {
    "express": "^5.3.0"
  }
}
store.js
import { readFile, writeFile, rename } from "node:fs/promises";

export async function load(file) {
  try {
    return JSON.parse(await readFile(file, "utf8"));
  } catch (err) {
    if (err.code === "ENOENT") return [];
    throw err;
  }
}

export async function save(file, items) {
  const tmp = `${file}.tmp`;
  await writeFile(tmp, JSON.stringify(items, null, 2));
  await rename(tmp, file);
}
server.js
import { createApp } from "./app.js";

const apiKey = process.env.API_KEY;
if (!apiKey) throw new Error("Set API_KEY in .env before starting the server");

const port = Number(process.env.PORT ?? 3000);
const app = createApp({ dataFile: process.env.DATA_FILE ?? "products.json", apiKey });

app.listen(port, () => console.log(`Souq API on http://localhost:${port}`));
.env
PORT=3000
API_KEY=change-me-long-random
DATA_FILE=products.json
.gitignore
node_modules
.env
products.json
Real output: node server.js (no .env loaded, first lines of the crash)
file:///home/you/souq-api/server.js:4
if (!apiKey) throw new Error("Set API_KEY in .env before starting the server");
                   ^
Real output: npm start
> souq-api@1.0.0 start
> node --env-file-if-exists=.env server.js

Souq API on http://localhost:3000

Replace change-me-long-random with a long random value of your own, for example from a password manager. The same rule as the last lesson applies: .env stays out of Git.

Sign in free to read the full lesson

You are reading the free preview. Create a free account (it takes one minute, no password) to unlock the rest of this lesson and track your progress.

Unlocks after sign-in:

  • 3 more sections with live code examples
  • Common mistakes to avoid
  • Hands-on coding exercise with automatic checks
  • Practice quiz and the graded lesson test
Sign in or create a free account

Free forever. No card, no paywall.

Questions people ask

What is the difference between PUT and PATCH?

PUT replaces the whole item with what you send, so missing fields are lost. PATCH changes only the fields in the body. This project uses PATCH because clients usually update one field, such as the price.

Is an API key enough security for a real API?

For a private API used by your own scripts or one partner, a long random key over HTTPS is a reasonable start. Public apps with many users need user accounts and sessions or tokens, plus rate limits and logging, and usually an identity provider.

Do I need Jest or Vitest to test Node.js code?

No. node:test and node:assert cover most needs, including mocks and watch mode, with coverage behind a flag, and nothing to install. Jest and Vitest are fine choices, especially when a project already uses them or tests front end code too.

Where can I host a Node.js API?

Any platform that runs Node.js apps, a container service, or your own VPS with a process manager. Pick one with HTTPS, environment variable settings and logs, and check where it stores data if you keep using a file.

What should I learn after this Node.js course?

SQL and a database such as PostgreSQL, authentication, and deploying with logs and monitoring. Adding TypeScript to this project, from the TypeScript course here, is a good next step that catches many mistakes before tests do.

Sources

Facts in this lesson were checked against these official pages on 28 November 2026.

Code examples stay in English and run in a sandbox on your device. If you spot a mistake, tell us through the contact page.