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
using System.Text.Json;
var http = new HttpClient();
http.DefaultRequestHeaders.Add("X-API-Key", Environment.GetEnvironmentVariable("AHR_KEY"));
var firstOfThis = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, 1);
var from = firstOfThis.AddMonths(-1).ToString("yyyy-MM-dd");
var to = firstOfThis.AddDays(-1).ToString("yyyy-MM-dd");
string Cell(JsonElement r, string a, string? b = null)
{
if (!r.TryGetProperty(a, out var v) || v.ValueKind == JsonValueKind.Null) return "";
if (b != null && !v.TryGetProperty(b, out v)) return "";
return "\"" + v.ToString().Replace("\"", "\"\"") + "\"";
}
var lines = new List<string> { "date,time,course,name,winner,sp,trainer" };
var cursor = "";
while (true)
{
var url = "https://api.apihorseracing.com/v1/races/search?region=GB&date_from=" + from + "&date_to=" + to
+ "&result_available=1&include=winner&limit=200&cursor=" + Uri.EscapeDataString(cursor);
var body = JsonDocument.Parse(await http.GetStringAsync(url)).RootElement;
foreach (var r in body.GetProperty("data").EnumerateArray())
lines.Add(string.Join(",", Cell(r, "date"), Cell(r, "time"), Cell(r, "course"), Cell(r, "name"),
Cell(r, "winner", "horse"), Cell(r, "winner", "sp"), Cell(r, "winner", "trainer")));
var meta = body.GetProperty("meta");
if (!meta.TryGetProperty("has_more", out var more) || !more.GetBoolean()) break;
cursor = meta.GetProperty("next_cursor").GetString() ?? "";
}
File.WriteAllLines("results.csv", lines);
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.