How to Debug Guzzle 6 Requests

Submitted by Perignon on Wed, 08/26/2015 - 06:13

If you are here, you probably already know what Guzzle does. If you do not know what Guzzle is, you should! Fun fact: did you know that Guzzle is incorporated into Drupal 8?

Guzzle is a very advanced HTTP request handler that is meant to cut down on the amount of code you write to interact with RESTful services on the web. Behind the curtain, Guzzle uses a combination of PHP streams or cURL to do the heavy lifting. While it does simplify code writing, it can make debugging a little more complicated because you have to extract the information (errors, variables, etc.) from Guzzle that you need to diagnose your code. Guzzle 6.x introduces the use of Middleware.  The most immediately useful middleware you can take advantage of for debugging is Middleware::tap. The best documentation for this method can be found in the Drupal 8 documentation. The name is exactly what it allows you to do, tap into Guzzle. It does not stop or prevent anything from happening, it just allows you to see what is being transferred across the wire.

// Grab the client's handler instance.
$clientHandler = $clienttest2->getConfig('handler');
// Create a middleware that echoes parts of the request.
$tapMiddleware = Middleware::tap(function ($request) {
  // Example of viewing the request sent across the wire.
  // This function will allow you to do things with the request data.

  // Get the headers sent as a JSON object
  $headers = $request->getHeaders();
  // Print out the headers.
  foreach ($request->getHeaders() as $name => $values) {
    echo $name . ': ' . implode(', ', $values) . "\r\n";
  }
  // Get the request body.
  $body = $request->getBody());
});

// Example query with Guzzle
use GuzzleHttp\Client;

$client = new Client([
    // Base URI is used with relative requests
    'base_uri' => 'http://httpbin.org',
]);
$testquery = array(
  'format' => 'json',
);
try {
  $response2 = $client->get('path/to/service', [
    'auth' => [
      'username',
      'password',
    ],
    'query' => $testquery,
    'handler' => $tapMiddleware($clientHandler),
  ]);
}
catch (GuzzleHttp\Exception\ClientException $e){
  echo $e;
}

The last part of the above code using a try-catch to perform the GET operation and catches any exceptions thrown by Guzzle.

Using the Middleware::tap is the quickest way to diagnose issues with Guzzle that doesn't require a lot of setup to perform. The data returned from tap can be used to populate information in Watchdog.