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

How to log API Requests with Guzzle in PHP (YouTube API Client)
12 Aug 2024
|
1 min read

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.

 1$service = new \Google\Service\YouTube(
 2    app(\Google\Client::class)
 3);
 4
 5$response = $service->videos->listVideos([
 6    'part' => 'snippet,contentDetails,status',
 7], [
 8    'id' => 'dQw4w9WgXcQ',
 9]);
10
11// $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.

 1$service = new \Google\Service\YouTube(
 2    app(\Google\Client::class)
 3);
 4
 5// Create a array accessible stack which guzzle pushes req/res to
 6$history = [];
 7
 8$handlerStack = \GuzzleHttp\HandlerStack::create();
 9$handlerStack->push(
10    \GuzzleHttp\Middleware::history($history) // pass by ref
11);
12
13// Create a new HTTP client. We need to set the 'base_uri' to the YouTube configured base path.
14$httpClient = new \GuzzleHttp\Client([
15    'base_uri' => $service->getClient()->getConfig('base_path'),
16    'debug' => true,
17    'handler' => $handlerStack,
18]);
19
20// Replace the default HTTP client with our HTTP client
21$service->getClient()->setHttpClient($httpClient);
22
23$response = $service->videos->listVideos([
24    'part' => 'snippet,contentDetails,status',
25], [
26    'id' => 'dQw4w9WgXcQ',
27]);
28
29// Dump the history stack
30dd($history);

It's that easy.


Read more...