LESSON VIEW
LAB-5 · AUTOMATION PRACTICE LAB · PRACTICAL QA

API Testing in the Suite

Objective: Build API checks that live inside your Playwright suite — for setup, for verification beneath the UI, and in hybrid API-plus-UI tests — with assertions that climb the ladder from semantic status to shape, values, and refusals.

⏱ ≈2 h practice unit · Code: copy, paste, practise · English edition — Español · العربية · বাংলা in translation

🧽 The practice business: FreshNest Home Cleaning — a fictional local cleaning company (owner: Maya Torres) invented for this course. Every example and exercise uses FreshNest, so you learn on a complete, realistic business without ever touching a real one.

⚡ Key Points

  • An API test sends a request and checks the response — no browser, no rendering, no clicking.
  • Three jobs in the suite: setup at machine speed, verification beneath the UI, contract checks.
  • Climb the assertion ladder: semantic status → shape (never the whole payload) → values that matter → refusals.
  • Hybrid pattern: API creates and cleans up, UI asserts the visible truth, API verifies the record.
  • Credentials live in environment variables only — code gets cloned, logged, and screenshotted.

📖 Read

Under every page, the browser makes requests — "give me this page", "here is the form data" — and gets responses with a status code attached. An API is programs making those requests without a browser. An API test therefore skips the screen entirely: send a request, check the response. That makes API tests much faster and more precise than UI tests, at the cost of not seeing what a user sees — which is why professionals layer them: many fast unit and API checks underneath, fewer slow UI journeys on top (the test pyramid). Four codes cover most of testing life: 200 = OK, here is your answer; 301/302 = moved, follow me; 404 = not found, wrong address; 500 = server error, their machine broke answering.

Inside a suite, API checks do three jobs. Setup at machine speed: create state via API instead of clicking through screens to seed it. Verification beneath the UI: after the UI acts, ask the API what the system recorded — the screen says "order placed", the API says whether an order with the right total actually exists. And contract checks: the response's shape and status semantics are sane. The professional assertion ladder is: status, semantically (201 for a create, 404 for a missing thing, 400 for nonsense — not a 500) → shape (required fields exist with the right types; extra fields are tolerated, because APIs may grow) → values that matter (totals reconcile, IDs echo back) → refusals (401 unauthenticated, 403 or 404 for another user's resource, 400 for bad input). Asserting an entire payload byte-for-byte is the trap at the top of the ladder: it makes the test a change-detector for every edit, including harmless ones — flake by design. Playwright fits this work in one suite because its request fixture shares context with the browser, so cookies and auth carry between the UI and API sides and hybrid tests are natural instead of glued.

The pattern worth stealing is the hybrid: the API creates fresh test data marked with this run's ID, the UI opens the page and asserts it renders with the API's values, the API fetches the record to assert what the visit recorded, and the API deletes it — cleanup that keeps runs independent. Each surface does what it is most truthful and fastest at: API for state logistics, UI for the human-visible truth. Most "slow UI suite" rescues are this pattern applied with discipline. Two honesty and safety rules close the unit. Authenticated testing uses a customer-provided test account on staging only, and credentials live in environment variables at runtime — never in code, because a credential in a test file is in every clone, every CI log, and every tutorial screenshot. And in this course's own practice project, the FreshNest API from lesson PQA-08 (api.freshnest.example) is a clearly-labelled simulated API on a reserved example domain: you practise the full ladder against its specified behaviour, and nothing touches a real system.

💻 Code for this unit — copy, paste, practise

The original worked code for this unit, verbatim, with its line-by-line explanations. Run it against the course practice project (download on the course page).

B-11 · Example 1 — API testing basics

const r = await fetch(target, { method: "HEAD" });
if (r.status !== 405) status = r.status;
expect(status).toBeGreaterThan(0);
expect(status).toBeLessThan(400);

Inside TC-002: ask cheaply first (HEAD = “just your status, not the whole page”), fall back if refused, then assert a RANGE — anything under 400 is healthy, because redirects are fine too. Request → status → assertion: an API test in miniature.

B-11 · Example 2 — API testing basics

const target = new URL(href, page.url()).toString();
let status = 0;
try { const r = await fetch(target, { method: "HEAD", redirect: "follow" }); if (r.status !== 405) status = r.status; } catch {}
if (!status) { try { const r = await fetch(target, { redirect: "follow" }); status = r.status; } catch {} }
if (!status) { const res = await request.get(href).catch(() => null); status = res ? res.status() : 0; }
expect(status, `target ${href} should respond < 400`).toBeGreaterThan(0);
expect(status, `target ${href} should respond < 400`).toBeLessThan(400);

From the module's full text.

A-06 · Example 1 — API testing in the suite

API: create a fresh listing (marked with this run's ID)
UI:  open its page → assert it renders with the API's values
API: fetch it → assert view-state recorded
API: delete it (cleanup)

The HYBRID pattern: each surface does what it's most truthful at. UI stays short because the API did the commuting. Most “slow UI suite” rescues are this pattern, applied with discipline.

A-06 · Example 2 — API testing in the suite

API: create a fresh listing (test data, marked with this run's ID)
UI:  open the listing page → assert it renders with the API's values
API: fetch the listing → assert view-state recorded correctly
API: delete the listing (cleanup, A-03)

From the module's full text.