Implementation:Microsoft Playwright APIResponse Methods
| Knowledge Sources | |
|---|---|
| Domains | API_Testing, HTTP, Assertions |
| Last Updated | 2026-02-11 00:00 GMT |
Overview
Concrete tool for validating HTTP response status codes, headers, and body content to verify API correctness, provided by the Playwright library.
Description
The APIResponse class (implemented in packages/playwright-core/src/client/fetch.ts:L305-389) provides a set of methods for inspecting every aspect of an HTTP response. It wraps the raw response data returned from the server and exposes it through a clean, typed interface.
Key methods:
ok(): Returnstrueif the status code is in the 200-299 range (L319-321). This is the most common initial assertion in API tests.status(): Returns the numeric HTTP status code (e.g., 200, 404, 500).statusText(): Returns the HTTP status text (e.g., "OK", "Not Found").headers(): Returns all response headers as a{ [key: string]: string }object. Header names are lowercased.headersArray(): Returns headers as an array of{ name: string, value: string }objects, preserving duplicate header entries.json(): Parses the response body as JSON (L363-366). The body bytes are decoded as UTF-8 before parsing.text(): Returns the response body as a UTF-8 string.body(): Returns the raw response body as aBuffer(L343-356). Internally, this fetches the body via thefetchResponseBodyprotocol channel if it has not been fetched yet.url(): Returns the final URL after any redirects.dispose(): Releases the response body from server-side memory.
The response body is lazily fetched: calling json(), text(), or body() triggers the actual body retrieval from the server process via the fetchResponseBody channel. Once fetched, the body is cached for subsequent calls.
Usage
Use these methods after every API request to verify the response. At minimum, check ok() or status(). For data validation, use json() to parse the body and apply assertions on the resulting object. Use text() for non-JSON responses and body() for binary content.
Code Reference
Source Location
- Repository: playwright
- File:
packages/playwright-core/src/client/fetch.ts:L305-389 - Dependencies:
@protocol/channels,RawHeadersfrom./network
Signature
class APIResponse {
ok(): boolean;
status(): number;
statusText(): string;
url(): string;
headers(): { [key: string]: string };
headersArray(): Array<{ name: string; value: string }>;
json(): Promise<object>;
text(): Promise<string>;
body(): Promise<Buffer>;
dispose(): Promise<void>;
}
Import
import { test, expect } from '@playwright/test';
// APIResponse is returned by request.get(), request.post(), etc.
// No separate import needed.
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| (instance) | APIResponse |
Yes | An APIResponse object returned from request.get(), request.post(), or any other request method. All methods are called on this instance with no additional parameters.
|
Outputs
| Name | Type | Description |
|---|---|---|
| ok() | boolean |
Returns true if the response status code is between 200 and 299 (inclusive). Equivalent to checking status() >= 200 && status() <= 299.
|
| status() | number |
The HTTP status code as an integer (e.g., 200, 201, 404, 500). |
| statusText() | string |
The HTTP status text corresponding to the status code (e.g., "OK", "Created", "Not Found"). |
| url() | string |
The final URL of the response after following any redirects. |
| headers() | { [key: string]: string } |
All response headers as a plain object. Header names are lowercased. When a header appears multiple times, values are joined with , .
|
| headersArray() | Array<{ name: string; value: string }> |
All response headers as an array, preserving individual entries for headers that appear multiple times. |
| json() | Promise<object> |
The response body parsed as JSON. Throws if the body is not valid JSON. The body is decoded as UTF-8 before parsing. |
| text() | Promise<string> |
The response body as a UTF-8 decoded string. |
| body() | Promise<Buffer> |
The raw response body as a Node.js Buffer. Useful for binary responses such as file downloads or images. |
| dispose() | Promise<void> |
Releases the response body from memory on the server side. Call this when the body is no longer needed to free resources. |
Usage Examples
Basic Example
import { test, expect } from '@playwright/test';
test.use({
baseURL: 'https://api.example.com',
});
test('validate a successful GET response', async ({ request }) => {
const response = await request.get('/api/users/1');
// Status code validation
expect(response.ok()).toBeTruthy();
expect(response.status()).toBe(200);
expect(response.statusText()).toBe('OK');
// Header validation
const headers = response.headers();
expect(headers['content-type']).toContain('application/json');
// JSON body validation
const user = await response.json();
expect(user).toHaveProperty('id', 1);
expect(user).toHaveProperty('name');
expect(user).toHaveProperty('email');
expect(user.email).toMatch(/@/);
});
Example: Validating Error Responses
import { test, expect } from '@playwright/test';
test('validate 404 Not Found response', async ({ request }) => {
const response = await request.get('/api/users/99999');
expect(response.ok()).toBeFalsy();
expect(response.status()).toBe(404);
const errorBody = await response.json();
expect(errorBody).toHaveProperty('error');
expect(errorBody.error).toBe('User not found');
});
test('validate 401 Unauthorized response', async ({ request }) => {
const response = await request.get('/api/admin/settings', {
headers: {
'Authorization': 'Bearer invalid-token',
},
});
expect(response.status()).toBe(401);
const body = await response.json();
expect(body.message).toContain('unauthorized');
});
Example: Validating List Responses
import { test, expect } from '@playwright/test';
test('validate paginated list response', async ({ request }) => {
const response = await request.get('/api/products', {
params: { page: 1, limit: 10 },
});
expect(response.ok()).toBeTruthy();
const data = await response.json();
// Validate structure
expect(data).toHaveProperty('results');
expect(data).toHaveProperty('total');
expect(data).toHaveProperty('page', 1);
// Validate array contents
expect(Array.isArray(data.results)).toBeTruthy();
expect(data.results.length).toBeLessThanOrEqual(10);
// Validate each item in the array
for (const product of data.results) {
expect(product).toHaveProperty('id');
expect(product).toHaveProperty('name');
expect(product).toHaveProperty('price');
expect(typeof product.price).toBe('number');
expect(product.price).toBeGreaterThan(0);
}
});
Example: Using text() and body()
import { test, expect } from '@playwright/test';
test('validate text response', async ({ request }) => {
const response = await request.get('/api/health');
const text = await response.text();
expect(text).toContain('healthy');
});
test('validate binary response', async ({ request }) => {
const response = await request.get('/api/reports/export.pdf');
expect(response.ok()).toBeTruthy();
expect(response.headers()['content-type']).toBe('application/pdf');
const body = await response.body();
expect(body.length).toBeGreaterThan(0);
// Check PDF magic bytes
expect(body.slice(0, 4).toString()).toBe('%PDF');
});