Skip to content

Module 05 · Lesson 5.3

Calling the API from the Frontend

40 minUpdated 19 Nov 2026Part of Frontend and API Integration · New Project Creation
On this page
  1. What you will learn
  2. Why one typed API client
  3. The client: one function per endpoint
  4. Testing the client with a fake fetch
  5. Worked scenario: Tidewell handles a taken slot
  6. Step-by-step workflow
  7. What the assistant can and cannot do when writing an API client
  8. Conclusion and your next step
  9. Reusable prompt
  10. Expected output
  11. Common errors and fixes
  12. Validation checklist
  13. Hands-on exercise
  14. Knowledge check
  15. Frequently asked questions
  16. References

Think of a restaurant. The waiter takes your order to the kitchen and brings back either your meal or an apology. You do not walk into the kitchen yourself. A good API client is that waiter for your screens: it carries requests to the server and brings back data, or a clear reason why it could not.

In this lesson you write that client for Tidewell's booking system. It has one function for each endpoint in the API contract. It never throws surprises. It returns either the data or a problem the screen can show. You test it with a fake server, so you can check a taken slot, a bad request and a dead connection without a real network.

What you will learn

  • Write typed functions that call each endpoint in the API contract.
  • Return a result that is either data or a problem, including network failures and timeouts.
  • Test the client with an injected fake fetch, without a real server.
  • Keep secrets out of frontend code and review generated API code for hidden risks.

Before you start

Why one typed API client

An API client is a small module that holds every call your frontend makes to the server. Screens call getFreeSlots(1, "2026-12-01"). They never build web addresses or read raw replies. If the contract changes, you change one file.

fetch
The browser's built-in function for sending a request to a web address and getting a reply. Like posting a letter and waiting for the answer.
Async function
A function that waits for something slow, such as a reply, without freezing the page. Like leaving your phone number at a shop and being called when the order is ready.
Timeout
A limit on how long you will wait. After it, you give up and say so. Like hanging up after twenty rings.
Problem details
A standard shape for error replies, described in RFC 9457. Your Module 4 API uses it, so the client reads one shape for every failure.

Start with the types. They copy the contract field by field. The fields are camelCase, such as slotId and startsAt, exactly as the API sends them. You can also generate types from the OpenAPI file with a tool such as openapi-typescript. Either way, the contract is the source and the types follow it.

TypeScriptsrc/features/bookings/types.ts
export interface Clinician {
  id: number;
  displayName: string;
}

export interface FreeSlot {
  slotId: number;
  startsAt: string; // ISO 8601 in UTC, for example "2026-12-01T09:00:00Z"
  endsAt: string;
}

export type BookingStatus = "booked" | "cancelled";

export interface Booking {
  bookingId: number;
  slotId: number;
  clinicianName: string;
  startsAt: string;
  endsAt: string;
  status: BookingStatus;
}

export interface FieldError {
  field: string;
  message: string;
}

export interface Problem {
  type: string; // "https://tidewell.example/problems/<code>"
  title: string;
  status: number; // 0 means "no answer from the server"
  detail: string;
  errors?: FieldError[]; // only for validation problems
}

export type ApiResult<T> = { ok: true; data: T } | { ok: false; problem: Problem };

Types for the data and the problem format. The rest of the file is in the next lesson.

What each part does

  • FreeSlot and Booking mirror the JSON the API sends. A typo in a field name now fails the type check.
  • Problem mirrors the problem-details format. errors is optional because only validation problems carry it.
  • status: 0 is our own choice for 'no answer from the server', because no real HTTP status exists in that case.
  • ApiResult<T> is either { ok: true, data } or { ok: false, problem }. The screen checks ok and TypeScript then knows which of the two it holds.

Why a result and not an exception? A failed request is not a surprise. Slots do get taken and connections do drop. Returning the failure as a normal value makes the screen handle it, instead of forgetting a try block and showing a blank page.

The client: one function per endpoint

The client has three parts: a few helpers, one private function called request, and the endpoint functions. First the helpers.

TypeScriptsrc/lib/api-client.ts
import type { ApiResult, Booking, Clinician, FreeSlot, Problem } from "../features/bookings/types";

