Thuta Learning
API Tutorial
BasicWeb DevelopmentIntermediate

What REST Is All About

API TutorialLesson 325 min

What you'll walk away with

  • Explain the difference between a resource, a representation and an endpoint
  • Design resource URLs with plural nouns instead of verbs
  • Say which HTTP methods are safe and which are idempotent, and what that means for retries
  • Explain why a stateless server needs every request to carry its own credentials

Explain it simply

Explain it simply

REST is a set of habits for designing web APIs so that they feel predictable. Everything the API manages, a user, an order, a note, is a thing with its own address (a URL). To read it you ask for that address with GET; to create one you send to the collection's address with POST; to remove one you use DELETE. You do not invent verbs like /getUser or /deleteOrder, because the HTTP method already is the verb.

Think of a library. Every book has a shelf code, which is its URL. The librarian understands a few standard requests: look at it, add one, replace it, remove it. Because everyone uses the same few requests, you can walk into any library and know how to ask.

Problem → Why → Solution

The problem: two APIs with no shared rules

Two teams build APIs for the same shop. Team A names its endpoints /getAllUsers, /createNewUser, /removeUserById and /user_update. Team B exposes only /users and /users/42 and lets the HTTP method say what to do. A new developer can guess Team B's API after seeing one example. For Team A they must read every endpoint in the docs, and each name hides small decisions: does /user_update replace or patch? Is it safe to call twice?

There is a deeper trouble as well. If the shopping cart is kept in one server's memory and the next request lands on a different server, the cart vanishes. Predictable resource design and requests that carry everything the server needs solve both problems together.

naming.txt
Inconsistent                        Consistent (REST style)
GET  /getAllUsers                   GET    /users
POST /createNewUser                 POST   /users
POST /removeUserById?id=42          DELETE /users/42
GET  /user_update?id=42&name=Bo     PATCH  /users/42

Why do conventions beat clever names?

A convention is documentation you do not have to write or read. When every resource follows the same pattern, caches and proxies can rely on it too: a cache may store GET responses because GET is defined as safe, but it must never replay a POST. An API that changes data through GET breaks those assumptions, and a crawler or a prefetching browser could delete records just by following links.

Core concept: resource, representation, endpoint

REST (Representational State Transfer) is an architectural style described by Roy Fielding in his doctoral dissertation in 2000. It is not a standard or a protocol; it is a set of constraints. The ones that matter most when you use an API are: client and server are separate, every request is stateless, responses can be cached, and all resources are reached through a uniform interface. In everyday conversation a REST API usually means an HTTP API organised around resources that speaks JSON. Strictly speaking, many such APIs follow only some of the constraints, and that is fine.

A resource is a thing the API manages, such as a user or an order, identified by a URL. A representation is how that resource is shown at one moment, usually a JSON document; the same user could also be shown as XML or as a CSV row. An endpoint is the combination of a URL and a method that you can actually call: GET /users/42 and DELETE /users/42 are two endpoints for one resource. Keep the three apart in your head: the user is the resource, the JSON is a representation, and GET /users/42 is an endpoint.

Collections and items follow a simple pattern. /users is the collection, and /users/42 is one item inside it. Use plural nouns for collections, put identifiers in the path, and let the HTTP method express the action: GET reads, POST creates a new item in a collection, PUT replaces an item completely, PATCH changes part of it and DELETE removes it. Relationships nest naturally, for example GET /users/42/orders, but avoid going deeper than two levels because URLs become hard to read.

Methods also carry guarantees defined by the HTTP standard (RFC 9110). A safe method does not change anything on the server: GET, HEAD and OPTIONS are safe. An idempotent method has the same effect on the server whether you send it once or ten times: GET, PUT and DELETE are idempotent, POST is not, and PATCH is not guaranteed to be. This matters when a request times out and you do not know whether it arrived. Retrying an idempotent request is safe, but retrying a POST can create a second order, so you need extra protection such as an idempotency key.

Finally, stateless means that the server does not remember you between requests. Every request carries what the server needs: the credentials, the identifiers, the page number. That is what lets many identical servers sit behind a load balancer, and it is why authorization travels in a header on every call instead of living in server memory.

Mental model: nouns in the URL, verbs in the method
  1. Pick the noun: /notes
  2. Pick the verb: GET, POST, PUT...
  3. Send everything the server needs
  4. Read the status, then the body

The URL says which thing; the method says what to do with it.

General pattern: collections and items

text
METHOD /collection            work on the whole collection
METHOD /collection/{id}       work on one item
METHOD /collection/{id}/sub   work on a nested collection

GET    /users           list           POST   /users           create
GET    /users/{id}      read one       PUT    /users/{id}      replace
PATCH  /users/{id}      change a part  DELETE /users/{id}      remove

{id} stands for a real identifier such as 42. The collection URL (/users) deals with many items, the item URL (/users/42) with exactly one, and changing only the method turns the same URL into a different action.

Example: sending POST and PUT twice each

