Project: A Notes API
💻 Node.jsBuild a complete notes API with validation, file storage and clean errors.
This project combines Express, the filesystem, async errors and REST design into one small service you can run and test.
- Structure an Express project.
- Persist data to a JSON file.
- Test every route.
Project Structure
Keep the server entry, routes and storage in separate files. A small structure now saves confusion later.
notes-api/
app.js
routes/notes.js
store.js
data/notes.jsonStorage
Write a small store module that reads and writes the JSON file. Serialise writes so two requests cannot corrupt the file.
import { readFile, writeFile } from "node:fs/promises";
const file = "data/notes.json";
export async function readNotes() {
try {
return JSON.parse(await readFile(file, "utf8"));
} catch (error) {
if (error.code === "ENOENT") return [];
throw error;
}
}
export async function saveNotes(notes) {
await writeFile(file, JSON.stringify(notes, null, 2));
}Routes
Provide GET /notes, POST /notes, PUT /notes/:id and DELETE /notes/:id. Validate a non-empty title and return 404 for missing ids.
Test the Edges
Try an empty title, a missing id, a malformed JSON body and a second server instance. Each should produce a clear response rather than a crash.
Practice
- Add a createdAt timestamp to each note.
- Add a query parameter to filter notes by a search word.
- Return the total count in a header or a wrapper object.
Hands-on exercise
Build the notes API.
1. GET /notes returns all notes.
2. POST /notes creates a note with a title and body.
3. DELETE /notes/:id removes one note.
4. Missing ids return 404 and empty titles return 422.
Recap
A finished API separates routes and storage, validates input, persists data and handles every error path.
Example
notes-api/
app.js
routes/notes.js
store.js
data/notes.json
Exercises
1. GET /notes returns all notes.
2. POST /notes creates a note with a title and body.
3. DELETE /notes/:id removes one note.
4. Missing ids return 404 and empty titles return 422.
Expected Output
A working notes API with validation, persistence and clear errors.