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
import csv, datetime, json, os, urllib.parse, urllib.request
first_of_this = datetime.date.today().replace(day=1)
last_month_end = first_of_this - datetime.timedelta(days=1)
last_month_start = last_month_end.replace(day=1)
def page(cursor):
q = {"region": "GB", "date_from": last_month_start, "date_to": last_month_end,
"result_available": 1, "include": "winner", "limit": 200}
if cursor:
q["cursor"] = cursor
req = urllib.request.Request("https://api.apihorseracing.com/v1/races/search?" + urllib.parse.urlencode(q),
headers={"X-API-Key": os.environ["AHR_KEY"]})
with urllib.request.urlopen(req) as r:
return json.load(r)
with open("results.csv", "w", newline="") as f:
out = csv.writer(f)
out.writerow(["date", "time", "course", "name", "winner", "sp", "trainer"])
cursor = None
while True:
body = page(cursor)
for race in body["data"]:
w = race.get("winner") or {}
out.writerow([race["date"], race["time"], race["course"], race["name"], w.get("horse"), w.get("sp"), w.get("trainer")])
if not body["meta"].get("has_more"):
break
cursor = body["meta"]["next_cursor"]
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.