Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

guzzle

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?

like image 306
Justin Watt Avatar asked Jun 15 '15 16:06

Justin Watt


People also ask

Are query params always strings?

Yes, URL query string params are of type string. It's up to you to convert them to and from the type you need.

What is Uri Param and query param?

URI parameter (Path Param) is basically used to identify a specific resource or resources whereas Query Parameter is used to sort/filter those resources. Let's consider an example where you want identify the employee on the basis of employeeID, and in that case, you will be using the URI param.

What is Guzzleexception?

A GuzzleHttp\Exception\ConnectException exception is thrown in the event of a networking error. This exception extends from GuzzleHttp\Exception\TransferException . A GuzzleHttp\Exception\ClientException is thrown for 400 level errors if the http_errors request option is set to true.

What is query string URI?

A query string is a part of a uniform resource locator (URL) that assigns values to specified parameters.


1 Answers

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

like image 173
max_spy Avatar answered Sep 28 '22 06:09

max_spy