HTTP Client#

Install the package:

composer require kinetis/revolt-http-client

Kinetis\RevoltHttpClient\Http calls other services over HTTP. A request suspends the calling Fiber while it waits on the network, so a worker keeps serving other requests during the round trip.

Send a request#

Http autowires with nothing to register. Inject it and call a verb:

use Kinetis\RevoltHttpClient\Http;

final readonly class ExchangeRates
{
    public function __construct(private Http $http) {}

    public function latest(string $currency): array
    {
        return $this->http
            ->get('https://rates.example.com/latest', ['base' => $currency])
            ->throw()
            ->json();
    }
}

get() takes a query array. post(), put(), patch() and delete() take a body array and send it as JSON; asForm() sends it as application/x-www-form-urlencoded instead. send() covers any other method, a raw or streamed body, and a header for one call (send() options and streamed bodies).

Register a configured client#

An API that needs a credential gets its own client, built once in bootstrap.php from configuration:

bootstrap.php#
use App\Shipping\CarrierApi;
use Kinetis\Config\Config;
use Kinetis\Container\AppScope;
use Kinetis\RevoltHttpClient\Http;

return static function (AppScope $app, Config $config): void {
    $app->instance(CarrierApi::class, new CarrierApi(
        new Http()
            ->withBaseUrl('https://api.carrier.example/v2')
            ->withToken($config->required('CARRIER_API_TOKEN'))
            ->withTimeout(10),
    ));
};
namespace App\Shipping;

use Kinetis\RevoltHttpClient\Http;

final readonly class CarrierApi
{
    public function __construct(private Http $http) {}

    public function track(string $number): array
    {
        return $this->http->get('/shipments', ['number' => $number])->throw()->json();
    }

    public function createLabel(string $orderId, array $address): array
    {
        return $this->http
            ->post('/labels', ['order' => $orderId, 'address' => $address])
            ->throw()
            ->json();
    }
}

The base URL’s path is a prefix: get('/shipments') above requests https://api.carrier.example/v2/shipments.

Every with* method returns a new client and leaves the original unchanged, so a shared client can be adjusted for one call — $this->http->withTimeout(30)->get('/reports') — without affecting other callers. Http holds no request state, so an AppScope instance is safe in a persistent worker, and it keeps its connection pool and keep-alive connections across requests. An autowired Http is built per request with a new pool. Under PHP-FPM both choices start a new pool for every request.

Read the response#

$response = $this->http->get('/shipments/42');

$response->status();              // 200
$response->successful();          // true for any 2xx
$response->json();                // the decoded body, as an array
$response->jsonPath('eta.date');  // one value by dot path, or null
$response->body();                // the raw string
$response->header('X-Request-Id');
$response->attempts();            // wire attempts sent, retries and redirects included

An error status is a response, not an exception. Branch on failed(), clientError(), serverError() or redirect(), or call throw() to raise HttpRequestException for any status outside 2xx. throw() returns the response when it succeeded, so it chains:

$response = $this->http->get("/shipments/{$number}");

if ($response->clientError()) {
    return null;
}

return $response->throw()->json();

Redirects are not followed by default. A 3xx is returned as the response, with its Location header to read. Follow redirects turns following on.

A gzip or deflate body arrives decoded, read whole or streamed; the Content-Encoding and Content-Length headers stay as the server sent them. A body in another encoding, or one whose compressed data is corrupt or cut short, throws with the Conversion category.

Reading a response has the JSON decoding rules and how to release a response you will not read.

Stream a response#

chunks() hands over the body as it arrives instead of buffering it, for a token stream, an NDJSON export or a large download:

$response = $this->http->withTimeout(120)->post('/v1/chat', $payload)->throw();

foreach ($response->chunks() as $bytes) {
    // each $bytes is the next non-empty piece of the body, in order
}

