Question

In my PHP Guzzle client code, I have something like

$c = new Client('http://test.com/api/1.0/function');

$request = $c->get('?f=4&l=2&p=3&u=5');

but instead I want to have something like:

$request->set('f', 4);
$request->set('l', 2);
$request->set('p', 3);
$request->set('u', 5);

Is it possible in Guzzle? From the documentation and random googling it would seem it is, but I can't find exactly how.

Was it helpful?

Solution

Guzzle 6 - you could use query option param

// Send a GET request to /get?foo=bar
$client->request('GET', '/get', ['query' => ['foo' => 'bar']]);

http://docs.guzzlephp.org/en/stable/request-options.html#query

OTHER TIPS

You can:

$c = new Client('http://test.com/api/1.0/function');

$request = $c->get();

$q = $request->getQuery();

$q->set('f', 4);
$q->set('l', 2);
$q->set('p', 3);
$q->set('u', 5);

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';
    const HOST = 'http://test.com/';
    const ENDPOINT = 'api/1.0/function';
    const TIMEOUT = 2.0;

    private function getData()
    {

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

        $response = $client->request('GET', self::ENDPOINT,
            [
                RequestOptions::HEADERS => [
                    'Accept' => self::DEFAULT_ACCEPT_HEADER,
                    'Cache-Control' => self::DEFAULT_CACHE_HEADER,
                ],
                RequestOptions::QUERY => [
                        'f' => 4,
                        'l' => 2,
                        'p' => 3,
                        'u' => 5
                ]
            ]
        );

        return json_decode($response->getBody(), JSON_OBJECT_AS_ARRAY);
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top