Skip to main content

The request fixture

Why This Matters

Not every check needs a browser. Whether the cart adds tax correctly, whether an out-of-stock product is refused, whether a cancelled order returns its stock: the API can answer all of that in a fraction of a second. Playwright has an HTTP client built in, so UI and API tests share one tool, one config, one report and one CI job.

The Shop API

practiceautomatedtesting.com documents its API at /api, with an openapi.json. The base URL is https://practiceautomatedtesting.com/api/shop. Three features make it good for testing:

  • Your own sandbox. Send any X-Session-Id header and you get your own cart, orders and stock. The response echoes the id back.
  • A clean start. POST /reset empties the cart, removes the orders and restores the stock.
  • Waiting practice. X-Delay-Ms: 2000 slows any response down (up to 5000 ms).

The built-in request fixture

Every test can ask for request, an HTTP client that uses the config’s baseURL:

import { expect, test } from "@playwright/test";

test("lists products", async ({ request }) => {
  const response = await request.get("/api/shop/products", { params: { limit: 4 } });
  expect(response.status()).toBe(200);
  const body = await response.json();
  expect(body.items).toHaveLength(4);
});

get, post, patch, put and delete all work the same way. params become the query string; data becomes a JSON body.

A fixture that gives every test its own sandbox

Sending the same headers in every call is repetitive, and forgetting the sandbox id means tests share a cart. The example repository therefore has its own fixture, in tests/fixtures/api.ts:

export const test = base.extend<{ sandboxId: string; api: APIRequestContext }>({
  sandboxId: async ({}, use) => {
    await use(`pw-${randomUUID()}`);
  },
  api: async ({ playwright, baseURL, sandboxId }, use) => {
    const api = await playwright.request.newContext({
      // The trailing slash matters: "products" then resolves to /api/shop/products.
      baseURL: `${baseURL}/api/shop/`,
      extraHTTPHeaders: { "X-Session-Id": sandboxId },
    });
    await use(api);
    await api.dispose();
  },
});

A test that imports test from this file gets an api client in a fresh sandbox, and can still read the id if it needs it:

import { expect, test } from "../fixtures/api";

test("echoes the sandbox id it used", async ({ api, sandboxId }) => {
  const response = await api.get("products");
  expect(response.headers()["x-session-id"]).toBe(sandboxId);
});

Lesson 32 (fixtures) explains test.extend in depth; for now, this one is ready to use.

A project without a browser

API tests do not need Chromium, Firefox and WebKit. The config runs every *.api.spec.ts file once, in its own project:

{ name: "api", testMatch: /\.api\.spec\.ts$/ },
npx playwright test --project=api

In the real run, most API tests took between 150 and 500 milliseconds; the browser tests in the same run took two to five seconds each.

Exercise

Write a test with the api fixture that adds two Bluetooth Headphones (product 5) to the cart with POST cart/items, and checks the response status and the cart’s itemCount.

Show suggested solution
test("adds two headphones", async ({ api }) => {
  const response = await api.post("cart/items", { data: { productId: 5, quantity: 2 } });
  expect(response.status()).toBe(201);
  const cart = await response.json();
  expect(cart.itemCount).toBe(2);
});

POST cart/items returns 201 (created) and the whole cart, so one call gives you everything to check. The full version, with schema checks and the tax, is in tests/module-4/cart.api.spec.ts.