1. Introduction & API Testing Strategy
While Playwright is widely known for UI automation, its built-in API request context provides a lightweight, highly efficient framework for REST API testing without needing Postman or RestAssured.
Executing API tests within Playwright allows for seamless integration tests—such as generating test data via API requests before executing end-to-end browser workflows.
2. Setting Up the Base API Request Context (playwright.config.ts)
Configure the base URL, headers, and authentication tokens globally within the configuration file:
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
baseURL: '[https://api.example.com/v1](https://api.example.com/v1)',
extraHTTPHeaders: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': Bearer ${process.env.API_TOKEN || 'test-token'},
},
},
});
3. Writing Modular CRUD Tests (tests/api/users.spec.ts)
Leverage Playwright's request fixture to perform standard HTTP actions and assert JSON response payloads:
import { test, expect } from '@playwright/test';
test.describe('Users API Endpoints', () => {
let createdUserId: string;
test('POST /users - Create new user record', async ({ request }) => {
const response = await request.post('/users', {
data: {
name: 'Automation Tester',
email: 'test.user@example.com',
role: 'QA Engineer',
},
});
expect(response.status()).toBe(201);
const body = await response.json();
expect(body.name).toBe('Automation Tester');
expect(body.id).toBeTruthy();
createdUserId = body.id;
});
test('GET /users/{id} - Fetch user details', async ({ request }) => {
const response = await request.get(/users/${createdUserId});
expect(response.ok()).toBeTruthy();
const body = await response.json();
expect(body.email).toBe('test.user@example.com');
});
test('DELETE /users/{id} - Clean up user record', async ({ request }) => {
const response = await request.delete(/users/${createdUserId});
expect(response.status()).toBe(204);
});
});
4. Key Takeaways
- Fast Execution: Running direct HTTP requests bypasses browser overhead, allowing hundreds of API assertions to execute in seconds.
- Hybrid Testing: You can combine API requests with UI automation—for instance, using API setup calls to prime database state before executing UI test scripts.
Top comments (0)