HTTP Methods & Status Codes
GET, POST, PUT, PATCH, DELETE — when to use each, and what responses mean
Skills taught: api.http-methods, api.status-codes, api.idempotency, api.put-vs-patch
HTTP methods and when to use them
// GET — read data, no body, safe + idempotent
const users = await fetch('/api/users').then(r => r.json());
const user = await fetch('/api/users/42').then(r => r.json());
// POST — create, has a body, NOT idempotent
const newUser = await fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Alice', email: 'alice@example.com' }),
}).then(r => r.json());
// → 201 Created { id: 100, name: 'Alice', ... }
// PUT — full replace, idempotent (must send complete object)
await fetch('/api/users/42', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id: 42, name: 'Alice', email: 'alice@new.com', role: 'admin' }),
});
// → 200 OK (complete object required — missing fields become null)
// PATCH — partial update, send only changed fields
await fetch('/api/users/42', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email: 'alice@new.com' }),
});
// → 200 OK (only email changes; other fields untouched)
// DELETE — remove, idempotent
await fetch('/api/users/42', { method: 'DELETE' });
// → 204 No Content (no body)
// HEAD — check existence without downloading body
const res = await fetch('/api/files/report.pdf', { method: 'HEAD' });
console.log(res.status); // 200 or 404
console.log(res.headers.get('content-length')); // file size in bytes
Tip: Use PATCH (not PUT) for most updates — it's more efficient since you only send the fields that changed. PUT is for replacing an entire resource (like uploading a file), where you always have the complete new version.
Frequently Asked Questions
When should I use PUT vs PATCH?
Use PATCH for most updates — you send only the fields you want to change: `{ "email": "new@example.com" }`. The server merges these into the existing record. Use PUT when replacing a complete resource — you must send all fields, and missing fields get their default/null values. A common example of PUT: uploading a file (you always send the full file). PATCH is better for record updates since you don't need to fetch the full object first.