Skip to main content

Overview

Playwright provides a powerful API testing framework through the request 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 in playwright.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

Use Setup and Teardown: Create test data in beforeAll and clean up in afterAll to ensure isolated tests.
  • Store credentials securely: Use environment variables for API keys and tokens
  • Use base URLs: Configure baseURL to 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.

Troubleshooting

Request timeout

Increase timeout for slow endpoints:

CORS errors

CORS doesn’t apply to API testing since requests are made directly:

Debug requests

Log request and response details:
Always validate SSL certificates in production. Use ignoreHTTPSErrors only for testing against development servers.