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
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
Admin token in use.extraHTTPHeaders
Every request from request carries it. "User" and "admin" become one role, and negative permission tests give false results.
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.
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:
| Option | What is sent |
|---|---|
data, an object | JSON, application/json |
data, a string or a Buffer | as is; without an explicit Content-Type it goes as application/octet-stream |
form | application/x-www-form-urlencoded |
multipart | multipart/form-data, files as { name, mimeType, buffer } |
params | the 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:
| Way | Context lifetime | When |
|---|---|---|
request fixture | one test, closes itself | ordinary API tests and data preparation |
page.request | with the page, shares cookies | requests on behalf of the browser user |
request.newContext in a test | until dispose() | another user or service |
| in a worker fixture | one per worker | admin 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.pollfor asynchronous processing: either flakes or wasted seconds. - A string in
datawithout a Content-Type when the server expects JSON: it goes asapplication/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.
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.