export const PROBLEM_BASE = "https://tidewell.example/problems/";

export interface ApiClientOptions {
  fetch?: typeof fetch; // tests pass a fake here
  baseUrl?: string; // "" means "the same site as the page"
  timeoutMs?: number;
}

export function problemCode(problem: Problem): string {
  return problem.type.split("/").pop() ?? "unknown";
}

function makeProblem(code: string, title: string, status: number, detail: string): Problem {
  return { type: PROBLEM_BASE + code, title, status, detail };
}

function looksLikeProblem(body: unknown): body is Problem {
  if (typeof body !== "object" || body === null) return false;
  const p = body as Record<string, unknown>;
  return (
    typeof p.type === "string" &&
    typeof p.title === "string" &&
    typeof p.status === "number" &&
    typeof p.detail === "string"
  );
}

The top of the file: options, a way to read the problem code, and a check that a reply really is a problem.

  • ApiClientOptions lists what a caller may change: the fetch to use, a base address and the time limit.
  • problemCode takes the last part of the problem's type address, so "https://tidewell.example/problems/slot-taken" becomes "slot-taken".
  • looksLikeProblem checks that a reply has the four required problem fields. Never trust a reply's shape without checking it.

Now the heart of the client. request sends the call, waits for the reply and turns every outcome into an ApiResult.

TypeScriptsrc/lib/api-client.ts
export function createApiClient(options: ApiClientOptions = {}) {
  const send = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
  const baseUrl = options.baseUrl ?? "";
  const timeoutMs = options.timeoutMs ?? 8000;

  async function request<T>(path: string, init: { method?: string; body?: unknown } = {}): Promise<ApiResult<T>> {
    let response: Response;
    try {
      response = await send(baseUrl + path, {
        method: init.method ?? "GET",
        headers:
          init.body === undefined
            ? { Accept: "application/json" }
            : { Accept: "application/json", "Content-Type": "application/json" },
        body: init.body === undefined ? undefined : JSON.stringify(init.body),
        signal: AbortSignal.timeout(timeoutMs),
      });
    } catch (error) {
      const timedOut = error instanceof Error && error.name === "TimeoutError";
      const detail = timedOut ? "The server took too long to answer." : "The server could not be reached.";
      return { ok: false, problem: makeProblem("network-error", "Network error", 0, detail) };
    }

    let body: unknown;
    try {
      body = await response.json();
    } catch {
      body = undefined;
    }

    if (response.ok && body !== undefined) return { ok: true, data: body as T };
    if (!response.ok && looksLikeProblem(body)) return { ok: false, problem: body };
    return {
      ok: false,
      problem: makeProblem("unexpected-response", "Unexpected response", response.status, "The server sent a reply this page could not read."),
    };
  }

The core of the client: one function that every endpoint uses.

What each part does

  • options.fetch ?? ... lets a test hand in a fake fetch. In the real app nothing is passed and the browser's own fetch is used. This is called making it injectable: like a plug socket, you can fit a real or a test appliance.
  • AbortSignal.timeout(timeoutMs) cancels the request after the limit. The wait ends and the catch block runs.
  • The catch block covers two cases: a dead connection and a timeout. Both become one problem with status: 0, so the screen needs only one message.
  • response.json() is wrapped in its own try, because a gateway error page is not JSON.
  • The last lines choose the result: data for a good reply, the server's problem for a failed one, and our own 'unexpected response' problem for anything else.

Now the endpoints. There is one function for each route in the contract. The names say what the screen wants, not how it is sent.

TypeScriptsrc/lib/api-client.ts
  return {
    listClinicians: () => request<Clinician[]>("/api/clinicians"),
    getFreeSlots: (clinicianId: number, date: string) =>
      request<FreeSlot[]>("/api/clinicians/" + clinicianId + "/free-slots?date=" + encodeURIComponent(date)),
    listMyBookings: () => request<Booking[]>("/api/bookings"),
    createBooking: (slotId: number) => request<Booking>("/api/bookings", { method: "POST", body: { slotId } }),
    moveBooking: (bookingId: number, slotId: number) =>
      request<Booking>("/api/bookings/" + bookingId + "/move", { method: "POST", body: { slotId } }),
    cancelBooking: (bookingId: number) => request<Booking>("/api/bookings/" + bookingId + "/cancel", { method: "POST" }),
  };
}

