How to combine default query string params and request-specific params using Guzzle?

4.4k views Asked by At

When I run the following code (using the latest Guzzle, v6), the URL that gets requested is http://example.com/foobar?foo=bar dropping the boo=far from the request.

$guzzle_http_client = new GuzzleHttp\Client([
    'base_uri' => 'http://example.com/',
    'query' => [
        'foo' => 'bar'
    ],
]);

$request = new \GuzzleHttp\Psr7\Request('GET', 'foobar?boo=far');
$response = $guzzle_http_client->send($request);

When I run the following code, passing boo=far instead as part of the Client::send() method, the URL that gets requested is http://example.com/foobar?boo=far

$guzzle_http_client = new GuzzleHttp\Client([
    'base_uri' => 'http://example.com/',
    'query' => [
        'foo' => 'bar'
    ],
]);

$request = new \GuzzleHttp\Psr7\Request('GET', 'foobar');
$response = $guzzle_http_client->send($request, ['query' => ['boo' => 'far']]);

Of course, the URL that I want to be requested is:

http://example.com/foobar?foo=bar&bar=foo

How do I make Guzzle combine default client query string parameters with request-specific parameters?

1

There are 1 answers

0
max_spy On

You can try to get default 'query' options using 'getConfig' method and then merge them with new 'query' options, here an example:

$client = new GuzzleHttp\Client([
    'base_uri' => 'http://example.com/',
    'query'   => ['foo' => 'bar']
]);

And then you can easy send a GET request:

$client->get('foobar', [
    'query' =>  array_merge(
        $client->getConfig('query'),
        ['bar' => 'foo']
     )
]);

Additional info you can find here Request Options