Each piece is the next bytes of the body, decoded from gzip or deflate when the response is compressed. A piece can end mid-line or mid-character; splitting into SSE events or JSON lines is the caller’s. The calling Fiber suspends between pieces, so the event loop keeps running: timers and other Fibers of the same request, such as work started with concurrently(), proceed meanwhile. status(), headers() and throw() work before and during the stream.

  • The timeout covers the whole stream. withTimeout() runs from the request to the last byte, so a long stream needs a timeout that long; a stream still running when it expires, or one that stalls, throws with the Timeout category.

  • The byte ceiling covers the whole stream. A Content-Length past withMaxResponseBytes() throws from chunks() before anything is read, and a stream with no declared length throws ResponseTooLarge instead of handing over the piece that would pass the ceiling. The ceiling counts decoded bytes, so a compressed stream is held to the size it inflates to. Raise the ceiling for a download known to be larger.

  • Stopping early releases the connection. A break, an exception thrown in the loop body, or a discarded generator cancels the transport response. A generator you keep in a variable holds the connection until it is destroyed.

  • The body is read once. After chunks(), body(), json() and another chunks() throw with the Consumed category, and so does chunks() after body().

  • A stream is never retried. With withRetries(), a retryable status is settled before the response is returned, so the stream always comes from the final attempt. A failure after the first byte throws; nothing is resent.

To relay an upstream to the browser, read it inside a Kinetis\Http\StreamedResponse emitter:

use Kinetis\Http\StreamedResponse;
use Nyholm\Psr7\Response;

$upstream = $this->http->withTimeout(120)->post('/v1/chat', $payload)->throw();

return new StreamedResponse(
    new Response(200, ['Content-Type' => 'text/event-stream', 'X-Accel-Buffering' => 'no']),
    static function () use ($upstream): void {
        foreach ($upstream->chunks() as $bytes) {
            echo $bytes;
            flush();
        }
    },
);

Runtime Adapters lists the runtimes that stream a StreamedResponse.

Credentials stay on one origin#

A client carrying an Authorization or Cookie header — from withToken(), withBasicAuth() or withHeaders() — requires a base URL, and every request URL is then a path relative to it:

// Refused: nothing says which origin may see the token.
$http->withToken($token)->get('https://api.carrier.example/v2/shipments');

// Sent to api.carrier.example and nowhere else.
$http->withBaseUrl('https://api.carrier.example/v2')->withToken($token)->get('/shipments');

Such a client refuses an absolute request URL and follows a redirect only to a URL under its base URL, so the credential reaches only the base URL’s origin. Reach a second API with a second client and that API’s own credential. Take the base URL from configuration, never from request input. Base URLs and request URLs has the URL, path and header rules.

Follow redirects#

withRedirects() follows up to $max redirects, five unless given:

$download = $http
    ->withRedirects(3, allow: static fn (string $url): bool => str_starts_with($url, 'https://cdn.example.com/'))
    ->get('https://files.example.com/reports/2026-11.csv');
  • 301, 302 and 303 are followed as a GET without the body and without Content-Type, Content-Length and Content-Encoding. A HEAD stays a HEAD.

  • 307 and 308 repeat the request as it was, and only when its method is GET, HEAD, OPTIONS, TRACE, PUT or DELETE and its body is not a stream or a Closure. A POST answered with 307 is returned, because sending it again could apply it twice.

  • Never from https to http, and never outside the base URL of a client that has one: that would take its credentials to another origin. A client without a base URL may follow to any origin, taking every header it carries except Authorization and Cookie, which it cannot carry; Redirects says when that matters.

  • allow receives every redirect’s absolute target URL before it is requested and must return true for it to be followed. Use it to keep a URL taken from user input off internal hosts.

A redirect not followed for any of these reasons, one whose Location is missing or not a URL this client would send, and the one past the limit are returned as the response, so redirect() tells you the chain stopped. The whole chain runs inside the request’s one timeout and byte ceiling, each hop is a wire attempt counted by attempts() and by withRetries(), and only the first request waits for a pacer slot.