export type ApiClient = ReturnType<typeof createApiClient>;

One typed function per endpoint in the contract.

Check this against the contract. listClinicians is GET /api/clinicians. getFreeSlots is GET /api/clinicians/{clinicianId}/free-slots with the date in the query string. createBooking, moveBooking and cancelBooking are POST calls, and the first two send { "slotId": ... }. Cancelling sends no body. encodeURIComponent makes sure the date cannot break the address.

Testing the client with a fake fetch

A fake is a stand-in that behaves the way you tell it to. Like a crash-test dummy, it lets you try dangerous things safely. A fake fetch answers with a reply you choose, so you can test a taken slot without needing two real patients.

TypeScripttests/fake-fetch.ts
export interface RecordedCall {
  method: string;
  url: string;
  body: string | undefined;
}

type Handler = (call: RecordedCall, signal: AbortSignal | undefined) => Response | Promise<Response>;

export function fakeFetch(handler: Handler) {
  const calls: RecordedCall[] = [];
  const fake = (async (input: RequestInfo | URL, init?: RequestInit) => {
    const call: RecordedCall = {
      method: init?.method ?? "GET",
      url: String(input),
      body: typeof init?.body === "string" ? init.body : undefined,
    };
    calls.push(call);
    return handler(call, init?.signal ?? undefined);
  }) as typeof fetch;
  return { fetch: fake, calls };
}

export function json(status: number, body: unknown): Response {
  return new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } });
}

export function problem(status: number, code: string, title: string, detail: string, errors?: unknown): Response {
  const body = { type: "https://tidewell.example/problems/" + code, title, status, detail, ...(errors ? { errors } : {}) };
  return new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/problem+json" } });
}

A small test helper. It records each call and answers with the reply you give it.

Now use it. This test makes createBooking(12) meet a 409 reply, the same one the server sends when the slot is taken. It checks that the client returns the problem and sent the right body.

TypeScripttests/test-api-client.ts
const fake = fakeFetch(() => problem(409, "slot-taken", "Slot already taken", "That slot has just been booked by someone else."));
const client = createApiClient({ fetch: fake.fetch });
const result = await client.createBooking(12);
assert.equal(result.ok, false);
if (!result.ok) assert.equal(problemCode(result.problem), "slot-taken");
assert.equal(fake.calls[0].body, '{"slotId":12}');
show("createBooking: 409 slot-taken", result);
console.log("request: " + fake.calls[0].method + " " + fake.calls[0].url + " " + fake.calls[0].body);

Part of the test: the 409 case.

Real output: success and the 409 problemCaptured from a real run
== getFreeSlots: success ==
{
  "ok": true,
  "data": [
    {
      "slotId": 12,
      "startsAt": "2026-12-01T09:00:00Z",
      "endsAt": "2026-12-01T09:45:00Z"
    },
    {
      "slotId": 13,
      "startsAt": "2026-12-01T10:00:00Z",
      "endsAt": "2026-12-01T10:45:00Z"
    }
  ]
}
request: GET /api/clinicians/1/free-slots?date=2026-12-01
== createBooking: 409 slot-taken ==
{
  "ok": false,
  "problem": {
    "type": "https://tidewell.example/problems/slot-taken",
    "title": "Slot already taken",
    "status": 409,
    "detail": "That slot has just been booked by someone else."
  }
}
request: POST /api/bookings {"slotId":12}

The other cases in the same test file give these results. A 422 reply from moveBooking comes back as a problem whose detail holds the clinic's phone number and opening hours. A 400 reply carries the list of field errors. A thrown network error and a timeout both come back as problems with status 0. A 502 reply with an HTML page comes back as an 'unexpected response' problem.

