Use it for
Fast API checks, backend validation, setup data creation, and combined API plus UI automation.
A quick reference for API testing with Playwright: request setup, validation, auth, and hybrid API plus UI workflows.
Fast API checks, backend validation, setup data creation, and combined API plus UI automation.
Assert both status and response content, not just the HTTP code.
Works best with the Playwright test runner and CI/CD sheets.
One framework for UI and API testing reduces tooling overhead and improves flow coverage.
Create a shared request client with base URL and headers.
import { request } from '@playwright/test';
const api = await request.newContext({
baseURL: 'https://api.example.com',
extraHTTPHeaders: {
Authorization: 'Bearer token',
},
});
Start with clear requests and inspect parsed JSON directly.
const response = await api.get('/users', {
params: { page: 1 },
});
expect(response.ok()).toBeTruthy();
const body = await response.json();
Use data for JSON payloads and assert the created response carefully.
const response = await api.post('/users', {
data: {
name: 'Lucky',
role: 'student',
},
});
Use multipart helpers when the endpoint expects files or classic form-style input.
const response = await api.post('/upload', {
multipart: {
file: {
name: 'report.txt',
mimeType: 'text/plain',
buffer: Buffer.from('sample'),
},
},
});
Use the correct verb for replacement, partial update, or deletion.
await api.put('/users/1', { data: { name: 'Updated' } });
await api.patch('/users/1', { data: { github: 'promoddutta' } });
await api.delete('/users/1');
Keep auth flows reusable so test code stays focused on behavior, not setup repetition.
const login = await api.post('/auth/login', {
data: { email: '[email protected]', password: 'secret' },
});
const { token } = await login.json();
Check status, payload shape, and business meaning.
expect(response.status()).toBe(200);
expect(body.user.name).toBe('Lucky');
expect(body.user.github).toContain('lucky');
Use the API to prepare state, then validate the user-facing result in the browser.
await api.post('/orders', { data: orderPayload });
await page.goto('/orders');
await expect(page.getByText(orderPayload.id)).toBeVisible();
Record timing and inspect error bodies for useful debugging context.
const start = Date.now();
const response = await api.get('/health');
const duration = Date.now() - start;
console.log('Response time:', duration);