A CRUD API with Express — Node.js

CRUD stands for Create, Read, Update, Delete: making, reading, changing and deleting data. In the notes API, the four become five routes: POST /notes (201)…

Open the notes app on your phone. You write a new note, read an old one, change what it says, and delete the ones you no longer need. Those four things are what almost every app does to its data, from online shops to social media.

Together they are called CRUD: Create, Read, Update, Delete. Our notes API does the same four things through four HTTP methods: Create through POST, Read through GET, Update through PUT, and Delete through DELETE.

Four letters, five routes

Read has two routes: one for every note, one for a single note. So four letters become five routes:

Letter Method and path On success When the id doesn't exist
Create POST /notes 201 Created + the new note
Read GET /notes 200 OK + every note
Read GET /notes/:id 200 OK + one note 404 Not Found
Update PUT /notes/:id 200 OK + the changed note 404 Not Found
Delete DELETE /notes/:id 204 No Content, no body 404 Not Found

You'll use one more status a lot: 400 Bad Request, for data that was sent wrong or incomplete. The next lesson, Input Validation, covers it.

The full code

Here is app.js with all five routes:

const express = require("express");
const app = express();
app.use(express.json());

const notes = [
  { id: 1, title: "Groceries", content: "buy 5 kg of rice" },
  { id: 2, title: "Study", content: "Node.js chapter" },
];
let nextId = 3;

// Read: every note
app.get("/notes", (req, res) => {
  res.json(notes);
});

// Read: one note
app.get("/notes/:id", (req, res) => {
  const item = notes.find((n) => n.id === Number(req.params.id));
  if (!item) return res.status(404).json({ error: "Note not found" });
  res.json(item);
});

// Create
app.post("/notes", (req, res) => {
  const { title, content } = req.body;
  const newNote = { id: nextId++, title, content };
  notes.push(newNote);
  res.status(201).json(newNote);
});

// Update
app.put("/notes/:id", (req, res) => {
  const item = notes.find((n) => n.id === Number(req.params.id));
  if (!item) return res.status(404).json({ error: "Note not found" });
  item.title = req.body.title;
  item.content = req.body.content;
  res.json(item);
});

// Delete
app.delete("/notes/:id", (req, res) => {
  const index = notes.findIndex((n) => n.id === Number(req.params.id));
  if (index === -1) return res.status(404).json({ error: "Note not found" });
  notes.splice(index, 1);
  res.status(204).end();
});

app.listen(3000, () => {
  console.log("Server running at http://localhost:3000");
});

Create: the id from nextId, not from the array length

In the Express.js Basics lesson, the new id was calculated with notes.length + 1. That's right as long as no note gets deleted. Follow the steps in this table. Each POST adds one note with the title shown. Which id will the Cooking note get? Answer before you look at the last row.

Step Ids in the array afterwards length + 1 gives nextId++ gives
start 1, 2
POST Workout 1, 2, 3 3 3
DELETE /notes/1 2, 3
POST Cooking 2, 3, ? 3 (a duplicate!) 4

The array now holds two notes, so length + 1 = 3, but id 3 is already taken by Workout. Cooking gets id 3, and now there are two notes with id 3. GET /notes/3 always finds Workout, which comes first in the array, so Cooking can't be reached.

nextId is a counter: a variable that holds the next id, starting at 3. nextId++ gives the current value of nextId, then raises it by one. The counter only goes up, never down, so an id is never used twice.

Update: PUT replaces the whole note

PUT means "replace this note with what I send". So send the complete note, title and content. The curl command below sends only title, on purpose, so you can see what happens:

curl -X PUT http://localhost:3000/notes/2 -H "Content-Type: application/json" -d '{"title":"Study Express"}'

The answer:

{"id":2,"title":"Study Express"}

The body only holds title, so req.body.content is undefined. The handler copies that undefined into item.content, so the old content is gone. In the answer, content doesn't appear at all, because JSON doesn't write undefined values.

