DEV Community

Ankit Verma
Ankit Verma

Posted on

How to Check External API Throttle Limit in Laravel

When working with external APIs, you don’t always know their rate limits in advance. Most APIs don’t publish limits or send headers until you exceed them.
So the only reliable way is to detect throttling from the API response itself.

This short example shows how to check if an API is throttling your requests in Laravel.

The Idea

  1. Call the external API
  2. Check if the response status is 429 (Too Many Requests)
  3. Read rate-limit headers (if provided)
  4. Handle throttling gracefully
use Illuminate\Support\Facades\Http;

public function checkApiThrottle()
{
    $response = Http::withOptions([
        'http_errors' => false, // prevent exceptions
    ])->get({API-ENDPOINT});

    // Check if API is throttling
    if ($response->status() === 429) {
        return response()->json([
            'throttled' => true,
            'message' => 'API rate limit exceeded',
            'retry_after' => $response->header('Retry-After'),
        ], 429);
    }

    // Read rate-limit headers (if available)
    $rateLimit = [
        'limit'     => $response->header('X-RateLimit-Limit'),
        'remaining' => $response->header('X-RateLimit-Remaining'),
        'reset'     => $response->header('X-RateLimit-Reset'),
    ];

    return response()->json([
        'throttled' => false,
        'rate_limit_headers' => $rateLimit,
        'data' => $response->json(),
    ]);
}

Enter fullscreen mode Exit fullscreen mode

Or you can check as your requirement ($maxCall)

public function checkApiThrottle()
{
    $statusCode = '';
    $count = 0;
    $responseArray = [];
    $maxCall = 10;

    while ($count < $maxCall) {
        $response = Http::get({API-ENDPOINT});

        $statusCode = $response->status();
        $count++;

        $responseArray[] = [
            'statusCode' => $statusCode,
            'count' => $count
        ];

        if ($statusCode !== 200) {
            break;
        }
    }

    echo "<pre>".print_r($responseArray,true)."</pre>";
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)