Dışsal API’lerle çalışırken, önceden oran kısıtlamalarını bilmek her zaman mümkün olmayabilir. Çoğu API, kısıtlamaları yayımlamaz veya bu kısıtlamaları aşana kadar başlık göndermez.
Bu nedenle, güvenilir bir yol, API yanıtının kendisinden boğulmayı (throttling) tespit etmektir.
Bu kısa örnek, Laravel’de bir API’nin isteklerinizi boğup boğmadığını nasıl kontrol edeceğinizi göstermektedir.
Temel Fikir
- Dışsal API’yi çağır
- Yanıt durumunu 429 (Too Many Requests) ile kontrol et
- Kısıtlamalara dair başlıkları oku (varsa)
- Boğulmayı (throttling) nazik bir şekilde yönet
use Illuminate\Support\Facades\Http;
public function checkApiThrottle()
{
$response = Http::withOptions([
'http_errors' => false, // prevent exceptions
])->get({API-ENDPOINT});
// API'nin boğulup boğulmadığını kontrol et
if ($response->status() === 429) {
return response()->json([
'throttled' => true,
'message' => 'API rate limit exceeded',
'retry_after' => $response->header('Retry-After'),
], 429);
}
// Kısıtlama başlıklarını oku (varsa)
$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(),
]);
}
İhtiyacınıza göre kontrol edebilirsiniz ($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 ""
.print_r($responseArray,true)."
}
Kaynak: Orijinal Makale


