Thuta Learning
API Tutorial
AdvancedWeb DevelopmentIntermediate

Update User

API TutorialLesson 1740 min

What you'll walk away with

  • Choose between PUT and PATCH and show the difference when an optional field is left out
  • Treat a missing field and an explicit null differently in a PATCH
  • Keep server-owned fields (id, role) immutable and validate the merged result
  • Prevent lost updates with ETag and If-Match, handling a 412 by re-reading and trying again

Explain it simply

Updating in plain language

Updating is editing a file that already exists. There are two ways to hand over the edit. PUT is like handing back the whole form: "this is what the user looks like now", and anything you leave off is gone. PATCH is a sticky note: "change the name to Alice K.", and everything else stays. The second problem is two people editing at once. If you and a colleague both open Bob's file and both save, whoever saves last silently erases the other's change, unless the server checks that the file is still the version you started from.

Problem → Why → Solution

The problem: the last write wins

A support agent opens Alice's profile and changes her name. At the same moment an admin edits her bio. Both screens loaded the same record. The agent's tool saves with PUT and sends back the whole form including the old bio, so the admin's change disappears and nobody sees an error. That is a lost update. A second bug hides in the same endpoint: PUT /v1/users/u_1 with only { "name": "Alice K." } resets every field the client did not mention, and a request containing "role": "admin" lets a member promote themself.

last-write-wins.js
// Last write wins: no version check, and the body overwrites everything
app.put("/v1/users/:id", async (req, res) => {
  await db.users.update(req.params.id, req.body); // role, id... all writable
  res.json(await db.users.findById(req.params.id));
});

Both failures are silent

Two things go wrong silently. A stale client can overwrite newer data because the server never asks "are you editing the version I have now?", and a careless merge can reset or overwrite fields the caller never meant to touch. Neither produces an error message, which is why you only find out when a user complains.

Core concept: PUT, PATCH and the version check

PUT replaces the resource's writable representation with the body you send. It is idempotent: sending it twice leaves the same result. Fields you omit are reset to their defaults (here bio becomes null), and required fields must be present, so PUT /v1/users/u_1 with only a name is a 422. PATCH changes only the fields present in the body and leaves the rest alone. The HTTP standard does not promise PATCH is idempotent (a patch such as "add one" is not), though a patch that sets fields to values is. Most APIs use PATCH for form edits and keep PUT for "save the whole document".

In a PATCH, a field that is missing means "leave it alone", while an explicit null means "clear it". { "name": "Alice K." } keeps the bio, and { "bio": null } erases it. JavaScript can tell them apart with 'bio' in body, which is why the server checks that a key is present instead of checking truthiness; a truthiness check would make it impossible to clear a value or to set an empty string. Required fields cannot be cleared: { "email": null } is a 422.

MethodThe body meansA field you leave out
PUTThe complete writable representationReset (bio becomes null); required ones give 422
PATCHOnly the fields to changeLeft alone
PATCH { bio: null }Clear this one fieldNot applicable, the key is present

Both methods share the creation rules: only name, email and bio are writable, id and role are ignored if they appear in the body, and the merged result is validated as a whole, because a PATCH that looks fine alone can still produce an invalid record. Changing the email to one that belongs to another user is a 409, exactly as on create. A user that does not exist is a 404; an update never creates one.

To prevent lost updates, give each version of a user an ETag and make the client say which version it is editing: If-Match: "v2". The server compares it with the current ETag. If it matches, the write goes ahead and the response carries the new ETag ("v3"). If another client saved in the meantime, the ETag has moved on, and the server answers 412 Precondition Failed without changing anything. The loser re-reads the user, decides how to merge (or asks the person), and sends the update again with the fresh ETag. This is called optimistic concurrency because it locks nothing: it assumes conflicts are rare and detects them when they happen. Whether If-Match is optional, as in this sample where a missing header means last-write-wins, or required (answer 428 Precondition Required) is a policy choice; required is safer for data that people edit by hand.

Check the version, merge, validate, bump
  1. Client reads the user and its ETag
  2. Client sends PUT/PATCH + If-Match
  3. Server merges, validates the result
  4. Same ETag? Save and bump it; else 412