Real output: network failureCaptured from a real run
{
  "ok": false,
  "problem": {
    "type": "https://tidewell.example/problems/network-error",
    "title": "Network error",
    "status": 0,
    "detail": "The server could not be reached."
  }
}
Real output: timeout after 30 millisecondsCaptured from a real run
{
  "ok": false,
  "problem": {
    "type": "https://tidewell.example/problems/network-error",
    "title": "Network error",
    "status": 0,
    "detail": "The server took too long to answer."
  }
}
request: POST /api/bookings/7/cancel body=undefined

The timeout test uses a fake server that never answers. The client was given a limit of 30 milliseconds. It gave up and reported 'The server took too long to answer.' Real apps use a longer limit, such as the default of eight seconds in this client.

Worked scenario: Tidewell handles a taken slot

Two patients look at the 10:00 slot at the same time. Patient A confirms first. Patient B confirms a moment later. The database rule you built in Module 4 allows only one live booking per slot, so the server answers Patient B with 409 and the code slot-taken.

Patient B's screen must do three things: say what happened, avoid blaming the patient, and show the current free times. The client hands the screen a problem. A small function turns every result into a state the screen can show.

TypeScriptsrc/lib/load-state.ts
import type { ApiResult, Booking, LoadState, SubmitState } from "../features/bookings/types";
import { problemCode } from "./api-client";

export function toLoadState<T>(result: ApiResult<T[]>): LoadState<T[]> {
  if (!result.ok) return { status: "error", problem: result.problem };
  if (result.data.length === 0) return { status: "empty" };
  return { status: "ready", data: result.data };
}

export function toSubmitState(result: ApiResult<Booking>): SubmitState {
  if (result.ok) return { status: "success", booking: result.data };
  if (problemCode(result.problem) === "slot-taken") return { status: "conflict", problem: result.problem };
  return { status: "error", problem: result.problem };
}

Two small functions that turn an API result into a state. The next lesson explains the states.

Real output: results turned into statesCaptured from a real run
no slots        -> {"status":"empty"}
one slot        -> ready
409 slot-taken  -> conflict
created booking -> success
500             -> error

A 409 with slot-taken becomes a conflict state. Any other failed booking becomes error. The screen reloads the free times after a conflict, so Patient B sees the 10:00 slot gone.

A 422 notice-period reply works the other way round: the server decides, and the screen shows the server's text. Remember the decision the practice manager confirmed. A patient can move or cancel online only if the appointment starts at least 24 hours from now, and exactly 24 hours counts as allowed. The client never calculates this. It passes the answer through.

Step-by-step workflow

  1. Step 1: Copy the contract into types

    Write or generate the types for every response and for the problem format. Keep the field names exactly as the API sends them.

    What you should see: A types file that a typo in a field name cannot slip past.

  2. Step 2: Write the one request function

    Handle the network error, the timeout, a reply that is not JSON, a problem reply and a good reply. Return an ApiResult every time.

    What you should see: One function that never throws for expected failures.

  3. Step 3: Add one function per endpoint

    Name each after what the screen wants. Check each path, method and body against the contract.

    What you should see: Six functions that match the six routes.

  4. Step 4: Test with a fake fetch

    Cover success, a 409, a 422, a 400 with errors, a network failure and a timeout. Run the tests twice to be sure the results are the same.

    What you should see: Test output that you can read and that does not change between runs.

  5. Step 5: Review the generated code for hidden risks

    Look for keys in the code, calls to addresses you did not list, swallowed errors and extra endpoints.

    What you should see: A short review note with 'accepted' or the changes you asked for.

From contract to tested client
  1. Contract

    Routes, fields, problems

  2. Types

    Same names

  3. Client

    One function per route

  4. Fake fetch tests

    Success and failure

  5. Review

    No secrets, no extras

The contract is the source. Each stage checks the one before it.

What the assistant can and cannot do when writing an API client

Assistants write fetch code easily, and that is the risk. The code compiles, looks tidy and quietly differs from your contract. Give it the contract and the problem format, ask for tests with a fake fetch, and check each endpoint by hand.

