Pass parameters using the guzzle client

Asked

Viewed 607 times

3

I need to consume an api, the passing of the parameters is done this way:

https://api.typeform.com/v1/form/[typeform_UID]? key=[your_API_key]

I’m using the guzzle to make the requisition.

I am instantiating the client with the base url of this form:

$client = new Client(['base_url' => 'https://api.typeform.com/v1']);

I wanted to pass the parameters "/form", "[typeform_UID]?key=[your_API_key]", using the $client->get(). If I use the get(query=>[]) guzzle it does not form the url the way I would like it.

Does anyone know any way to do this by using the Client with base_url?

  • Which version of Guzzle did you install?

1 answer

2

The way to set the default parameter in Guzzle is using query.

Behold:

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

If you need to use other parameters in url combined with the standard parameters you want to define, I suggest using the method Client::getConfig('query'), combining with the new values desired, thus:

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

Another thing you need to take care of is that the Guzzle has some specific rules for the "assembly" of path of his base_url.

If you put the base_url with the / at the end, you cannot make a request to uri putting / at the beginning. And if you do not put the / at the end of base_url, there is already the reverse, you need to put the bar, whenever you make the requests:

Example A:

$cli = new GuzzleHttp\Client(['base_url' => 'http://meusite.com/api/v1/']);
$cli->get('usuarios/list');

Example B:

$cli = new GuzzleHttp\Client(['base_url' => 'http://meusite.com/api/v1']);
$cli->get('/usuarios/list');

Browser other questions tagged

You are not signed in. Login or sign up in order to post.