46

I read this answer but I believe there is a better way to create a http url query in Guzzle, I am looking for something like this, but cannot get it to work correctly, nor do I know if there is a way to dump the url string to see if it is processing correctly. Could someone show me the correct way to do this?

// works correctly
$client = New GuzzleHttp\Client();
$request = $client->get('http://192.168.50.8/foo?-db=database&-lay=layout&-find');
print_r($request->getBody());

Does not work

$request = $client->get($config->Layout['server'], [], [
        'query' => [
            $config->Layout['switches'], // ([ '-db' => 'database', '-lay' => 'layout', '-find' => true)
            $config->Layout['options'], // other params
        ]
]);
Community
  • 1
  • 1
ehime
  • 8,025
  • 14
  • 51
  • 110

4 Answers4

52

Another variation of the correct answer:

$params = [
   'query' => [
      'option_1' => string,
      'option_2' => string
   ]
];

And then call your request:

$response = $guzzle_client->request('GET','/api.com',$params);
kaleazy
  • 5,922
  • 2
  • 47
  • 51
43

I have the same problem. I found solution

public static function getGroupList($current=false) {
$response = self::getRestClient()->get(
    [
        'domains/{domainId}/pricelists',
        ['domainId' => self::getDomainId()]
    ],
    [
        'query' => [
        current => $current
        ]
    ]
);

return new RestResponse($response);

Try

$response = $client->get(
        [
            $config->Layout['server'],
            []
        ],
        [
            'query' => [
                $config->Layout['switches'], // ([ '-db' => 'database', '-lay' => 'layout', '-find' => true)
                $config->Layout['options'], // other params
            ]
        ]
);
  • 49
    With guzzle 6 you can do `$client->get('http://example.com', ['query' => ['param1' => 'value1']]);` – hansn Jul 10 '17 at 18:09
0

There is a better way to create a http url query in Guzzle. This example follows best practices according to Guzzle architecture and documentation. Have a look at Guzzle documentaton https://docs.guzzlephp.org/en/stable/request-options.html As you can see it has RequestOptions. RequestOptions are constants. They are defined at GuzzleHttp\RequestOptions. You can look at class source code and see all of them right there. Thus, to keep good and professional programming style you can write following source code below, for example

use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;

class DataClass extends BaseClass
{
    const DEFAULT_ACCEPT_HEADER = 'application/json';
    const DEFAULT_CACHE_HEADER = 'no-cache';

    private function getData(array $ids)
    {

        $client = new Client([
                'base_uri' => env("HTTP_HOST"),
                'timeout' => env("TIMEOUT")
            ]
        );

        $response = $client->request('GET', env('ENDPOINT'),
            [
                RequestOptions::HEADERS => [
                    'Accept' => self::DEFAULT_ACCEPT_HEADER,
                    'Cache-Control' => self::DEFAULT_CACHE_HEADER,
                ],
                RequestOptions::QUERY => [
                    'ids' => implode(',', $ids),
                    'stats' => 1
                ]
            ]
        );

        return json_decode($response->getBody(), JSON_OBJECT_AS_ARRAY);
    }
0

This example uses the same variables used in original question. The only env("TIMEOUT") is a variable described in some .env file and can be replaced with a constant. This is how it should work. If it doesn't work in your case, probably the problem is somewhere else

        $client = new Client([
                'base_uri' => $config->Layout['server'],
                'timeout' => env("TIMEOUT")
            ]
        );  

        $response = $client->request('GET', $config->Layout['url'],
            [
                RequestOptions::QUERY => array_merge(
                   $config->Layout['switches'],
                   $config->Layout['options']
                ) 
            ]
        );
  • 2
    Please add some explanation to your answer such that others can learn from it – Nico Haase Aug 03 '20 at 09:28
  • Hi Nico, please see my previous example. I think it should help you to understand the code better. – bashconsole Nov 26 '20 at 11:19
  • Even the previous answer has a comment below asking for an explanation. Additionally, is there any reason that you've posted two answers to this question? – Nico Haase Nov 26 '20 at 11:23
  • I have deleted first answer because somebody set -1 score to it and made the answer more simple. Probably I shouldn't do that. – bashconsole Nov 26 '20 at 11:25
  • Hi again, Nico. I have added detailed description. Let me know if you have more comments. I am professional software engineer and I always glad to help. But not in case I get -1 score for the time I contribute. I just came back because I noticed 3 bronze badges... – bashconsole Nov 26 '20 at 11:49
  • It is highly unusual to add two answers. – Prof. Falken Nov 26 '20 at 11:50
  • This answer we are commenting on has not seen any edit since Aug 3rd - can you also add some explanation here such that other users can understand why you've posted two answers? – Nico Haase Nov 26 '20 at 12:36
  • Added description for second answer. I believe both answers are necessary in this case. – bashconsole Nov 26 '20 at 12:59