Lenzork
Lenzork

Reputation: 15

problem with multiple HTTP requests in Laravel with Guzzle

I'm using Guzzle version 6.3.3. I want to make multiple HTTP requests from an external API. The code shown below worker perfect for me. This is just one single request.

public function getAllTeams()
{
    $client = new Client();
    $uri = 'https://api.football-data.org/v2/competitions/2003/teams';
    $header = ['headers' => ['X-Auth-Token' => 'MyKey']];
    $res = $client->get($uri, $header);
    $data = json_decode($res->getBody()->getContents(), true);
    return $data['teams'];
}

But now I want to make multiple requests at once. In the documentation of Guzzle I found out how to do it, but it still didn't work properly. This is the code I try to use.

    $header = ['headers' => ['X-Auth-Token' => 'MyKey']];
    $client = new Client(['debug' => true]);
    $res = $client->send(array(
        $client->get('https://api.football-data.org/v2/teams/666', $header),
        $client->get('https://api.football-data.org/v2/teams/1920', $header),
        $client->get('https://api.football-data.org/v2/teams/6806', $header)
    ));
    $data = json_decode($res->getBody()->getContents(), true);
    return $data;

I get the error:

Argument 1 passed to GuzzleHttp\Client::send() must implement interface Psr\Http\Message\RequestInterface, array given called in TeamsController.

If I remove the $header after each URI then I get this error:

resulted in a '403 Forbidden' response: {"message": "The resource you are looking for is restricted. Please pass a valid API token and check your subscription fo (truncated...)

I tried several ways to set X-Auth-Token with my API key. But I still get errors and I don't know many other ways with Guzzle to set them.

I hope someone can help me out :)

Upvotes: 1

Views: 2936

Answers (1)

Alexey Shokov
Alexey Shokov

Reputation: 5010

Guzzle 6 uses a different approach to Guzzle 3, so you should use something like:

use function GuzzleHttp\Promise\all;

$header = ['headers' => ['X-Auth-Token' => 'MyKey']];
$client = new Client(['debug' => true]);
$responses = all([
    $client->getAsync('https://api.football-data.org/v2/teams/666', $header),
    $client->getAsync('https://api.football-data.org/v2/teams/1920', $header),
    $client->getAsync('https://api.football-data.org/v2/teams/6806', $header)
])->wait();
$data = [];
foreach ($responses as $i => $res) {
    $data[$i] = json_decode($res->getBody()->getContents(), true);
}
return $data;

Take a look at different questions on the same topic (#1, #2) to see more usage examples.

Upvotes: 2

Related Questions