Implementation:Microsoft Playwright APIRequest NewContext
| Knowledge Sources | |
|---|---|
| Domains | API_Testing, HTTP |
| Last Updated | 2026-02-11 00:00 GMT |
Overview
Concrete tool for configuring an HTTP client context with base URLs, default headers, and authentication credentials provided by the Playwright library.
Description
Playwright provides two primary mechanisms for configuring an API request context:
test.use()fixture configuration: Declares context-level settings such asbaseURLandextraHTTPHeadersthat are automatically applied to the built-inrequestfixture available in every test. This is the most common approach for test suites targeting a single API.APIRequest.newContext()programmatic creation: Explicitly creates a newAPIRequestContextinstance with full control over all options. This is useful when a test needs to interact with multiple APIs or requires distinct authentication contexts.
The server-side implementation in GlobalAPIRequestContext stores the resolved configuration including baseURL, userAgent, httpCredentials, and proxy settings. When requests are made through this context, the stored configuration is automatically merged with per-request options.
Usage
Use test.use() when all tests in a file share the same API configuration. Use APIRequest.newContext() when you need multiple contexts with different configurations, or when creating contexts dynamically in setup hooks.
Code Reference
Source Location
- Repository: playwright
- Fixture config:
packages/playwright/types/test.d.ts:L6205 - Client implementation:
packages/playwright-core/src/client/fetch.ts:L67-86 - Server implementation:
packages/playwright-core/src/server/fetch.ts:L628-648
Signature
// Fixture-based configuration (declarative)
test.use({
baseURL: string,
extraHTTPHeaders: { [key: string]: string }
}): void;
// Programmatic context creation
APIRequest.newContext(options?: {
baseURL?: string;
extraHTTPHeaders?: { [key: string]: string };
httpCredentials?: {
username: string;
password: string;
origin?: string;
send?: 'unauthorized' | 'always';
};
ignoreHTTPSErrors?: boolean;
proxy?: {
server: string;
bypass?: string;
username?: string;
password?: string;
};
storageState?: string | {
cookies: Array<Cookie>;
origins: Array<OriginStorage>;
};
userAgent?: string;
timeout?: number;
}): Promise<APIRequestContext>;
Import
import { test, expect } from '@playwright/test';
// For standalone usage outside test framework
import { request } from 'playwright';
// or
import { request } from '@playwright/test';
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| baseURL | string |
No | Root URL prepended to all relative request URLs. For example, if baseURL is https://api.example.com/v1 and a request targets /users, the full URL becomes https://api.example.com/v1/users.
|
| extraHTTPHeaders | { [key: string]: string } |
No | Headers applied to every request made through this context. Commonly used for Authorization tokens, Accept headers, and API keys. |
| httpCredentials | { username: string; password: string; origin?: string; send?: string } |
No | HTTP Basic authentication credentials. The send option controls whether credentials are sent only on 401 challenge ('unauthorized') or with every request ('always').
|
| ignoreHTTPSErrors | boolean |
No | Whether to ignore HTTPS certificate errors. Defaults to false. Useful for testing against servers with self-signed certificates.
|
| proxy | { server: string; bypass?: string; username?: string; password?: string } |
No | Network proxy configuration. The server field specifies the proxy URL; bypass is a comma-separated list of domains to access directly.
|
| storageState | StorageState | No | Path to a file or an object containing cookies and localStorage entries. Used to reuse authentication state across contexts. |
| userAgent | string |
No | Custom User-Agent header string for all requests from this context. |
| timeout | number |
No | Default timeout in milliseconds for requests made through this context. Defaults to 30000 (30 seconds). |
Outputs
| Name | Type | Description |
|---|---|---|
| context | APIRequestContext |
A configured API request context instance that provides methods for making HTTP requests (get, post, put, delete, patch, head, fetch, dispose). When using test.use(), this context is automatically available as the request fixture.
|
Usage Examples
Basic Example
import { test, expect } from '@playwright/test';
// Configure the request fixture for all tests in this file
test.use({
baseURL: 'https://api.example.com/v1',
extraHTTPHeaders: {
'Accept': 'application/json',
'Authorization': 'Bearer my-api-token',
},
});
test('should list users', async ({ request }) => {
// request fixture is pre-configured with baseURL and headers
const response = await request.get('/users');
expect(response.ok()).toBeTruthy();
});
Advanced Example: Programmatic Context Creation
import { test, expect, request as playwrightRequest } from '@playwright/test';
test('interact with multiple APIs', async () => {
// Create a context for the Users API
const usersAPI = await playwrightRequest.newContext({
baseURL: 'https://users-api.example.com',
extraHTTPHeaders: {
'Authorization': 'Bearer users-token',
},
});
// Create a separate context for the Orders API
const ordersAPI = await playwrightRequest.newContext({
baseURL: 'https://orders-api.example.com',
extraHTTPHeaders: {
'Authorization': 'Bearer orders-token',
},
});
const usersResponse = await usersAPI.get('/users');
expect(usersResponse.ok()).toBeTruthy();
const ordersResponse = await ordersAPI.get('/orders');
expect(ordersResponse.ok()).toBeTruthy();
// Dispose contexts when done
await usersAPI.dispose();
await ordersAPI.dispose();
});
Example: HTTP Basic Authentication
import { request } from '@playwright/test';
const context = await request.newContext({
baseURL: 'https://api.example.com',
httpCredentials: {
username: 'admin',
password: 'secret',
send: 'always',
},
ignoreHTTPSErrors: true,
});
const response = await context.get('/protected-endpoint');