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.
<?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');Creating a Client
Section titled “Creating a Client”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.
Making Requests
Section titled “Making Requests”// 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.
Reading Responses
Section titled “Reading Responses”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 JSONThe client does not throw for 4xx or 5xx statuses. Check $response->status yourself:
if ($response->status >= 400) { throw new RuntimeException("Upstream answered {$response->status}.");}Server-Sent Events
Section titled “Server-Sent Events”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);}Redirects
Section titled “Redirects”301, 302, 303, 307 and 308 responses with a Location header are followed up to maxRedirects times. Like browsers:
303, and301/302after aPOST, switch toGETand drop the body;- the
Authorizationheader is removed when a redirect leaves the original host; - relative
Locationvalues are resolved against the current URL.
Timeouts and Cancellation
Section titled “Timeouts and Cancellation”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);Concurrent Requests
Section titled “Concurrent Requests”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);Limitations
Section titled “Limitations”- 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-Encodingdefaults toidentity. - Only
httpandhttpsURLs, 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.
Security
Section titled “Security”- Leave
verifyTlsenabled 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
maxResponseBytesclose to what you expect; it is your protection against an upstream that sends gigabytes.
Next Steps
Section titled “Next Steps”- Async I/O: futures, deadlines and cancellation in depth.
- Streams & SSE: raw sockets and streaming responses.
- Observability & Diagnostics: trace outgoing work with
Telemetry::span().