API Testing
Relevant source files
The following files were used as context for generating this wiki page:
Playwright provides powerful tools for API testing, enabling developers to test backend services, mock API responses for robust frontend testing, and record and analyze network traffic. This functionality is centered around the APIRequestContext object, which can be used standalone for direct API testing or in conjunction with browser automation to intercept and modify network requests.
The core features include a dedicated request fixture for making API calls, APIResponse assertions for validating server responses, and network interception capabilities through page.route(). Additionally, Playwright can generate HAR files for detailed network analysis.
Core Concepts
APIRequestContext
The APIRequestContext is the primary interface for making API requests. It provides methods for all standard HTTP verbs (get, post, put, delete, etc.) and manages request headers, cookies, and authentication state.
An APIRequestContext can be obtained in two main ways:
- Using the built-in
requestfixture within a Playwright test. - Creating a new context manually via
playwright.request.newContext().
Sources: packages/playwright/types/test.d.ts:4036-4055
The request Fixture
Playwright Test includes a built-in request fixture that provides an isolated APIRequestContext instance for each test. This is the most common and convenient way to perform API testing.
// examples/github-api/tests/test-api.spec.ts:10-17
test('should create a bug report', async ({ request }) => {
const newIssue = await request.post(`/repos/${REPO}/issues`, {
data: {
title: '[Bug] report',
body: 'Bug report description',
}
});
expect(newIssue.ok()).toBeTruthy();
});
This diagram illustrates the typical flow of an API test using the request fixture.
Making API Requests
The APIRequestContext offers methods for all standard HTTP requests.
Request Configuration
Requests can be configured with various options. The most common ones are summarized below.
| Option | Type | Description |
|---|---|---|
data | any | Sets the request body. Can be a string, Buffer, or a serializable object. |
params | {[key: string]: any} | Sets the URL search parameters. |
headers | {[key: string]: string} | Sets the HTTP headers for the request. |
form | {[key: string]: any} | Sets the request body for application/x-www-form-urlencoded requests. |
multipart | {[key: string]: any} | Sets the request body for multipart/form-data requests. |
Sources: packages/playwright-core/src/client/fetch.ts:100-117
Handling Responses
All request methods return a promise that resolves to an APIResponse object. This object contains the response status, headers, and body.
Key APIResponse methods:
| Method | Return Type | Description |
|---|---|---|
ok() | boolean | Returns true if the response status is between 200 and 299. |
status() | number | Returns the HTTP status code of the response. |
statusText() | string | Returns the status text of the response. |
url() | string | Returns the URL of the response. |
headers() | object | Returns an object with all response HTTP headers. |
json() | Promise<any> | Returns the response body parsed as JSON. |
text() | Promise<string> | Returns the response body as a string. |
body() | Promise<Buffer> | Returns the response body as a Buffer. |
Playwright also provides APIResponseAssertions for use with expect. The most common assertion is expect(response).toBeOK(), which checks for a successful status code (2xx).
This class diagram shows the relationship between the core API testing components.
Network Interception and Mocking
Beyond direct API calls, Playwright allows for intercepting and mocking network requests made from a Page. This is crucial for creating stable and fast frontend tests by controlling backend dependencies.
Routing with page.route()
The page.route(url, handler) method is used to intercept network requests that match a given URL pattern (string, glob, or regex). The handler function receives the Route object, which can be used to modify or complete the request.
// README.md:120-127
// Log and continue all network requests
await page.route('**', route => {
console.log(route.request().url());
route.continue();
});
await page.goto('http://todomvc.com');
The following diagram illustrates the flow of network interception.
Advanced Topics
HAR File Generation
Playwright can record network activity into a HAR (HTTP Archive) file for detailed analysis. This is enabled via the recordHar option when creating a BrowserContext.
// tests/library/har.spec.ts:21-25
async function pageWithHar(contextFactory: (options?: BrowserContextOptions) => Promise<BrowserContext>, testInfo: any, options: { outputPath?: string } & Partial<Pick<BrowserContextOptions['recordHar'], 'content' | 'omitContent' | 'mode'>> = {}) {
const harPath = testInfo.outputPath(options.outputPath || 'test.har');
const context = await contextFactory({ recordHar: { path: harPath, ...options }, ignoreHTTPSErrors: true });
// ...
}
The recordHar option accepts several properties to customize the output:
| Option | Type | Description |
|---|---|---|
path | string | Path to the HAR file. |
urlFilter | string | RegExp | A glob pattern or regex to filter recorded requests. |
mode | 'full' | 'minimal' | 'full' records all data. 'minimal' reduces overhead by omitting some details. |
content | 'attach' | 'embed' | 'omit' | Specifies how to handle response content. 'attach' saves content to separate files (for zip archives), 'embed' includes it in the HAR, and 'omit' excludes it. |
Sources: tests/library/har.spec.ts:21-25, packages/playwright/types/test.d.ts:4208-4210
Internal API Testing
Playwright's own test suite demonstrates the power of its API testing capabilities. For instance, the TestServerConnection class is used to test the UI Mode's backend server over a WebSocket connection, showcasing how Playwright can be used to test complex, real-time API interactions.
// tests/playwright-test/test-server.spec.ts:25-39
class TestServerConnectionUnderTest extends TestServerConnection {
events: [string, any][] = [];
constructor(wsUrl: string) {
super(new WSTransport(wsUrl));
this.onTestFilesChanged(params => this.events.push(['testFilesChanged', params]));
this.onStdio(params => this.events.push(['stdio', params]));
this.onLoadTraceRequested(params => this.events.push(['loadTraceRequested', params]));
}
}
This internal usage highlights the flexibility of Playwright's API testing tools, which are capable of handling not just standard REST APIs but also WebSocket-based communication.
Sources: tests/playwright-test/test-server.spec.ts:25-39
Conclusion
Playwright provides a comprehensive and versatile suite of tools for API testing. Whether you need to perform standalone tests against a backend service using the request fixture, mock API responses for frontend tests with page.route(), or perform detailed network analysis with HAR files, Playwright has the necessary features. Its integration with the browser context makes it uniquely powerful for testing complex applications where frontend and backend interactions are tightly coupled.