How to set timeouts when working with API in Laravel
When you’re working with third-party platform APIs that aren’t very stable, you can make use of some built-in methods on the HTTP client to do some error handling.
For example, if you’re making requests to some website API, but the server is slow or there’s an issue with connectivity, you can add a timeout
method and a retry
method to ensure that you’re still getting a response.
Timeout: If the request takes longer than 5 seconds (for example), it will abort. You can also add a message that gives your user more details on what’s happening.
Retry: If the first attempt is unsuccessful, retry the request. This is especially useful for requests where the user might be waiting for their response, like checking for notifications or messages.
Here is the code:
use Illuminate\Support\Facades\Http;
$response = Http::acceptJson()
->timeout(30)
->retry(10, 5000)
->get('https://api.platform.com/v1/account')
->throw();
With these options, Laravel will wait for 30 seconds after making a request. If it doesn’t receive one, it will wait for 5 seconds (5000 milliseconds), then try again, up to 10 times. If it doesn’t help, then Laravel will throw an exception.