Keep cookies for a session#

A CookieJar keeps the cookies a server sets, redirect hops included, and sends the matching ones back on every request and every hop:

use Kinetis\RevoltHttpClient\CookieJar;

$session = $this->http->withCookieJar(new CookieJar());

$session->post('https://portal.example.com/login', $credentials)->throw();
$invoices = $session->get('https://portal.example.com/invoices')->json();
  • One jar per session. The jar is the cookies of whoever it was built for. Create it where the session starts, inside the request or job that owns it, and never register a jar, or a client carrying one, in the application scope: under a persistent worker every request would send the same user’s session. No client has a jar until you give it one.

  • Exact host only. A cookie is sent to the host that set it and to no other, whatever its Domain attribute names. Telling a domain one owner controls from one shared by strangers needs a public-suffix list; without one, widening a cookie to a parent domain could hand it to another tenant’s host, so the jar never widens it.

  • Path, Secure and expiry follow RFC 6265: Path scopes a cookie to that path and below it, a Secure cookie goes only over https and is refused when set over http, Max-Age wins over Expires, and an expired cookie is deleted. HttpOnly and SameSite mean nothing outside a browser and are ignored.

  • Bounded. A jar keeps at most 50 cookies per host and 300 in all, dropping the oldest to make room, and ignores a cookie longer than 4 KiB, so a hostile server cannot grow it without limit.

A Cookie header you set yourself still requires a base URL (Base URLs and request URLs). The jar’s cookies need none, since each is scoped to its own host. When both are present, one Cookie header carries yours first and the jar’s after it; a name in both is sent twice, so keep them apart. Cookie values never appear in an exception message.

Timeouts, response size and retries#

$reports = $http
    ->withBaseUrl('https://reports.example.com')
    ->withTimeout(60)
    ->withMaxResponseBytes(64 * 1024 * 1024)
    ->withRetries(2);
  • withTimeout() is the total budget for one call, in seconds: every attempt, every wait between retries, and reading the response. The default is 30. Running out throws with the Timeout category. Set it below the deadline of whatever is waiting on the call.

  • withMaxResponseBytes() caps the response body, counted after gzip or deflate decoding. The default, 8 MiB, keeps one large reply from exhausting worker memory. A larger body throws with the ResponseTooLarge category; raise the cap for an endpoint known to return more.

  • withRetries() resends only GET, HEAD, OPTIONS, TRACE, PUT and DELETE, after a transport failure or a 429, 500, 502, 503 or 504 status, waiting between attempts inside the same timeout and at least as long as a Retry-After header asks. When the server’s wait does not fit in what is left of the timeout, its response is returned instead of being retried early. It never resends POST or PATCH. HTTP defines PUT and DELETE as idempotent; enable retries only for an API whose PUT and DELETE really are. A client without withRetries() sends every request once. A second argument narrows the retried statuses, for an API that answers 429 when a quota is spent rather than when it asks for a wait.

Deadline and retries has the exact deadline and retry behavior, and Response byte ceiling the byte ceiling.

Pace requests to a host#

withPacer() spaces the attempts a client sends, for example to keep every worker process together under a third-party API’s rate limit. It takes an implementation of Kinetis\RevoltHttpClient\RequestPacer. Kinetis ships none; Pacing a host has implementations over PostgreSQL, MySQL and Redis.

$carrier = new Http()
    ->withBaseUrl('https://api.carrier.example/v2')
    ->withRetries(3)
    ->withPacer($pacer);

