DEV Community

Cover image for Log Request Body in Guzzle
Nasrul Hazim Bin Mohamad
Nasrul Hazim Bin Mohamad

Posted on

5 1

Log Request Body in Guzzle

Debugging when using Guzzle, is quiet easy by providing the debug key in the payload:

$client->request('GET', '/url, ['debug' => true]);
Enter fullscreen mode Exit fullscreen mode

This is quiet easy and not an issue if your are not passing any body content, using only query string to dump what's been request.

It will different story if you are sending JSON content - you need to know the write data send to your URI destination.

You can create a middleware for this purpose.

TLDR


use GuzzleHttp\Client;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use Psr\Http\Message\RequestInterface;

$stack = new HandlerStack();
$stack->setHandler(new CurlHandler());

$middleware = Middleware::tap(function (RequestInterface $request) {
    if(config('services.api.debug')) {
        $body = (string) $request->getBody();

        if(!empty($body)) {
            $body = json_decode($body, JSON_OBJECT_AS_ARRAY);
        }

        logger()->channel('api')->info([
            'url' => $request->getUri(),
            'body' => $body,
            'headers' => $request->getHeaders(),
        ]);
    }
});

$stack->push($middleware);

$client = new Client(
    [
        'base_uri' => config('services.api.base_url'),
        'handler' => $stack,
    ]
);

$client->request('GET', '/url', ['json' => ['abc' => 123]]);
Enter fullscreen mode Exit fullscreen mode

With this piece of codes, it helps you to debug what kind of data being send before request is send.

p/s: I'm using Laravel, hence some of the syntax related to Laravel.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay