Node.js theorytheory 0/50 · 0%
Web frameworks · medium

26. REST API design basics

Resources, status codes and predictable shapes.

A REST API models data as resources addressed by URLs, manipulated via HTTP methods: `GET` (read), `POST` (create), `PUT`/`PATCH` (update), `DELETE` (remove). Status codes communicate outcome without needing to inspect the body: `200` OK, `201` Created, `400` bad request, `401`/`403` auth issues, `404` not found, `500` server error.

js
app.post("/transactions", (req, res) => {
  const { to, amount } = req.body;
  if (!to || !amount) {
    return res.status(400).json({ error: "to and amount are required" });
  }
  const tx = createTransaction(to, amount);
  res.status(201).json(tx);
});

app.get("/transactions/:hash", (req, res) => {
  const tx = findTransaction(req.params.hash);
  if (!tx) return res.status(404).json({ error: "not found" });
  res.json(tx);
});

Consistent, predictable error shapes (e.g. always `{ error: string }`) make an API far easier for clients — including your own front-end — to handle reliably.

Check your understanding

  1. 1. Which status code should a successful resource creation return?

  2. 2. Which status code fits a request missing required fields?

  3. 3. Why keep error response shapes consistent across an API?