Data as a Service

Sport Data API

Who won every event

List the winner of every event in a sport with one paging loop. The same code works for smx, wsl, masl and hlr.

Goal: a table of every event and who won it, with readable names.

The calls

GET /v1/{sport}/event-results   → event_id, competitor_id, division, finish_position, status, …
GET /v1/{sport}/competitors     → competitor_id, competitor_name, competitor_type
GET /v1/{sport}/events          → event_id, event_name, start_date

All three are cursor-paged. Send limit (1 to 100) and pass each next_page_token back as page_token until it comes back null.

finish_position == 1 on event_results is the event winner in every sport. You do not need per-sport logic: supercross, surfing, arena soccer and sprint car racing all answer the same way. The program reads the three tables in full and joins them in memory.

The program

import os
import sys

import requests
import time

BASE_URL = "https://platform-api.altsportsleagues.ai"
HEADERS = {"Authorization": f"Bearer {os.environ['ASD_API_KEY']}"}
SPORT = sys.argv[1] if len(sys.argv) > 1 else "wsl"  # smx, wsl, masl or hlr


def all_rows(path: str, **params):
    token = None
    while True:
        res = requests.get(
            f"{BASE_URL}{path}",
            headers=HEADERS,
            params={**params, "limit": 100, **({"page_token": token} if token else {})},
            timeout=65,
        )
        if res.status_code == 429:  # keys allow 10 requests a minute: wait and retry
            time.sleep(int(res.headers.get("Retry-After", "15")))
            continue
        res.raise_for_status()
        body = res.json()
        yield from body["data"]
        token = body.get("next_page_token")
        if not token:
            return


names = {c["competitor_id"]: c for c in all_rows(f"/v1/{SPORT}/competitors")}
events = {e["event_id"]: e for e in all_rows(f"/v1/{SPORT}/events")}
winners = [r for r in all_rows(f"/v1/{SPORT}/event-results") if r["finish_position"] == 1]

winners.sort(key=lambda r: str(events.get(r["event_id"], {}).get("start_date") or ""))

for row in winners:
    event = events.get(row["event_id"], {})
    competitor = names.get(row["competitor_id"], {})
    who = competitor.get("competitor_name") or row["competitor_id"]
    kind = competitor.get("competitor_type", "?")  # "athlete" or "team"
    print(
        f"{event.get('start_date') or '----------'}  "
        f"{(event.get('event_name') or row['event_id'])[:40]:<40}  "
        f"[{row['division'] or '-'}]  {who} ({kind})"
    )
const BASE_URL = 'https://platform-api.altsportsleagues.ai';
const headers = { Authorization: `Bearer ${process.env.ASD_API_KEY}` };
const SPORT = process.argv[2] ?? 'wsl'; // smx, wsl, masl or hlr

type Competitor = {
  competitor_id: string;
  competitor_name: string | null;
  competitor_type: 'athlete' | 'team';
};
type Event = { event_id: string; event_name: string | null; start_date: string | null };
type EventResult = {
  event_id: string;
  competitor_id: string;
  division: string | null;
  finish_position: number | null;
};

async function collect<T>(path: string): Promise<T[]> {
  const rows: T[] = [];
  let token: string | null | undefined;
  do {
    const qs = new URLSearchParams({ limit: '100', ...(token ? { page_token: token } : {}) });
    const res = await fetch(`${BASE_URL}${path}?${qs}`, { headers });
    if (res.status === 429) {
      // keys allow 10 requests a minute: wait and retry the same page
      await new Promise((r) => setTimeout(r, 1000 * Number(res.headers.get('retry-after') ?? '15')));
      continue;
    }
    if (!res.ok) throw new Error(`${res.status} ${await res.text()}`);
    const body = (await res.json()) as { data: T[]; next_page_token?: string | null };
    rows.push(...body.data);
    token = body.next_page_token;
  } while (token);
  return rows;
}

// One walk at a time: the three walks share one rate limit, and together they take minutes.
const competitors = await collect<Competitor>(`/v1/${SPORT}/competitors`);
const events = await collect<Event>(`/v1/${SPORT}/events`);
const results = await collect<EventResult>(`/v1/${SPORT}/event-results`);

const names = new Map(competitors.map((c) => [c.competitor_id, c]));
const eventsById = new Map(events.map((e) => [e.event_id, e]));

const winners = results
  .filter((r) => r.finish_position === 1)
  .sort((a, b) =>
    (eventsById.get(a.event_id)?.start_date ?? '').localeCompare(
      eventsById.get(b.event_id)?.start_date ?? '',
    ),
  );

for (const row of winners) {
  const event = eventsById.get(row.event_id);
  const competitor = names.get(row.competitor_id);
  const who = competitor?.competitor_name ?? row.competitor_id;
  console.log(
    `${event?.start_date ?? '----------'}  ${(event?.event_name ?? row.event_id).slice(0, 40).padEnd(40)}` +
      `  [${row.division ?? '-'}]  ${who} (${competitor?.competitor_type ?? '?'})`,
  );
}

Run it for any sport: python winners.py masl, npx tsx winners.ts hlr.

Watch out

  • One event can have several winners. Winners are per division: a supercross round has a 450 and a 250 winner, and a surf event can run men's and women's divisions. Group by (event_id, division) if you want one line per race class.
  • MASL names are teams. For masl, every competitor has competitor_type: "team", so the winner is a club. Check competitor_type before you label a row as a person.
  • Names can be missing. Some HLR competitors have a null competitor_name. The program falls back to competitor_id.
  • HLR carries no points or score data. points and score arrive as null on every row, and meta.absent_columns names them. This recipe only reads finish_position, so it works unchanged.
  • Do not change filters mid-walk. A page_token is bound to the query that issued it. Reusing it with different filters returns 400 invalid_request.

On this page