If-Match is a promise: "apply this edit only if the user is still exactly the version I saw."

General pattern

text
PATCH /v1/<collection>/<id>
If-Match: "<etag from the last read>"
Content-Type: application/json

{ <only the fields to change; null clears one> }

200 OK  ETag: "<new etag>"  { <the updated resource> }
412 Precondition Failed      (someone else changed it first)

You send the ETag from your last read back as If-Match. On success you receive the new ETag and the updated resource; if someone else changed it first, you receive 412.

Worked example: PUT, PATCH and a stale update

The sample runs a users API on a random local port with Alice and Bob. The first six lines show the PUT/PATCH differences: PATCH keeps the bio, PUT nulls it, a PUT without an email is a 422, id and role are ignored, null clears the bio, and changing to someone else's email is a 409. The last three lines are two clients reading Bob at the same moment: A saves, B gets a 412, and B re-reads and succeeds.

users-update.mjs
import http from "node:http";

// The users API (stands in for https://api.example.com/v1/users)
const row = (n, name, role, bio = null) => ({
  id: "u_" + n,
  name,
  email: name.toLowerCase() + "@example.com",
  role,
  bio,
  version: 1,
});
const users = new Map([
  ["u_1", row(1, "Alice", "admin", "Maintainer")],
  ["u_2", row(2, "Bob", "member")],
]);

const WRITABLE = ["name", "email", "bio"]; // id and role are never taken from a body
const publicView = ({ id, name, email, role, bio }) => ({ id, name, email, role, bio });
const etagOf = (user) => '"v' + user.version + '"';
const looksLikeEmail = (s) => typeof s === "string" && /^[^@ ]+@[^@ ]+[.][^@ ]+$/.test(s);

const send = (res, status, body, headers = {}) => {
  res.writeHead(status, { "Content-Type": "application/json", ...headers });
  res.end(JSON.stringify(body));
};
const fail = (res, status, code, message, fields) =>
  send(res, status, { error: { code, message, ...(fields && { fields }) } });

async function readJsonObject(req) {
  let raw = "";
  for await (const chunk of req) raw += chunk;
  try {
    const value = JSON.parse(raw);
    return value?.constructor === Object ? value : null; // plain objects only
  } catch {
    return null;
  }
}

// PUT replaces the writable representation; PATCH changes only what was sent
function merge(method, user, input) {
  const next = { ...user };
  for (const key of WRITABLE) {
    if (key in input) next[key] = input[key]; // sent: take it (null clears)
    else if (method === "PUT") next[key] = null; // PUT: a missing field is reset
  }
  return next;
}

function validate(user) {
  const fields = {};
  if (typeof user.name !== "string" || !user.name.trim()) fields.name = "is required";
  if (user.email === null) fields.email = "is required";
  else if (!looksLikeEmail(user.email)) fields.email = "must be a valid email address";
  return fields;
}