TaskAssistant's partYour part
Writing the clientDraft it from the contract and types.Check each path, method and body against the contract.
Handling failuresCover network errors, timeouts and bad replies.Check that none are swallowed and that every failure becomes a problem.
Writing testsDraft tests with a fake fetch.Check that each test would fail if the client broke.
Using the browser's fetchNothing special.Make sure the fake is injectable and no real network is used in tests.
Choosing a data libraryMention options if asked.Decide whether one is worth its upkeep.

Conclusion and your next step

One typed client keeps every server call in a single place. It returns data or a problem, never a surprise. A fake fetch lets you test success, a taken slot, a bad request and a dead connection without a real server.

Your next step: write the client for your own capstone API and test it with a fake fetch, then continue to Loading, Empty and Error States. There you decide what the person sees while waiting and when things fail.

For more help, read API-First Development: OpenAPI Contracts with AI, which explains how a contract keeps both sides in step. The AI-Generated Code Review Checklist lists what to look for in generated code.

Reusable prompt

API client from a contract

Asks for a typed API client built only from your contract, with injectable fetch and tests for success and failure.

You are helping me write a typed API client. Use only the contract below. Do not add endpoints, libraries or secrets.

Project: Tidewell Physiotherapy booking system (fictional). TypeScript strict, Next.js App Router, runs in the browser. Use the built-in fetch.

Contract (JSON fields are camelCase):
GET  /api/clinicians -> 200 [{ id, displayName }]
GET  /api/clinicians/{clinicianId}/free-slots?date=YYYY-MM-DD -> 200 [{ slotId, startsAt, endsAt }]
GET  /api/bookings -> 200 [{ bookingId, slotId, clinicianName, startsAt, endsAt, status }]
POST /api/bookings { slotId } -> 201 booking
POST /api/bookings/{bookingId}/move { slotId } -> 200 booking
POST /api/bookings/{bookingId}/cancel -> 200 booking
Errors use problem details: { type, title, status, detail, errors? }. Codes: invalid-request (400), not-found (404), slot-taken (409), notice-period (422), internal-error (500).

Requirements:
1. One function per endpoint: listClinicians, getFreeSlots, listMyBookings, createBooking, moveBooking, cancelBooking.
2. Each returns { ok: true, data } or { ok: false, problem }. Do not throw for expected failures.
3. A network failure or timeout (use AbortSignal.timeout) returns a problem with status 0 and type ending in network-error.
4. fetch must be injectable so tests can pass a fake.
5. No keys, tokens or fixed server addresses in the code.

Output: src/lib/api-client.ts and a test file that uses a fake fetch for success, 409, 422, a network failure and a timeout. List anything you assumed.
Show the reusable template

Replace each {{placeholder}} with your own details.

You are helping me write a typed API client. Use only the contract below. Do not add endpoints, libraries or secrets.

Project: {{project_and_stack}}.

Contract:
{{endpoint_list_with_fields}}
Errors: {{problem_format_and_codes}}

Requirements:
1. One function per endpoint: {{function_names}}.
2. Each returns { ok: true, data } or { ok: false, problem }. Do not throw for expected failures.
3. A network failure or timeout returns a problem with status 0.
4. fetch must be injectable so tests can pass a fake.
5. No keys, tokens or fixed server addresses in the code.

Output: {{files_to_produce}}, and a test file that uses a fake fetch for success, each error code you care about, a network failure and a timeout. List anything you assumed.

Expected output and limitations

A client file with one typed function per endpoint, a shared request function that returns a result, and a test file that uses a fake fetch. Assumptions are listed at the end.

Sample responseIllustrative — your output will differ
// src/lib/api-client.ts (excerpt)
async function request<T>(path: string, init = {}): Promise<ApiResult<T>> {
  try {
    const response = await send(baseUrl + path, { ...init, signal: AbortSignal.timeout(timeoutMs) });
    ...
  } catch {
    return { ok: false, problem: networkProblem() };
  }
}

export const listMyBookings = () => request<Booking[]>("/api/bookings");

Assumptions:
- The base address is empty because the pages and the API share one site.
- Dates are sent as YYYY-MM-DD text and not changed.
- Tests pass the fake through an options object.

