Thuta Learning
JavaScript
AdvancedProgrammingBeginner

REST API Integration

JavaScriptLesson 3840 min

What you'll walk away with

  • Combine resource URLs such as /users and /users/:id with GET, POST, PATCH, PUT and DELETE for CRUD
  • Predict status codes such as 200, 201, 204 and 404 for each operation
  • Explain which methods are idempotent and use an idempotency key to retry a POST safely
  • Read every page of a list endpoint that takes page and limit query parameters

Explain it simply

REST in plain language

REST is a style of designing APIs. Everything on the server, a user, an order, a product, is a resource with its own URL: /users is all users and /users/7 is user number 7. What you want to do is not written in the URL but said with the HTTP method: GET reads, POST creates, PATCH updates and DELETE removes.

Think of a library. Every book has a shelf number, its URL, and the front desk offers only a few actions: look it up, add a new one, change it, withdraw it. Because the verbs are few and fixed, you can guess how to use a new REST API before reading much of its documentation.

Problem → Why → Solution

The problem: a retry that creates two orders

A customer presses Checkout. The POST /orders request reaches the server and the order is saved, but the mobile connection drops while the response travels back. The client only sees a network error, assumes the order failed and retries automatically. The customer ends up with two orders and is charged twice.

blind-retry.js
async function placeOrder(cart) {
  for (let attempt = 1; attempt <= 3; attempt++) {
    try {
      const response = await fetch("/api/orders", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(cart),
      });
      return await response.json();
    } catch {
      // "it failed" - but the server may already have saved the order
    }
  }
}

Why a POST is unsafe to retry

A network error does not mean the request never reached the server; it only means no response came back. GET, PUT and DELETE are idempotent, so sending them twice has the same effect as once. A POST creates a new resource each time. If the server supports an Idempotency-Key header, send the same key on every retry, and the server recognises the repeat and returns the original order.

Core concept: resources, methods and statuses

In a REST API, the URL is the noun, the resource, and the method is the verb. There are two kinds of URL: a collection (/users) and an item (/users/7). URLs that contain verbs, such as /getUser?id=7 or /deleteUser/7, are not REST style. The method plus the URL describes the operation, and the status code reports how it went.

RequestOperationSuccess status
GET /usersread the list200 with an array
GET /users/7read one200 (404 if missing)
POST /userscreate201 with a Location header
PUT /users/7replace entirely200 or 204
PATCH /users/7update some fields200
DELETE /users/7remove204 No Content

Each request is stateless: the server does not remember previous requests, so every request carries its authentication token and any context it needs. A method is idempotent when sending it once or many times leaves the server in the same state. GET, PUT and DELETE are idempotent; POST is not; PATCH depends on how it is designed.

Large collections are never sent in one go. Pagination, filtering and sorting are expressed with query parameters such as /orders?page=2&limit=20&status=paid&sort=-createdAt, and the response includes paging information such as totalPages or a next link. A consistent error shape such as { error: "..." } keeps client code simple.

Mind the difference between PUT and PATCH. PUT says 'replace this resource with this complete object', so fields you leave out can disappear. PATCH says 'change only these fields'. When a form edits one or two fields, PATCH is the natural choice. Always check the documentation for which methods an API accepts.

The URL is the noun, the method is the verb
  1. Pick the resource: /users or /users/7
  2. Pick the verb: GET POST PATCH PUT DELETE
  3. Send data as JSON body or query
  4. The status code reports the outcome
  5. Ask 'idempotent?' before any retry

If a URL contains a verb such as getUser or deleteOrder, the API is usually RPC style rather than REST.

General pattern

javascript
async function request(method, path, data) {
  const response = await fetch(baseUrl + path, {
    method,                                  // GET, POST, PUT, PATCH, DELETE
    headers: { "Content-Type": "application/json", Authorization: auth },
    body: data ? JSON.stringify(data) : undefined,
  });
  if (!response.ok) throw new Error(`${method} ${path}: ${response.status}`);
  return response.status === 204 ? null : response.json();
}

Keep a single request function for the whole client and vary only the method, path and data. A 204 No Content has no body, so do not call json() on it.

Worked example: CRUD against an in-memory REST server

