Data as a Service

Sport Data API

Load a season into pandas

Pull one season of events and results into typed DataFrames, join them, run an analysis, and save to parquet so you never walk the API twice.

Goal: a season of events and results as two pandas DataFrames with proper dtypes, joined and ready to analyse, with requests and pandas only.

If you have used yfinance or a similar library, the difference here is that there is no client package: you call a paged REST API, and the paging is yours to drive. The function below does that once, and the rest is ordinary pandas.

The calls

GET /v1/{sport}/seasons                               → season_id, …
GET /v1/{sport}/events?season_id=&sort=-start_date    → event_id, event_name, season_id, start_date, end_date, status, round, venue_name, city, state, country
GET /v1/{sport}/event-results?event_id=               → event_id, competitor_id, division, finish_position, points, score, status
GET /v1/{sport}/competitors                           → competitor_id, competitor_name, competitor_type

Every call takes Authorization: Bearer <key> with the key from the ASD_API_KEY environment variable. Every list is cursor-paged: send limit (1 to 100) and pass each next_page_token back as page_token until it comes back null.

Setup

pip install requests pandas pyarrow
export ASD_API_KEY=asd_live_…

pyarrow is what pandas uses to write and read parquet. The API code uses requests only.

One fetch function

fetch_all is a generator that walks a paged resource to the end. It waits on 429 (keys allow 10 requests a minute, shared across every endpoint) and uses a 65 second timeout because a cold warehouse query can take 20 seconds or more.

import os
import time
from typing import Iterator

import pandas as pd
import requests

BASE_URL = "https://platform-api.altsportsleagues.ai"
SESSION = requests.Session()
SESSION.headers["Authorization"] = f"Bearer {os.environ['ASD_API_KEY']}"


def fetch_all(path: str, **params) -> Iterator[dict]:
    """Yield every row of a paged resource, following next_page_token to the end."""
    token = None
    while True:
        query = {**params, "limit": 100}
        if token:
            query["page_token"] = token
        res = SESSION.get(f"{BASE_URL}{path}", params=query, timeout=65)
        if res.status_code == 429:
            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

Build the DataFrames

Pick a sport and a season, then build events, results and competitors with explicit dtypes. start_date becomes a datetime, finish_position becomes nullable Int64 (it can be missing), and points becomes float (it is null for sports with no points data, and NaN after the cast).

SPORT = "smx"  # smx, wsl, masl or hlr

seasons = pd.DataFrame(fetch_all(f"/v1/{SPORT}/seasons"))
SEASON_ID = seasons.iloc[0]["season_id"]  # or pick by season_year / season_name

EVENT_COLS = ["event_id", "event_name", "season_id", "start_date", "end_date",
              "status", "round", "venue_name", "city", "state", "country"]
RESULT_COLS = ["event_id", "competitor_id", "division", "finish_position",
               "points", "score", "status"]
COMPETITOR_COLS = ["competitor_id", "competitor_name", "competitor_type"]

events = (
    pd.DataFrame(fetch_all(f"/v1/{SPORT}/events", season_id=SEASON_ID, sort="-start_date"))
    .reindex(columns=EVENT_COLS)
    .astype({"event_id": "string", "event_name": "string", "season_id": "string",
             "status": "string", "venue_name": "string", "city": "string",
             "state": "string", "country": "string"})
)
events["start_date"] = pd.to_datetime(events["start_date"], errors="coerce")
events["end_date"] = pd.to_datetime(events["end_date"], errors="coerce")

# One request per event, paged. At 10 requests a minute this is the slow part.
results = (
    pd.DataFrame(
        row
        for event_id in events["event_id"]
        for row in fetch_all(f"/v1/{SPORT}/event-results", event_id=event_id)
    )
    .reindex(columns=RESULT_COLS)
    .astype({"event_id": "string", "competitor_id": "string", "division": "string",
             "status": "string"})
)
results["finish_position"] = pd.to_numeric(results["finish_position"]).astype("Int64")
results["points"] = pd.to_numeric(results["points"]).astype("float")
results["score"] = pd.to_numeric(results["score"], errors="coerce").astype("float")

competitors = (
    pd.DataFrame(fetch_all(f"/v1/{SPORT}/competitors"))
    .reindex(columns=COMPETITOR_COLS)
    .astype({"competitor_id": "string", "competitor_name": "string",
             "competitor_type": "string"})
)

print(events.dtypes, results.dtypes, competitors.dtypes, sep="\n\n")

How long this takes

Every key is limited to 10 requests a minute, shared across every endpoint. A season with 30 events costs at least 30 result requests plus the event, season and competitor pages, so expect several minutes. Walking a whole sport, every season, takes long enough that you should do it once and save the result (see below), not on every run.

Join

results joins to events on event_id and to competitors on competitor_id. Use left joins so a result whose competitor has no row (or a null name) is kept.

season = (
    results
    .merge(events[["event_id", "event_name", "start_date", "round", "venue_name"]],
           on="event_id", how="left")
    .merge(competitors, on="competitor_id", how="left")
    .sort_values(["start_date", "division", "finish_position"])
    .reset_index(drop=True)
)

season.head()

Example analysis: wins per competitor

finish_position == 1 on event-results is the event winner in every sport. Winners are per division, so a supercross round has a 450 and a 250 winner; group by division if you want them apart.

wins = (
    season[season["finish_position"] == 1]
    .groupby(["division", "competitor_id", "competitor_name"], dropna=False)
    .size()
    .rename("wins")
    .reset_index()
    .sort_values(["division", "wins"], ascending=[True, False])
)

print(wins.head(10))

# Points standings, where the sport has points. NaN means no points data, not zero.
standings = (
    season.groupby(["division", "competitor_id", "competitor_name"], dropna=False)["points"]
    .sum(min_count=1)
    .rename("points")
    .reset_index()
    .sort_values(["division", "points"], ascending=[True, False])
)

sum(min_count=1) keeps the total as NaN when every input is NaN, which is what you want for a sport such as High Limit Racing that carries no points at all. Without it pandas reports 0.0.

Watch out

  • points and score can be null. For a sport with no points data every row is null and the response lists the fields in meta.absent_columns. After the cast they are NaN. Do not read NaN as zero.
  • competitor_name can be null. Group with dropna=False as above, or fall back to competitor_id.
  • MASL competitors are teams. Check competitor_type before labelling a row as a person.
  • Do not change filters mid-walk. A page_token is bound to the query that issued it.

Save to parquet and reload

Save the three frames once. On later runs, load from disk and skip the API unless you need fresh data.

from pathlib import Path

out = Path(f"data/{SPORT}/{SEASON_ID}")
out.mkdir(parents=True, exist_ok=True)
events.to_parquet(out / "events.parquet", index=False)
results.to_parquet(out / "results.parquet", index=False)
competitors.to_parquet(out / "competitors.parquet", index=False)
events = pd.read_parquet(out / "events.parquet")
results = pd.read_parquet(out / "results.parquet")
competitors = pd.read_parquet(out / "competitors.parquet")

Parquet keeps the dtypes, including the nullable Int64 and the datetimes, so the reload needs no re-casting. When you want to know whether the warehouse has changed since you saved, check GET /v1/status/freshness and follow Status, finality and corrections.

On this page