Learn CRUD API: API Lesson

CRUD is the four operations on data: Create, Read, Update, Delete. Create: POST /books builds { ...req.body, id: nextId++ } (the client's body, with an id the…

The endpoints in the previous lesson only answered. The server stored no data, so no book could be added, changed or removed. A real shop needs more than that. Look at the stock list in the Bookshop warehouse. You write a new line when a book arrives, read what's there, fix a stock number, and cross out a book that's no longer sold.

Those four jobs on the stock list have a name: CRUD, short for Create, Read, Update, Delete. Create is writing a new line, Read is looking at what's there, Update is fixing a number, and Delete is crossing a book out. In the HTTP Methods lesson you learned which method does what. Now we write the code: six endpoints, and four of them really change data.

Mapping CRUD to HTTP

Operation Request On success When the id doesn't exist
Create POST /books 201 Created + a Location header
Read (list) GET /books 200 OK
Read (one) GET /books/2 200 OK 404 Not Found
Update (replace all) PUT /books/2 200 OK 404 Not Found
Update (part) PATCH /books/2 200 OK 404 Not Found
Delete DELETE /books/2 204 No Content 404 Not Found

For now we keep the data in the array books, and GET /books answers with the whole array. A database comes in the lesson Querying the Database from an API.

let books = [
  { id: 1, title: "The Rainbow Troops", author_id: 1, price: 89000, stock: 12 },
  { id: 2, title: "This Earth of Mankind", author_id: 2, price: 125000, stock: 0 },
  { id: 3, title: "Beauty Is a Wound", author_id: 3, price: 110000, stock: 5 },
];
let nextId = 4; // the id for the next book

app.get("/books", (req, res) => {
  res.json(books);
});

Read one: an id from the URL is text

app.get("/books/:id", (req, res) => {
  const id = Number(req.params.id);
  const book = books.find((b) => b.id === id);
  if (!book) {
    return res.status(404).json({ error: "Book not found" });
  }
  res.json(book);
});

Create: POST, 201 and Location

app.post("/books", (req, res) => {
  const book = { ...req.body, id: nextId++ };
  books.push(book);
  res.set("Location", "/books/" + book.id);
  res.status(201).json(book);
});

Say the client sends POST /books with the body {"title": "The Dancer", "author_id": 4, "price": 95000, "stock": 3}. This is the answer:

HTTP/1.1 201 Created
Location: /books/4
Content-Type: application/json; charset=utf-8

{"title":"The Dancer","author_id":4,"price":95000,"stock":3,"id":4}

Update: PUT replaces, PATCH patches

app.put("/books/:id", (req, res) => {
  const id = Number(req.params.id);
  const index = books.findIndex((b) => b.id === id);
  if (index === -1) return res.status(404).json({ error: "Book not found" });
  books[index] = { ...req.body, id };
  res.json(books[index]);
});

app.patch("/books/:id", (req, res) => {
  const id = Number(req.params.id);
  const book = books.find((b) => b.id === id);
  if (!book) return res.status(404).json({ error: "Book not found" });
  Object.assign(book, req.body, { id });
  res.json(book);
});

The same body, {"stock": 7}, is sent to book 2 with each of the two methods. The result:

Request Book 2 afterwards
PATCH /books/2 {"id":2,"title":"This Earth of Mankind","author_id":2,"price":125000,"stock":7}
PUT /books/2 {"stock":7,"id":2}

So when you only want to change some fields, say only a student's name, use PATCH. Use PUT when you send the whole record.

Delete: 204, then 404

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

The first DELETE /books/3 gets 204. The second DELETE /books/3 gets 404, and so does GET /books/3, because the book is gone.

⚠️ Small bugs that make CRUD answer wrong

const { title, author_id, price, stock } = req.body;
const book = { id: nextId++, title, author_id, price, stock };

Any other field in the body, for example "is_featured": true, does not get into book, because the code copies only the four fields it names.

TL;DR: CRUD is the four operations on data: Create, Read, Update, Delete. Create: POST /books builds { ...req.body, id: nextId++ } (the client's body, with an id the server picks) and adds it to the array with push. Then it answers res.status(201) with a Location header (the new book's address). Read: GET /books for the list, and GET /books/:id for one book. An id from the URL is text, so convert it with Number(req.params.id) before you look for it with find. Update: PUT replaces the whole record (fields not sent are gone), while PATCH changes only the fields that were sent. For a partial update, use PATCH. Delete: find the book's position with findIndex, remove it with splice, then answer res.status(204).send() with no body. An id that doesn't exist gets 404 on read, update and delete, including a second DELETE of the same book. In a real API, copy only the fields the client may fill in, so a body like {"role": "admin"} is not saved (the mass assignment hole).

⚡ CRUD over HTTP

Meaning: CRUD is the four operations on data: Create, Read, Update, Delete. Create is POST /books (201), Read is GET (200), Update is PUT or PATCH (200), and Delete is DELETE (204). An id that doesn't exist gets 404 on read, update and delete.

⚡ Create: 201 and Location

Write:

app.post("/books", (req, res) => {
  const book = { ...req.body, id: nextId++ };
  books.push(book);
  res.set("Location", "/books/" + book.id);
  res.status(201).json(book);
});

Meaning: books is the array where the books are kept, and nextId is the id for the next book. ...req.body copies the fields the client sent. id is written last, so it replaces any id from the body: the server picks the number, not the client. The Location header gives the new book's address.

⚡ PUT replaces, PATCH patches

Guess first: book 2 has the fields title, author_id, price and stock. The body {"stock": 7} is sent to book 2 with PUT /books/2. What does book 2 hold afterwards?

Only {"stock":7,"id":2}. Its title, author and price are gone, because PUT builds a new object from the body alone. The id is still there because the server adds it from the URL.

Meaning: PUT replaces the whole book. PATCH writes only the fields that were sent, and the other fields stay. So when you only want to change some fields, say only a student's name, use PATCH.

⚡ Delete: check first, then splice

Write:

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

Meaning: findIndex gives the book's position in the array books, or -1 when the book isn't there. splice(index, 1) removes one item at that position, and 204 means it worked, with no body. Check index === -1 first. Without that check, books.splice(-1, 1) removes the last book, because -1 means "from the end".

What you will learn