How to log API Requests with Guzzle in PHP (YouTube API Client)

How to log API Requests with Guzzle in PHP (YouTube API Client)

A quick tip if you want to see/log the raw HTTP responses when interfacing with a PHP library that does not expose the responses

Roman Zipp, August 12th, 2024

A quick tip if you want to see/log the raw HTTP responses when interfacing with a PHP library that does not expose the responses.

Default Situation

Imagine you want to request some video details from the YouTube API but also want to inspect some headers of the response.

$service = new \Google\Service\YouTube(
    app(\Google\Client::class)
);

$response = $service->videos->listVideos([
    'part' => 'snippet,contentDetails,status',
], [
    'id' => 'dQw4w9WgXcQ',
]);

// $response->getHttpResponse() ??? doesn't exist...

The Google/YouTube PHP library does not allow you to do so.

Add Guzzle Middleware

Instead, we simply add a history middleware to the HTTP client, in our case Guzzle.

$service = new \Google\Service\YouTube(
    app(\Google\Client::class)
);

// Create a array accessible stack which guzzle pushes req/res to
$history = [];

$handlerStack = \GuzzleHttp\HandlerStack::create();
$handlerStack->push(
    \GuzzleHttp\Middleware::history($history) // pass by ref
);

// Create a new HTTP client. We need to set the 'base_uri' to the YouTube configured base path.
$httpClient = new \GuzzleHttp\Client([
    'base_uri' => $service->getClient()->getConfig('base_path'),
    'debug' => true,
    'handler' => $handlerStack,
]);

// Replace the default HTTP client with our HTTP client
$service->getClient()->setHttpClient($httpClient);

$response = $service->videos->listVideos([
    'part' => 'snippet,contentDetails,status',
], [
    'id' => 'dQw4w9WgXcQ',
]);

// Dump the history stack
dd($history);

It's that easy.