The users live inside fakeServer, a function with the same signature as fetch(url, options), so the client sends a method, URL and JSON body exactly as it would to a real REST API and gets real Response objects back. Six requests cover every CRUD operation, and the last one shows the 404 for a user that was just deleted.

rest-crud.js
// A tiny in-memory REST server with the same signature as fetch(url, options).
const users = [
  { id: 1, name: "Aung Kyaw", email: "aung@example.com" },
  { id: 2, name: "Su Su", email: "susu@example.com" },
];
let nextId = 3;

async function fakeServer(url, { method = "GET", body } = {}) {
  const { pathname } = new URL(url);
  const match = pathname.match(/^\/users(?:\/(\d+))?$/);
  if (!match) return Response.json({ error: "Not found" }, { status: 404 });
  const id = match[1] && Number(match[1]);
  const index = users.findIndex((u) => u.id === id);

  if (method === "GET" && !id) return Response.json(users);
  if (method === "GET" && index >= 0) return Response.json(users[index]);
  if (method === "POST" && !id) {
    const user = { id: nextId++, ...JSON.parse(body) };
    users.push(user);
    const headers = { Location: `/users/${user.id}` };
    return Response.json(user, { status: 201, headers });
  }
  if (method === "PATCH" && index >= 0) {
    Object.assign(users[index], JSON.parse(body));
    return Response.json(users[index]);
  }
  if (method === "DELETE" && index >= 0) {
    users.splice(index, 1);
    return new Response(null, { status: 204 });
  }
  return Response.json({ error: "User not found" }, { status: 404 });
}

// The client: one function that every REST call goes through.
async function request(method, path, data) {
  const response = await fakeServer(`https://api.example.com${path}`, {
    method,
    headers: data ? { "Content-Type": "application/json" } : {},
    body: data ? JSON.stringify(data) : undefined,
  });
  const body = response.status === 204 ? null : await response.json();
  console.log(`${method} ${path} -> ${response.status}`, body ?? "(no body)");
  return body;
}

async function main() {
  await request("GET", "/users");
  await request("GET", "/users/1");
  await request("POST", "/users", { name: "Min Min", email: "min@example.com" });
  await request("PATCH", "/users/3", { name: "Min Min Oo" });
  await request("DELETE", "/users/2");
  await request("GET", "/users/2");
}

main();

Code breakdown

  1. Route by URLconst match = pathname.match(/^\/users(?:\/(\d+))?$/);

    The regex matches both /users (the collection) and /users/3 (an item) and captures the id in match[1]. Real server frameworks do this with routes such as /users/:id.

  2. 201 plus Locationreturn Response.json(user, { status: 201, headers });

    A successful POST answers 201 Created with the new resource, and the Location header gives its new URL, /users/3.

  3. 204 has no bodyreturn new Response(null, { status: 204 });

    A successful DELETE has nothing to send back, so it answers 204 No Content with no body.

  4. One request functionconst body = response.status === 204 ? null : await response.json();

    The client treats 204 specially, because calling json() on an empty body throws a SyntaxError.

  5. Partial updateawait request("PATCH", "/users/3", { name: "Min Min Oo" });

    PATCH changes only the fields sent, here name, and leaves email alone. A PUT would replace the whole object, so email would have to be sent as well.

You should see
GET /users -> 200 [
  { id: 1, name: 'Aung Kyaw', email: 'aung@example.com' },
  { id: 2, name: 'Su Su', email: 'susu@example.com' }
]
GET /users/1 -> 200 { id: 1, name: 'Aung Kyaw', email: 'aung@example.com' }
POST /users -> 201 { id: 3, name: 'Min Min', email: 'min@example.com' }
PATCH /users/3 -> 200 { id: 3, name: 'Min Min Oo', email: 'min@example.com' }
DELETE /users/2 -> 204 (no body)
GET /users/2 -> 404 { error: 'User not found' }
Deciding whether to retry
  1. A request fails
  2. Was it a network error, a 5xx or a 429?
  3. Is the method idempotent, or is an Idempotency-Key attached?

Both yes

Retry with backoff, same key

Either no

Do not retry; show the error

Pagination: page numbers and cursors

List endpoints usually use one of two pagination styles. Page numbers, also called offsets, are easy to understand and let users jump straight to page 5, but if new items arrive while you read, items can repeat or be skipped. A cursor remembers 'continue after this item', which stays stable for feeds that change constantly.

