PUT and PATCH let your server update data sent by users. They help keep information fresh and correct.
PUT and PATCH route handling in Express
Introduction
Syntax
Express
app.put('/path/:id', (req, res) => { // Replace entire item with req.body }); app.patch('/path/:id', (req, res) => { // Update parts of item with req.body });
PUT expects the full new data for the item.
PATCH expects only the fields to change.
Examples
Express
app.put('/users/:id', (req, res) => {
// Replace whole user data
});Express
app.patch('/users/:id', (req, res) => {
// Update some user fields
});Express
app.put('/products/:id', (req, res) => {
// Replace product info
});Express
app.patch('/products/:id', (req, res) => {
// Change product price only
});Sample Program
This example shows a simple server with users data. PUT replaces the whole user info except the id. PATCH changes only the fields sent in the request.
Express
import express from 'express'; const app = express(); app.use(express.json()); let users = [ { id: '1', name: 'Alice', age: 25 }, { id: '2', name: 'Bob', age: 30 } ]; // PUT replaces entire user app.put('/users/:id', (req, res) => { const { id } = req.params; const index = users.findIndex(u => u.id === id); if (index === -1) { return res.status(404).send('User not found'); } // Replace whole user data, keep id same users[index] = { id, ...req.body }; res.send(users[index]); }); // PATCH updates parts of user app.patch('/users/:id', (req, res) => { const { id } = req.params; const user = users.find(u => u.id === id); if (!user) { return res.status(404).send('User not found'); } // Update only given fields Object.assign(user, req.body); res.send(user); }); app.listen(3000, () => console.log('Server running on port 3000'));
Important Notes
PUT is like replacing a whole book page; PATCH is like editing a few words.
Always check if the item exists before updating.
Use express.json() middleware to read JSON data from requests.
Summary
PUT replaces the entire resource with new data.
PATCH updates only specific fields of a resource.
Both are used to update data on the server in APIs.
Practice
1. What is the main difference between
PUT and PATCH methods in Express route handling?easy
Solution
Step 1: Understand HTTP method semantics
PUTis designed to replace the entire resource with the new data sent in the request.Step 2: Understand
PATCHbehaviorPATCHupdates only the fields specified in the request, leaving other fields unchanged.Final Answer:
PUTreplaces the entire resource, whilePATCHupdates only specified fields. -> Option BQuick Check:
PUT replaces, PATCH updates partial [OK]
Hint: Remember: PUT replaces all, PATCH changes parts only [OK]
Common Mistakes:
- Confusing PUT and PATCH behavior
- Thinking PATCH deletes resources
- Assuming PUT only updates parts
2. Which of the following is the correct way to define a
PATCH route in Express to update a user by ID?easy
Solution
Step 1: Identify the HTTP method for partial updates
PATCHis used to update parts of a resource, so the route should useapp.patch.Step 2: Check route syntax
The route path includes/:idto specify which user to update, and the handler function is correctly defined.Final Answer:
app.patch('/user/:id', (req, res) => { /* update logic */ }); -> Option CQuick Check:
PATCH route uses app.patch() [OK]
Hint: PATCH routes use app.patch(path, handler) syntax [OK]
Common Mistakes:
- Using app.put instead of app.patch for partial updates
- Using app.get or app.post incorrectly
- Missing route parameter syntax
3. Given this Express code snippet, what will be the response after a
PATCH request to /product/5 with JSON body {"price": 20}?
const products = { 5: { name: "Pen", price: 10, stock: 100 } };
app.patch('/product/:id', (req, res) => {
const id = req.params.id;
Object.assign(products[id], req.body);
res.json(products[id]);
});medium
Solution
Step 1: Understand the initial product data
Product with ID 5 has name "Pen", price 10, and stock 100.Step 2: Analyze the PATCH handler logic
The handler usesObject.assignto update the product with fields fromreq.body. The JSON body contains {"price": 20}, so only the price changes.Final Answer:
{"name":"Pen","price":20,"stock":100} -> Option AQuick Check:
PATCH updates price only, other fields stay same [OK]
Hint: PATCH merges fields; unchanged fields remain [OK]
Common Mistakes:
- Expecting full replacement of product data
- Ignoring unchanged fields
- Assuming error due to missing fields
4. What is wrong with this Express
PUT route handler?
app.put('/item/:id', (req, res) => {
const id = req.params.id;
items[id] = req.body;
res.send('Item updated');
});
Assuming items is an object storing item data.medium
Solution
Step 1: Check if JSON body parsing middleware is used
Withoutexpress.json()middleware,req.bodywill be undefined for JSON requests.Step 2: Identify the impact on the handler
Assigningitems[id] = req.bodywill set the item to undefined, causing data loss or errors.Final Answer:
It does not parse JSON body, soreq.bodywill be undefined. -> Option DQuick Check:
Missing express.json() causes undefined req.body [OK]
Hint: Always use express.json() to read JSON request bodies [OK]
Common Mistakes:
- Forgetting to add express.json() middleware
- Confusing PUT and PATCH usage
- Ignoring response content type
5. You want to implement a
PUT route to replace a user profile but keep the id field unchanged. Which approach correctly handles this in Express?hard
Solution
Step 1: Understand
PUTsemanticsPUTreplaces the entire resource, so the user object will be overwritten byreq.body.Step 2: Preserve the
Sinceidfieldidshould not change, after overwriting, manually setuser.idback to the original value.Final Answer:
Overwrite the entire user object withreq.bodyexcept manually setidback after assignment. -> Option AQuick Check:
PUT replaces all; preserve id manually [OK]
Hint: PUT replaces all; reset id manually after update [OK]
Common Mistakes:
- Using PATCH when full replacement is needed
- Allowing id to be overwritten unintentionally
- Deleting and recreating user unnecessarily
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
