Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I configure default query parameters with Guzzle 6?

Migrating from 5 to 6, and I've run into a snag and can't find the relevant docs.

Guzzle docs here, http://guzzle.readthedocs.io/en/latest/quickstart.html#creating-a-client, site that we can add "any number of default request options".

I want to send "foo=bar" with every request. E.g.:

$client = new Client([
    'base_uri' => 'http://google.com',
]);

$client->get('this/that.json', [
    'query' => [ 'a' => 'b' ],
]);

This will generate GET on http://google.com/this/that.json?a=b

How do I modify the client construction so that it yields:

http://google.com/this/that.json?foo=bar&a=b

Thanks for your help!

like image 874
Saeven Avatar asked Aug 04 '16 00:08

Saeven


2 Answers

Alright, so far, this works here:

        $extraParams = [
            'a' => $config['a'],
            'b' => $config['b'],
        ];

        $handler = HandlerStack::create();
        $handler->push(Middleware::mapRequest(function (RequestInterface $request) use ($extraParams) {

            $uri  = $request->getUri();
            $uri .= ( $uri ? '&' : '' );
            $uri .= http_build_query( $extraParams );

            return new Request(
                $request->getMethod(),
                $uri,
                $request->getHeaders(),
                $request->getBody(),
                $request->getProtocolVersion()
            );
        }));

        $this->client = new Client([
            'base_uri' => $url,
            'handler' => $handler,
            'exceptions' => false,
        ]);

If anyone knows how to make it less sinister-looking, I would say thank you!

like image 142
Saeven Avatar answered Oct 03 '22 03:10

Saeven


I found a nice solution here.

Basically, anything defined in the first array of arguments, become part of the config for the client.

this means you can do this when initialising:

$client = new Client([
    'base_uri' => 'http://google.com',
    // can be called anything but defaults works well
    'defaults' => [
        'query'  => [
            'foo' => 'bar',
        ]
    ]
]);

Then, when using the client:

$options = [
    'query'  => [
        'nonDefault' => 'baz',
    ]
];

// merge non default options with default ones
$options = array_merge_recursive($options, $client->getConfig('defaults'));

$guzzleResponse = $client->get('this/that.json', $options);

It's woth noting that the array_merge_recursive function appends to nested arrays rather than overwrites. If you plan on changing a default value, you'll need a different utility function. It works nicely when the default values are immutable though.

like image 31
DazBaldwin Avatar answered Oct 03 '22 02:10

DazBaldwin