Is there a built-in way to retry failed requests in Guzzle?

Yes, Guzzle, a PHP HTTP client, provides a built-in way to retry failed requests using middleware. Middleware in Guzzle allows you to modify the request and response objects before and after the HTTP request is executed. To implement retry logic, you can use the retry middleware provided by Guzzle.

Here is an example of how you can add retry logic to your Guzzle client:

require 'vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Exception\RequestException;

// Create a handler stack
$stack = HandlerStack::create();

// Define the retry middleware
$retryMiddleware = Middleware::retry(
    function ($retries, $request, $response, $exception) {
        // Limit the number of retries to 5
        if ($retries >= 5) {
            return false;
        }

        // Retry on server errors (5xx HTTP status codes)
        if ($response && $response->getStatusCode() >= 500) {
            return true;
        }

        // Retry on connection exceptions
        if ($exception instanceof RequestException && $exception->getCode() === 0) {
            return true;
        }

        return false;
    },
    function ($retries) {
        // Define a delay function (e.g., exponential backoff)
        return (int) pow(2, $retries) * 1000; // Delay in milliseconds
    }
);

// Add the retry middleware to the handler stack
$stack->push($retryMiddleware);

// Create a new client with the handler stack
$client = new Client(['handler' => $stack]);

// Send a request
$response = $client->request('GET', 'http://example.com');

// Output the response body
echo $response->getBody();

In the $retryMiddleware definition, the first callable decides whether the request should be retried, and the second callable defines the delay between retries. In the example above, the retry logic is as follows:

  • Retry up to 5 times.
  • Retry on server errors (HTTP 5xx status codes).
  • Retry on connection exceptions (e.g., network issues).
  • Use exponential backoff as the delay strategy, with a base delay of 1 second that doubles with each retry.

Remember to replace 'http://example.com' with the URL you want to request. Also, note that you can customize the retry conditions and backoff strategy according to your specific requirements.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon