Stub an API

Fulfill an API request with a stubbed JSON response.

This example intercepts one API request and returns a small JSON response from PHP instead of letting the browser reach the real backend.

Use it when a page needs data from an endpoint that is slow, unstable, unavailable in CI, or outside the behavior you want to test.

Run it

bash
php content/examples/route-stub-api.php

Expected output:

text
Stubbed items count: 1

The script registers the route before the page makes the request. That ordering matters: routes only intercept requests emitted after they are registered.

What it demonstrates

  • route() installs a handler for matching URLs.
  • fulfill() returns a response controlled by the test.
  • The page can call fetch('/api/todos') and receive the stubbed JSON.
  • The test can still inspect the result from the browser.

Keep the stub narrow. Mock the unavailable dependency, not the whole application path you are trying to prove.

Go next

Source

route-stub-api.php
php
<?php

declare(strict_types=1);

/*
 * This file is part of the community-maintained Playwright PHP project.
 * It is not affiliated with or endorsed by Microsoft.
 *
 * (c) 2025-Present - Playwright PHP - https://github.com/playwright-php
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

require_once __DIR__.'/../../vendor/autoload.php';

use Playwright\Playwright;

$context = Playwright::chromium(['headless' => true]);
$page = $context->newPage();

// Stub an API endpoint at the context level
$context->route('**/api/todos', function ($route): void {
    $route->fulfill([
        'status' => 200,
        'contentType' => 'application/json',
        'body' => json_encode(['items' => [
            ['id' => 1, 'title' => 'stubbed'],
        ]]),
    ]);
});

$page->goto('https://example.com');

// Trigger the stubbed endpoint and print the result length
$count = $page->evaluate(<<<'JS'
    async () => {
        const res = await fetch('/api/todos');
        const json = await res.json();
        return Array.isArray(json.items) ? json.items.length : 0;
    }
JS);

echo "Stubbed items count: {$count}".PHP_EOL;

$context->close();