๐ŸŽญ
Next Gen QA ยท Senior SDET Reference

Playwright API Testing
Cheat Sheet

โšก JavaScript โœ… Playwright Test ๐Ÿ”ฅ Production-Level 10+ Years SDET Patterns ยท Real-World Implementation
01

Core Setup & Configuration

๐Ÿ”€request fixture vs APIRequestContext โ€” Detailed Difference
Concept
request = Playwright built-in fixture โ€” auto-created, auto-disposed per test. APIRequestContext = raw class instance you create/manage manually. Both make HTTP calls; lifecycle & isolation differ entirely.
Code
// โœ… 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());
Usage
Use request fixture for stateless, isolated tests. Use APIRequestContext when you need a shared authenticated session across a suite, or when managing cookies/storage manually.
Mistake
Creating a new APIRequestContext per test โ€” memory leak. Not calling .dispose() โ€” leaks TCP connections. Sharing the request fixture across test files โ€” it's already scoped per test.
Interview
"request fixture internally calls request.newContext() and disposes it in afterEach. APIRequestContext is the underlying class โ€” use it when you need lifecycle control, cookie jar sharing, or pre-authenticated sessions."
โš™๏ธplaywright.config.js โ€” API Testing Setup
Concept
Centralize baseURL, timeout, retry, reporter, extraHTTPHeaders per environment. For API-only projects, disable browserName and use the api project with no browser.
Code
// 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',
});
Usage
baseURL from env means all requests use relative paths /api/users. Combine with projects to run smoke vs full regression on different ENV targets.
Mistake
Hardcoding URLs inside test files. Forgetting retries: 2 on CI โ€” flaky network calls cause false failures. Setting timeout too low for slow QA environments.
Interview
"extraHTTPHeaders in playwright.config applies to the request fixture only โ€” not to manually created APIRequestContext unless explicitly passed during newContext()."
๐ŸŒBaseURL & Environment Config (dev/qa/prod)
Concept
Drive environment selection via ENV variable. Single config file resolves the correct baseURL, credentials, and timeouts per environment.
Code
// 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
Mistake
Putting prod credentials in source control. Using process.env.BASE_URL directly in tests โ€” no validation, silent failures if env is misconfigured.
Interview
"We validate the ENV value at startup and throw early if it's invalid โ€” fail fast is better than silent wrong-environment tests."
๐ŸŒGlobal Setup / Teardown for API Tests
Concept
globalSetup runs once before ALL tests. Use it to get an auth token, seed test data, or validate environment health. Result is stored in process.env for all workers.
Code
// 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');
}
Mistake
Storing large objects in process.env โ€” it's string-only, no objects. Instead, write to a auth.json file and read back. Forgetting that globalSetup runs in its own worker context.
Interview
"globalSetup runs before the test workers are forked โ€” process.env changes here propagate to all workers, but imported module state does not."
02

APIRequestContext โ€” Deep Dive

๐Ÿ”ฌInternal Working & Lifecycle
Concept
Wraps Node.js fetch/http under the hood. Maintains its own cookie jar, connection pool, and default headers. Lifecycle: newContext() โ†’ use โ†’ dispose().
Code
// 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();
Mistake
Not calling .dispose() โ†’ leaked file descriptors + open sockets. Creating context inside a loop for each request โ€” extreme overhead.
Interview
"storageState serializes cookies + localStorage to disk โ€” this is how we persist login state across test files without repeating the auth flow on every test run."
๐Ÿ—๏ธIsolated vs Shared Context Strategy
Concept
Isolated = each test gets its own context (request fixture). Shared = one context for a suite (beforeAll). Choose based on whether tests share session state.
Code
// 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', {...}); });
});
Usage
Shared context saves N ร— auth round-trip time. For a suite of 50 tests that each take 200ms to login, that's 10 seconds saved per run.
Mistake
Sharing context between parallel workers โ€” contexts are not thread-safe across workers. Keep shared context within a single test.describe block.
03

HTTP Methods with Real Scenarios

๐Ÿ“ฅGET โ€” Pagination & Filtering
Code
// 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);
});
Mistake
Only testing page 1. Not validating meta.totalCount matches actual items fetched. Ignoring edge case: empty data array (zero results).
Interview
"params in Playwright request are auto-encoded and appended to the URL โ€” no manual URLSearchParams needed."
๐Ÿ“คPOST โ€” Dynamic Payload Creation
Code
// 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
});
Mistake
Hardcoded email in POST payload โ€” duplicate key error on second run. Not asserting 201 specifically (only ok() which includes 200).
๐Ÿ”„PUT vs PATCH โ€” Difference + Usage
Concept
PUT = full replacement (send complete resource). PATCH = partial update (send only changed fields). Missing fields in PUT = nulled; missing in PATCH = untouched.
Code
// 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
});
Interview
"Always validate the unchanged fields after PATCH โ€” that's the real assertion. Missing this catches bugs where PATCH accidentally nullifies unspecified fields."
๐Ÿ—‘๏ธDELETE โ€” Cleanup Strategy in Automation
Code
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;
});
Mistake
Only checking 204 but not verifying GET returns 404. Not testing idempotency (double DELETE). Cleanup in afterAll instead of afterEach โ€” if suite fails mid-way, data leaks.
04

Request Building โ€” Advanced

