API testing in Playwright
The request fixture (APIRequestContext) sends HTTP requests straight from the worker's Node process, with no browser, so API tests and E2E share a runner. It does not throw on 4xx and 5xx, so status and body are checked explicitly. The API is a fast way to prepare data for UI tests, cleaned up in a fixture teardown. An API test does not see CORS or prove the frontend sent the right request.
Playwright · API tests
Creating an account through the UI takes seconds, through the API milliseconds. So why use a browser to prepare data?
In an E2E suite every scenario spends half a minute on preparation: open the form, fill the fields, press "Create", wait for the response. The scenario itself checks one account card, while the preparation takes most of the time and breaks on any small UI change. The same account creation over HTTP takes a fraction of a second. This lesson is about calling the API in Playwright without a browser, both for standalone API tests and as a helper for E2E, and about where this ability ends.
How it works and why. The request fixture is of type APIRequestContext. It sends HTTP requests straight from the worker's Node process: get, post, put, patch, delete, head. There is no browser in this chain, so no rendering, no page JavaScript and no CORS: just a request and a response. If a test does not ask for the page fixture, no browser is even launched for it. The idea is that browser and API tests live in one runner: shared config, fixtures, retries, parallelism and report. A separate API tool would mean a second set of configs and a second report.
Two paths to the same API
page.request sits in between: the same cookies as the page, but no rendering.Setup. baseURL and extraHTTPHeaders (for example a token) are set in the config at project level, to keep them apart from browser tests. Then every request from the request fixture carries them automatically.
// playwright.config.ts
export default defineConfig({
projects: [
{
name: 'api',
testMatch: '**/*.api.spec.ts',
use: {
// the trailing slash matters: the /v1/ prefix is kept for relative paths
baseURL: 'https://api.test.bank/v1/',
extraHTTPHeaders: {
Accept: 'application/json',
Authorization: 'Bearer ' + process.env.API_TOKEN,
},
},
},
],
});
There is a trap with paths. Playwright builds the address as new URL(path, baseURL), so a leading slash makes the path absolute and the /v1/ prefix disappears. The trailing slash in baseURL is needed, and the request path is written without a leading slash.
A slash at the start of the path
get('/accounts')
The address becomes https://api.test.bank/accounts. The /v1/ prefix is lost, the server answers 404, and it looks as if the resource broke.
get('accounts')
The address becomes https://api.test.bank/v1/accounts. The prefix is kept. If in doubt, print response.url().
A first test. The full account cycle: create, read, delete, make sure it is gone. The status is read with response.status(), the body with response.json(), and the general "2xx" check comes from the web-first assertion expect(response).toBeOK().
import { test, expect } from '@playwright/test';
test('create, read and delete an account', async ({ request }) => {
const created = await request.post('accounts', { data: { currency: 'UAH' } });
expect(created.status()).toBe(201);
const { id } = await created.json();
const fetched = await request.get('accounts/' + id); // no leading slash
await expect(fetched).toBeOK();
expect(await fetched.json()).toMatchObject({ id, currency: 'UAH', balance: 0 });
const removed = await request.delete('accounts/' + id);
expect(removed.status()).toBe(204);
expect((await request.get('accounts/' + id)).status()).toBe(404);
});
Negative scenarios. By default request does not throw on 4xx and 5xx, it returns the response. So checking 401, 403, 404 or 422 is an ordinary expect(res.status()) together with a check of the error body. A status alone says little: a 200 with an empty or mangled JSON passes too. To check the response shape, zod or ajv is plugged in: a schema catches vanished fields and changed types, which a toMatchObject on two or three fields will not see.
import { z } from 'zod';
const Account = z.object({
id: z.string().min(1),
currency: z.enum(['UAH', 'USD', 'EUR']),
balance: z.number(),
});
test('GET /accounts matches the schema', async ({ request }) => {
const res = await request.get('accounts');
await expect(res).toBeOK();
const parsed = z.array(Account).safeParse(await res.json());
expect(parsed.success, JSON.stringify(parsed.error?.issues)).toBe(true);
});
Before and after: preparing data for a UI test. First, what happens most often:
// before: preparation by clicking, cleanup after the asserts
test('the account card shows the balance', async ({ page }) => {
await page.goto('/accounts/new');
await page.getByLabel('Currency').selectOption('UAH');
await page.getByLabel('Owner').fill('qa-test'); // the same key in every run
await page.getByRole('button', { name: 'Create' }).click();
await expect(page.getByTestId('balance')).toHaveText('0.00 UAH');
await page.getByRole('button', { name: 'Delete' }).click(); // skipped on failure
});
There are three problems. The preparation clicks through a form, so the test fails when the form changes although it checks something else. The key qa-test is the same in every run, and parallel workers will collide. The deletion comes after the assertion: if the assertion fails, an exception interrupts the test body, the account stays on the server, and the next run stumbles on it. The fix:
// after: one POST prepares the data, the fixture cleans up
// baseURL of this e2e project is the app root (no prefix), so a leading slash is safe
export const test = base.extend<{ account: { id: string } }>({
account: async ({ request }, use) => {
const res = await request.post('/api/accounts', {
data: { currency: 'UAH', owner: 'qa-' + crypto.randomUUID() },
});
const account = await res.json();
await use(account);
await request.delete('/api/accounts/' + account.id); // also after a failed test
},
});
test('the account card shows the balance', async ({ page, account }) => {
await page.goto('/accounts/' + account.id);
await expect(page.getByTestId('balance')).toHaveText('0.00 UAH');
const me = await page.request.get('/api/me'); // shares cookies with the page
await expect(me).toBeOK();
});
One POST with a unique key creates the data. The code after use in a fixture runs even when the test failed, so cleanup always happens. The UI checks only what the test must check. The page.request context (likewise context.request) shares cookies with the browser context: after a UI login the requests are already authorized, and vice versa.
Limits and alternatives. An API test in Playwright does not check what the browser does. It will not see CORS errors, because the request does not come from a browser. It will not prove that the frontend sent the right body, so for that a UI test creates page.waitForRequest before the click and awaits it afterwards. It is not a load tool either: parallel workers do not replace k6 or JMeter. Compared with Postman or REST Assured the gain is that tests live in the same repository and language as the UI tests, and the loss is that there is no ready collection for manual exploration.
| Task | Tool |
|---|---|
| Check the contract, statuses, errors | an API test with request |
| Prepare data before a UI test | a fixture with request and cleanup |
| Sign in without the login form | API login and storageState |
| Prove the UI sent the right request | waitForRequest in the UI test |
Common mistakes.
- A leading slash in the path with a prefixed
baseURL: the request bypasses/v1/and returns 404. - Checking only the status: an empty or wrong body with code 200 passes, and a broken contract goes unnoticed.
- Preparing data by clicking where a single POST would do: the test is slow and depends on a UI it does not check.
- Cleaning up after the assertions in the test body instead of a fixture: on failure it does not run, and data piles up.
- Static identifiers in data (
test@test.com): parallel workers conflict.
Check yourself
The config has baseURL: 'https://api.test.bank/v1/', and request.get('/accounts') returns 404 although the resource exists. What is the cause and how do you see it?
Answer
A leading slash makes the path absolute: new URL('/accounts', baseURL) gives https://api.test.bank/accounts, and the /v1/ prefix is lost. You can see it through response.url(). The fix is get('accounts').
The account fixture creates an account and deletes it after use. The test fails on an assertion. Does the account stay on the server? And if the deletion sits at the end of the test body?
Answer
With the fixture it does not stay: the code after use runs even on failure. At the end of the test body it does stay: a failed expect throws, and execution never reaches the deletion.
A test checks only expect(res.status()).toBe(200). The backend started returning {} instead of a list, and the frontend broke. Why is the test green and what should be added?
Answer
Status 200 says only that the server answered successfully, not that the body is right. Add a body check: a schema through zod or ajv, or at least toMatchObject on the key fields.
request fixture with baseURL and a token in the config. I check the status and body explicitly, because a 4xx does not throw. Middle/Senior: I add a schema check through zod and prepare E2E data through the API with a unique key, then clean up in the fixture teardown so cleanup runs even after a failure. I remember the limits: an API test will not see CORS and does not prove that the frontend sent the right request, which is what waitForRequest in a UI test is for.