Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save aleksandertabor/538d4a5986b5d8b3b430b1a168b80a71 to your computer and use it in GitHub Desktop.
Save aleksandertabor/538d4a5986b5d8b3b430b1a168b80a71 to your computer and use it in GitHub Desktop.
How to consume JSON APIs with pagination using async HTTP requests in Laravel?
<?php
$source = Http::get('https://rickandmortyapi.com/api/character');
$results = lazyJsonPages($source, 'results', static fn (Config $config): Config => $config
->items('info.count')
->perPage(20, 'page')
->concurrency(5)
);
$results->each(function ($result) {
dump($result);
});
// Asyncs vs sync HTTP requests (performance)
$asynchronousCalls = lazyJsonPages($source, 'results', static fn (Config $config): Config => $config
->items('info.count')
->perPage(20, 'page')
->concurrency(5)
);
$synchronousCalls = lazyJsonPages($source, 'results', static fn (Config $config): Config => $config
->items('info.count')
->perPage(20, 'page')
->sync()
);
Benchmark::dd([
'Async calls' => fn() => $asynchronousCalls->count(),
'Sync calls' => fn() => $synchronousCalls->count(),
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment