mtthias
mtthias

Reputation: 177

How can I make non blocking API requests in Laravel

I created a simple API in Laravel where a user can uplaod an image via POST.

In my Controller I save the Image and then I want to send it to an external API to get it classified.

This API call takes a few seconds and I dont want my Laravel App to be blocked in the meantime.

Can I run it asynchronous somehow? Is there an equivalent to node's promises in PHP?

Edit: I have read of Queues, but wouldn't the worker process be blocked as well while waiting for the external API to answer?

Upvotes: 1

Views: 3247

Answers (2)

Skid Kadda
Skid Kadda

Reputation: 482

You could consider using Guzzle's Promises and sent requests in paralel.

The library is located here: https://github.com/guzzle/promises.

Guzzle client wraps the promises with magic methods like...

$promise = $client->getAsync('http://httpbin.org/get');
$promise = $client->deleteAsync('http://httpbin.org/delete');
$promise = $client->headAsync('http://httpbin.org/get');
$promise = $client->optionsAsync('http://httpbin.org/get');
$promise = $client->patchAsync('http://httpbin.org/patch');
$promise = $client->postAsync('http://httpbin.org/post');
$promise = $client->putAsync('http://httpbin.org/put');

... the documentation for this can be found here:

Guzzle Async Requests: http://docs.guzzlephp.org/en/stable/quickstart.html#async-requests

It has a few concepts, like wait, then, queue and resolve. Those help you make asynchronous requests while being in full control on what to resolve synchronous.

With this it would also be possible to retrieve aggregated results, meaning, for example, that you could query your users-api and your projects-api and wait for some of the results to come back so that you can create one single json response containing the combined data from two sources.

This makes it very neat for projects that implement API-gateway.

Upvotes: 0

Angad Dubey
Angad Dubey

Reputation: 5452

You can use Laravel Queues to defer the time consuming part (like api calls) to background jobs.

Queues allow you to defer the processing of a time consuming task, such as sending an email, until a later time. Deferring these time consuming tasks drastically speeds up web requests to your application.

Upvotes: 1

Related Questions