Write API tests with Playwright's request context
✓Works with OpenClaudeYou are a QA engineer writing API tests using Playwright's request context API. The user wants to write automated API tests that verify endpoints, handle authentication, validate responses, and manage test data lifecycle.
What to check first
- Run
npm list @playwright/testto confirm Playwright is installed (v1.40+) - Verify your API base URL and authentication requirements (API key, token, OAuth)
- Check if your API requires specific headers (Content-Type, User-Agent, Authorization)
Steps
- Create a test file using Playwright's
APIRequestContextby importingtestandexpectfrom@playwright/test - Use the
requestfixture (automatically provided) to create API requests without a browser context - Set the base URL in
playwright.config.tsusingwebServer.urlor pass it directly in requests - Chain
.post(),.get(),.put(),.delete()methods on therequestobject with endpoint paths - Add authentication headers via the
request.post(url, { headers: { Authorization: 'Bearer token' } })option - Parse JSON responses with
.json()method and validate structure withexpect()assertions - Use
test.beforeAll()to set up test data (create resources) andtest.afterAll()to clean up (delete resources) - Extract IDs from creation responses and pass them to subsequent tests using shared test context
Code
import { test, expect } from '@playwright/test';
const API_BASE_URL = 'https://api.example.com';
const API_KEY = process.env.API_KEY || 'test-key';
test.describe('User API Tests', () => {
let userId: string;
let authToken: string;
test.beforeAll(async ({ playwright }) => {
// Optional: Get auth token if needed
authToken = `Bearer ${API_KEY}`;
});
test('POST /users - Create a new user', async ({ request }) => {
const response = await request.post(`${API_BASE_URL}/users`, {
headers: {
'Authorization': authToken,
'Content-Type': 'application/json',
},
data: {
name: 'John Doe',
email: 'john@example.com',
role: 'admin',
},
});
expect(response.status()).toBe(201);
const body = await response.json();
expect(body).toHaveProperty('id');
expect(body.email).toBe('john@example.com');
userId = body.id; // Store for use in other tests
});
test('GET /users/:id - Retrieve created user', async ({ request }) => {
const response = await request.get(
`${API_BASE_URL}/users/${userId}`,
{
headers: { 'Authorization': authToken },
}
);
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Testing Skills
Other Claude Code skills in the same category — free to download.
Unit Test Generator
Generate unit tests for any function or class
Test Coverage Analyzer
Analyze test coverage gaps and suggest tests to write
Mock Generator
Generate mocks, stubs, and fakes for dependencies
Snapshot Test Creator
Create snapshot tests for UI components
E2E Test Writer
Write end-to-end tests using Playwright or Cypress
Test Data Factory
Create test data factories and fixtures
API Test Suite
Generate API test suites for REST endpoints
Mutation Testing Setup
Set up mutation testing to verify test quality
Want a Testing skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.