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);
});
:idis a path parameter. For/books/1,req.params.idholds"1"."1"is text, not a number.1 === "1"isfalse. So withoutNumber(...)(orparseInt),findnever finds a book, and every id gets404.findlooks for the first book whose id matches. When nothing matches, it returnsundefined. Check for that withif (!book), then answer404.returnstops the handler right there, so it doesn't answer twice.
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);
});
...req.bodycopies every field the client sent into a new object.- The server picks the id. In an object, a field written later replaces a field with the same name written earlier. Because
idis written last, anyidin the body is replaced, so the client can't pick its own id.nextId++uses the value 4 first, then raises it to 5 for the next book. res.set("Location", ...)tells the client the new book's address.res.status(201)sets the status before.json(...)sends the body.
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);
});
PUTfinds the book withfindIndex, which gives the book's position in the array, or-1when the book isn't there. Thenbooks[index] = ...replaces the book at that position with a new object built from the body alone. Fields that weren't sent are gone.PATCHfinds the book withfind. ThenObject.assignwrites the fields that were sent over that book's fields. Fields that weren't sent stay as they were.idis written last in both endpoints, so a body of{"id": 99}can't change the book's number.if (...) return res.status(404)...is the same404check as in Read one, written on one line.
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();
});
- As in
PUT,findIndexgives the book's position, or-1when the book isn't there. splice(index, 1)removes one item of the array at that position.204 No Contentmeans it worked, with no body.res.status(204).send()sends that response with nothing in it.
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
- Comparing a text id with a number.
b.id === req.params.idis alwaysfalse, becauseb.idis a number andreq.params.idis text. Convert it first withNumber(...)orparseInt(...). - Answering a create with 200.
res.json(book)on its own answers200. New data getsres.status(201).json(...). - Forgetting the 404. Without the
if (!book)check, an id that doesn't exist gets200with an empty body. In delete the result is worse. Without theindex === -1check, the code runsbooks.splice(-1, 1), and that removes the last book, because-1means "from the end". - A body on a 204.
res.status(204).json({ message: "Deleted" })sends nothing, because Express drops the body from a204response. If you want to send a confirmation, use200with a body. - Saving any field the client sends. The code above, with
{ ...req.body }andObject.assign(book, req.body), protects onlyid. Every other field is saved too, including fields the client must not change. Example: a profile is changed withPATCHand the body{"name": "Sam", "role": "admin"}, and Sam becomes an admin. This security hole is called mass assignment. In a real API, copy only the fields the client may fill in:
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".