API Testing
Test the practice API directly with Playwright's request fixture. No browser needed.
Why test the API directly?
API tests skip the browser, so they run in milliseconds and fail with a precise reason. Use them to check business rules and error handling, and to create test data quickly for your UI tests.
Your first request
The request fixture uses the baseURL from playwright.config.ts, so relative paths work. Set it to https://playwright-playground.com.
import { expect, test } from '@playwright/test';
test('lists users', async ({ request }) => {
const response = await request.get('/api/users');
await expect(response).toBeOK(); // any 2xx status
const body = await response.json();
expect(body.users).toContainEqual(
expect.objectContaining({ firstName: 'John', role: 'Admin' })
);
});Create, verify, clean up
test('creates a user', async ({ request }) => {
const response = await request.post('/api/users', {
data: { firstName: 'Eve', lastName: 'Adams', role: 'User' },
});
expect(response.status()).toBe(201);
const user = await response.json();
expect(user).toEqual({
id: expect.any(Number),
firstName: 'Eve',
lastName: 'Adams',
role: 'User',
});
expect(response.headers()['location']).toBe(`/api/users/${user.id}`);
// Leave the API as you found it.
await request.delete(`/api/users/${user.id}`);
});data is sent as JSON with the right Content-Type header. Use params for query strings, for example request.get('/api/users', { params: { role: 'Admin' } }).
Test the unhappy paths
Error responses are where APIs most often break. Assert the status and the error message.
const response = await request.post('/api/users', {
data: { firstName: 'Eve' },
});
expect(response.status()).toBe(400);
expect(await response.json()).toEqual({ error: 'lastName is required' });Authenticated requests
Log in once, then send the token with every request through a dedicated request context:
test('reads the current user', async ({ playwright, baseURL }) => {
const anonymous = await playwright.request.newContext({ baseURL });
const login = await anonymous.post('/api/auth/login', {
data: { username: 'TedBuckland', password: 'Alligator3' },
});
const { token } = await login.json();
const api = await playwright.request.newContext({
baseURL,
extraHTTPHeaders: { Authorization: `Bearer ${token}` },
});
const me = await api.get('/api/me');
expect(await me.json()).toEqual({ username: 'TedBuckland', role: 'Admin' });
await anonymous.dispose();
await api.dispose();
});Use the API to set up UI tests
Creating data through the UI is slow and fragile. Create it with an API call, then test only the screen you care about.
test('new user appears in the table', async ({ page, request }) => {
const created = await request.post('/api/users', {
data: { firstName: 'Zoe', lastName: 'Setup', role: 'Manager' },
});
const user = await created.json();
await page.goto('/network/api');
await page.getByRole('button', { name: 'GET Users' }).click();
await expect(page.getByRole('row').filter({ hasText: 'Setup' })).toBeVisible();
await request.delete(`/api/users/${user.id}`);
});Your data is private: every visitor gets their own copy of the users, so nobody else can change it while you work. It resets to the three original users after an hour of inactivity.
/api/reset from a test: another test may be using the data you would delete. Create your own uniquely named data, assert on that, and delete it afterwards. Reset once, before the whole run, in a global setup instead.API Reference
Base URL: https://playwright-playground.com. Request and response bodies are JSON. Errors look like { "error": "message" }. A known endpoint called with the wrong method answers 405, with an Allow header listing the methods it accepts. An unknown endpoint answers 404.
| Endpoint | Request body | Responses | Notes |
|---|---|---|---|
| Users | |||
GET/api/users | — | 200 { users: User[] } | Optional ?role=Admin|Manager|User filter. |
GET/api/users/:id | — | 200 User · 400 non-numeric id · 404 not found | |
POST/api/users | { firstName, lastName, role } | 201 User + Location header · 400 validation error | All fields required. role must be Admin, Manager or User. |
PUT/api/users/:id | { firstName, lastName, role } | 200 User · 400 · 404 | Replaces the user, so every field is required. |
PATCH/api/users/:id | any of { firstName, lastName, role } | 200 User · 400 · 404 | Updates only the fields you send. |
DELETE/api/users/:id | — | 204 no body · 404 | |
| Authentication | |||
POST/api/auth/login | { username, password } | 200 { token } · 401 | Demo credentials: TedBuckland / Alligator3. |
GET/api/me | — | 200 { username, role } · 401 | Requires an Authorization: Bearer <token> header. |
| Other | |||
GET/api/products | — | 200 { products: Product[] } | Optional ?search=text and ?delay=ms (max 10000). |
GET/api/employees | — | 200 { employees, page, pageSize, total, totalPages } · 400 | Read-only. Optional ?search=text, ?page=1, ?pageSize=5 (max 50). |
GET/api/notifications | — | 200 { notifications: Notification[] } | |
GET/api/cities | — | 200 { cities: string[] } | Up to 8 matches for ?search=text. Optional ?delay=ms. |
GET/api/usernames/:name | — | 200 { username, available } · 400 | |
POST/api/register | { email, age } | 201 { email, age } · 400 · 409 email taken | Validates only; nothing is stored. taken@example.com is always taken. |
POST/api/upload | multipart/form-data, "files" field | 200 { files: { name, size, type }[], totalBytes } · 400 · 413 | Max 2 MB in total. Files are read, not stored. |
GET/api/reports/monthly | — | 200 text file, Content-Disposition: attachment | |
GET/api/checkout/cart | — | 200 { items, subtotal } | |
GET/api/checkout/shipping | — | 200 { shipping } | Takes about 1.5 seconds on purpose. |
POST/api/checkout/pay | { total } | 201 { order } · 400 · 422 { error, code } when the total is wrong | Every response has an X-Request-Id header. |
GET/api/checkout/payments/:id | — | 200 { id, failed } | failed is true for your own rejected payments. |
GET/api/status/:code | — | Responds with the requested status (200–599) | |
POST/api/reset | — | 204 no body | Restores your three seed users and signs out your tokens. Other visitors are not affected. |
Data Models
type User = {
id: number;
firstName: string;
lastName: string;
role: 'Admin' | 'Manager' | 'User';
};
type Product = {
id: number;
name: string;
price: number;
category: string;
};
type Employee = {
id: number;
firstName: string;
lastName: string;
department: string;
city: string;
};
type Notification = {
id: number;
message: string;
};Related exercises
- Network & APIIntermediateAPI PlaygroundCheck both what the UI shows and what actually went over the network.
- Mini ShopAdvancedUI + API TogetherCombine the API and the browser for tests that are fast, independent and thorough.
- AuthenticationAdvancedSign In & SessionsTest a sign-in session, then reuse it so other tests start signed in.
Read the guide: Playwright network mocking and API testing