Sikau

Web essentials · Day 3 · about 30 min

REST APIs and JSON

Read, create and handle errors.

Apps talking to servers

Most apps load and save data through a REST API: URLs for things (/users, /users/2) and HTTP methods for actions. You've used fetch to read data; now you'll send it, and handle every kind of answer properly.

GET and POST with fetch

// A pretend server, so this works offline.
const DB = { 1: { id: 1, name: "Asha", city: "Pokhara" }, 2: { id: 2, name: "Ram", city: "Patan" } };
async function fakeFetch(url, options = {}) {
  await new Promise((r) => setTimeout(r, 20));
  const { pathname, searchParams } = new URL(url, "https://api.sikau.test");
  const method = (options.method ?? "GET").toUpperCase();
  const reply = (status, body) => ({ ok: status >= 200 && status < 300, status, json: async () => body });
  const match = pathname.match(/^\/users\/(\d+)$/);
  if (method === "GET" && pathname === "/users") {
    const city = searchParams.get("city");
    return reply(200, Object.values(DB).filter((u) => !city || u.city === city));
  }
  if (method === "GET" && match) return DB[match[1]] ? reply(200, DB[match[1]]) : reply(404, { error: "Not found" });
  if (method === "POST" && pathname === "/users") {
    const body = JSON.parse(options.body ?? "{}");
    if (!body.name) return reply(400, { error: "name is required" });
    return reply(201, { id: 3, ...body });
  }
  return reply(405, { error: "Method not allowed" });
}

async function main() {
  const res = await fakeFetch("/users/1");
  console.log(res.status, await res.json());

  const missing = await fakeFetch("/users/99");
  console.log(missing.ok, missing.status);

  const created = await fakeFetch("/users", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ name: "Gita", city: "Dharan" }),
  });
  console.log(created.status, await created.json());
}
main();
  • fetch only rejects on network failure. A 404 or 500 still resolves — check response.ok or response.status yourself.
  • Send JSON with method, a Content-Type: application/json header and body: JSON.stringify(data).
  • REST style: GET /users list, GET /users/2 one, POST /users create, PATCH /users/2 update, DELETE /users/2 remove.

The rest of this lesson

  • Designing REST endpointsexplain
  • Handling every kind of answerexplain
  • What happens?predict
  • Method for each actionmatch
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 16 lessons of Web essentials