API Testing
The request fixture provides APIRequestContext for HTTP calls sharing cookies and storage with browser context when configured — fast API-level testing.
APIRequestContext Basics Call request.get/post/put/patch/delete with relative paths against baseURL. Pass data for JSON, headers for auth, params for query strings.
API tests validate backend contracts independently; use them to seed data before UI tests or verify endpoints the UI depends on.
test('creates order via API', async ({ request }) => {
const res = await request.post('/api/orders', {
data: { productId: 'sku-1', qty: 2 },
headers: { Authorization: 'Bearer test-token' },
});
expect(res.status()).toBe(201);
const { orderId } = await res.json();
expect(orderId).toBeTruthy();
}); request respects baseURL and extraHTTPHeaders from config.
HTTP Methods await request.get('/api/items')
await request.post('/api/items', { data: { name: 'x' } })
await request.put('/api/items/1', { data: { name: 'y' } })
await request.delete('/api/items/1') data serializes to JSON with content-type application/json. form and multipart for other content types. failOnStatusCode: false prevents throw on 4xx/5xx. Share storageState between browser and API contexts. API Testing Reference request fixture quick reference.
Operation Example GET request.get('/api/health') POST JSON request.post('/api/x', { data: {} }) Auth header headers: { Authorization: 'Bearer x' } Query params params: { page: '2' } Ignore fail failOnStatusCode: false Dispose custom await request.dispose()
API Setup + UI Verification test('shows order in UI', async ({ page, request }) => {
const res = await request.post('/api/orders', { data: { sku: 'A' } });
const { id } = await res.json();
await page.goto(`/orders/${id}`);
await expect(page.getByText('Order confirmed')).toBeVisible();
}); API Tests for Setup Create test users via request.post('/api/users') in beforeAll faster than driving registration UI — then use storageState for browser tests.
Common Mistakes Testing only status code, not response body shape. API tests hitting same prod endpoints as E2E. Not cleaning up created entities. Missing auth on protected endpoints. Key Takeaways request fixture enables fast HTTP testing. Seed UI tests via API for speed. Validate status, headers, and JSON body. Align API tests with contract expectations.
Pro Tip
Generate OpenAPI-derived types for response bodies — catch API drift at compile time when fields rename.
Route Mocking Go to next item