QA Interview Hub · Knowledge base · Quizzes · Українська

Playwright

API testing in Playwright

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

API test: no browser test request API E2E: through the browser test page browser API page.request: cookies of the page,but no clicks and no rendering
Figure 1. An API test goes straight to the API; a UI test goes through the browser. 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

Typical

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.

Better

get('accounts')

The address becomes https://api.test.bank/v1/accounts. The prefix is kept. If in doubt, print response.url().

Figure 2. One extra slash changes the address while the test stays syntactically correct.

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.

TaskTool
Check the contract, statuses, errorsan API test with request
Prepare data before a UI testa fixture with request and cleanup
Sign in without the login formAPI login and storageState
Prove the UI sent the right requestwaitForRequest 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.

In an interview. Junior: For the API I use the 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.

APIRequestContext in depth

An APIRequestContext is an HTTP client with its own baseURL and headers that sends requests without a browser. The request fixture and request.newContext have isolated cookies, while page.request shares them with the browser context. The request fixture closes itself, and a manual context is closed with dispose(). A separate context is needed for different roles in one test: the admin token goes into its own context, best in a worker fixture.

Playwright · API tests

The admin token sits in the config, and the "regular" user in the test acts as an admin too. Where is the bug?

The test "a regular user cannot delete someone else's account" expects 403 and gets 204: the account is really deleted. The server is not at fault. The config has extraHTTPHeaders with an admin token, and every request from the request fixture carries it, so the "user" acted as an admin all along. The request fixture is enough for typical cases, but when one test needs different roles, another service, or a token that is expensive to get, a separate APIRequestContext is created. This lesson covers what that object is, how long it lives and where it shares state with the browser.

How it works and why. An APIRequestContext is a client with its own settings: baseURL, headers, timeout, httpCredentials, ignoreHTTPSErrors, storageState, and with its own cookie storage. A context from request.newContext() is independent of the browser, while page.request and context.request share cookies with the browser context. A manually created context has its own cookie storage and does not share it with other contexts. But inside a test or hook request.newContext() takes from the config every option you did not set explicitly (baseURL, extraHTTPHeaders, storageState), so for another role you set them yourself, and then two roles in one test do not mix. The difference between the ways to get a context is exactly whose cookies it uses and who closes it.

Where a context comes from and whose cookies it has

page.requestcontext.requestbrowser cookiesshared with the page requestfixtureown cookiesone test, closes itself newContext()dispose() by handown cookiesuntil dispose()
Figure 1. The highlighted block shares state with the browser, the green ones have their own. A context created by hand is closed by the test author.

Creation and lifecycle. A context is created with request.newContext (imported from @playwright/test) or with playwright.request.newContext inside a fixture. The built-in request fixture closes itself, while a manually created context must be closed with dispose(): this frees connections and stored response bodies.

import { request, expect } from '@playwright/test';

const admin = await request.newContext({
  baseURL: 'https://api.test.bank/v1/',
  extraHTTPHeaders: { Authorization: 'Bearer ' + process.env.ADMIN_TOKEN },
  timeout: 15_000,
});
const res = await admin.post('accounts', {
  data: { currency: 'UAH', type: 'savings' },
  params: { dryRun: 'false' },
});
await expect(res).toBeOK();
const { id } = await res.json();
await admin.dispose(); // frees the connection and the stored responses

Before and after: roles in one test. The setup the story began with: an admin token in the shared config.

Where the admin token lives

Typical

Admin token in use.extraHTTPHeaders

Every request from request carries it. "User" and "admin" become one role, and negative permission tests give false results.

Better

A separate context for the admin

The plain request carries the user token. The admin context is created only where it is needed, and once per worker.

Figure 2. Permissions are checked with the token that is in the request, not the one the author had in mind.

The fix: the regular user token stays in the config, and the admin context moves into a worker-scoped fixture. It is created once per worker and closed when the worker finishes; fixture scopes are covered in the fixtures lesson.

import { test as base, expect, type APIRequestContext } from '@playwright/test';

export const test = base.extend<{}, { admin: APIRequestContext }>({
  admin: [
    async ({ playwright }, use) => {
      const ctx = await playwright.request.newContext({
        baseURL: 'https://api.test.bank/v1/',
        extraHTTPHeaders: { Authorization: 'Bearer ' + process.env.ADMIN_TOKEN },
      });
      await use(ctx);
      await ctx.dispose(); // runs when the worker finishes
    },
    { scope: 'worker' }, // one context per worker, not per test
  ],
});

test('a regular user cannot delete someone else\'s account', async ({ request, admin }) => {
  const created = await admin.post('accounts', { data: { currency: 'UAH' } });
  const { id } = await created.json();

  const denied = await request.delete('accounts/' + id); // the user token from the config
  expect(denied.status()).toBe(403);
  await expect(await admin.get('accounts/' + id)).toBeOK(); // still there

  await admin.delete('accounts/' + id);
});

Now the test separates roles clearly: admin does the preparation, and request with the user token is what is being checked. The last check (admin.get after the delete attempt) proves that the account did not just get a 403 but really stayed in place.

Body format. The body is set by an option, and the Content-Type depends on it:

