Overview
Playwright provides a powerful API testing framework through therequest context, allowing you to test REST APIs, GraphQL endpoints, and web services without launching a browser.
Getting Started
Basic API Request
Make HTTP requests using the request context:HTTP Methods
Request Configuration
Set Base URL and Headers
Configure common request options:Global Configuration
Set API defaults inplaywright.config.ts:
Authentication
Token-Based Authentication
1
Set authorization header
2
Make authenticated requests
API Key Authentication
Request Options
Query Parameters
Custom Headers
Form Data
Multipart Form Data
Response Handling
Parse Response Body
Response Validation
Real-World Example: GitHub API
Complete example testing GitHub API from the Playwright repository:Error Handling
Handle Failed Requests
Advanced Patterns
Retry Failed Requests
Chain API Calls
Parallel API Requests
Best Practices
- Store credentials securely: Use environment variables for API keys and tokens
- Use base URLs: Configure
baseURLto avoid repeating the same URL prefix - Test error scenarios: Verify your API handles errors gracefully
- Validate response schemas: Ensure API responses match expected structure
- Clean up test data: Delete created resources in teardown hooks
- Use meaningful assertions: Check both status codes and response bodies
API tests run faster than browser tests and can be used for comprehensive integration testing.
