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.
// Rate limits and errors: wait out a 429, stop on the named error for anything else
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"strconv"
"time"
)
func get(url string, tries int) (any, error) {
for i := 0; i < tries; i++ {
req, _ := http.NewRequest("GET", url, nil)
req.Header.Set("X-API-Key", os.Getenv("AHR_KEY"))
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
if res.StatusCode == 429 {
wait, _ := strconv.Atoi(res.Header.Get("Retry-After"))
if wait == 0 {
wait = 5
}
res.Body.Close()
time.Sleep(time.Duration(wait) * time.Second)
continue
}
var body map[string]any
json.NewDecoder(res.Body).Decode(&body)
res.Body.Close()
// no_key, plan_needed (it names the plan), invalid_param (it names the parameter)
if res.StatusCode != 200 {
return nil, fmt.Errorf("%d %v", res.StatusCode, body["error"])
}
return body["data"], nil
}
return nil, fmt.Errorf("still rate limited after %d tries", tries)
}
func main() {
data, err := get("https://api.apihorseracing.com/v1/results/latest?limit=5", 5)
if err != nil {
panic(err)
}
out, _ := json.MarshalIndent(data, "", " ")
fmt.Println(string(out))
}
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.