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
# needs: install.packages("httr2")
library(httr2)
end <- as.Date(format(Sys.Date(), "%Y-%m-01")) - 1
start <- as.Date(format(end, "%Y-%m-01"))
rows <- list(); cursor <- ""
repeat {
body <- request("https://api.apihorseracing.com/v1/races/search") |>
req_url_query(region = "GB", date_from = format(start), date_to = format(end), result_available = 1,
include = "winner", limit = 200, cursor = cursor) |>
req_headers(`X-API-Key` = Sys.getenv("AHR_KEY")) |> req_perform() |> resp_body_json()
for (r in body$data) rows[[length(rows) + 1]] <- data.frame(date = r$date, time = r$time, course = r$course, name = r$name,
winner = r$winner$horse %||% NA, sp = r$winner$sp %||% NA, trainer = r$winner$trainer %||% NA)
if (!isTRUE(body$meta$has_more)) break
cursor <- body$meta$next_cursor
}
write.csv(do.call(rbind, rows), "results.csv", row.names = FALSE)
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.