Reliability › Rate limits and errors
Rate limits and errors
Every call can say no. This waits out a rate limit and tries again, and reads the named error for everything else: no key, a plan that does not reach it, a bad parameter.
<?php
// Rate limits and errors: wait out a 429, throw the named error for anything else
function get(string $url, int $tries = 5): array
{
$ctx = stream_context_create(["http" => ["header" => "X-API-Key: " . getenv("AHR_KEY"), "ignore_errors" => true]]);
for ($i = 0; $i < $tries; $i++) {
$raw = file_get_contents($url, false, $ctx);
$status = (int)explode(" ", $http_response_header[0])[1];
if ($status === 429) {
$wait = 5;
foreach ($http_response_header as $h) {
if (stripos($h, "Retry-After:") === 0) {
$wait = (int)trim(substr($h, 12));
}
}
sleep($wait);
continue;
}
$body = json_decode($raw, true);
// no_key, plan_needed (it names the plan), invalid_param (it names the parameter)
if ($status !== 200) {
throw new RuntimeException($status . " " . $body["error"]["code"] . ": " . $body["error"]["message"]);
}
return $body["data"];
}
throw new RuntimeException("still rate limited after $tries tries");
}
print_r(get("https://api.apihorseracing.com/v1/results/latest?limit=5"));
What the reply holds
- 401 no_key
- The key is missing or mistyped.
- 403 plan_needed
- Your plan does not reach this; the error names the plan that does.
- 422 invalid_param
- A parameter is wrong; the error says which.
- 429 rate_limited
- Too fast: wait the seconds in Retry-After.
When it says no
401no_key The key is missing or mistyped. Every sample reads it from AHR_KEY.403plan_needed Your plan does not reach this. The reply names the plan that does.429rate_limited Too fast. Wait the seconds in Retry-After, then try again.