← Back to Backend, page 1

backend-0001 · Easy fresher

How do you design REST resources and URLs, and what do safe and idempotent mean for GET, POST, PUT, PATCH and DELETE?

REST models your data as resources (nouns such as /students/42) and uses HTTP methods as the verbs. GET and HEAD are safe (they do not change state). GET, PUT and DELETE are idempotent (doing them twice leaves the same state as doing them once). POST is neither: it usually creates a new resource each time. PATCH is not guaranteed to be idempotent.

Full answer

Resources and URLs

  • Use plural nouns for collections (/students) and an id for one item (/students/42). Nest only when the child cannot exist without the parent (/students/42/enrollments). Keep URLs shallow.
  • Put the action in the method, not the path. Avoid /createStudent. When an action is not CRUD (for example "cancel an order"), model it as a sub-resource or state change (POST /orders/7/cancellation).

Method semantics

  • GET: read. Safe and idempotent. Cacheable.
  • POST: create a child in a collection, or run a non-idempotent action. Success is 201 with a Location header.
  • PUT: replace the whole resource at a known URL. Idempotent: sending the same body twice gives the same state.
  • PATCH: change part of a resource. Can be idempotent, but is not required to be (for example "add 1 to the counter").
  • DELETE: remove. Idempotent in state: the second call finds nothing, so the status may be 404, but the server state is the same.

Why it matters: clients, proxies and retry libraries use these rules. A network client may safely retry GET, PUT and DELETE after a timeout, but a blind retry of POST can create duplicates (idempotency keys fix that, see the idempotency items).

javascript
const http = require('node:http');

const students = new Map();
let nextId = 1;
const readJson = (req) => new Promise((resolve) => { let t = ''; req.on('data', (c) => (t += c)); req.on('end', () => resolve(t ? JSON.parse(t) : {})); });

const server = http.createServer(async (req, res) => {
  const send = (status, body, headers = {}) => { res.writeHead(status, { 'content-type': 'application/json', ...headers }); res.end(body === undefined ? '' : JSON.stringify(body)); };
  const [, collection, id] = req.url.split('/');
  if (collection !== 'students') return send(404, { error: 'not found' });
  if (req.method === 'POST' && !id) { const s = { id: nextId++, ...(await readJson(req)) }; students.set(s.id, s); return send(201, s, { location: `/students/${s.id}` }); }
  if (req.method === 'GET' && id) return students.has(+id) ? send(200, students.get(+id)) : send(404, { error: 'not found' });
  if (req.method === 'PUT' && id) { students.set(+id, { id: +id, ...(await readJson(req)) }); return send(200, students.get(+id)); }
  if (req.method === 'DELETE' && id) return students.delete(+id) ? send(204) : send(404, { error: 'not found' });
  send(405, { error: 'method not allowed' }, { allow: 'GET, POST, PUT, DELETE' });
});

server.listen(0, '127.0.0.1', async () => {
  const base = `http://127.0.0.1:${server.address().port}`;
  const call = async (method, path, body) => {
    const r = await fetch(base + path, { method, body: body && JSON.stringify(body), headers: { 'content-type': 'application/json' } });
    return `${method} ${path} -> ${r.status}${r.headers.get('location') ? ' Location ' + r.headers.get('location') : ''}`;
  };
  console.log(await call('POST', '/students', { name: 'Asha' }));
  console.log(await call('POST', '/students', { name: 'Asha' }), '(a second POST made a second resource)');
  console.log(await call('PUT', '/students/1', { name: 'Asha Rao' }));
  console.log(await call('PUT', '/students/1', { name: 'Asha Rao' }), '(same body again, same state)');
  console.log('students stored:', JSON.stringify([...students.values()]));
  console.log(await call('DELETE', '/students/2'));
  console.log(await call('DELETE', '/students/2'), '(state is the same, status differs)');
  console.log(await call('PATCH', '/students/1', { name: 'x' }));
  server.close();
});

A tiny in-memory server on a random port and fetch calls show the method rules directly. The numbers of resources and statuses are the point, not the storage. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): POST /students -> 201 Location /students/1 POST /students -> 201 Location /students/2 (a second POST made a second resource) PUT /students/1 -> 200 PUT /students/1 -> 200 (same body again, same state) students stored: [{"id":1,"name":"Asha Rao"},{"id":2,"name":"Asha"}] DELETE /students/2 -> 204 DELETE /students/2 -> 404 (state is the same, status differs) PATCH /students/1 -> 405

Key points

  • Resources are nouns; methods are the verbs.
  • GET is safe and idempotent; PUT and DELETE are idempotent; POST is not.
  • POST to a collection creates a resource and returns 201 with Location.
  • PUT replaces the whole resource; PATCH changes part of it.
  • Retry rules depend on idempotency.

Common mistakes

  • Using verbs in URLs (/getStudent).
  • Using POST for everything.
  • Using GET for actions that change state (crawlers and prefetchers will trigger them).
  • Nesting URLs five levels deep.
  • Retrying POST after a timeout without an idempotency key.

Follow-ups

  • What is the difference between safe and idempotent?
  • Why can DELETE return 404 on the second call and still be idempotent?
  • When is a sub-resource better than a custom verb?

Tips

  • Say 'nouns in the URL, verbs in the method'.
  • Give the safe and idempotent table from memory.
  • Mention retries as the reason it matters.