0
0
Expressframework~30 mins

PUT and PATCH route handling in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
PUT and PATCH Route Handling in Express
📖 Scenario: You are building a simple Express server to manage a list of books. Each book has an id, title, and author. You want to allow users to update book details either fully or partially.
🎯 Goal: Create two routes in Express: a PUT route to fully replace a book's details, and a PATCH route to update only some fields of a book.
📋 What You'll Learn
Create an array called books with three book objects, each having id, title, and author.
Create a variable app by calling express() and use express.json() middleware.
Create a PUT route at /books/:id that replaces the entire book object with the request body if the book exists.
Create a PATCH route at /books/:id that updates only the provided fields of the book if it exists.
💡 Why This Matters
🌍 Real World
APIs often need to let users update data fully or partially. PUT replaces the whole item, PATCH changes only some parts.
💼 Career
Understanding PUT and PATCH routes is essential for backend developers building RESTful APIs with Express.
Progress0 / 4 steps
1
Create the initial books array
Create an array called books with these exact objects: { id: 1, title: '1984', author: 'George Orwell' }, { id: 2, title: 'Brave New World', author: 'Aldous Huxley' }, and { id: 3, title: 'Fahrenheit 451', author: 'Ray Bradbury' }.
Express
Need a hint?

Use const books = [ ... ] with three objects inside.

2
Set up Express app and JSON middleware
Create a variable called app by calling express(). Then add JSON parsing middleware by calling app.use(express.json()).
Express
Need a hint?

Remember to import express first with const express = require('express').

3
Create the PUT route to replace a book
Create a PUT route at /books/:id. Inside, find the book with id matching Number(req.params.id). If found, replace the entire book object in books with req.body. Use res.status(200).send() to send the updated book. If not found, send status 404.
Express
Need a hint?

Use findIndex to locate the book, then replace it with req.body.

4
Create the PATCH route to update part of a book
Create a PATCH route at /books/:id. Find the book with id matching Number(req.params.id). If found, update only the fields present in req.body on the book object. Send the updated book with res.status(200).send(). If not found, send status 404.
Express
Need a hint?

Use Object.assign to update only the fields sent in req.body.