inspector.restDocs

Hooks for other clients

Report requests from any PHP HTTP client with the Inspector hooks onRequest, onResponse, onBody, onError and onSettled, which mirror the Node.js lifecycle events.

The Guzzle middleware is built on public hooks. You can call them from any HTTP client (Symfony HttpClient, a cURL wrapper, a legacy client). They mirror the lifecycle events of the Node.js SDK; the payload keys are the same snake_case names.

MethodPayload keys
onRequestrequest_id, labels?, attempt? (default 1), method, url, headers?, proxy_url?, body?
onResponserequest_id, labels?, attempt?, status, headers?, duration_ms?
onBodyrequest_id, labels?, attempt?, bytes?, parse_ok?, read_ms?, raw_body?
onRetryrequest_id, labels?, attempt?, policy?, stage?, delay_ms?, exhausted?
onErrorrequest_id, labels?, attempt? (omit for a request-level error), phase?, error (a Throwable or a message)
onSettledrequest_id, labels?, method?, url?, attempts?, outcome ('ok' or 'error'), duration_ms?, error?

Events of one request are matched by request_id and merged into one record that is sent when the request is settled. The hooks never throw.

Bodies can be strings, PSR-7 streams, InspectorRest\BodySource objects (an unread stream) or arrays (encoded as JSON). error can be a Throwable; its getPrevious() chain is recorded as cause.

PHP
$requestId = \InspectorRest\Transport::newRequestId();
$start = hrtime(true);

$inspector->onRequest(['request_id' => $requestId, 'method' => 'GET', 'url' => $url, 'headers' => $headers]);

try {
    $response = $legacyClient->get($url);
    $ms = (hrtime(true) - $start) / 1e6;
    $inspector->onResponse(['request_id' => $requestId, 'status' => $response->status, 'headers' => $response->headers, 'duration_ms' => $ms]);
    $inspector->onBody(['request_id' => $requestId, 'raw_body' => $response->body]);
    $inspector->onSettled(['request_id' => $requestId, 'outcome' => $response->status < 400 ? 'ok' : 'error', 'duration_ms' => $ms]);
} catch (Throwable $e) {
    $inspector->onError(['request_id' => $requestId, 'phase' => 'network', 'error' => $e]);
    $inspector->onSettled(['request_id' => $requestId, 'outcome' => 'error', 'error' => $e]);
    throw $e;
}

Use InspectorRest\Transport::newRequestId() for the request_id of each request. A retry of the same logical request is another attempt with the same request_id; report it with onRetry.

A request-level error (attempt omitted, or phase: 'domain') is kept even when it arrives after onSettled, as long as the batch has not been built yet, and it makes the outcome error.