Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify parameters in Guzzle middleware?

I want to write a middleware for Guzzle that adds a specific key to the form_params and populates it with a value. In the docs I have read how to modify the headers but have not found anything about other properties of the $request object. Following the example from the docs this is what I have:

$key = 'asdf';

$stack = new HandlerStack();
$stack->setHandler(new CurlHandler());
$stack->push(Middleware::mapRequest(function (RequestInterface $request) use ($key) {

    // TODO: Modify the $request so that
    // $form_params['api_key'] == 'default_value'

    return $request;
}));

$client = new Client(array(
    'handler' => $stack
));

The middleware should modify the request so that this:

$client->post('example', array(
    'form_params' => array(
        'foo' => 'some_value'
    )
));

has the same effect as this:

$client->post('example', array(
    'form_params' => array(
        'foo' => 'some_value',
        'api_key' => 'default_value'
    )
));
like image 618
hielsnoppe Avatar asked Nov 03 '25 20:11

hielsnoppe


1 Answers

Having done something similar to this, I can say it is very easy.

If you reference GuzzleHttp\Client two things happen when you pass an array into the request in the 'form_params' input option. First, the contents of the array become the body of the request after being urlencoded using http_build query() and secondly, the 'Content-Type' header is set to 'x-www-form-urlencoded'

The snippet below is akin to what you are looking for.

$stack->push(Middleware::mapRequest(function (RequestInterface $request) {

    // perform logic


    return new GuzzleHttp\Psr7\Request(
        $request->getMethod(),
        $request->getUri(),
        $request->getHeaders(),
        http_build_query($added_parameters_array) . '&' . $request->getBody()->toString()
    );

}));
like image 63
Shaun Bramley Avatar answered Nov 05 '25 15:11

Shaun Bramley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!