Before every wire attempt, retries included, the client calls $pacer->reserve($origin, $maxWaitSeconds) with the request’s origin (https://api.carrier.example above) and what is left of the timeout, then waits the seconds it returns inside that timeout. A negative wait means now. A client without retries paces its one attempt too.

  • First attempt. null, or a wait that does not fit in what is left of the timeout, throws HttpRequestException with the Timeout category, and nothing is sent.

  • Retry. The slot is reserved only once the backoff and Retry-After rules above have decided to retry, and the retry waits for the later of its backoff and its slot. When the pacer returns null, or that wait does not fit in what is left of the timeout, the retries end as they do for a Retry-After that does not fit: the last response is returned, or the transport failure is thrown when no response arrived.

  • Unused slots. A slot reserved for a retry that then does not fit is not given back, so the next caller waits behind it.

  • Failures. An exception from reserve() passes through unchanged, after the client releases any response it holds.

reserve() runs on the calling Fiber, so its I/O must suspend rather than block. One pacer serves every request for the worker’s lifetime and holds no request state.

When a request fails#

HttpRequestException is the only exception the client throws; an exception from a pacer passes through unchanged. Branch on its category:

Category

Meaning

InvalidRequest

The request was refused before it was sent. A repeat is refused the same way.

Transport

No complete response arrived. The server may have received and applied the request.

Timeout

The total budget ran out. The server may have received and applied the request.

ResponseTooLarge

A response arrived with a body past the byte ceiling.

ErrorStatus

throw() met a status outside 2xx; $e->status holds it.

Conversion

json() or jsonPath() met a body that is not a JSON object or array, or a body arrived in a content encoding this client does not decode or with corrupt or truncated gzip or deflate data.

Discarded

The response was read after discard().

Consumed

The body was read a second way: body() or json() after chunks(), or chunks() after body(), json() or chunks().

A failed write can already have happened. A connection can drop after the server acted but before its response arrived, so Transport and Timeout do not mean the request was not applied. Before sending a POST or PATCH again, find out whether the first one took effect, or use the API’s own idempotency mechanism if it has one:

use Kinetis\RevoltHttpClient\Exception\HttpFailure;
use Kinetis\RevoltHttpClient\Exception\HttpRequestException;

try {
    return $this->http->post('/labels', ['order' => $orderId])->throw()->json();
} catch (HttpRequestException $e) {
    if ($e->category !== HttpFailure::Transport && $e->category !== HttpFailure::Timeout) {
        throw $e;
    }

    // The label may exist already: look it up instead of posting again.
    return $this->http->get('/labels', ['order' => $orderId])->throw()->json();
}

An exception names the method, the origin and the status, never the path, query string, headers, credentials or bodies. An upstream’s own error payload is on the response: read it with body() before calling throw() when you need it (Failures).

Several requests at once#

use function Kinetis\Async\concurrently;

[$shipment, $events] = concurrently([
    fn (): array => $this->http->get("/shipments/{$number}")->throw()->json(),
    fn (): array => $this->http->get("/shipments/{$number}/events")->throw()->json(),
]);

The two requests overlap instead of running one after the other. concurrently() lets every task finish, then rethrows the first failure in task order; see Concurrency.

Testing#

Construct Http over Symfony’s MockHttpClient to test code that uses it without a network. The mock answers with its MockResponse list in order, and getRequestsCount() reports how many requests were sent:

use App\Shipping\CarrierApi;
use Kinetis\RevoltHttpClient\Http;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Response\MockResponse;

final class CarrierApiTest extends TestCase
{
    public function test_a_503_is_retried(): void
    {
        $mock = new MockHttpClient([
            new MockResponse('', ['http_code' => 503]),
            new MockResponse('{"status": "delivered"}'),
        ]);

        $carrier = new CarrierApi(
            new Http($mock)
                ->withBaseUrl('https://api.carrier.example/v2')
                ->withToken('test-token')
                ->withRetries(2),
        );

        self::assertSame(['status' => 'delivered'], $carrier->track('1Z999'));
        self::assertSame(2, $mock->getRequestsCount());
    }
}

Build the client under test the way the application does: a client carrying a token needs withBaseUrl() there too, and the mock receives the same absolute URLs and headers the real transport would. A request past the end of the list fails with the InvalidRequest category. Injected transports and tests states what any injected transport must uphold.

See also#