Use API request context

Create data, call backend endpoints, and verify side effects with the browser context's API client.

Use APIRequestContext when a test needs to create data, call a backend endpoint, or verify a side effect without rendering another page.

Keep the user journey in the browser and use direct requests for the supporting work around it.

Shortest working pattern

Get the request context from the browser context:

php
use Playwright\Assertions\Expect;

$request = $context->request();

$response = $request->get('https://jsonplaceholder.typicode.com/todos/1');

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

$data = $response->json();

self::assertSame(1, $data['id']);

The API assertion proves the endpoint response. A browser assertion should still prove the user-visible result when the request supports a UI flow.

Use it for setup

Create or seed data through an endpoint, then open the page that should display it:

php
$response = $context->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();

This keeps setup fast while the browser still validates the product path.

Expected result

  • the API call returns an OK response;
  • JSON parsing works for JSON endpoints;
  • the browser assertion proves the state the user should see.

Keep it reliable

  • Finish setup requests with a browser assertion for the visible product result.
  • Create data in an isolated environment with an explicit cleanup path.
  • Keep authentication, cookies, and headers visible in the test setup.
  • Name the boundary between mocked browser routes and real API assertions.

Go next

← All recipes