Designing REST APIs · Lesson 5 of 30
HTTP Methods in REST: GET, POST, PUT, PATCH, DELETE
The HTTP method says what the client wants to do with a resource. Using the right one isn't pedantry: proxies, caches, browsers and client libraries all behave differently depending on the method. A GET may be cached and retried automatically; a POST must not be. This lesson covers each method, the two properties that matter most – safe and idempotent – and the classic PUT vs PATCH question.
In this lesson
- The five main methods on a working API
- PUT vs PATCH, side by side
- Safe and idempotent methods
- HEAD, OPTIONS and 405 Method Not Allowed
One resource, every method
// server.js
import express from 'express';
const app = express();
app.use(express.json());
const students = new Map([[1, { id: 1, name: 'Asha', email: 'asha@example.com', city: 'Pune' }]]);
let nextId = 2;
app.get('/api/students/:id', (req, res) => { // read
const s = students.get(Number(req.params.id));
return s ? res.json(s) : res.status(404).json({ error: 'Not found' });
});
app.post('/api/students', (req, res) => { // create – server assigns the id
const student = { id: nextId++, name: req.body.name, email: req.body.email, city: req.body.city ?? null };
students.set(student.id, student);
res.status(201).location(`/api/students/${student.id}`).json(student);
});
app.put('/api/students/:id', (req, res) => { // replace the whole resource
const id = Number(req.params.id);
if (!students.has(id)) return res.status(404).json({ error: 'Not found' });
const student = { id, name: req.body.name, email: req.body.email, city: req.body.city ?? null };
students.set(id, student);
res.json(student);
});
app.patch('/api/students/:id', (req, res) => { // change only the fields sent
const id = Number(req.params.id);
const current = students.get(id);
if (!current) return res.status(404).json({ error: 'Not found' });
const updated = { ...current, ...req.body, id };
students.set(id, updated);
res.json(updated);
});
app.delete('/api/students/:id', (req, res) => { // remove
students.delete(Number(req.params.id));
res.status(204).end(); // 204: success, no body
});
app.listen(process.env.PORT ?? 3000);
$ curl -X POST http://localhost:3000/api/students -H 'Content-Type: application/json' -d '{"name":"Ravi","email":"ravi@example.com","city":"Delhi"}'
HTTP/1.1 201 Created
Location: /api/students/2
Content-Type: application/json; charset=utf-8
{
"id": 2,
"name": "Ravi",
"email": "ravi@example.com",
"city": "Delhi"
}
$ curl -X PATCH http://localhost:3000/api/students/2 -H 'Content-Type: application/json' -d '{"city":"Mumbai"}'
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
{
"id": 2,
"name": "Ravi",
"email": "ravi@example.com",
"city": "Mumbai"
}
$ curl -X PUT http://localhost:3000/api/students/2 -H 'Content-Type: application/json' -d '{"name":"Ravi Kumar","email":"ravi@example.com"}'
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
{
"id": 2,
"name": "Ravi Kumar",
"email": "ravi@example.com",
"city": null
}
$ curl -X DELETE http://localhost:3000/api/students/2
HTTP/1.1 204 No Content
$ curl http://localhost:3000/api/students/2
HTTP/1.1 404 Not Found
Content-Type: application/json; charset=utf-8
{
"error": "Not found"
}PUT vs PATCH
Look closely at the panel: PATCH sent only city and kept everything else. PUT sent a full representation without a city – so the city was reset to null. That's the difference:
| PUT | PATCH | |
|---|---|---|
| Body | the complete new representation | only the changes |
| Missing fields | cleared / set to defaults | left as they were |
| Idempotent | yes – sending it twice gives the same result | not guaranteed (e.g. "add 1 to quantity") |
| Typical use | forms that edit every field, config documents, "create at this URL" | most partial updates from UIs |
Safe and idempotent
| Method | Safe (no changes) | Idempotent (repeat = same effect) | Cacheable |
|---|---|---|---|
| GET, HEAD | ✔ | ✔ | ✔ |
| OPTIONS | ✔ | ✔ | — |
| PUT | ✗ | ✔ | — |
| DELETE | ✗ | ✔ | — |
| POST | ✗ | ✗ | rarely |
| PATCH | ✗ | ✗ (unless designed to be) | — |
- Safe methods must not change server state – crawlers, prefetchers and caches call GETs freely. Never delete or charge anything on a GET.
- Idempotent methods can be retried safely after a timeout: deleting twice leaves the resource deleted. A retried POST can create a duplicate order – the idempotency-key lesson shows the professional fix.
Why idempotency matters
- Client sends PUTthe network times out before the response arrives
- Did it work?the client can't know
- RetryPUT/DELETE: safe to send again · POST: may create a second record
HEAD, OPTIONS and 405
// server.js
import express from 'express';
const app = express();
app.route('/api/reports/:id')
.get((req, res) => res.json({ id: req.params.id, rows: 1200 }))
.all((req, res) => res.status(405).set('Allow', 'GET, HEAD').json({ error: `${req.method} is not allowed here` }));
app.listen(process.env.PORT ?? 3000);
$ curl -I http://localhost:3000/api/reports/q3
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
$ curl -X DELETE http://localhost:3000/api/reports/q3
HTTP/1.1 405 Method Not Allowed
Allow: GET, HEAD
Content-Type: application/json; charset=utf-8
{
"error": "DELETE is not allowed here"
}HEADreturns the headers of a GET without the body – useful to check existence, size or ETag cheaply. Express answers HEAD automatically for GET routes.OPTIONSasks which methods are allowed; browsers send it automatically for CORS preflight (see the CORS lesson).- A method the resource doesn't support gets
405 Method Not Allowedwith anAllowheader listing the valid ones.
Practice
Try it yourself
A client sends
PATCH /cart/items/9 {"quantity": "+1"}meaning "add one". Is that idempotent? How would you redesign it?Show solution
No – each retry adds another item. Send the absolute value instead:
PATCH /cart/items/9 {"quantity": 3}, which gives the same result however many times it's repeated. If you must support increments, protect them with an idempotency key.
Quick check
Which methods are idempotent?
GET, HEAD, OPTIONS, PUT and DELETE.
What happens to fields missing from a PUT body?
They're cleared – PUT replaces the whole representation.
What does a 405 response include?
An Allow header listing the methods the resource supports.
Summary
- GET reads, POST creates, PUT replaces, PATCH changes part, DELETE removes.
- Safe methods never change state; idempotent methods can be retried safely.
- Answer unsupported methods with 405 and an Allow header.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.