This mock server keeps a notes resource in memory. The client sends the same POST /notes twice, then the same PUT /notes/1 twice. Look at the results: the two POSTs create two notes, while the two PUTs leave one note in exactly the same state. That is what idempotent means.

notes-rest.mjs
import http from "node:http";

// An in-memory "notes" resource: POST creates, PUT replaces, GET lists.
const notes = new Map();
let nextId = 1;

function readJson(req) {
  return new Promise((resolve) => {
    let raw = "";
    req.on("data", (chunk) => (raw += chunk));
    req.on("end", () => resolve(raw ? JSON.parse(raw) : null));
  });
}

function send(res, status, payload) {
  res.writeHead(status, { "Content-Type": "application/json" });
  res.end(JSON.stringify(payload));
}

const server = http.createServer(async (req, res) => {
  const body = await readJson(req);
  const item = req.url.match(/^\/notes\/(\d+)$/);
  if (req.method === "POST" && req.url === "/notes") {
    const note = { id: nextId++, text: body.text };
    notes.set(note.id, note);
    send(res, 201, note);
  } else if (req.method === "PUT" && item) {
    const note = { id: Number(item[1]), text: body.text };
    notes.set(note.id, note);
    send(res, 200, note);
  } else if (req.method === "GET" && req.url === "/notes") {
    send(res, 200, [...notes.values()]);
  } else {
    send(res, 404, { error: "not_found" });
  }
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${server.address().port}`;

async function call(method, path, payload) {
  const options = { method };
  if (payload) {
    options.headers = { "Content-Type": "application/json" };
    options.body = JSON.stringify(payload);
  }
  const res = await fetch(base + path, options);
  console.log(method, path, "->", res.status, JSON.stringify(await res.json()));
}

await call("POST", "/notes", { text: "buy rice" });
await call("POST", "/notes", { text: "buy rice" });
await call("PUT", "/notes/1", { text: "buy tea" });
await call("PUT", "/notes/1", { text: "buy tea" });
await call("GET", "/notes");

server.close();

Code breakdown

  1. Collection endpointif (req.method === "POST" && req.url === "/notes") {

    A POST to the collection URL means create a new item. The client does not choose the id; the server does.

  2. Server-assigned idconst note = { id: nextId++, text: body.text };

    Every POST bumps nextId and makes a brand-new note, so sending it twice makes two notes. That is exactly why POST is not idempotent.

  3. Item endpoint} else if (req.method === "PUT" && item) {

    PUT /notes/1 names the item, and the client sends the complete representation. Sending it again leaves note 1 in exactly the same state.

  4. Status 201send(res, 201, note);

    Returning 201 Created for a new resource is the convention, while replacing an existing one answers 200. A fuller API would also send a Location header with the new item's URL.

  5. One helperasync function call(method, path, payload) {

    With a single helper, calls differ only in method and path, which makes them easy to compare.

  6. The same call twiceawait call("PUT", "/notes/1", { text: "buy tea" });

    Running this line twice leaves one note. Compare it with the two POSTs before it, which left two.

You should see
POST /notes -> 201 {"id":1,"text":"buy rice"}
POST /notes -> 201 {"id":2,"text":"buy rice"}
PUT /notes/1 -> 200 {"id":1,"text":"buy tea"}
PUT /notes/1 -> 200 {"id":1,"text":"buy tea"}
GET /notes -> 200 [{"id":1,"text":"buy tea"},{"id":2,"text":"buy rice"}]

Safe and idempotent at a glance

MethodSafeIdempotent
GETYesYes
HEADYesYes
POSTNoNo
PUTNoYes
PATCHNoNot guaranteed
DELETENoYes

Idempotent is about the server's state, not about the response. The first DELETE /notes/1 may answer 204 and the second may answer 404 because the note is already gone. The statuses differ, but after two calls the server is in the same state as after one, so DELETE is still idempotent.

Never change data with GET

An endpoint such as GET /deleteUser?id=42 can be triggered by a prefetching browser, a search crawler or a link-preview tool. A method that is supposed to be read-only deleting a record breaks the safety guarantee. Make every change with POST, PUT, PATCH or DELETE.

Stateless in practice

When many servers sit behind a load balancer, you cannot know which one a given request will reach. If the token travels with every request, any server can answer without having to remember the client.

text
Stateless requests behind a load balancer
-----------------------------------------
 client --GET /cart + token--> load balancer --> server A  (answers)
 client --GET /cart + token--> load balancer --> server B  (answers too)

 The token rides in every request, so no server has to remember the client.

A server that stores sessions in memory (stateful) works too, but once you add servers you need extra machinery to share those sessions. That is why most public APIs choose the stateless style.

In real projects

How REST conventions show up in real projects

From payments to source hosting, many public APIs use plural nouns and the standard methods, so once you have learned one, the next is easy to read. CDNs and browser caches can store GET responses, which makes data that rarely changes fast to deliver. Adding more servers behind a load balancer is easy precisely because requests are stateless.

Retry logic builds on the method too. HTTP client libraries and gateways may automatically resend idempotent requests after a timeout, but they tend to leave POST alone. For important POSTs such as payments, some providers accept an idempotency key header: if the client sends the same key again, the server treats the repeat as the original, not as a new request. Always check the provider's documentation for it. And when an action does not fit CRUD, a sub-resource action such as POST /orders/42/cancel is a practical answer.

Common mistakes

Common mistakes

1. Putting verbs in the URL

Names like /getUsers, /createOrder and /deleteItem repeat what the HTTP method already says, and they invite mismatches such as GET /deleteItem. Keep only the noun in the URL, as in /users and /orders/7, and let the method be the action.

2. Blindly resending a POST that timed out

If you send POST /orders and no response arrives, the order may already exist. Resending can create a second order and charge twice. Use an idempotency key, or check with a GET whether the order exists before you resend.

3. Using PUT for a partial update

PUT replaces the whole item, so sending a single field can wipe the others. For a partial change use PATCH, or send the complete representation with PUT.

Best practices

Best practices

  • Name collections with plural, lowercase, hyphenated nouns (/order-items) and never mix singular with plural.
  • Put filtering, sorting and paging in the query string, not the path (/orders?status=paid).
  • Answer a successful POST with 201 and the representation of the item you just created.
  • Nest paths at most two levels deep; beyond that give each resource its own URL.

Mini challenge

Mini challenge: a request reviewer

Write a review() function that takes a request line such as "METHOD /path" and says whether it targets a collection or an item and whether it can be retried. A verb URL such as /getUser must produce a warning instead.

  • Fill an ADVICE object with text saying whether each method is safe or idempotent
  • Strip the query string; if the last path segment is only digits it is an item, otherwise a collection
  • If the first path segment starts with get, create, delete, update or remove followed by an uppercase letter or _, return "warning: verb in path"
  • Review the five given requests and print each as "<request> -> <kind>, <advice>"
review.mjs
const ADVICE = {
  // TODO: one entry per method: GET, HEAD, OPTIONS, PUT, DELETE, PATCH, POST
};

function review(request) {
  const [method, url] = request.split(" ");
  // TODO: path = url without the query string
  // TODO: return a warning when the first segment looks like /getUser or /createOrder
  // TODO: kind = "item" when the last path segment is only digits, else "collection"
  // TODO: return "<request> -> <kind>, <advice>"
}

// TODO: review "GET /users", "DELETE /users/42", "POST /orders",
//       "PATCH /orders/7" and "GET /getUser?id=3", printing each result

Expected: The output should be: GET /users -> collection, safe, retry freely DELETE /users/42 -> item, idempotent, retry freely POST /orders -> collection, not idempotent, use an idempotency key PATCH /orders/7 -> item, not guaranteed idempotent, use an idempotency key GET /getUser?id=3 -> warning: verb in path

Show hint

Use url.split("?")[0] to drop the query. Take the last segment with path.split("/").filter(Boolean).pop() and test it with /^\d+$/. For the verb check try the regular expression /^\/(get|create|delete|update|remove)[A-Z_]/.

Show solution
review.mjs
const ADVICE = {
  GET: "safe, retry freely",
  HEAD: "safe, retry freely",
  OPTIONS: "safe, retry freely",
  PUT: "idempotent, retry freely",
  DELETE: "idempotent, retry freely",
  PATCH: "not guaranteed idempotent, use an idempotency key",
  POST: "not idempotent, use an idempotency key",
};

function review(request) {
  const [method, url] = request.split(" ");
  const path = url.split("?")[0];
  if (/^\/(get|create|delete|update|remove)[A-Z_]/.test(path)) {
    return `${request} -> warning: verb in path`;
  }
  const last = path.split("/").filter(Boolean).pop();
  const kind = /^\d+$/.test(last) ? "item" : "collection";
  return `${request} -> ${kind}, ${ADVICE[method]}`;
}

const requests = [
  "GET /users",
  "DELETE /users/42",
  "POST /orders",
  "PATCH /orders/7",
  "GET /getUser?id=3",
];
for (const request of requests) console.log(review(request));

Quick quiz 1 / 3

A POST /orders request times out and you do not know whether it arrived. What is the safest next step?

Quick quiz 2 / 3

Which request follows REST naming conventions best?

Quick quiz 3 / 3

What does it mean to call a REST API server "stateless"?

What to remember

  • A resource is what the API manages, a representation is how it is shown (JSON), and an endpoint is a callable URL plus method.
  • Keep plural nouns in the URL (/users, /users/42) and let the method express the action.
  • GET, HEAD and OPTIONS are safe; GET, PUT and DELETE are idempotent; POST is neither, so resending it needs protection.
  • A stateless server needs every request to carry its own credentials and everything else it needs.

RFC 9110 — HTTP Semantics — IETF

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

What REST Is All About | Thuta Learning