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!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay