principlejavascriptMajor
HTTP PUT vs PATCH: PUT Replaces, PATCH Updates
Viewed 0 times
putpatchidempotentpartial updatereplacerest semantics
Problem
Developers use PUT to send partial updates, causing the server to overwrite fields that were not included in the request body, silently deleting data.
Solution
Use PUT only to replace the entire resource. Use PATCH for partial updates. PUT must be idempotent — sending the same PUT twice produces the same result. PATCH is not required to be idempotent.
// Correct: PATCH for partial update
await fetch(`/users/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email: 'new@example.com' })
});
// Wrong: PUT with partial body silently drops other fields
await fetch(`/users/${id}`, {
method: 'PUT',
body: JSON.stringify({ email: 'new@example.com' }) // name, role, etc. get wiped
});Why
RFC 7231 defines PUT as replacing the target resource's current representation. Servers that treat PUT as a merge operation are non-conformant and create surprising behavior.
Gotchas
- Some ORMs like Sequelize
update()do partial updates regardless of HTTP verb — the semantics are enforced by your route handler. - PATCH requests should describe the change, not the new state, but JSON Merge Patch (RFC 7396) is a common simpler alternative.
- PUT requires the client to send the full resource, which can cause race conditions if two clients read-modify-write concurrently.
Revisions (0)
No revisions yet.