Sikau

Web essentials · Day 4 · about 35 min

Project: A tiny API client

One helper for every request.

Stop repeating yourself

Every request needs the same boilerplate: build the URL, set headers, stringify the body, check the status, parse JSON. Real apps wrap it once in a small API client.

Why one helper

Libraries like axios and ky exist for exactly this reason; building your own small version shows you what they do inside.

In a real app, dozens of places talk to the server. If each builds its own URL, sets headers, stringifies the body and checks the status, those details drift: one forgets the JSON header, another forgets to check ok, a third parses errors differently. A single api() helper puts every rule in one place. Fix a bug there and it's fixed everywhere; add an auth header there and every request gets it.

const user = await api("/users/2");
const results = await api("/search", { query: { q: "momo", page: 2 } });
const created = await api("/orders", { method: "POST", body: { dish: "momo", qty: 2 } });

Callers now say *what* they want, not *how* HTTP works. That's the essence of good abstraction: hide repetitive details behind a small, well-named function with sensible defaults.

The rest of this lesson

  • Inside the helperexplain
  • One api() callorder
  • Query as an objectpredict
  • Who handles what?match
  • Build api()challenge
  • Badge quizquiz
  • Unit 1 complete!recap

Continue this lesson free — run real code in your browser

Continue with Google

See all 16 lessons of Web essentials