Skip to content

Quickstart ​

Install FetchPHP ​

From your application's root directory, install the package with Composer:

sh
composer require jerome/fetch-php

Make a request ​

Save this as example.php beside your composer.json, then run php example.php. It sends a GET request to the public JSONPlaceholder API; replace the URL with your own API endpoint when you are ready.

php
<?php

declare(strict_types=1);

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

use Fetch\Exceptions\ClientException;

try {
    $response = fetch('https://jsonplaceholder.typicode.com/users/1');

    if ($response->successful()) {
        $user = $response->json();
        echo $user['name'].PHP_EOL;
    } else {
        echo 'HTTP '.$response->status().PHP_EOL;
    }
} catch (ClientException $exception) {
    echo 'The request could not be completed.'.PHP_EOL;
}

Requests are synchronous by default. HTTP status codes such as 404 remain responses: use successful() or isStatus() before handling the body. A transport failure raises a ClientException; the example handles that separately from HTTP errors.

Run the offline demonstration ​

The repository's test fixture below uses MockServer, prevents stray requests, and checks the result. Its autoloader path is specific to this repository. This is validation scaffolding for contributors, rather than application setup.

Complete offline fixture
php
<?php

declare(strict_types=1);

require dirname(__DIR__, 3).'/vendor/autoload.php';

use Fetch\Interfaces\Response as FetchResponse;
use Fetch\Testing\MockResponse;
use Fetch\Testing\MockServer;

MockServer::fake([
    'GET https://api.example.test/v1/users/42' => MockResponse::json([
        'id' => 42,
        'name' => 'Ada Lovelace',
    ]),
]);
MockServer::preventStrayRequests();

$response = fetch('https://api.example.test/v1/users/42');

if (
    ! ($response instanceof FetchResponse) ||
    ! $response->isStatus(200) ||
    $response->json()['name'] !== 'Ada Lovelace'
) {
    throw new RuntimeException(
        'The quickstart request returned an unexpected response.',
    );
}

The documentation runner also executes the exact application example above in a temporary Composer-style directory with a fake response. It never calls the public API during validation.

Next: make requests with helpers, clients, and handlers.

Released under the MIT License.