Async HTTP Client Requests Are Coming In Laravel 8.x

Do you know guys that Asynchronous HTTP client requests are coming in Laravel 8.x. Look in March 2020, when Laravel 7 was released, a brand new HTTP client was introduced by Laravel which was essentially a wrapper of Guzzle HTTP client.

You already seen that this made the developer experience a lot smoother and easier. For example, a typical POST request using the HTTP client would look like this

$response = Http::post('http://test.com/users', [
    'name' => 'Mahedi Hasan',
    'role' => 'Software Engineer',
]);

 

Concurrent Asynchronous Requests

As I mentioned above, this PR by Andrea Marco Sartori is bringing concurrency while sending asynchronous client requests with the Laravel HTTP client by using Guzzle/Promises under-the-hood. This PR will be included in the next release of Laravel 8.x.

There are essentially two ways you can make asynchronous requests using this.

  • Asynchronous requests using async()
  • A pool to handle multiple asynchronous requests concurrently

 

Asynchronous client requests using async()

If you want to create an asynchronous request, you can create it like so.

$promise = Http::async()->get($url);

 

For making an asynchronous client request you need to chain the async() method on the Http client before making the request. But instead of returning a response, it will return a promise which you can resolve/reject like this

$promise = Http::async()->get($url)->then(
    fn (Response|TransferException $result) => $this->handleResult($result)
);

 

And this is how we can get the response of an asynchronous request.

The pool for multiple async requests

If you would like to make multiple async requests at the same time, you can use the pool like so.

use Illuminate\Http\Client\Pool;

// the waiting time will be ~6 seconds instead of 12
$responses = Http::pool(fn (Pool $pool) => [
    $pool->get('https://httpbin.org/delay/6')->then(/* ... */),
    $pool->get('https://httpbin.org/delay/3')->then(/* ... */),
    $pool->get('https://httpbin.org/delay/3')->then(/* ... */),
]);

$responses[0]->ok();
$responses[1]->successful();

 

Read also: Laravel Sanctum Authentication Example with Product Api

 

Hope it can help you.

 

#laravel #http-client #async-laravel