Explain it simply
Deleting in plain language
Deleting is the last step of the life cycle you built across the previous three lessons: create, read, update, delete. DELETE /v1/users/u_3 means "remove this user". If it works the server answers 204 No Content: success, and nothing to send back, because the resource you would describe no longer exists. The interesting questions are around it: what happens if you delete the same user twice, what if the user must not be removed, and does "removed" really mean the data is gone?
Problem → Why → Solution
The problem: a one-line delete that checks nothing
A first delete endpoint is usually one line: remove the row, reply with { "success": true }. It has three holes. The reply has a body for a resource that no longer exists, so clients have no consistent shape to rely on. Nothing stops an admin from deleting the last administrator, leaving a system in which nobody can manage users. And a client that retries after a timeout meets unpredictable behaviour: the second DELETE crashes with a 500 because the row it expects is already gone. Later, when legal asks for a person's data to be erased, the team finds that the endpoint only flipped a flag.
app.delete("/v1/users/:id", async (req, res) => {
await db.users.delete(req.params.id); // throws if the row is already gone
res.json({ success: true }); // 200 with a body, and no rules checked
});A delete is hard to undo, so the contract must be exact
A delete is a state change that people cannot easily undo, so the contract has to be exact: which status on success, what a repeat means, which rules can block it, and what "deleted" means for the stored data. Client retries after timeouts are normal, so an endpoint that fails on the second call turns a harmless retry into an incident.
Core concept: 204, idempotency and the rules that block a delete
DELETE /v1/users/{id} asks the server to remove the resource. Success is 204 No Content: no body, and the client must not try to parse one (calling res.json() on a 204 throws SyntaxError: Unexpected end of JSON input). Some APIs return 200 with a short body or with the deleted resource; both are allowed, but 204 is the usual choice and the one used in this chapter.
DELETE is idempotent: HTTP defines that as "the intended effect on the server of several identical requests is the same as for one", and here the intended effect is that the user is gone. It does not say the response must be the same. After the first call returns 204, a second call finds nothing. APIs differ: some answer 404 again, others answer 204 every time. This API answers 404 user_not_found, because that tells the client the truth: there was nothing to delete this time. The price is that a client that retried after a timeout cannot tell whether its first attempt worked or the user never existed; for a cleanup the rule is simple: treat 404 as "already gone" and carry on. Choose one rule, document it and keep it across every resource. Do not assume other APIs do the same.
Business rules can block a delete. If the user is the last administrator, or still owns open orders, the server answers 409 Conflict with the usual error body (code last_admin) and deletes nothing. Authorization comes first, as for reads: a caller who may not delete this user gets 404 (hiding whether it exists) or 403 depending on policy, and the check is made for every id.
| Choice | What the server does | Trade-off |
|---|---|---|
| Hard delete | Removes the row | Simple, frees the email; cannot be undone |
| Soft delete | Flags it and hides it | Restorable; the data is still stored |
| Anonymise / purge | Overwrites or removes personal fields | Satisfies erasure; loses detail |
| Async (202) | Queues the work, returns a status URL | For slow cascades; the client must poll |
Hard delete removes the row: it is simple and frees the email address, but it is gone for good, and related records (orders, comments) must be deleted, anonymised or blocked. Soft delete marks the record (for example with a deleted flag) and hides it from reads: GET answers 404, lists skip it, and an admin can restore it. It helps with mistakes and audit trails, but it is not erasure: the personal data is still stored, so when a law or a user demands erasure you must really purge or anonymise it, backups included on a schedule. If the work takes time (cascades, search indexes, backups), the server may answer 202 Accepted with a status URL instead of 204, and the client polls it.
- Find the user (404 if gone)
- Check rules: last admin gives 409
- Remove or flag the record
- Answer 204 with no body
A delete succeeds once the user is gone, so a repeat of the same request finds nothing, and 404 is an honest answer.
General pattern
DELETE /v1/<collection>/<id>
204 No Content (deleted; there is no body)
404 Not Found { "error": { ... } } (nothing to delete)
409 Conflict { "error": { ... } } (a rule blocks the delete)
202 Accepted Location: <status url> (deleted later; poll the URL)The request needs no body. The status alone reports the outcome: 204 removed, 404 nothing to remove, 409 a rule blocks it, 202 it will be removed later.
Worked example: 204, a repeated delete and the last admin
The sample runs a users API on a random local port with Alice (admin), Bob and Carol. First it deletes Carol and sees 204 with an empty body, then a GET answers 404 and a second DELETE answers 404 user_not_found. After that the deleteUser() helper turns 204 into "deleted" and 404 into "already gone", and Alice, the last admin, is refused with 409 last_admin.
import http from "node:http";
// The users API (stands in for https://api.example.com/v1/users)
const row = (n, name, role) => ({
id: "u_" + n,
name,
email: name.toLowerCase() + "@example.com",
role,
bio: null,
version: 1,
});
const users = new Map([
["u_1", row(1, "Alice", "admin")],
["u_2", row(2, "Bob", "member")],
["u_3", row(3, "Carol", "member")],
]);
const publicView = ({ id, name, email, role, bio }) => ({ id, name, email, role, bio });
const send = (res, status, body, headers = {}) => {
if (body === undefined) return res.writeHead(status, headers).end(); // 204: no body
res.writeHead(status, { "Content-Type": "application/json", ...headers });
res.end(JSON.stringify(body));
};
const fail = (res, status, code, message, headers) =>
send(res, status, { error: { code, message } }, headers);
const server = http.createServer((req, res) => {
const [, , resource, id] = new URL(req.url, "http://localhost").pathname.split("/");
if (resource !== "users" || !id) return fail(res, 404, "not_found", "No such route");
const user = users.get(id);
if (req.method === "GET") {
if (!user) return fail(res, 404, "user_not_found", "No user " + id);
return send(res, 200, publicView(user));
}
if (req.method !== "DELETE") {
const allow = { Allow: "GET, DELETE" };
return fail(res, 405, "method_not_allowed", "Use GET or DELETE", allow);
}
if (!user) return fail(res, 404, "user_not_found", "No user " + id);
const admins = [...users.values()].filter((u) => u.role === "admin");
if (user.role === "admin" && admins.length === 1) {
return fail(res, 409, "last_admin", "The last admin cannot be deleted");
}
users.delete(id);
send(res, 204); // success, and nothing to send back
});
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 deleteUser(id) {
const res = await fetch(base + "/v1/users/" + id, { method: "DELETE" });
if (res.status === 204) return "deleted";
if (res.status === 404) return "already gone"; // the goal (user absent) is met
const { error } = await res.json();
throw new Error(res.status + " " + error.code);
}
const first = await fetch(base + "/v1/users/u_3", { method: "DELETE" });
const emptyBody = JSON.stringify(await first.text());
console.log("DELETE u_3:", first.status, "ok:", first.ok, "body:", emptyBody);
const check = await fetch(base + "/v1/users/u_3");
console.log("GET u_3:", check.status);
const second = await fetch(base + "/v1/users/u_3", { method: "DELETE" });
console.log("DELETE u_3 again:", second.status, (await second.json()).error.code);
console.log("deleteUser(u_3):", await deleteUser("u_3"));
console.log("deleteUser(u_2):", await deleteUser("u_2"));
try {
await deleteUser("u_1");
} catch (err) {
console.log("deleteUser(u_1) failed:", err.message);
}
server.close();Code breakdown
- 204 has no body
if (body === undefined) return res.writeHead(status, headers).end(); // 204: no bodyWith no body, the response ends at once without a Content-Type. A 204 must not carry a body, so on the client res.text() returns just "".
- 404 for what is not there
if (!user) return fail(res, 404, "user_not_found", "No user " + id);Deleting an already deleted user reaches this line. GET returns the same error, which matches the 404 you see from GET after the delete.
- A rule blocks the delete
return fail(res, 409, "last_admin", "The last admin cannot be deleted");When the user is an admin and the only one left, the answer is 409. The request is valid but clashes with the current state, so 409 is used here as it was on create.
- Remove, then answer 204
users.delete(id);The Map is changed only after every rule has passed, so the 404 and 409 paths change nothing.
- Do not parse a 204
if (res.status === 204) return "deleted";The client checks the status first and never calls res.json() on a 204, which would throw a SyntaxError. The error body is read only for statuses other than 204 and 404.
- 404 as already gone
if (res.status === 404) return "already gone"; // the goal (user absent) is metThe goal of a cleanup is that the user is absent, so a 404 means the goal is already met. A retrying client stays correct even when its first attempt had succeeded.
DELETE u_3: 204 ok: true body: ""
GET u_3: 404
DELETE u_3 again: 404 user_not_found
deleteUser(u_3): already gone
deleteUser(u_2): deleted
deleteUser(u_1) failed: 409 last_admin- Look the user up by id
- Check the caller may delete it
- Check the rules (the last admin)
- Remove it and answer 204
User not found
404 user_not_found and nothing changes
A rule blocks it
409 last_admin and nothing is deleted
Everything passes
204 No Content with an empty body
Soft delete, restore and purge
The code below shows the essence of soft delete. softDelete does not remove the record but flags it, so reads no longer see it while it stays in the array and restore can bring it back. Only purge really removes it. One thing to watch is the email uniqueness rule: the email of a soft-deleted user is still stored, so someone signing up again with that email can hit a 409, which means you have to decide what happens to deleted users (release the email, or point to restore).
const users = [
{ id: "u_1", name: "Alice", email: "alice@example.com", deleted: false },
{ id: "u_2", name: "Bob", email: "bob@example.com", deleted: false },
];
// Reads only see users that are not flagged
const find = (id) => users.find((u) => u.id === id && !u.deleted);
function softDelete(id) {
const user = find(id);
if (!user) return 404;
user.deleted = true; // still stored, just hidden
return 204;
}
function restore(id) {
const user = users.find((u) => u.id === id && u.deleted);
if (!user) return 404;
user.deleted = false;
return 200;
}
function purge(id) {
const index = users.findIndex((u) => u.id === id);
if (index === -1) return 404;
users.splice(index, 1); // really gone
return 204;
}
console.log(softDelete("u_2")); // 204
console.log(find("u_2") ?? "hidden"); // hidden: GET would answer 404
console.log(users.length); // 2: the row is still stored
console.log(restore("u_2")); // 200
console.log(find("u_2").name); // Bob
console.log(purge("u_2"), users.length); // 204 1Slow deletes and the 202 pattern
When deleting a user also means cleaning up orders, search indexes and backups, the work cannot finish inside one request. The server then answers 202 Accepted and gives a URL for the job's status in Location, and the client polls that URL. Unlike 204, a 202 means "accepted, not finished", so the client must not assume the user is already gone. The operations URL below is illustrative; follow the real API's docs.
DELETE /v1/users/u_3 HTTP/1.1
Host: api.example.com
HTTP/1.1 202 Accepted
Location: /v1/operations/op_17
Content-Type: application/json
{ "status": "pending" }curl -i -X DELETE https://api.example.com/v1/users/u_3
# HTTP/1.1 204 No ContentIn real projects
Delete endpoints in real projects
Providers differ on these points. The GitHub REST API answers most DELETE calls with 204, while Stripe returns 200 with a small object containing deleted: true. Both are valid, so follow the docs. Many SaaS apps soft delete an account and purge it after a set period (for example 30 days), during which the user can restore it if they change their mind. Privacy laws such as the GDPR give people a right to erasure, so setting a flag is not enough; talk to your legal advisers.
- An admin dashboard asks "are you sure?" before deleting and shows why when a 409 comes back.
- Cleanup scripts must be safe to run repeatedly, so they treat a 404 as a success.
- Tests cover GET answering 404 after the delete, 404 on a repeat, 409 for the last admin, and restore and purge.
Common mistakes
Common delete mistakes
Calling res.json() on a 204
A 204 has no body, so await res.json() throws SyntaxError: Unexpected end of JSON input, and since res.ok is true you end up reporting a successful delete as an error. Check the status first.
Treating the 404 of a repeated delete as a failure
A retrying cleanup that throws on 404 breaks completely on the second attempt even though the first one worked. The goal is that the user is absent, so treat 404 as "already gone"; this applies to DELETE only, since for a GET a 404 is a real error.
Deleting without checking the rules
If nothing stops you deleting the last admin, or an owner with unfinished work, the system loses its managers. Check the rules before the database changes, and refuse with 409.
Believing soft delete is erasure
A deleted: true flag only hides the data; the personal data stays in the database. When erasure is requested you need a separate purge or anonymise process.
Best practices
Best practices
- Choose 404 or 204 for a repeated delete, write it in the API docs, and keep it the same for every resource.
- Check permission and business rules before any data changes, and use 404 or 403 for forbidden deletes consistently, as your policy says.
- For important data combine soft delete with a purge after a set period, and plan for erasure requirements.
Mini challenge
Write deleteUser and cleanup yourself
Write deleteUser(users, id) without HTTP: { status: 404, error: "user_not_found" } when the id does not exist, { status: 409, error: "last_admin" } for the last admin, otherwise remove it from the array and return { status: 204 }. Then write cleanup(users, ids): delete each id, count 204 as deleted and 404 as alreadyGone, and push every other outcome into blocked as an "id:error" string.
- Use the number of admins in users to detect the last admin
- Really remove the deleted user from the array (splice)
- cleanup must not throw on a repeated id or on a missing id
- Return the result as a { deleted, alreadyGone, blocked } object
const users = [
{ id: "u_1", name: "Alice", role: "admin" },
{ id: "u_2", name: "Bob", role: "member" },
{ id: "u_3", name: "Carol", role: "member" },
{ id: "u_4", name: "Dan", role: "admin" },
];
function deleteUser(users, id) {
// TODO: 404 { error: "user_not_found" } when the id does not exist
// TODO: 409 { error: "last_admin" } when it is the only admin
// TODO: otherwise remove it from the array and return { status: 204 }
}
function cleanup(users, ids) {
// TODO: delete every id and count 204 as "deleted" and 404 as "alreadyGone"
// TODO: put any other outcome into "blocked" as "id:error"
// TODO: return { deleted, alreadyGone, blocked }
}Expected: Two lines print: {"deleted":2,"alreadyGone":2,"blocked":["u_4:last_admin"]} and the remaining user ids u_2 u_4.
Show hint
Find the index with findIndex; -1 means 404. Count admins with filter and check users[index].role === "admin" && admins.length === 1. cleanup needs just one if / else if / else for the three kinds of status.
Show solution
const users = [
{ id: "u_1", name: "Alice", role: "admin" },
{ id: "u_2", name: "Bob", role: "member" },
{ id: "u_3", name: "Carol", role: "member" },
{ id: "u_4", name: "Dan", role: "admin" },
];
function deleteUser(users, id) {
const index = users.findIndex((u) => u.id === id);
if (index === -1) return { status: 404, error: "user_not_found" };
const admins = users.filter((u) => u.role === "admin");
if (users[index].role === "admin" && admins.length === 1) {
return { status: 409, error: "last_admin" };
}
users.splice(index, 1);
return { status: 204 };
}
function cleanup(users, ids) {
const summary = { deleted: 0, alreadyGone: 0, blocked: [] };
for (const id of ids) {
const result = deleteUser(users, id);
if (result.status === 204) summary.deleted++;
else if (result.status === 404) summary.alreadyGone++;
else summary.blocked.push(id + ":" + result.error);
}
return summary;
}
console.log(JSON.stringify(cleanup(users, ["u_3", "u_3", "u_99", "u_1", "u_4"])));
console.log(users.map((u) => u.id).join(" "));Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A successful DELETE answers 204 with no body; check the status first and never call res.json() on a 204.
- The end state of DELETE is idempotent (the user is gone) while the response may differ by API: this API answers 404 on a repeat and a cleanup treats 404 as already gone.
- Refuse a delete that would break a rule (the last admin) with 409 and the shared error body, and delete nothing.
- Soft delete hides, hard delete removes, erasure needs a purge or anonymise step, and a slow delete may answer 202.
RFC 9110 — HTTP Semantics — IETF