How to use retry functionality of specific failed API call by use of PHP Magento 2?

You can use retry functionality to re-use your existing API call while you deal with some third-party API access.

If your request failed and you want to give more chances to connect with third-party API, you can use the retry functionality to wait up to a few seconds before throwing an error for an API call.

I have given a demo to call specific API up to three times based on the delay of 5 seconds, 10 seconds, and 15 seconds.

  • The first Time API call failed and the status response is not 200, We have to call it again by waiting 5 seconds.
  • If the Second time API failed and the status response code is not 200, we have to wait up to 10 seconds before executing again and the same as the third time wait up to 15 seconds to call API again.

If all three instances failed, We have to throw an exception and the API call will be not executed because of some error on the API server level.

Use the given code in your project based on your waiting time to call the same failed API again and again.

<?php declare(strict_types=1);

namespace Rbj\Blog\Model;

class RetryApiCall
{
    private const MAX_ERROR_RETRY = 3;

    public function callThirdPartyAPI()
    {
        $retries = 0;

        // Submit the API request and read response body
        try {
            do {
                try {
                    //CALL API BY CURL OR GUZZLE HTTP AND FETCH RESPONSE
                    $response = ['status' => 200, 'body' => []];
                    $statusCode = (int) $response['status'];
                    if ($statusCode === 200) {
                        
                        $shouldRetry = false;
                        //EXECUTE LOGIC AFTER SUCCESS
                    } else {
                        $shouldRetry = true;
                        // call API again upto max. no. of retries possible.
                        $this->waitOnRetry(++$retries, $statusCode);
                    }
                } catch (\Exception $e) {
                    throw $e;
                }
            } while ($shouldRetry);

        } catch (\Exception $exception) {
            throw $exception;
        }

        return $response;
    }

    /* Exponential sleep on failed request
     * Up to three retries will occur if the first request fails
     * After 5.0 seconds, 10 seconds, and finally 15.0 seconds
     * @param retries current retry
     * @throws Exception if the maximum number of retries has been reached,
     */
    private function waitOnRetry(int $retries, int $status)
    {
        if ($retries <= self::MAX_ERROR_RETRY) {
            $delay = 5 * $retries; //First-time 5-second delay, Second Time wait up to 10 seconds, and third time wait up to 15 sec.
            sleep($delay);
        } else {
            throw new \Exception('A Maximum number of retry attempts - '. $retries .' reached.');
        }
    }
}

This is the way you can use retry options in PHP-related projects.