← Back to Node.js, page 7

nodejs-0136 · Easy fresher

What are the REST basics for a Node.js API: methods, status codes, idempotency and headers like Location?

Model resources as nouns (/students/1) and use methods for actions: GET reads, POST creates, PUT replaces, PATCH changes part, DELETE removes. Answer with accurate status codes: 200, 201 with a Location header, 204 for no content, 400, 404, 409. GET, PUT and DELETE are idempotent (repeating them gives the same state), POST is not, so protect payments and orders with an idempotency key.

Full answer

Resources and methods

  • URLs name things: /students, /students/42, /students/42/marks. Avoid verbs in paths (/createStudent).
  • GET: read. Safe and idempotent. Must not change state. Cacheable.
  • POST: create (or run an action). Not idempotent. Send 201 Created with a Location header that points to the new resource.
  • PUT: replace the full resource at a known URL. Idempotent.
  • PATCH: partial update. Idempotent only if designed so (set a value, not 'add 1').
  • DELETE: remove. Idempotent. 204 No Content on success. A second delete may return 404 or 204. Both are acceptable if documented.

Status codes that interviews expect

  • 200 OK, 201 Created, 204 No Content.
  • 400 Bad Request (malformed), 401 Unauthorized (not logged in), 403 Forbidden (logged in but not allowed), 404 Not Found, 409 Conflict (duplicate or version conflict), 422 Unprocessable Content, 429 Too Many Requests.
  • 500 Internal Server Error, 503 Service Unavailable.

Idempotency and retries

  • Networks fail, and clients retry. An idempotent method is safe to repeat. For POST requests that must not run twice (payment, order), accept an Idempotency-Key header, store the key with the response, and return the stored response for a repeat.
  • Use ETag with If-Match for safe concurrent updates (412 when it does not match).

Other habits: use JSON with the right content type, return the created or updated object, use plural nouns, support filtering and pagination on collections, and keep behaviour consistent.

javascript
const express = require('express');

const students = new Map();
let nextId = 1;
const seenKeys = new Map(); // Idempotency-Key -> stored response

const app = express();
app.use(express.json());

app.post('/students', (req, res) => {
  const key = req.get('Idempotency-Key');
  if (key && seenKeys.has(key)) return res.status(201).set('Location', seenKeys.get(key).location).json(seenKeys.get(key).body);
  const student = { id: nextId++, name: req.body.name };
  students.set(student.id, student);
  const location = '/students/' + student.id;
  if (key) seenKeys.set(key, { location, body: student });
  res.status(201).set('Location', location).json(student);
});
app.get('/students/:id', (req, res) => {
  const student = students.get(Number(req.params.id));
  student ? res.json(student) : res.status(404).json({ error: 'not found' });
});
app.put('/students/:id', (req, res) => {
  const id = Number(req.params.id);
  students.set(id, { id, name: req.body.name }); // replaces, so repeating gives the same result
  res.json(students.get(id));
});
app.delete('/students/:id', (req, res) => {
  students.delete(Number(req.params.id)) ? res.status(204).end() : res.status(404).json({ error: 'not found' });
});

const server = app.listen(0, '127.0.0.1', async () => {
  const base = 'http://127.0.0.1:' + server.address().port;
  const call = async (method, path, body, headers = {}) => {
    const res = await fetch(base + path, { method, headers: { 'content-type': 'application/json', ...headers }, body: body && JSON.stringify(body) });
    const text = await res.text();
    console.log(method.padEnd(6), path.padEnd(14), res.status, res.headers.get('location') || '', text);
  };
  await call('POST', '/students', { name: 'Asha' }, { 'Idempotency-Key': 'abc-1' });
  await call('POST', '/students', { name: 'Asha' }, { 'Idempotency-Key': 'abc-1' }); // retry: no second student
  await call('POST', '/students', { name: 'Ravi' });
  await call('GET', '/students/1');
  await call('PUT', '/students/1', { name: 'Asha Rao' });
  await call('PUT', '/students/1', { name: 'Asha Rao' }); // same call again, same state
  await call('DELETE', '/students/1');
  await call('DELETE', '/students/1');
  await call('GET', '/students/1');
  server.close();
});

A small CRUD server is called with every method. The retried POST with the same key does not create a second student. Install first with npm install express (run here with express 5.3.0). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): POST /students 201 /students/1 {"id":1,"name":"Asha"} POST /students 201 /students/1 {"id":1,"name":"Asha"} POST /students 201 /students/2 {"id":2,"name":"Ravi"} GET /students/1 200 {"id":1,"name":"Asha"} PUT /students/1 200 {"id":1,"name":"Asha Rao"} PUT /students/1 200 {"id":1,"name":"Asha Rao"} DELETE /students/1 204 DELETE /students/1 404 {"error":"not found"} GET /students/1 404 {"error":"not found"}

Key points

  • Resources are nouns, methods carry the action.
  • POST returns 201 with Location, DELETE often returns 204.
  • GET, PUT and DELETE are idempotent, POST is not.
  • Use an idempotency key for unsafe retries.
  • Use 401 for not logged in and 403 for not allowed.

Common mistakes

  • Using verbs in URLs, such as /deleteStudent.
  • Returning 200 for every outcome.
  • Changing data in a GET request.
  • Confusing 401 and 403.
  • Retrying a POST without any idempotency protection.

Follow-ups

  • What is the difference between PUT and PATCH?
  • How does an ETag with If-Match prevent lost updates?
  • When do you return 409 instead of 400?

Tips

  • Walk through the methods in one breath.
  • Say 'idempotent' and explain it with a retry example.
  • Mention Location on 201.