API requests

Use APIRequestContext for setup, cleanup, backend checks, and shared browser authentication.

API requests let a test talk to HTTP endpoints without going through the page UI.

Use them for setup, teardown, seed data, and checks that do not need rendering or browser behavior.

Mental model

The browser proves user-visible behavior. API requests handle supporting work faster and more directly.

php
use Playwright\Assertions\Expect;

$request = $context->request();

$response = $request->post('https://app.example.test/api/users', [
    'data' => ['name' => 'Ada Lovelace'],
]);

Expect::response($response)->toBeOK();

Then use the browser for the flow the user actually performs.

Choose API request or browser flow

Need Prefer
Create test data before a UI flow API request
Verify an endpoint contract API request
Prove the user can complete a task browser flow
Test rendering, focus, forms, or navigation browser flow
Control what the page receives routing

API requests handle supporting work efficiently, while browser assertions keep the user-visible behavior covered.

Good uses

  • create a user before a browser test;
  • call a cleanup endpoint after a run;
  • verify a backend side effect after a UI action;
  • share cookies or auth with the browser context when supported;
  • test an API workflow separately from rendering.

Minimal useful pattern

Create data through the API, then assert the browser can use it.

php
use Playwright\Assertions\Expect;
use function Playwright\Testing\expect;

$request = $context->request();

$response = $request->post('https://app.example.test/api/projects', [
    'data' => ['name' => 'Migration'],
]);

Expect::response($response)->toBeOK();

$page->goto('https://app.example.test/projects');
expect($page->getByRole('link', ['name' => 'Migration']))->toBeVisible();

The API call sets up state. The browser assertion proves the product path.

Keep the browser for user journeys

Keep checkout, signup, upload, and permission flows in the browser when those interactions are the behavior under test.

Use an isolated test environment with explicit data creation and cleanup for API setup.

Working habits

  • Use API calls for setup and backend checks, then assert the visible result in the browser.
  • Keep headers, cookies, and authentication context explicit.
  • Create data in an isolated test environment with a matching cleanup path.
  • Name the boundary between mocked browser routes and real API assertions.

Go next