Limitations to keep in mind

  • The assistant may add an endpoint the contract does not have, or a helper library. Compare every route with the contract.
  • Tests may check only the happy path. Ask for the failure cases by name and read each assertion.
  • It may catch an error and return an empty list, which hides the failure. Check that every failure is returned as a problem.

Common errors and how to fix them

A failed request shows a blank page.

Why it happens: The client threw, and no screen caught it.

Fix: Return failures as an ApiResult, so the screen must handle both cases.

The client treats any non-JSON reply as a crash.

Why it happens: A gateway or proxy sent an HTML error page.

Fix: Wrap response parsing in its own try, and return an 'unexpected response' problem.

An API key or token is typed into the frontend code.

Why it happens: It was copied from an example, or the assistant made it up.

Fix: Remove it. Keep secrets on the server, and rotate any real key that was exposed.

Validation checklist

Tick each item once you have confirmed it.

Hands-on exercise

A Ferngate client function

Ferngate Cycle Repairs has an endpoint POST /api/stock-movements that takes { partId, jobId, quantity } and returns the new movement. Write a typed client function for it that returns data or a problem, and test it with a fake fetch for success, a 422 'unknown-part' problem and a lost connection.

You will need

  • Endpoint: POST /api/stock-movements with body { partId: number, jobId: number, quantity: number }.
  • Success reply: 201 with { movementId, partId, jobId, quantity }.
  • Problem reply: 422 with type ending in unknown-part, in the same problem-details format as Tidewell.
  • Note: the workshop connection is unreliable, so a timeout is likely.

Acceptance criteria

Your work is done when every one of these is true.

Hints (2)
  • Reuse the shape of the Tidewell request function. Only the path and types change.
  • After a timeout a POST may still have reached the server. Decide how the screen should word that.
Show a model answer

A strong answer defines a StockMovement type and a problem type, and wraps the single call in the same request function used for Tidewell. The three tests are: a 201 returns ok true with the movement, a 422 returns ok false with the unknown-part problem, and a fetch that throws returns status 0. The lost-connection test checks the message says the entry may not have been saved and tells the mechanic where to check, because a timed-out POST can still have succeeded. The code holds no key or fixed server address, and the fake fetch is passed in as an option.

Knowledge check

Choose an answer, then check it. Nothing is recorded — this is for you.

  1. 1.Why does the API client return { ok: false, problem } instead of throwing?
    Show the answer and explanation

    Answer: B. A slot being taken is normal, so it should be a normal value that code must deal with. Speed is not the reason, which is the tempting answer. TypeScript can catch errors, but it cannot force a screen to write a try block, whereas a result type makes the check unavoidable.

  2. 2.What does injecting fetch allow?
    Show the answer and explanation

    Answer: A. Injection means the client accepts its fetch from outside, so a test can supply a fake. Caching and type checking are separate matters that injection does not touch.

  3. 3.A POST to cancel a booking times out. What should the screen tell the patient?
    Show the answer and explanation

    Answer: C. After a timeout the request may or may not have reached the server, so neither 'nothing changed' nor 'cancelled' is safe to claim. 'Nothing has been changed' sounds reassuring, which makes it tempting, but if the cancellation went through the patient could be told the opposite of the truth.

Frequently asked questions

What is an API client in frontend development?

It is a module that holds all the calls your frontend makes to the server. Screens call its functions and do not build web addresses or parse raw replies. When the API changes, you update one file.

How do I handle a fetch error in TypeScript?

Wrap the call in try and catch, turn the failure into a value such as { ok: false, problem }, and return it. Also check the reply status, because fetch does not throw for a 404 or 500. The screen then checks ok and shows the right message.

How do I test code that uses fetch?

Make fetch something you can pass in, then hand in a fake function that returns the replies you want. You can then test success, error codes and a dead connection without any network. This course's client takes its fake through an options object.

Can I put an API key in my frontend code?

No. Anything in frontend code is sent to the browser, where anyone can read it. Keep keys on the server and let your own API call the outside service. If a key was exposed, revoke it and create a new one.

Written by
PromptFable Editorial
Last updated 19 Nov 2026
Review
Reviewed by Waseem Nadir, Technical Reviewer
Last reviewed 27 Nov 2026

References

Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.

PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.