StyleExample requestGood for
Page / offsetGET /orders?page=3&limit=20admin tables with page numbers
CursorGET /orders?after=ord_81&limit=20infinite scroll, busy feeds

In real projects

REST in real projects

Most public APIs, such as GitHub, Stripe and Shopify, and most in-house backends follow the REST style. Frontend teams usually write one client module per resource, with functions such as usersApi.list, usersApi.get and usersApi.update, so components never deal with URLs and status codes directly.

  • Some payment providers, Stripe for example, accept an Idempotency-Key header on POST requests, and checkout code sends the same key on every attempt.
  • Admin tables load data piece by piece with ?page=&limit= or cursor-based pagination, and jump back to page 1 whenever the filter changes.
  • When two people edit the same record at once, the server can answer 409 Conflict or 412 Precondition Failed, and the client asks the user to reload the latest version.

Common mistakes

Common mistakes with REST APIs

Blindly retrying a POST

Resending a POST after every network error can duplicate orders, payments or messages. Retry only when the server supports an idempotency key; otherwise tell the user to check whether the order went through.

Using PUT where PATCH is meant

PUT replaces the whole resource. Sending only { name } with PUT may wipe other fields such as email, depending on the API. Use PATCH to change just a few fields.

Calling json() on a 204 response

DELETE often answers 204 No Content with no body. Calling response.json() then throws a SyntaxError such as 'Unexpected end of JSON input', and a successful delete is reported as an error.

Best practices

Best practices

  • Group the client functions for each resource in one module so components never need to know URLs.
  • Limit retries to network errors, 5xx and 429, and never retry a POST without an idempotency key.
  • Always read lists page by page instead of relying on an 'everything at once' endpoint.

Mini challenge

Mini challenge: idempotent createOrder and pagination

The provided shopServer saves the order but 'loses' the response when dropNextResponse is true. Write createOrder, which retries only network errors, and listAllOrders, which reads every page. Show that an idempotency key yields one order while no key yields a duplicate.

  • createOrder creates the key with crypto.randomUUID() once, before any retry
  • Retry only a TypeError (network error); throw HTTP errors immediately
  • listAllOrders reads from page=1 up to totalPages with limit=2
  • Finally print every order as id:item
orders-client.js
// Fake order service. When dropNextResponse is true, the server SAVES the
// order but the response is lost, like a connection dropping mid-request.
const orders = [
  { id: 1, item: "Tea" },
  { id: 2, item: "Coffee" },
  { id: 3, item: "Cake" },
];
const savedByKey = new Map();
let dropNextResponse = false;

async function shopServer(url, { method = "GET", headers, body } = {}) {
  const { pathname, searchParams } = new URL(url);
  if (method === "GET" && pathname === "/orders") {
    const page = Number(searchParams.get("page") ?? 1);
    const limit = Number(searchParams.get("limit") ?? 2);
    const items = orders.slice((page - 1) * limit, page * limit);
    return Response.json({ items, page, totalPages: Math.ceil(orders.length / limit) });
  }
  if (method === "POST" && pathname === "/orders") {
    const key = new Headers(headers).get("idempotency-key");
    const earlier = key && savedByKey.get(key);
    if (earlier) return Response.json(earlier, { status: 201 });
    const order = { id: orders.length + 1, ...JSON.parse(body) };
    orders.push(order);
    if (key) savedByKey.set(key, order);
    if (dropNextResponse) {
      dropNextResponse = false;
      throw new TypeError("connection reset");
    }
    return Response.json(order, { status: 201 });
  }
  return Response.json({ error: "Not found" }, { status: 404 });
}

const BASE = "https://shop.example.com";

async function createOrder(data, fetchFn, { idempotent = true, attempts = 3 } = {}) {
  // TODO: build headers; add an Idempotency-Key once when idempotent is true
  // TODO: loop: POST, throw on !response.ok, return the JSON on success
  // TODO: catch: retry only a TypeError and only while attempts remain
}

async function listAllOrders(fetchFn) {
  // TODO: GET /orders?page=N&limit=2 until page > totalPages, collect items
}

// TODO: main(): set dropNextResponse = true, create "Juice" with a key;
// set it again, create "Soup" with { idempotent: false }; print all orders

