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.
{
"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"
}
}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);
}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}`));PORT=3000
API_KEY=change-me-long-random
DATA_FILE=products.jsonnode_modules
.env
products.jsonfile:///home/you/souq-api/server.js:4
if (!apiKey) throw new Error("Set API_KEY in .env before starting the server");
^> souq-api@1.0.0 start
> node --env-file-if-exists=.env server.js
Souq API on http://localhost:3000Replace 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
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.
- Node.js docs: Test runner
- Node.js docs: Assert
- Express 5 API reference
- MDN: HTTP request methods
- npm docs: npm ci
Code examples stay in English and run in a sandbox on your device. If you spot a mistake, tell us through the contact page.