In your case, I would first check, if the rest api exposes an endpoint, that makes it possible to send the data for all entries at once. In that case, you would need only a single call, or maybe a couple, if there is a limit on the amount of allowed entries to be attached.
If that is not the case, then there is no other way, then calling the rest endpoint 2000 times. You said it already. Your call is synchronous, which is inefficient, as it waits for each request to finish, before it starts the next.
To avoid that, use the async functions instead $client->postAsync
. This will make it possible, to run the requests concurrently. Each request returns a promise. Basically, you want to wait for all promises to resolve and continue with the program execution. For that, store all promises in an array and use Promise\settle($promises)->wait();
or Promise\unwrap($promises);
, if you want execution to stop, in case of an error.
The code could look like this:
<?php
use GuzzleHttp\Client;
use GuzzleHttp\Promise;
public function fetchBooks () {
$client = new Client();
$promises = [];
for ($i=1; $i < 2000; $i++) {
$promise = $client->postAsync('https://example.com/api/book?id=' . $i);
array_push($promises, $promise);
}
$results = Promise\settle($promises)->wait();
$responses = [];
foreach ($results as $result) {
array_push($responses, json_decode($result->getBody(), true));
}
return $responses;
}
?>