API Testing with Playwright
Intermediate12 min
Use Playwright's built-in request context to test REST APIs directly, validate responses, and combine API calls with browser tests.
Prerequisites
- -Playwright installed
- -A REST API to test
Steps
1
Create an API test file
Write tests using Playwright's APIRequestContext without a browser.
$ cat > tests/api.spec.ts << 'EOF'
import { test, expect } from '@playwright/test';
test.describe('API Tests', () => {
test('GET /api/users returns user list', async ({ request }) => {
const response = await request.get('/api/users');
expect(response.ok()).toBeTruthy();
expect(response.status()).toBe(200);
const data = await response.json();
expect(data).toHaveProperty('users');
expect(data.users.length).toBeGreaterThan(0);
});
test('POST /api/users creates a user', async ({ request }) => {
const response = await request.post('/api/users', {
data: {
name: 'Test User',
email: 'test@example.com',
},
});
expect(response.status()).toBe(201);
const user = await response.json();
expect(user.name).toBe('Test User');
});
});
EOF
2
Add authentication to API tests
Set up a test fixture that includes an auth token for all requests.
$ cat > tests/fixtures.ts << 'EOF'
import { test as base } from '@playwright/test';
export const test = base.extend({
request: async ({ playwright }, use) => {
const context = await playwright.request.newContext({
baseURL: 'http://localhost:3000',
extraHTTPHeaders: {
'Authorization': 'Bearer ' + process.env.API_TOKEN,
'Content-Type': 'application/json',
},
});
await use(context);
await context.dispose();
},
});
export { expect } from '@playwright/test';
EOF
Use custom fixtures to avoid repeating auth setup in every test file.
3
Test API response schema
Validate that API responses match the expected structure.
$ cat >> tests/api.spec.ts << 'EOF'
test('response matches expected schema', async ({ request }) => {
const response = await request.get('/api/users/1');
const user = await response.json();
expect(user).toMatchObject({
id: expect.any(Number),
name: expect.any(String),
email: expect.stringContaining('@'),
createdAt: expect.any(String),
});
});
EOF
4
Combine API and browser tests
Use API calls to set up state before browser tests.
$ cat > tests/e2e-with-api.spec.ts << 'EOF'
import { test, expect } from '@playwright/test';
test('create item via API, verify in UI', async ({ page, request }) => {
// Create data via API
const response = await request.post('/api/items', {
data: { title: 'E2E Test Item', status: 'active' },
});
const item = await response.json();
// Verify in browser
await page.goto('/items');
await expect(page.getByText('E2E Test Item')).toBeVisible();
// Cleanup via API
await request.delete('/api/items/' + item.id);
});
EOF
Full Script
FAQ
Discussion
Loading comments...