Expected: Juice, sent with a key, fails on attempt 1, is retried and ends up as a single order 4. Soup, sent without a key, becomes orders 5 and 6, so the last line is 1:Tea, 2:Coffee, 3:Cake, 4:Juice, 5:Soup, 6:Soup.

Show hint

Create the key outside the loop; inside it, every retry would get a new key and the server could not recognise the repeat. A do...while loop fits 'read at least one page'.

Show solution
orders-client.js
// Fake order service. When dropNextResponse is true, the server SAVES the
// order but the response is lost, like a connection dropping mid-request.
const orders = [
  { id: 1, item: "Tea" },
  { id: 2, item: "Coffee" },
  { id: 3, item: "Cake" },
];
const savedByKey = new Map();
let dropNextResponse = false;

async function shopServer(url, { method = "GET", headers, body } = {}) {
  const { pathname, searchParams } = new URL(url);
  if (method === "GET" && pathname === "/orders") {
    const page = Number(searchParams.get("page") ?? 1);
    const limit = Number(searchParams.get("limit") ?? 2);
    const items = orders.slice((page - 1) * limit, page * limit);
    return Response.json({ items, page, totalPages: Math.ceil(orders.length / limit) });
  }
  if (method === "POST" && pathname === "/orders") {
    const key = new Headers(headers).get("idempotency-key");
    const earlier = key && savedByKey.get(key);
    if (earlier) return Response.json(earlier, { status: 201 });
    const order = { id: orders.length + 1, ...JSON.parse(body) };
    orders.push(order);
    if (key) savedByKey.set(key, order);
    if (dropNextResponse) {
      dropNextResponse = false;
      throw new TypeError("connection reset");
    }
    return Response.json(order, { status: 201 });
  }
  return Response.json({ error: "Not found" }, { status: 404 });
}

const BASE = "https://shop.example.com";

async function createOrder(data, fetchFn, { idempotent = true, attempts = 3 } = {}) {
  const headers = { "Content-Type": "application/json" };
  if (idempotent) headers["Idempotency-Key"] = crypto.randomUUID(); // reused on retry
  for (let attempt = 1; ; attempt++) {
    try {
      const response = await fetchFn(`${BASE}/orders`, {
        method: "POST",
        headers,
        body: JSON.stringify(data),
      });
      if (!response.ok) throw new Error(`HTTP ${response.status}`); // not retried
      return await response.json();
    } catch (error) {
      const retryable = error instanceof TypeError; // network failures only
      if (!retryable || attempt === attempts) throw error;
      console.log(`  attempt ${attempt} failed (${error.message}), retrying`);
    }
  }
}

async function listAllOrders(fetchFn) {
  const all = [];
  let page = 1;
  let totalPages = 1;
  do {
    const response = await fetchFn(`${BASE}/orders?page=${page}&limit=2`);
    const body = await response.json();
    all.push(...body.items);
    totalPages = body.totalPages;
    page += 1;
  } while (page <= totalPages);
  return all;
}

async function main() {
  console.log("with an idempotency key:");
  dropNextResponse = true;
  const juice = await createOrder({ item: "Juice" }, shopServer);
  console.log("  created", juice);

  console.log("without a key:");
  dropNextResponse = true;
  await createOrder({ item: "Soup" }, shopServer, { idempotent: false });

  const all = await listAllOrders(shopServer);
  console.log("all orders:", all.map((o) => `${o.id}:${o.item}`).join(", "));
}

main();

Quick quiz 1 / 3

You want to change only the email of user 7. Which request fits REST style best?

Quick quiz 2 / 3

Which request is most likely to cause an unwanted result if it is resent after a network error?

Quick quiz 3 / 3

DELETE /users/2 answers 204. What happens if the client calls await response.json()?

What to remember

  • In REST, the URL is the resource (the noun) and the HTTP method is the operation (the verb).
  • The usual pattern is POST → 201 with Location, GET → 200, DELETE → 204, missing resource → 404.
  • GET, PUT and DELETE are idempotent; POST is not, so retrying it needs an idempotency key.
  • Express pagination, filters and sorting as query parameters, and read pages until totalPages.

MDN — Fetch API — MDN Web Docs

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.

REST API Integration | Thuta Learning