๐Ÿ”‘Headers โ€” Authorization & Dynamic Tokens
Code
// 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
});
Mistake
Hardcoding token strings in tests. Not rotating x-correlation-id โ€” makes production log tracing impossible.
๐Ÿ“ฆBody Types โ€” JSON, form-data, x-www-form-urlencoded
Code
// 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
});
Interview
"data = JSON, form = urlencoded, multipart = multipart/form-data. Playwright sets Content-Type automatically for each โ€” don't set it manually or it may conflict."
05

Authentication โ€” Real-World Patterns

๐Ÿ”Bearer Token โ€” Generate & Reuse Pattern
Code
// 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();
});
Mistake
Fetching a new token per test (N ร— auth latency). Not accounting for token expiry mid-run โ€” tests fail with 401 after 1 hour if token lifetime is short.
Interview
"We cache the token with a 60-second expiry buffer to handle clock skew between our test runner and the auth server."
๐Ÿ—๏ธAPI Key, Session & storageState Pattern
Code
// 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');
Mistake
Committing auth-state/admin.json to git โ€” contains session cookies. Add to .gitignore.
06

Response Handling โ€” Deep

๐Ÿ“Šstatus(), ok(), headers() & JSON Parsing
Code
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
});
Mistake
Calling res.json() multiple times โ€” it reads the stream, second call returns empty. Store result in a variable. Using res.body() and then res.json() โ€” same issue.
Interview
"ok() returns true for any 2xx status โ€” but in POST, 201 โ‰  200. Always use status() for precise status code assertion in CRUD tests."
๐Ÿ“ฆHandling Large / Complex Responses
Code
// 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
});
Mistake
expect(body).toEqual(hugeExpectedObject) โ€” any tiny schema change breaks test. Use targeted assertions on specific fields.
07

Assertions โ€” Advanced

โœ…Advanced Assertion Patterns
Code
// 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);
}
Interview
"toMatchObject does partial deep matching โ€” ideal for API responses where server adds computed fields (id, createdAt) you don't control. toEqual would fail on those."
Mistake
Using toEqual for full response comparison โ€” will break whenever server adds new optional fields. Prefer toMatchObject for response bodies.
๐Ÿ”Schema Validation with JSON Schema
Concept
Use ajv (JSON Schema validator) for contract testing โ€” validate structure without caring about values. Catches breaking API changes early.
Code
// 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);
});
Interview
"Schema validation as contract testing โ€” we catch API breaking changes before they reach UI tests. It's the cheapest integration test you can write."
08

Error Handling & Debugging

๐Ÿ”Retry Logic & 4xx/5xx Handling
Code
// 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"
});
Interview
"We retry on 429 and 5xx only โ€” not on 4xx, because those are test/data bugs, not transient. Retrying on 4xx masks real failures."
๐ŸชตLogging Request & Response for Debugging
Code
// 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
Usage
Set DEBUG=pw:api env variable to get Playwright's built-in HTTP logging. Use the wrapper for business-level logging in your CI reports.
Mistake
Logging entire response body in production CI โ€” may expose PII/secrets. Truncate with .slice(0, 500) or mask sensitive fields.
09

Parallel Execution

โšกParallel API Tests โ€” Safe Data Strategy
Concept
Playwright runs test files in parallel by default. API tests must use unique test data per worker to avoid conflicts (unique email, userId, etc.).
Code
// 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 */ });
});
Mistake
Shared global state between parallel workers (like a module-level let userId). Each worker is a separate Node.js process โ€” module state is not shared.
Interview
"testInfo.workerIndex gives worker ID (0,1,2โ€ฆ). Combined with timestamp it guarantees uniqueness even when workers start at the same millisecond."
10

Framework Design โ€” VERY IMPORTANT

๐Ÿ›๏ธ API Service Layer โ€” Client Class Architecture
// 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();
});
๐ŸญTest Data Factory Pattern
Code
// 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 });
๐Ÿ“Recommended Framework Structure
Concept
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
11

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.

๐Ÿ“‹ Quick Reference โ€” Status Codes & When to Test Them
Status Meaning When Your Test Should Hit This Playwright Assertion
200OKGET success, POST/PATCH returning resourceexpect(res.status()).toBe(200)
201CreatedPOST creates a new resourceexpect(res.status()).toBe(201)
204No ContentDELETE, sometimes PATCH with no bodyexpect(res.status()).toBe(204)
400Bad RequestInvalid payload, missing required fieldAssert body has .message / .errors
401UnauthorizedMissing or invalid tokenTest without Authorization header
403ForbiddenValid token but wrong role/permissionTest with viewer role on admin endpoint
404Not FoundAfter DELETE, or non-existent IDVerify resource is gone after delete
409ConflictDuplicate email, unique constraint violationPOST same email twice
422UnprocessableSemantically invalid dataInvalid enum value, wrong date format
429Rate LimitedToo many requests (test with retry)Implement backoff, assert retry works
500Server ErrorBug in server โ€” should NEVER be expectedFail immediately, file a defect
โšก Playwright API Methods โ€” Quick Reference
MethodPlaywright CallBody KeyContent-Type SetUse Case
GETrequest.get(url, {params})paramsnone (query string)Read data, search, filter
POSTrequest.post(url, {data})dataapplication/jsonCreate resource
PUTrequest.put(url, {data})dataapplication/jsonFull replacement
PATCHrequest.patch(url, {data})dataapplication/jsonPartial update
DELETErequest.delete(url)โ€”noneRemove resource
POST formrequest.post(url, {form})formapplication/x-www-form-urlencodedOAuth, legacy APIs
POST filerequest.post(url, {multipart})multipartmultipart/form-dataFile upload