Network and API
APIRequestContext in Playwright
APIRequestContext in Playwright: definition, API setup usage, examples, mistakes, interview notes, and practice.
Definition and Brief Explanation
Definition: APIRequestContext is Playwright’s API client for making HTTP requests directly from tests.
Explanation: It is commonly used to create test data, authenticate, clean up records, or validate APIs without driving the UI for every setup step. This makes UI tests faster and more stable.
Why It Matters
- It makes tests faster and more controlled when backend state matters.
- It lets you test success, failure, and edge cases without depending on unstable services.
- It helps verify that the UI sends or receives the expected API traffic.
- It supports clean setup for UI tests through API calls.
How It Works
- Identify the request or API state involved in the test.
- Set up the route, request context, or response wait before the UI action.
- Trigger the UI behavior.
- Assert both the page result and important request/response details when needed.
Syntax and Examples
Example 1: GET request
const response = await request.get('/api/users');
expect(response.ok()).toBeTruthy();
Explanation: Sends an API request without using browser UI.
Example 2: POST request
await request.post('/api/users', { data: { name: 'QA User' } });
Explanation: Creates data through API.
Common Mistakes
- Mocking so much that the test no longer checks real integration.
- Using URL patterns that match unrelated requests.
- Creating shared backend data that breaks parallel tests.
- Forgetting the UI assertion after network setup.
Interview Notes
- What problem does APIRequestContext solve?
- When would you mock instead of using the real API?
- How do you avoid over-mocking?
- How do network waits differ from UI assertions?
Practice Task
Create a small Playwright example for APIRequestContext. Add one positive assertion, one note about what can go wrong, and one improvement that would make the test more maintainable.