OptionWhat is sent
data, an objectJSON, application/json
data, a string or a Bufferas is; without an explicit Content-Type it goes as application/octet-stream
formapplication/x-www-form-urlencoded
multipartmultipart/form-data, files as { name, mimeType, buffer }
paramsthe query string of the address
await api.post('login', { form: { username: 'qa', password: 'Secret123' } });
await api.post('documents', {
  multipart: {
    title: 'Statement',
    file: { name: 'a.pdf', mimeType: 'application/pdf', buffer: Buffer.from('%PDF-1.4') },
  },
});
await api.get('transactions', { params: { from: '2026-01-01', limit: 50 } });
await api.fetch('accounts/1', { method: 'PATCH', data: { nickname: 'Savings' } });

Errors, statuses and repeated checks. 4xx and 5xx do not throw by default, which is convenient for negative tests. The failOnStatusCode: true option turns any error into an exception, and it fits data preparation, where a failure must stop the test at once. For network failures (a dropped connection) fetch and the other calls have a maxRetries option; it does not retry on a response code. Asynchronous processes, for example a payment processed for several seconds, are not checked with a single request: the status is polled through expect.poll instead of a fixed pause. The function in poll returns a value and the assertion after it compares; poll exits as soon as the value matches, so the fast case does not wait longer than needed.

// a negative test: 4xx does not throw by default
const bad = await api.post('transfers', { data: { amount: -1 } });
expect(bad.status()).toBe(422);
expect(await bad.json()).toMatchObject({ code: 'invalid_amount' });

// preparation where an error must stop the test at once
await api.post('accounts', { data: { currency: 'UAH' }, failOnStatusCode: true });

// eventual consistency: poll the status instead of sleeping
await expect
  .poll(
    async () => {
      const r = await api.get('transfers/' + id);
      return (await r.json()).status;
    },
    { timeout: 15_000, intervals: [500, 1000, 2000] },
  )
  .toBe('completed');

State, cookies and projects. After a login through the API the state is saved: await ctx.storageState({ path: '.auth/user.json' }), and used in browser tests, which saves the time of logging in through the form.

// log in through the API and hand the state to the browser tests
const api = await request.newContext({ baseURL: 'https://app.test/' });
await api.post('api/login', { data: { email: 'qa@example.com', password: 'Secret123' } });
await api.storageState({ path: '.auth/user.json' });
await api.dispose();

For pure API tests it is handy to make a separate project without browser settings: a browser starts only when a test asks for page, so an API test does not launch one.

// playwright.config.ts: the API project has no browser settings
projects: [
  { name: 'api', testMatch: '**/*.api.spec.ts' },
  {
    name: 'e2e',
    testIgnore: '**/*.api.spec.ts',
    use: { ...devices['Desktop Chrome'], storageState: '.auth/user.json' },
  },
],

Limits and alternatives. A manual context is a responsibility: the runner will not close it, and if the test fails before dispose() the resources stay, so a context in a fixture is safer than one in the test body. A context has no "smart" token refresh: when a token expires in the middle of a long run, you have to log in again yourself. For a browser user a context is not needed: page.request is enough there. A comparison of the ways:

WayContext lifetimeWhen
request fixtureone test, closes itselfordinary API tests and data preparation
page.requestwith the page, shares cookiesrequests on behalf of the browser user
request.newContext in a testuntil dispose()another user or service
in a worker fixtureone per workeradmin token, expensive authorization

Common mistakes.

  • A forgotten dispose() in a manual context: connections and response bodies hang around, and the finish time grows on CI.
  • Assuming a 4xx throws an exception: a test without a status check passes with an error.
  • An admin token in the shared config for all tests instead of a separate context only where it is needed: all roles merge into one.
  • A fixed pause instead of expect.poll for asynchronous processing: either flakes or wasted seconds.
  • A string in data without a Content-Type when the server expects JSON: it goes as application/octet-stream, and the server rejects the body.

Check yourself

The config has an admin token in extraHTTPHeaders, and the test "a user cannot delete someone else's account" gets 204. Why, and how do you fix it?

Answer

Every request from the request fixture carries the token from the config, so the test acts as an admin. Keep the regular user token in the config and give the admin a separate context (preferably in a worker fixture).

A test creates request.newContext in the body and fails on an assertion before dispose(). What happens to the context and how do you avoid it?

Answer

The exception interrupts the body, dispose() is not called, and the resources stay. Move the context into a fixture (the code after use runs even on failure) or wrap it in try/finally.

A payment is processed for several seconds. Why is expect.poll better than waitForTimeout(5000), and what should its function return?

Answer

A pause is either too long or too short, while poll exits as soon as the value matches and fails only after the timeout. The function should return a value to compare (for example the status from the body), not an assertion; the comparison is done by the matcher after poll.

In an interview. Junior: I create a separate API context with request.newContext with its own baseURL and token, and I call dispose. I remember that 4xx and 5xx do not throw by default, so I check the status explicitly. Middle/Senior: I do not keep an admin token in the shared config: I make the admin context a worker fixture, so roles do not merge and authorization is not repeated in every test. I check asynchronous processes with expect.poll, and after an API login I save storageState for UI tests.