What is the difference between PUT and PATCH in a REST API?
PUT replaces the whole resource with the body you send, so missing fields are cleared. PATCH changes only the fields you send. PUT is idempotent by definition; PATCH is not guaranteed to be.
Explain it simply
Imagine a student's record card. With PUT you hand the office a completely new card and they throw the old one away. If you forgot to write the phone number on the new card, the phone number is gone. With PATCH you hand over a sticky note saying "change the phone number to this" and everything else stays as it was.
Example
Existing record: { "name": "Anjali", "city": "Pune", "phone": "98xxxxxx10" }
PUT /students/7
{ "name": "Anjali", "city": "Jamshedpur" }
=> record becomes { "name": "Anjali", "city": "Jamshedpur" } (phone removed)
PATCH /students/7
{ "city": "Jamshedpur" }
=> record becomes { "name": "Anjali", "city": "Jamshedpur", "phone": "98xxxxxx10" }app.patch("/students/:id", async (req, res) => {
const updated = await Student.findByIdAndUpdate(
req.params.id,
{ $set: req.body }, // only the sent fields
{ new: true }
);
if (!updated) return res.status(404).json({ error: "Not found" });
res.json(updated);
});Idempotent means repeating the same request gives the same final state. Sending the same PUT twice leaves the same record. A PATCH like "increase marks by 5" is not idempotent, though "set city to Pune" is.
What to say in the interview
"PUT is a full replacement and idempotent; PATCH is a partial update. I use PATCH for small edits like profile changes and PUT when the client holds the complete resource, and I validate the body in both cases."
Common mistakes
- Using PUT with a partial body and wiping other fields.
- Using POST for every update.