To change only part of a note, APIs usually offer PATCH. PATCH overwrites only the fields (parts of the data, like title or content) that were sent. We have no PATCH route yet, so Express answers a PATCH /notes/2 request with Cannot PATCH /notes/2.

Delete: 204 No Content

curl -i -X DELETE http://localhost:3000/notes/1 prints HTTP/1.1 204 No Content, a few headers, and stops: there's no body. 204 means "it worked, and nothing comes back". res.status(204).end() ends the answer with no body. Delete /notes/1 once more and the answer is 404 {"error":"Note not found"}, because the note is already gone.

📌 Express 5: a body with no Content-Type

express.json() only reads a body whose Content-Type header says JSON. curl -d '{"title":"Workout"}' without -H "Content-Type: application/json" sends the body as form data (like an HTML form sends it), so express.json() skips it. In Express 5, req.body stays undefined. The line const { title, content } = req.body then throws an error, and Express answers 500: TypeError: Cannot destructure property 'title' of 'req.body' as it is undefined. Express 4 fills req.body with {}. So in Express 4 the handler quietly saves a note with no title and no content, like {"id":3}.

In the exercise: CRUD with no server

In the exercise, the starter has the books array, the nextId counter and two functions. listBooks() is already there. You fill in addBook(title, author):

  1. Build the object { id: nextId++, title, author }.
  2. push that object into books.
  3. return that object.

When addBook is right, the starter's console.log lines print:

Books at start: 1
Book added: {"id":2,"title":"Earth","author":"Tere Liye"}
Book added: {"id":3,"title":"Home","author":"Leila S. Chudori"}
Books after adding: 3

⚠️ Doubled ids, lost fields, dropped bodies

TL;DR: CRUD stands for Create, Read, Update, Delete: making, reading, changing and deleting data. In the notes API, the four become five routes: POST /notes (201), GET /notes and GET /notes/:id (200), PUT /notes/:id (200), DELETE /notes/:id (204). An id that doesn't exist gets a 404 with return res.status(404).json(...). Install express.json() so req.body gets filled. New ids come from a nextId++ counter, which only goes up. Don't use the array length, notes.length + 1: the ids can repeat after a DELETE. PUT replaces the whole note, PATCH only part of it. res.status(204).end() answers success with no body, res.json() sends data, and res.status(201) sets the status.

⚡ Create: POST answers 201

Write:

app.post("/notes", (req, res) => {
  const { title, content } = req.body;
  const newNote = { id: nextId++, title, content };
  notes.push(newNote);
  res.status(201).json(newNote);
});

Meaning: CRUD = Create, Read, Update, Delete (making, reading, changing, deleting data), through the methods POST, GET, PUT, DELETE. This route saves a new note into the notes array, with an id from the nextId counter. 201 Created means something new was made, and the new data is sent back.

⚡ The id from a counter

Guess first: the notes array holds notes with ids 1, 2 and 3. Note 1 is deleted, then a new POST comes in. Which id does notes.length + 1 give?

3, but id 3 is already taken. Now there are two notes with id 3. A search for id 3 always stops at the first one, so the second can't be reached.

Meaning: Use a nextId counter, a variable that holds the next id. nextId++ gives the current value, then goes up by one. The counter only goes up, never down, so an id is never used twice.

⚡ Delete: 204, no body

Write:

app.delete("/notes/:id", (req, res) => {
  const index = notes.findIndex((n) => n.id === Number(req.params.id));
  if (index === -1) return res.status(404).json({ error: "Note not found" });
  notes.splice(index, 1);
  res.status(204).end();
});

Meaning: findIndex finds the note's position in the array (-1 when it isn't there), and splice(index, 1) removes it. 204 No Content means it worked, and nothing comes back. An id that doesn't exist gets a 404 with return, so the code below it doesn't run.

What you will learn