Back to cheat sheet hub

Playwright API Cheat Sheet

A quick reference for API testing with Playwright: request setup, validation, auth, and hybrid API plus UI workflows.

Playwright Module 6 APIRequestContext Hybrid testing

Use it for

Fast API checks, backend validation, setup data creation, and combined API plus UI automation.

Default habit

Assert both status and response content, not just the HTTP code.

Best pair

Works best with the Playwright test runner and CI/CD sheets.

Main value

One framework for UI and API testing reduces tooling overhead and improves flow coverage.

APIRequestContext Setup

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',
  },
});

GET Requests

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();

POST Requests

Use data for JSON payloads and assert the created response carefully.

const response = await api.post('/users', {
  data: {
    name: 'Lucky',
    role: 'student',
  },
});

Form Data and File Uploads

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'),
    },
  },
});

PUT, PATCH, DELETE

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');

Authentication

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();

Response Validation

Check status, payload shape, and business meaning.

expect(response.status()).toBe(200);
expect(body.user.name).toBe('Lucky');
expect(body.user.github).toContain('lucky');

Hybrid API + UI Pattern

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();

Performance and Error Handling

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);