Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple duplicate uri parameters in GuzzleHttp

Tags:

guzzle

I am accessing the Echo Nest API, which requires me to repeat the same uri parameter name bucket. However I can't make this work in Guzzle 6. I read a similar issue from 2012, however the approach does not work.

I have tried adding it manually into the query string without any success.

A sample API call could be:

http://developer.echonest.com/api/v4/song/search?format=json&results=10&api_key=someKey&artist=Silbermond&title=Ja&bucket=id:spotify&bucket=tracks&bucket=audio_summary

Here's my example Client:

/**
 * @param array $urlParameters
 * @return Client
 */
protected function getClient()
{
    return new Client([
        'base_uri' => 'http://developer.echonest.com/api/v4/',
        'timeout'  => 5.0,
        'headers' => [
            'Accept' => 'application/json',
        ],
        'query' => [
            'api_key' => 'someKey',
            'format' => 'json',
            'results' => '10',
            'bucket' => 'id:spotify'         // I need multiple bucket parameter values with the 'bucket'-name
    ]);
}

/**
 * @param $artist
 * @param $title
 * @return stdClass|null
 */
public function searchForArtistAndTitle($artist, $title)
{
    $response = $this->getClient()->get(
        'song/search?' . $this->generateBucketUriString(),
        [
            'query' => array_merge($client->getConfig('query'), [
                'artist' => $artist,
                'title' => $title
            ])
        ]
    );

    // ...
}

Can you help me?

like image 740
skovmand Avatar asked Nov 12 '15 13:11

skovmand


1 Answers

In the Guzzle 6 you are not allowed to pass any aggregate function anymore. Whenever you will pass an array to the query config it will be serialized with the http_build_query function:

if (isset($options['query'])) {
    $value = $options['query'];
    if (is_array($value)) {
        $value = http_build_query($value, null, '&', PHP_QUERY_RFC3986);
    }

To avoid it you should serialize a query string by your own and pass it as string.

new Client([
    'query' => $this->serializeWithDuplicates([
        'bucket' => ['id:spotify', 'id:spotify2']
    ]) // serialize the way to get bucket=id:spotify&bucket=id:spotify2
...
$response = $this->getClient()->get(
    ...
        'query' => $client->getConfig('query').$this->serializeWithDuplicates([
            'artist' => $artist,
            'title' => $title
        ])
    ...
);

Otherwise you could pass into the handler option an adjusted HandlerStack that will have in its stack your Middleware Handler. The one will read some new config param, say, query_with_duplicates, build acceptable Query String and modify Request's Uri with it accordingly.

like image 198
origaminal Avatar answered Nov 11 '22 01:11

origaminal