Skip to content

Request Context

APIRequestContext can be created standalone via playwright.request.newContext() or accessed through the request fixture — with its own cookies and headers.

Standalone Request Context

Use request.newContext({ baseURL, storageState, extraHTTPHeaders }) when you need separate API sessions from the browser page — admin API vs user browser, for example.

Always dispose() standalone contexts when done to free sockets.

import { request as playwrightRequest } from '@playwright/test';

const apiContext = await playwrightRequest.newContext({
  baseURL: 'https://api.example.com',
  extraHTTPHeaders: { 'X-API-Key': process.env.API_KEY! },
});
const res = await apiContext.get('/v1/status');
await apiContext.dispose();

Fixture request is disposed automatically; manual contexts are not.

Context Options

newContext({
  baseURL,
  storageState: 'auth.json',
  ignoreHTTPSErrors: true,
  proxy: { server: 'http://proxy:8080' },
})
  • storageState shares cookies with saved auth file.
  • Multiple contexts = multiple isolated cookie jars.
  • baseURL makes paths relative in get/post.
  • Fixture request inherits from test options.

Request Context Options

Configure API client behavior.

Option Purpose
baseURL Prefix for relative paths
storageState Authenticated session
extraHTTPHeaders Default headers all requests
ignoreHTTPSErrors Self-signed certs in dev
proxy Route through corporate proxy
dispose() Free resources when done

Browser + API Auth Alignment

After UI login, save storageState and create API context with same file — both share cookies for hybrid tests.

await page.context().storageState({ path: 'auth.json' });
const api = await playwrightRequest.newContext({ storageState: 'auth.json' });

baseURL on APIRequestContext

When creating a standalone context, set baseURL so request.get('/users') resolves relative paths like the browser page fixture does.

Common Mistakes

  • Leaking undisposed manual request contexts.
  • Different baseURL on API vs browser causing wrong host.
  • Assuming request fixture cookies sync live with page without storageState save.
  • Missing API key header on standalone context.

Key Takeaways

  • APIRequestContext is a full HTTP client with cookie jar.
  • Create standalone contexts for multi-user API scenarios.
  • storageState aligns browser and API authentication.
  • Dispose manual contexts explicitly.

Pro Tip

In globalSetup, use request.newContext to obtain tokens once and write storageState — faster than per-file API login.