Bulk and spreadsheets › A month of results into CSV
A month of results into CSV
Every settled race in Great Britain last month with its winner, page by page, into one CSV file you can open in any spreadsheet.
// A month of results into CSV: page by page with the cursor
package main
import (
"encoding/csv"
"encoding/json"
"fmt"
"net/http"
"net/url"
"os"
"time"
)
func main() {
now := time.Now().UTC()
firstOfThis := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC)
from := firstOfThis.AddDate(0, -1, 0).Format("2006-01-02")
to := firstOfThis.AddDate(0, 0, -1).Format("2006-01-02")
f, _ := os.Create("results.csv")
defer f.Close()
w := csv.NewWriter(f)
defer w.Flush()
w.Write([]string{"date", "time", "course", "name", "winner", "sp", "trainer"})
cursor := ""
for {
q := url.Values{"region": {"GB"}, "date_from": {from}, "date_to": {to}, "result_available": {"1"},
"include": {"winner"}, "limit": {"200"}, "cursor": {cursor}}
req, _ := http.NewRequest("GET", "https://api.apihorseracing.com/v1/races/search?"+q.Encode(), nil)
req.Header.Set("X-API-Key", os.Getenv("AHR_KEY"))
res, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
var body struct {
Data []map[string]any
Meta struct {
HasMore bool `json:"has_more"`
NextCursor string `json:"next_cursor"`
}
}
json.NewDecoder(res.Body).Decode(&body)
res.Body.Close()
for _, r := range body.Data {
win, _ := r["winner"].(map[string]any)
w.Write([]string{fmt.Sprint(r["date"]), fmt.Sprint(r["time"]), fmt.Sprint(r["course"]), fmt.Sprint(r["name"]),
fmt.Sprint(win["horse"]), fmt.Sprint(win["sp"]), fmt.Sprint(win["trainer"])})
}
if !body.Meta.HasMore {
break
}
cursor = body.Meta.NextCursor
}
}
What the reply holds
- data[]
- One row per race.
- winner
- The winner, its SP and trainer.
- meta.has_more
- Whether there is another page.
- meta.next_cursor
- Pass it as cursor for the next page.
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.