Core Setup & Configuration
// โ
request fixture โ auto lifecycle, good for most tests
test('GET users', async ({ request }) => {
const res = await request.get('/api/users');
// context is auto-disposed after test
});
// โ
APIRequestContext โ manual control, ideal for shared sessions
import { request as playwrightRequest } from '@playwright/test';
let apiContext;
test.beforeAll(async () => {
apiContext = await playwrightRequest.newContext({
baseURL: 'https://api.qa.myapp.com',
extraHTTPHeaders: { 'Authorization': `Bearer ${process.env.TOKEN}` }
});
});
test.afterAll(async () => await apiContext.dispose());
// playwright.config.js
import { defineConfig } from '@playwright/test';
import { config } from './src/config/env.config';
export default defineConfig({
testDir: './tests',
timeout: 30000,
retries: process.env.CI ? 2 : 0,
reporter: [['html', { open: 'never' }], ['list']],
use: {
baseURL: config.baseUrl, // from env config
extraHTTPHeaders: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'x-api-version': 'v2'
},
ignoreHTTPSErrors: true, // for self-signed QA certs
},
projects: [
{ name: 'api-smoke', testMatch: '**/*.smoke.spec.js' },
{ name: 'api-regression', testMatch: '**/*.spec.js' },
],
globalSetup: './src/global/globalSetup.js',
globalTeardown: './src/global/globalTeardown.js',
});
// src/config/env.config.js
const environments = {
dev: { baseUrl: 'https://api.dev.myapp.com', timeout: 5000 },
qa: { baseUrl: 'https://api.qa.myapp.com', timeout: 10000 },
prod: { baseUrl: 'https://api.myapp.com', timeout: 8000 },
};
const env = process.env.ENV || 'qa';
if (!environments[env]) throw new Error(`Unknown ENV: ${env}`);
export const config = { ...environments[env], env };
// Run: ENV=prod npx playwright test
// CI pipeline: ENV=qa npx playwright test --project=api-smoke
// src/global/globalSetup.js
import { request } from '@playwright/test';
import { config } from '../config/env.config.js';
export default async function globalSetup() {
const ctx = await request.newContext({ baseURL: config.baseUrl });
const res = await ctx.post('/auth/login', {
data: { email: process.env.API_USER, password: process.env.API_PASS }
});
if (!res.ok()) throw new Error('Global auth failed: ' + await res.text());
const { token } = await res.json();
process.env.AUTH_TOKEN = token; // shared across all workers
await ctx.dispose();
}
// src/global/globalTeardown.js
export default async function globalTeardown() {
// revoke token, cleanup seeded data, send Slack notification, etc.
console.log('๐งน Global teardown complete');
}
APIRequestContext โ Deep Dive
// Lifecycle diagram in code
import { request } from '@playwright/test';
// 1. CREATE โ allocates connection pool + cookie store
const ctx = await request.newContext({
baseURL: 'https://api.qa.myapp.com',
storageState: './auth.json', // pre-load cookies/token
extraHTTPHeaders: { 'x-request-id': 'automation' },
httpCredentials: { username: 'u', password: 'p' }, // Basic Auth
});
// 2. USE โ all calls share the same context (cookies persist)
const loginRes = await ctx.post('/auth/login', { data: creds });
const profileRes = await ctx.get('/users/me'); // cookie auto-sent
// 3. SAVE STATE (optional โ for reuse across test files)
await ctx.storageState({ path: './auth.json' });
// 4. DISPOSE โ closes connections, clears cookie jar
await ctx.dispose();
// PATTERN A โ Isolated (Stateless REST APIs)
test('create user', async ({ request }) => {
// fresh context, no pollution from other tests
const res = await request.post('/users', { data: userData });
});
// PATTERN B โ Shared (Session / Token reuse across suite)
import { test, expect } from '@playwright/test';
import { request } from '@playwright/test';
let apiCtx;
test.describe('User CRUD Suite', () => {
test.beforeAll(async () => {
apiCtx = await request.newContext({
baseURL: 'https://api.qa.myapp.com',
storageState: './auth.json' // pre-authenticated
});
});
test.afterAll(async () => await apiCtx.dispose());
test('get user list', async () => { await apiCtx.get('/users'); });
test('update user', async () => { await apiCtx.patch('/users/1', {...}); });
});
HTTP Methods with Real Scenarios
// Pagination โ traverse all pages
async function getAllUsers(request) {
let page = 1, all = [];
while (true) {
const res = await request.get('/users', {
params: { page, limit: 50, status: 'active' }
});
expect(res).toBeOK();
const { data, meta } = await res.json();
all.push(...data);
if (page >= meta.totalPages) break;
page++;
}
return all;
}
test('all active users returned', async ({ request }) => {
const users = await getAllUsers(request);
expect(users.length).toBeGreaterThan(0);
expect(users.every(u => u.status === 'active')).toBe(true);
});
// Test data factory + POST
import { buildUser } from '../factories/user.factory';
test('create user with dynamic payload', async ({ request }) => {
const payload = buildUser({ role: 'admin', verified: true });
const res = await request.post('/users', {
data: payload,
headers: { 'Idempotency-Key': payload.email } // prevent duplicate on retry
});
expect(res.status()).toBe(201);
const body = await res.json();
expect(body).toMatchObject({
email: payload.email,
role: 'admin',
id: expect.any(String)
});
});
// src/factories/user.factory.js
import { faker } from '@faker-js/faker';
export const buildUser = (overrides = {}) => ({
name: faker.person().fullName(),
email: faker.internet().email(),
role: 'viewer',
verified: false,
...overrides
});
// PUT โ full replacement (all fields required)
test('PUT replaces entire user object', async ({ request }) => {
const res = await request.put(`/users/${userId}`, {
data: { name: 'Amir Khan', email: 'amir@qa.com', role: 'admin' }
});
expect(res.status()).toBe(200);
const body = await res.json();
expect(body.role).toBe('admin');
});
// PATCH โ partial update (only changed fields)
test('PATCH updates only role field', async ({ request }) => {
// Capture pre-state
const before = await (await request.get(`/users/${userId}`)).json();
const res = await request.patch(`/users/${userId}`, {
data: { role: 'viewer' } // ONLY role changes
});
expect(res.status()).toBe(200);
const after = await res.json();
expect(after.role).toBe('viewer');
expect(after.name).toBe(before.name); // name must be unchanged
});
test('delete user โ full lifecycle', async ({ request }) => {
// Setup โ create resource for this test
const createRes = await request.post('/users', { data: buildUser() });
const { id } = await createRes.json();
// DELETE
const delRes = await request.delete(`/users/${id}`);
expect(delRes.status()).toBe(204); // No Content
// Verify โ 404 on subsequent GET
const getRes = await request.get(`/users/${id}`);
expect(getRes.status()).toBe(404);
// Idempotency โ DELETE again should still be 404
const del2 = await request.delete(`/users/${id}`);
expect(del2.status()).toBe(404); // not 500!
});
// Cleanup pattern โ afterEach tracking
const createdIds = [];
test.afterEach(async ({ request }) => {
for (const id of createdIds) {
await request.delete(`/users/${id}`).catch(() => {}); // best-effort
}
createdIds.length = 0;
});
Request Building โ Advanced
// Dynamic token in each request
const getAuthHeader = () => ({
'Authorization': `Bearer ${process.env.AUTH_TOKEN}`,
'x-correlation-id': crypto.randomUUID(), // traceability
'x-test-run': process.env.CI_RUN_ID || 'local',
});
// Per-request header override
const res = await request.get('/admin/users', {
headers: {
...getAuthHeader(),
'x-admin-key': process.env.ADMIN_KEY
}
});
// Context-level default (applies to all calls in this context)
const ctx = await request.newContext({
extraHTTPHeaders: getAuthHeader() // set once, used everywhere
});
// 1. JSON body (default with 'data')
await request.post('/users', {
data: { name: 'Amir', email: 'a@qa.com' } // auto Content-Type: application/json
});
// 2. form-data (file upload)
import { readFileSync } from 'fs';
await request.post('/upload', {
multipart: {
file: {
name: 'report.pdf',
mimeType: 'application/pdf',
buffer: readFileSync('./fixtures/report.pdf')
},
category: 'finance' // additional form field
}
});
// 3. x-www-form-urlencoded (legacy / OAuth token endpoints)
await request.post('/oauth/token', {
form: {
grant_type: 'client_credentials',
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET,
scope: 'read:users write:users'
}
// auto Content-Type: application/x-www-form-urlencoded
});
Authentication โ Real-World Patterns
// src/helpers/auth.helper.js
import { request } from '@playwright/test';
import { config } from '../config/env.config.js';
let cachedToken = null;
let tokenExpiry = 0;
export async function getToken() {
if (cachedToken && Date.now() < tokenExpiry) return cachedToken;
const ctx = await request.newContext({ baseURL: config.baseUrl });
const res = await ctx.post('/auth/token', {
form: {
grant_type: 'client_credentials',
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET
}
});
const { access_token, expires_in } = await res.json();
cachedToken = access_token;
tokenExpiry = Date.now() + (expires_in - 60) * 1000; // 60s buffer
await ctx.dispose();
return cachedToken;
}
// Usage in test
test('authenticated call', async ({ request }) => {
const token = await getToken();
const res = await request.get('/profile', {
headers: { 'Authorization': `Bearer ${token}` }
});
expect(res).toBeOK();
});
// API Key โ header or query param
const res = await request.get('/data', {
headers: { 'X-API-Key': process.env.API_KEY }
// OR: params: { api_key: process.env.API_KEY }
});
// Session via storageState โ save after login, reuse across files
// Step 1: globalSetup โ login and save
const ctx = await request.newContext({ baseURL: config.baseUrl });
await ctx.post('/auth/login', { data: creds });
await ctx.storageState({ path: './auth-state/admin.json' });
await ctx.dispose();
// Step 2: In tests โ load saved state
const authedCtx = await request.newContext({
baseURL: config.baseUrl,
storageState: './auth-state/admin.json'
});
// All cookies from login are automatically sent
const profile = await authedCtx.get('/me');
Response Handling โ Deep
test('response deep dive', async ({ request }) => {
const res = await request.get('/users/42');
// status + ok
console.log(res.status()); // 200
console.log(res.ok()); // true (200-299)
console.log(res.statusText()); // "OK"
console.log(res.url()); // actual URL hit
// headers
const headers = res.headers(); // returns plain object
expect(headers['content-type']).toContain('application/json');
expect(headers['x-request-id']).toBeDefined(); // traceability
// JSON โ always await, call once and store
const body = await res.json();
expect(body.id).toBe(42);
// Response time โ custom validation
const timing = res.headers()['x-response-time']; // if server sends it
const start = Date.now();
const slow = await request.get('/heavy-report');
const ms = Date.now() - start;
expect(ms).toBeLessThan(3000); // SLA: under 3s
});
// Large response โ extract only what you need
test('validate report summary in large response', async ({ request }) => {
const res = await request.get('/reports/annual?year=2024');
const body = await res.json();
// Destructure only needed fields
const { summary, status, generatedAt } = body;
expect(status).toBe('completed');
expect(summary.totalRevenue).toBeGreaterThan(0);
expect(new Date(generatedAt)).toBeInstanceOf(Date);
// Find in array โ avoid full array assertion
const q4 = body.quarters.find(q => q.name === 'Q4');
expect(q4.growth).toBeGreaterThan(0.05); // 5%+ growth
});
Assertions โ Advanced
// Status codes
expect(res.status()).toBe(201);
expect([200, 201]).toContain(res.status()); // either OK
// Deep nested object validation
expect(body).toMatchObject({
user: {
profile: {
address: {
city: 'Noida',
pincode: expect.any(String)
}
},
roles: expect.arrayContaining(['admin'])
}
});
// Partial match โ extra fields OK
expect(body.user).toMatchObject({ email: 'amir@qa.com' });
// Array shape
expect(body.items).toHaveLength(10);
expect(body.items[0]).toMatchObject({
id: expect.any(String),
price: expect.any(Number),
});
// Custom assertion util
function assertPagination(meta, { page, limit }) {
expect(meta.currentPage).toBe(page);
expect(meta.perPage).toBe(limit);
expect(meta.totalPages).toBeGreaterThanOrEqual(1);
expect(meta.totalCount).toBeGreaterThanOrEqual(0);
}
// npm install ajv
import Ajv from 'ajv';
const ajv = new Ajv();
const userSchema = {
type: 'object',
required: ['id', 'email', 'role'],
properties: {
id: { type: 'string' },
email: { type: 'string', format: 'email' },
role: { type: 'string', enum: ['admin', 'viewer'] },
age: { type: 'integer', minimum: 0 }
},
additionalProperties: false // strict โ no surprise fields
};
test('user schema is valid', async ({ request }) => {
const body = await (await request.get('/users/1')).json();
const valid = ajv.validate(userSchema, body);
expect(valid, ajv.errorsText()).toBe(true);
});
Error Handling & Debugging
// Utility: retry with exponential backoff
async function retryRequest(fn, { retries = 3, delayMs = 500 } = {}) {
let attempt = 0;
while (true) {
try {
const res = await fn();
if (res.status() === 429 || res.status() >= 500) {
if (++attempt > retries) throw new Error(`Failed after ${retries} retries: ${res.status()}`);
await new Promise(r => setTimeout(r, delayMs * 2 ** attempt));
continue;
}
return res;
} catch (e) {
if (++attempt > retries) throw e;
await new Promise(r => setTimeout(r, delayMs * 2 ** attempt));
}
}
}
// Test: 4xx should contain error message
test('400 Bad Request has error detail', async ({ request }) => {
const res = await request.post('/users', { data: { email: 'bad' } });
expect(res.status()).toBe(400);
const err = await res.json();
expect(err.message).toContain('email');
expect(err.code).toBeDefined(); // e.g. "VALIDATION_ERROR"
});
// Logging wrapper โ wraps any request method
export async function loggedRequest(fn, label = '') {
const start = Date.now();
let res;
try {
res = await fn();
const ms = Date.now() - start;
const body = await res.text();
console.log(`[API] ${label} โ ${res.status()} (${ms}ms)\n` +
` URL: ${res.url()}\n` +
` Body: ${body.slice(0, 500)}`);
return { res, body: JSON.parse(body) };
} catch (e) {
console.error(`[API] ${label} FAILED:`, e.message);
throw e;
}
}
// Usage
const { res, body } = await loggedRequest(
() => request.post('/payment', { data: payload }),
'POST /payment'
);
// Built-in: DEBUG=pw:api npx playwright test โ logs all HTTP
Parallel Execution
// playwright.config.js
export default defineConfig({
workers: process.env.CI ? 4 : 2, // parallel workers
fullyParallel: true, // tests within file also parallel
// Use test.describe.configure({ mode: 'serial' }) for dependent tests
});
// Unique data per test โ worker index + timestamp
test('parallel safe user creation', async ({ request }, testInfo) => {
const uniqueSuffix = `${testInfo.workerIndex}_${Date.now()}`;
const payload = {
email: `user_${uniqueSuffix}@test.com`,
name: `Test User ${uniqueSuffix}`
};
const res = await request.post('/users', { data: payload });
expect(res.status()).toBe(201);
});
// Serial mode for dependent tests (login โ action โ logout)
test.describe.configure({ mode: 'serial' });
test.describe('Payment flow', () => {
let orderId;
test('create order', async ({ request }) => { orderId = ...; });
test('pay order', async ({ request }) => { /* uses orderId */ });
test('verify payment', async ({ request }) => { /* sequential */ });
});
Framework Design โ VERY IMPORTANT
// src/services/UserService.js โ API Client class
export class UserService {
constructor(request) {
this.request = request;
this.base = '/api/v2/users';
}
async getAll({ page = 1, limit = 20, status } = {}) {
return this.request.get(this.base, { params: { page, limit, status } });
}
async getById(id) { return this.request.get(`${this.base}/${id}`); }
async create(data) { return this.request.post(this.base, { data }); }
async update(id, data) { return this.request.patch(`${this.base}/${id}`, { data }); }
async replace(id, data){ return this.request.put(`${this.base}/${id}`, { data }); }
async remove(id) { return this.request.delete(`${this.base}/${id}`); }
// Domain-specific method
async promoteToAdmin(id) {
return this.request.post(`${this.base}/${id}/promote`);
}
// With response parsing (shorthand)
async createAndParse(data) {
const res = await this.create(data);
expect(res.status()).toBe(201);
return res.json();
}
}
// Custom fixture โ injects service into tests
// src/fixtures/apiFixtures.js
import { test as base } from '@playwright/test';
import { UserService } from '../services/UserService.js';
export const test = base.extend({
userService: async ({ request }, use) => {
await use(new UserService(request));
}
});
// Test using fixture
import { test, expect } from '../fixtures/apiFixtures.js';
test('create and verify user', async ({ userService }) => {
const user = await userService.createAndParse(buildUser());
expect(user.id).toBeDefined();
});
// src/factories/index.js
import { faker } from '@faker-js/faker';
export const buildUser = (o = {}) => ({
name: faker.person().fullName(),
email: faker.internet().email(),
phone: faker.phone().number('+91##########'),
role: 'viewer',
verified: false,
...o // caller overrides win
});
export const buildProduct = (o = {}) => ({
name: faker.commerce().productName(),
price: parseFloat(faker.commerce().price({ min: 10, max: 999 })),
sku: faker.string().alphanumeric(8).toUpperCase(),
stock: faker.number().int({ min: 1, max: 100 }),
...o
});
// Edge case builders
export const buildUserMinimal = () => buildUser({ phone: undefined });
export const buildAdminUser = () => buildUser({ role: 'admin', verified: true });
playwright-api-framework/
โโโ src/
โ โโโ config/
โ โ โโโ env.config.js # env + baseURL
โ โโโ services/
โ โ โโโ UserService.js # API client per domain
โ โ โโโ AuthService.js
โ โ โโโ PaymentService.js
โ โโโ factories/
โ โ โโโ index.js # buildUser, buildProduct
โ โโโ fixtures/
โ โ โโโ apiFixtures.js # extended test fixtures
โ โโโ helpers/
โ โ โโโ auth.helper.js # token cache, login
โ โ โโโ request.helper.js # retry, logging
โ โโโ schemas/
โ โ โโโ user.schema.json # AJV schemas
โ โโโ global/
โ โโโ globalSetup.js
โ โโโ globalTeardown.js
โโโ tests/
โ โโโ users/
โ โ โโโ users.smoke.spec.js
โ โ โโโ users.spec.js
โ โโโ payments/
โ โโโ payments.spec.js
โโโ auth-state/ # gitignored!
โโโ playwright.config.js
โโโ package.json
Best Practices
Never Hardcode URLs or Tokens
All URLs via config.baseUrl, all secrets via process.env. Any hardcoded value = a maintenance nightmare at scale.
Assert What Matters, Not Everything
3 precise assertions beat 20 shallow ones. Focus on: status code, key field value, response structure (schema). Skip timestamps and IDs you don't control.
Test Data Isolation
Each test owns its data. Create in setup, cleanup in teardown. Use afterEach cleanup tracking arrays. Never reuse data between tests.
One Concern Per Test
Don't test CRUD in one test. create user, get user, delete user = 3 separate tests. Easier to debug, faster to rerun.
Use test.step() for Clarity
await test.step('Create user', async () => {...}) โ shows in HTML report as nested steps. Makes complex test flows readable without comments.
Tag Tests for Selective Running
test('login @smoke @critical', ...) โ npx playwright test --grep @smoke. Use tags for smoke, regression, blocker, slow, api-only.
HTML Report + Allure
Enable built-in HTML reporter for local runs. Add Allure for CI dashboards. Attach request/response body to failed tests via test.info().attach().
Security Test Coverage
Test for: missing Authorization โ 401, wrong role โ 403, another user's resource โ 403/404, expired token โ 401. These are free regression tests.
Performance Baselines in API Tests
Wrap time-sensitive calls with Date.now(). Assert toBeLessThan(2000) for critical endpoints. Catch regressions before UAT.
CI/CD Integration
Run ENV=qa npx playwright test --project=api-smoke on every PR. Full regression nightly. Never block deploy on flaky non-critical tests โ use retries: 2.
Service Layer = Maintainability
If the API endpoint changes, update one file (UserService.js), not 50 test files. This is the single biggest maintainability win in large frameworks.
Contract Testing First
Run schema (AJV) validation on every endpoint before value assertions. If schema fails โ data assertions are meaningless. Fail fast, fail clear.
| Status | Meaning | When Your Test Should Hit This | Playwright Assertion |
|---|---|---|---|
| 200 | OK | GET success, POST/PATCH returning resource | expect(res.status()).toBe(200) |
| 201 | Created | POST creates a new resource | expect(res.status()).toBe(201) |
| 204 | No Content | DELETE, sometimes PATCH with no body | expect(res.status()).toBe(204) |
| 400 | Bad Request | Invalid payload, missing required field | Assert body has .message / .errors |
| 401 | Unauthorized | Missing or invalid token | Test without Authorization header |
| 403 | Forbidden | Valid token but wrong role/permission | Test with viewer role on admin endpoint |
| 404 | Not Found | After DELETE, or non-existent ID | Verify resource is gone after delete |
| 409 | Conflict | Duplicate email, unique constraint violation | POST same email twice |
| 422 | Unprocessable | Semantically invalid data | Invalid enum value, wrong date format |
| 429 | Rate Limited | Too many requests (test with retry) | Implement backoff, assert retry works |
| 500 | Server Error | Bug in server โ should NEVER be expected | Fail immediately, file a defect |
| Method | Playwright Call | Body Key | Content-Type Set | Use Case |
|---|---|---|---|---|
| GET | request.get(url, {params}) | params | none (query string) | Read data, search, filter |
| POST | request.post(url, {data}) | data | application/json | Create resource |
| PUT | request.put(url, {data}) | data | application/json | Full replacement |
| PATCH | request.patch(url, {data}) | data | application/json | Partial update |
| DELETE | request.delete(url) | โ | none | Remove resource |
| POST form | request.post(url, {form}) | form | application/x-www-form-urlencoded | OAuth, legacy APIs |
| POST file | request.post(url, {multipart}) | multipart | multipart/form-data | File upload |