Back to All Questions
Question 8 of 100
API
Beginner
API Testing in Playwright?
The Answer
Playwright includes `APIRequestContext` via the `request` fixture for sending HTTP requests without a browser. It shares cookies with the browser context, making combined UI+API testing seamless.
Deep Dive Explanation
The API + UI hybrid pattern (API for data setup, UI for interaction testing) is the most efficient testing strategy. It's dramatically faster than setting up data via the UI and avoids coupling your setup to UI implementation details that change frequently.
example.spec.ts
import { test, expect } from '@playwright/test';
// Pure API test (no browser launched)
test('REST API: create and verify user', async ({ request }) => {
// CREATE
const createRes = await request.post('/api/users', {
data: { name: 'Alice', email: 'alice@test.com' },
headers: { 'Content-Type': 'application/json' }
});
expect(createRes.status()).toBe(201);
const { id } = await createRes.json();
// READ
const getRes = await request.get(`/api/users/${id}`);
await expect(getRes).toBeOK();
expect((await getRes.json()).name).toBe('Alice');
// CLEANUP
await request.delete(`/api/users/${id}`);
});
// Use API to set up data for UI test
test('UI test with API setup', async ({ page, request }) => {
const { id } = await (await request.post('/api/products', {
data: { name: 'Test Widget', price: 9.99 }
})).json();
await page.goto(`/products/${id}`);
await expect(page.getByRole('heading')).toHaveText('Test Widget');
});