Last active
January 28, 2023 14:00
-
-
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?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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