0

i'm working on a project where i need to perform 2000 asynchronous requests using Guzzle to an endpoint and each time i need to change the ID in the url.

the endpoint looks like this: https://jsonplaceholder.typicode.com/posts/X

I tried to use a for loop to do that the only issue is that it's not asynchronous. what's the more efficient way to do such task?

use GuzzleHttp\Client;
public function fetchPosts () {
    $client = new Client();
    $posts = [];
    for ($i=1; $i < 2000; $i++) { 
        $response = $client->post('https://jsonplaceholder.typicode.com/posts/' . $i);
        array_push($posts, $response->getBody());
    }
    return $posts;
}

1 Answers1

1

You can try this,

public function fetchBooks()
    {
        $results = [];
        $client = new \GuzzleHttp\Client([
            'base_uri' => 'https://jsonplaceholder.typicode.com'
        ]);
        $headers = [
            'Content-type' => 'application/json; charset=UTF-8'
        ];
        
        $requests = function () use ($client,$headers) {
            for ($i = 1; $i < 7; $i++) {
                yield function() use ($client, $headers,$i) {
                    return $client->postAsync('/posts',[
                        'headers' => $headers,
                        'json' => [
                            'title' => 'foonov2020',
                            'body' => 'barfoonov2020',
                            'userId' => $i,
                        ]
                    ]);
                };
            }
            
        };
    
        $pool = new \GuzzleHttp\Pool($client, $requests(),[
            'concurrency' => 5,
            'fulfilled' => function (Response $response, $index) use (&$results) {
                $results[] = json_decode($response->getBody(), true);
            },
            'rejected' => function (\GuzzleHttp\Exception\RequestException $reason, $index) {
                throw new \Exception(print_r($reason->getBody()));
            },
        ]);
    
        $pool->promise()->wait();
        return response()->json($results);
    }

It will give you output,

output image

bhucho
  • 3,903
  • 3
  • 16
  • 34