4 min read
ā¢Question 4 of 28easyWhat is the difference between PUT and PATCH?
Understanding PUT vs PATCH for updates.
What You'll Learn
- PUT method usage
- PATCH method usage
- When to use each
PUT vs PATCH
| Feature | PUT | PATCH |
|---|---|---|
| Update type | Full replacement | Partial update |
| Required data | Complete resource | Only changed fields |
| Idempotent | Yes | Yes |
PUT Example
code.jsJavaScript
// Replace entire user object
PUT /api/users/1
{
"id": 1,
"name": "John Updated",
"email": "john@example.com",
"age": 30,
"role": "admin"
}
// All fields required, missing fields become null/defaultPATCH Example
code.jsJavaScript
// Update only specific fields
PATCH /api/users/1
{
"name": "John Updated"
}
// Only name changes, other fields remain unchangedNode.js Implementation
code.jsJavaScript
// PUT - replace entire resource
app.put('/users/:id', (req, res) => {
users[req.params.id] = req.body;
res.json(users[req.params.id]);
});
// PATCH - merge updates
app.patch('/users/:id', (req, res) => {
users[req.params.id] = { ...users[req.params.id], ...req.body };
res.json(users[req.params.id]);
});