const server = http.createServer(async (req, res) => {
  const [, , resource, id] = new URL(req.url, "http://localhost").pathname.split("/");
  const user = users.get(id);
  if (resource !== "users" || !user) {
    return fail(res, 404, "user_not_found", "No user " + id);
  }
  if (req.method === "GET") {
    return send(res, 200, publicView(user), { ETag: etagOf(user) });
  }
  if (req.method !== "PUT" && req.method !== "PATCH") {
    const error = { code: "method_not_allowed", message: "Use GET, PUT or PATCH" };
    return send(res, 405, { error }, { Allow: "GET, PUT, PATCH" });
  }

  // Optimistic concurrency: a client that names the version it edited
  // must still be looking at the current one
  const ifMatch = req.headers["if-match"];
  if (ifMatch && ifMatch !== etagOf(user)) {
    return fail(res, 412, "precondition_failed", "The user changed since you read it");
  }

  const input = await readJsonObject(req);
  if (!input) return fail(res, 400, "invalid_json", "Body must be a JSON object");

  const next = merge(req.method, user, input);
  const fields = validate(next);
  if (Object.keys(fields).length) {
    return fail(res, 422, "validation_failed", "One or more fields are invalid", fields);
  }
  next.email = next.email.trim().toLowerCase();
  const taken = [...users.values()].some((u) => u.id !== id && u.email === next.email);
  if (taken) {
    return fail(res, 409, "email_taken", "A user with this email already exists");
  }

  next.version = user.version + 1;
  users.set(id, next);
  send(res, 200, publicView(next), { ETag: etagOf(next) });
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = "http://127.0.0.1:" + server.address().port;

// The client
async function call(method, path, body, headers = {}) {
  const res = await fetch(base + path, {
    method,
    headers: { "Content-Type": "application/json", ...headers },
    body: body === undefined ? undefined : JSON.stringify(body),
  });
  return { status: res.status, etag: res.headers.get("etag"), data: await res.json() };
}
function show(label, r) {
  const detail = r.data.error
    ? r.data.error.code + " " + JSON.stringify(r.data.error.fields ?? {})
    : JSON.stringify(r.data, ["name", "bio", "role"]);
  console.log(label.padEnd(14), r.status, r.etag ?? "-", detail);
}

const alice = "/v1/users/u_1";
const bob = "/v1/users/u_2";
show("PATCH name", await call("PATCH", alice, { name: "Alice K." }));
const keepEmail = { name: "Alice K.", email: "alice@example.com" };
show("PUT, no bio", await call("PUT", alice, keepEmail));
show("PUT, no email", await call("PUT", alice, { name: "Alice K." }));
show("PATCH extras", await call("PATCH", bob, { id: "u_9", role: "admin", bio: "Hi" }));
show("PATCH null", await call("PATCH", bob, { bio: null }));
show("PATCH email", await call("PATCH", bob, { email: "alice@example.com" }));

// Two clients read Bob at the same moment...
const a = await call("GET", bob);
const b = await call("GET", bob);
show("A saves", await call("PATCH", bob, { name: "Robert" }, { "If-Match": a.etag }));
show("B is stale", await call("PATCH", bob, { name: "Bobby" }, { "If-Match": b.etag }));
// ...B re-reads, sees Robert, and edits again on top of the fresh version
const fresh = await call("GET", bob);
const retry = { "If-Match": fresh.etag };
show("B retries", await call("PATCH", bob, { bio: "Hi from B" }, retry));
server.close();

Code breakdown

  1. Writable allowlistconst WRITABLE = ["name", "email", "bio"]; // id and role are never taken from a body

    merge copies only the keys on this list from the input, which is why the PATCH extras line sends id: "u_9" and role: "admin" and nothing changes.

  2. Present versus missingif (key in input) next[key] = input[key]; // sent: take it (null clears)

    If the key is present its value is taken, null included, so PATCH { bio: null } clears the bio. The in operator checks only that the key exists, not whether the value is truthy.

  3. PUT resetselse if (method === "PUT") next[key] = null; // PUT: a missing field is reset

    In a PUT, every writable field that did not arrive is set to null, so a PUT without bio erases the bio and a PUT without name or email fails validation.

  4. Validate the merged resultconst fields = validate(next);

    The merged record is validated, not the raw input, so PUT and PATCH share one set of rules and a problem like email: null is caught.

  5. The preconditionif (ifMatch && ifMatch !== etagOf(user)) {

    If the If-Match the client sent differs from the current ETag, nothing is written and the answer is 412. B's "v3" no longer equals "v4" after A saved.

  6. Bump the versionnext.version = user.version + 1;

    Every successful write bumps the version and so produces a new ETag. A validation failure, a 409 or a 412 does not bump it, because nothing changed.

You should see
PATCH name     200 "v2" {"name":"Alice K.","bio":"Maintainer","role":"admin"}
PUT, no bio    200 "v3" {"name":"Alice K.","bio":null,"role":"admin"}
PUT, no email  422 - validation_failed {"email":"is required"}
PATCH extras   200 "v2" {"name":"Bob","bio":"Hi","role":"member"}
PATCH null     200 "v3" {"name":"Bob","bio":null,"role":"member"}
PATCH email    409 - email_taken {}
A saves        200 "v4" {"name":"Robert","bio":null,"role":"member"}
B is stale     412 - precondition_failed {}
B retries      200 "v5" {"name":"Robert","bio":"Hi from B","role":"member"}
How the server handles PUT and PATCH
  1. Find the user (404 if missing)
  2. Compare If-Match with the current ETag
  3. Merge the allowlisted fields
  4. Validate, check email clashes, save, bump version

ETag matches and validation passes

200 with the updated user and a new ETag

ETag differs or validation fails

412, 422 or 409 and nothing is written

What to do when you get a 412

A 412 is not a plain error; it is news that someone else changed the resource. The client must not just resend: the old ETag would give another 412, and removing If-Match would wipe out the other person's edit. The correct sequence is this.

Re-read the user

Call GET /v1/users/u_2 to get the current version and its new ETag.

Decide what the difference means

If different fields changed (A the name, B the bio) you can merge automatically. If the same field changed, show the person both values and let them choose.

Send again with the fresh ETag

Send the edit with If-Match set to the new ETag. If you get another 412, repeat the sequence, with a limit on attempts.

text
PATCH /v1/users/u_2 HTTP/1.1
Host: api.example.com
Content-Type: application/json
If-Match: "v3"

{ "name": "Bobby" }

HTTP/1.1 412 Precondition Failed
Content-Type: application/json

{ "error": { "code": "precondition_failed",
             "message": "The user changed since you read it" } }

PATCH with curl, and JSON Merge Patch

The PATCH style in this lesson (send only the fields to change, null clears) is standardised as JSON Merge Patch (RFC 7396, media type application/merge-patch+json). Its limits are that an array is replaced as a whole and that null cannot be a value. For more complex edits, JSON Patch (RFC 6902) sends a list of operations instead. Some APIs accept plain application/json and others insist on the merge-patch media type, so check the docs.

bash
curl -i -X PATCH https://api.example.com/v1/users/u_2 \
  -H "Content-Type: application/json" \
  -H 'If-Match: "v3"' \
  -d '{"name":"Bobby"}'

In real projects

Update endpoints in real projects

Any data that people edit by hand (profiles, product descriptions, documents) can suffer lost updates, which is why admin consoles, CMSs and collaborative apps use ETags or a version field. Some APIs put a version or updated_at field in the body instead of using a header; the idea is the same. A mobile app that syncs offline edits back also checks the version to detect conflicts.

  • A frontend form sends a PATCH containing only the changed fields, so it does not trample edits made in another tab.
  • When a 412 arrives, the UI asks "someone else changed this user, view the new version?".
  • An audit log records who changed which field from what to what, and a PATCH already carries the list of changed fields, which helps.

Common mistakes

Common update mistakes

Sending a partial body with PUT

A PUT with only a name resets the other fields or gives a 422, by the PUT rules. To change a few fields use PATCH; for PUT, edit the full representation you got from GET and send it back.

Checking truthiness instead of presence

if (body.bio) drops null and "", so the bio can no longer be cleared. Check that the key exists with 'bio' in body or Object.hasOwn(body, "bio").

Accepting id and role from the body

An update endpoint can suffer mass assignment too: a member sends { "role": "admin" } and promotes themself. Define the writable fields explicitly, and give role changes a separate admin-only endpoint.

Answering a 412 by resending without If-Match

Dropping the header to get past a 412 brings back last-write-wins and loses the other person's edit. Re-read, merge, and send with the new ETag.

Best practices

Best practices

  • Keep the list of writable fields in one place in the code and share it between PUT and PATCH.
  • Return the full resource with the new ETag, so the client can make its next edit without another GET.
  • For data people edit by hand, make If-Match required and answer 428 when it is missing.

Mini challenge

Write applyUpdate yourself

Write applyUpdate(user, method, input, ifMatch) without HTTP. Return 412 when ifMatch is given and is not "v" + user.version. PATCH must leave missing fields alone and let null clear one. PUT must set a missing bio to null. Return 422 with the names of the problem fields when name or email is missing or empty, otherwise 200 with version + 1. Ignore id and role from the input.

  • Check ifMatch only when it is given, and return { status: 412 } if it differs
  • PATCH: change a field only when its key is present; PUT: a missing writable field becomes null
  • A bad name or email gives { status: 422, fields: [...] }
  • On success bump the version by one and leave id and role unchanged
apply-update.js
const WRITABLE = ["name", "email", "bio"];

function applyUpdate(user, method, input, ifMatch = null) {
  // TODO: 412 when ifMatch is given and is not "v" + user.version
  // TODO: PATCH keeps fields that are missing; "bio": null clears bio
  // TODO: PUT resets a missing writable field to null
  // TODO: ignore id and role from the input
  // TODO: 422 when name or email is missing or empty, else 200 with version + 1
}

Expected: Six lines: PATCH name keeps the bio, PATCH null clears it, a PUT without bio nulls it, a PUT without email is 422 email, PATCH role changes nothing, and the stale request is 412.

Show hint

Start from next = { ...user } and loop over WRITABLE, using key in input to test presence. id and role are protected automatically because they are not in WRITABLE. Testing ifMatch !== null allows requests that carry no If-Match.

Show solution
apply-update-solution.js
const WRITABLE = ["name", "email", "bio"];
const etagOf = (u) => '"v' + u.version + '"';

function applyUpdate(user, method, input, ifMatch = null) {
  if (ifMatch !== null && ifMatch !== etagOf(user)) {
    return { status: 412, error: "precondition_failed" };
  }
  const next = { ...user };
  for (const key of WRITABLE) {
    if (key in input) next[key] = input[key];
    else if (method === "PUT") next[key] = null;
  }
  const fields = [];
  if (typeof next.name !== "string" || !next.name.trim()) fields.push("name");
  if (typeof next.email !== "string" || !next.email.includes("@")) fields.push("email");
  if (fields.length) return { status: 422, error: "validation_failed", fields };
  return { status: 200, user: { ...next, version: user.version + 1 } };
}

const alice = {
  id: "u_1",
  name: "Alice",
  email: "alice@example.com",
  role: "admin",
  bio: "Maintainer",
  version: 1,
};

function show(label, r) {
  const u = r.user;
  const detail = u
    ? etagOf(u) + " name=" + u.name + " bio=" + u.bio + " role=" + u.role
    : r.error + (r.fields ? " " + r.fields.join(",") : "");
  console.log(label.padEnd(13), r.status, detail);
}
show("PATCH name", applyUpdate(alice, "PATCH", { name: "Alice K." }));
show("PATCH null", applyUpdate(alice, "PATCH", { bio: null }));
show("PUT, no bio", applyUpdate(alice, "PUT", { name: "Alice K.", email: alice.email }));
show("PUT, no email", applyUpdate(alice, "PUT", { name: "Alice K." }));
show("PATCH role", applyUpdate(alice, "PATCH", { role: "member", id: "u_9" }));
show("stale", applyUpdate(alice, "PATCH", { name: "X" }, '"v0"'));

Quick quiz 1 / 3

A user has bio: "Maintainer". A client sends PUT /v1/users/u_1 with { name: "Alice K.", email: "alice@example.com" } and no bio. What is the bio afterwards?

Quick quiz 2 / 3

In a PATCH, what does { "bio": null } mean?

Quick quiz 3 / 3

Client B sends a PATCH with If-Match: "v3", but another client already saved, so the user is at v4. What should the server and B do?

What to remember

  • PUT replaces the whole writable representation (missing fields reset); PATCH changes only the fields sent, null clears, and a missing key means leave it.
  • Never take server-owned fields such as id and role from the body, validate the merged result, answer 409 for an email clash and 404 for a missing user.
  • Prevent lost updates with ETag + If-Match: a version mismatch is 412, after which you re-read, merge and resend with the new ETag.
  • Whether If-Match is optional or required (428) is a policy choice; required is better for data that people edit.

RFC 9110 — HTTP Semantics — IETF

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Update User | Thuta Learning