HTTP Networking
Pam\Native\Http\Http is PAM Native’s built-in HTTP client. Requests run on
the native networking stack — OkHttp on Android, URLSession on iOS — and PHP
only receives the settled result. Your PHP code never blocks waiting for the
network, and a slow server never freezes the interface.
There are two ways to use it:
- Callbacks —
Http::get(),Http::json(),Http::request()take a closure that receives anHttpResponse. Small and explicit. - An Axios-style client —
Http::create()returns anHttpClientwith a base URL, default headers, interceptors, and retries. Its requests return aPendingResponseyou chain withthen()/catch().
Both are bounded: HTTPS only in release builds, 1 MiB request bodies, 1 MiB responses by default (up to 16 MiB when you ask), and a 120-second ceiling per request. For WebSockets or transfers that must survive the app being closed, see Beyond request/response.
Sending a JSON request
Section titled “Sending a JSON request”use Pam\Native\Http\Http;use Pam\Native\Http\HttpResponse;
Http::json( method: 'POST', url: 'https://api.example.com/session', data: ['email' => $this->email, 'password' => $this->password], callback: function (HttpResponse $response): void { if ($response->transportFailed()) { $this->error = 'Check your connection and try again.'; return; } if (!$response->successful()) { $this->error = "Sign-in failed ({$response->statusCode})."; return; } $payload = json_decode($response->body, true, flags: JSON_THROW_ON_ERROR); $this->authenticated($payload['token']); }, headers: ['X-Client-Version' => '1.0.0'], timeoutMs: 45_000,);Http::json() encodes data with exceptions enabled, sets
Accept: application/json and Content-Type: application/json, and then
applies your headers (which can override them).
Request methods
Section titled “Request methods”Http::get($url, $callback);Http::post($url, $callback, headers: [], body: $body, timeoutMs: 30_000);Http::put($url, $callback, headers: [], body: $body, timeoutMs: 30_000);Http::patch($url, $callback, headers: [], body: $body, timeoutMs: 30_000);Http::delete($url, $callback, headers: [], body: $body, timeoutMs: 30_000);Use Http::request() when the verb is chosen at runtime, or when a response
may be larger than 1 MiB:
Http::request( method: 'GET', url: 'https://api.example.com/catalog/export', callback: $callback, headers: ['Authorization' => "Bearer {$token}"], timeoutMs: 60_000, maxResponseBytes: 4 * 1024 * 1024,);Every method returns the native request ID immediately.
Cancelling a request
Section titled “Cancelling a request”Pass the ID to Http::cancelRequest() when its result is no longer needed —
the user typed a new search, or the screen went away. The connection stops and
the callback is never invoked:
public function search(string $query): void{ if ($this->pending !== null) { Http::cancelRequest($this->pending); }
$this->pending = Http::get( 'https://api.example.com/search?q='.rawurlencode($query), function (HttpResponse $response): void { $this->pending = null; $this->results = json_decode($response->body, true) ?? []; }, );}
public function unmount(): void{ if ($this->pending !== null) { Http::cancelRequest($this->pending); }}The response
Section titled “The response”| Member | Meaning |
|---|---|
statusCode |
HTTP status, or 0 when no response arrived |
body |
Response body as a string |
headers |
Response headers, keyed by lower-case name |
error |
Transport error message (empty on HTTP responses) |
successful() |
true for 200–299 |
transportFailed() |
true when statusCode is 0 and error is not empty |
header($name) |
One header value, or null |
date() |
The Date header as a DateTimeImmutable, or null |
A 404 or 500 is an HTTP response, not a transport failure. DNS errors,
lost connectivity, TLS failures, and timeouts arrive as a status-0 response,
so expected network failures never become uncaught exceptions.
Redirects are not followed: a 3xx response is returned to your callback
with its status code. Point the app at canonical URLs.
An API client
Section titled “An API client”Http::create() builds an immutable client for one API: a base URL, default
headers, a timeout, retries, and interceptors that run in registration order.
<?php
declare(strict_types=1);
namespace App\Api;
use Pam\Native\Http\Http;use Pam\Native\Http\HttpClient;use Pam\Native\Http\HttpError;use Pam\Native\Http\Request;
final class Api{ private static ?HttpClient $client = null;
public static function client(): HttpClient { return self::$client ??= Http::create( baseUrl: 'https://api.example.com', timeout: 20_000, retry: 2, ) ->onRequest(fn (Request $request) => Session::token() !== null ? $request->withToken(Session::token()) : $request) ->onError(function (HttpError $error) { if ($error->status === 401) { Session::expire(); } throw $error; }); }}Requests return a PendingResponse, a thenable of Response:
use Pam\Native\Http\HttpError;
Api::client() ->get('/orders', ['page' => 2]) ->json() ->then(fn (array $orders) => $this->orders = $orders) ->catch(fn (HttpError $error) => $this->error = $error->isNetworkError() ? 'You are offline.' : "Could not load orders ({$error->status}).");
Api::client()->post('/orders', ['product_id' => 42, 'quantity' => 1]);| Piece | What it does |
|---|---|
get($url, $query, $headers), delete(...) |
Query parameters are encoded for you |
post($url, $data, $headers), put(...), patch(...) |
Array data is sent as JSON |
->json($key, $default), ->text() |
Decode the body when the request succeeds |
->cancel() |
Abort the request; nothing settles |
onRequest(fn (Request $r) => ...) |
Return a modified Request (for example withToken()), null, or a thenable of one |
onResponse(fn (Response $r) => ...) |
Inspect or replace a successful response |
onError(fn (HttpError $e) => ...) |
Recover with a Response, resend a Request, or rethrow |
retry / retryDelay |
Extra attempts (0–5) for idempotent requests after a transport failure, 408, 429, or 5xx |
A status of 400 or above rejects with an HttpError, which exposes status,
request, response, isNetworkError(), isTimeout(), isClientError(),
isServerError(), and json() for a JSON error body.
For lists that load page by page, pair the client with the useResource()
composable — it handles pagination, caching, and refresh on focus. See
State and lifecycle.
Uploading files
Section titled “Uploading files”All uploads stream a private sandbox file natively — the bytes never pass
through PHP. Pass the file’s sandbox-relative path (from a FileReference),
not its pam-file:// URI.
Raw PUT
Section titled “Raw PUT”Http::upload() sends a file as the raw body of a PUT — the usual shape of
a pre-signed object-storage URL:
use Pam\Native\FileReference;use Pam\Native\Http\Http;use Pam\Native\Http\HttpResponse;
/** @var FileReference $file from Files::pick() */Http::upload( url: $signedUploadUrl, path: $file->path, callback: fn (HttpResponse $response) => $this->uploaded = $response->successful(), headers: ['Content-Type' => $file->mimeType],);With progress
Section titled “With progress”Http::uploadWithProgress() reports TransferProgress (bytesSent,
totalBytes, fraction(), percent()) and returns an HttpTransfer you can
cancel:
use Pam\Native\Http\Http;use Pam\Native\Http\TransferProgress;
$this->transfer = Http::uploadWithProgress( url: $signedUploadUrl, path: $file->path, callback: fn ($response) => $this->uploaded = $response->successful(), progress: fn (TransferProgress $progress) => $this->percent = $progress->percent(), headers: ['Content-Type' => $file->mimeType],);
// If the user leaves the screen:$this->transfer->cancel();Multipart forms
Section titled “Multipart forms”use Pam\Native\Http\Http;use Pam\Native\Http\HttpResponse;use Pam\Native\Http\TransferProgress;
$this->transfer = Http::multipart('https://api.example.com/media') ->file('media', $file->path, $file->mimeType) ->field('caption', 'Hello from Acme') ->bearer($token) ->onProgress(fn (TransferProgress $progress) => $this->progress = $progress->fraction()) ->send(fn (HttpResponse $response) => $this->posted = $response->successful());App-supplied headers cannot override Host, Content-Length,
Transfer-Encoding, Connection, Trailer, or Upgrade on uploads.
Uploads run in the foreground: they have no automatic retry or process-restart
recovery — for those, use
Background Transfer.
Distributed tracing
Section titled “Distributed tracing”Pass an OutboundTraceContext to propagate a W3C traceparent header. It is
bound to one exact HTTPS origin, and PAM refuses to send it anywhere else, so
trace identifiers never leak to third-party hosts:
use Pam\Native\Http\Http;use Pam\Native\Http\OutboundTraceContext;
$trace = new OutboundTraceContext( traceparent: '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01', origin: 'https://api.example.com',);
Http::get('https://api.example.com/orders', $callback, trace: $trace);Setting traceparent or tracestate as a plain header is rejected.
Limits and validation
Section titled “Limits and validation”| Rule | Value |
|---|---|
| Methods | GET, POST, PUT, PATCH, DELETE |
| Scheme | HTTPS. Plain http:// is accepted only in debug builds, for a local dev server |
| Request body | At most 1 MiB |
| Response body | 1 MiB by default; maxResponseBytes up to 16 MiB |
| Headers | At most 32; names [A-Za-z0-9-], up to 64 bytes; single-line values up to 8,192 bytes |
| Timeout | Requests 1,000–120,000 ms (default 30,000); progress uploads up to 600,000 ms |
Invalid methods, bodies, headers, or limits fail synchronously with an exception before any native call, so they surface during development.
Lean networking
Section titled “Lean networking”Every request wakes the radio and costs battery and data:
- Do not poll from hidden screens. Start periodic refreshes with
Timers::every()inresumed()and cancel them inpaused()/unmount(). - Cancel what you no longer need with
Http::cancelRequest(),PendingResponse::cancel(), orHttpTransfer::cancel(). - Respect metered and power-saving states. Check
useNetwork()->expensiveorDeviceStatusbefore prefetching — see Location and sensors. - Cache what you already fetched in SQLite, a
store, or
useResource(cache: ...), and show it instantly while a refresh runs.
Beyond request/response
Section titled “Beyond request/response”| Need | Use |
|---|---|
| Live updates over WebSockets (Pusher, Reverb) | Realtime WebSockets |
| Uploads/downloads that survive app exit, with retries | Background Transfer |
| Offline outbox and incremental sync with Laravel | Offline Sync, Laravel Sync |
| Embedding a web page | WebView |
Next steps
Section titled “Next steps”- Storage and SQLite — keep what you fetch.
- Forms and validation — submit forms and show server errors.
- Notifications — register push tokens with your API.