Skip to content

HTTP Client

Pam\Http\Client is a small HTTP/1.1 client built on PAM’s async socket functions. While it waits for the network, it suspends only the current request’s Fiber, so one slow upstream does not freeze every request on the worker the way curl_exec() or file_get_contents() would.

It is deliberately strict: every response is bounded in size, TLS certificates are verified by default, and the whole exchange, redirects included, shares one timeout.

index.php
<?php
declare(strict_types=1);
use Pam\Http\Client;
use Pam\Http\Request;
use Pam\Http\Response;
use Pam\Http\Server;
$client = new Client(timeout: 5.0);
Server::create(static function (Request $request, Response $response) use ($client): Response {
$upstream = $client->get('https://api.example.com/status', [
'Accept' => 'application/json',
]);
return $response->json([
'status' => $upstream->status,
'body' => $upstream->json(),
]);
})->listen(3000, '127.0.0.1');

All options are constructor arguments. The defaults are:

Argument Default Meaning
timeout 30.0 Seconds for the whole request, including connect, TLS, redirects and body
maxResponseBytes 16 * 1024 * 1024 Largest accepted body (after chunked decoding)
maxHeaderBytes 64 * 1024 Largest accepted header block
maxRedirects 5 Redirects to follow; 0 returns the 3xx response itself
verifyTls true Verify the server certificate and host name
use Pam\Http\Client;
$client = new Client(
timeout: 10.0,
maxResponseBytes: 4 * 1024 * 1024,
maxRedirects: 2,
);

A non-positive timeout or limit throws InvalidArgumentException. The client object holds no connection, so one instance can be shared by every request of a worker.

// GET with headers
$response = $client->get('https://api.example.com/products?page=2', [
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . $token,
]);
// POST with a body
$response = $client->post(
'https://api.example.com/orders',
json_encode(['sku' => 'ACME-1', 'quantity' => 2], JSON_THROW_ON_ERROR),
['Content-Type' => 'application/json'],
);
// Any method
$response = $client->request('DELETE', 'https://api.example.com/orders/42');

The full signatures are:

public function get(string $url, array $headers = [], ?CancellationToken $cancellation = null): ClientResponse;
public function post(string $url, string $body = '', array $headers = [], ?CancellationToken $cancellation = null): ClientResponse;
public function request(string $method, string $url, array $headers = [], string $body = '', ?CancellationToken $cancellation = null): ClientResponse;

Header values can be a string or a list of strings. The client sets Host, Connection: close, Accept-Encoding: identity and a User-Agent of Pam/<version> unless you provide your own, and adds Content-Length when there is a body.

Every call returns an immutable Pam\Http\ClientResponse:

$response->status; // 200
$response->headers; // ['content-type' => ['application/json'], ...] (lower-case names)
$response->header('Content-Type'); // "application/json", multiple values joined with ", "
$response->header('X-Missing', 'none'); // default when absent
$response->body; // raw body string
$response->json(); // json_decode(..., true), throws JsonException on invalid JSON

The client does not throw for 4xx or 5xx statuses. Check $response->status yourself:

if ($response->status >= 400) {
throw new RuntimeException("Upstream answered {$response->status}.");
}

serverSentEvents() parses an text/event-stream body and yields the data of each event (multi-line data: fields are joined with a newline):

$response = $client->get('https://api.example.com/feed');
foreach ($response->serverSentEvents() as $data) {
$event = json_decode($data, true);
}

301, 302, 303, 307 and 308 responses with a Location header are followed up to maxRedirects times. Like browsers:

  • 303, and 301/302 after a POST, switch to GET and drop the body;
  • the Authorization header is removed when a redirect leaves the original host;
  • relative Location values are resolved against the current URL.

timeout is one budget for the whole call. When it runs out, the client throws RuntimeException('HTTP client request timed out.'). To stop a request early from elsewhere, or to share a budget across several calls, pass a CancellationToken:

use Pam\Async\CancellationToken;
use Pam\Async\Deadline;
$token = new CancellationToken(Deadline::after(1.5));
$inventory = $client->get('https://inventory.example.com/items/42', cancellation: $token);
$pricing = $client->get('https://pricing.example.com/items/42', cancellation: $token);

Wrap calls in futures to run them side by side:

use function Pam\Async\all;
use function Pam\Async\async;
[$inventory, $pricing] = all([
async(static fn () => $client->get('https://inventory.example.com/items/42')),
async(static fn () => $client->get('https://pricing.example.com/items/42')),
], timeout: 3.0);
  • HTTP/1.1 only, one connection per request (Connection: close). There is no connection pooling or keep-alive, so each call pays a TCP and TLS handshake.
  • Responses are fully buffered in memory, up to maxResponseBytes; there is no streaming body API.
  • No automatic compression: Accept-Encoding defaults to identity.
  • Only http and https URLs, with no user info in the URL.
  • No proxy support and no cookie jar.

When you need any of these, a Composer client such as Guzzle still works under PAM; it just blocks the worker while it waits.

  • Leave verifyTls enabled in production. Disabling it also allows self-signed certificates.
  • Treat any URL that comes from user input as untrusted: validate the scheme and host and block internal networks yourself to avoid server-side request forgery. The client does not restrict destinations.
  • Keep maxResponseBytes close to what you expect; it is your protection against an upstream that sends gigabytes.