Sport Data API
Competitor profile
Build a profile for one athlete or team, with every event finish and their latest Pressbox articles.
Goal: given a name, show that competitor's event-by-event record and the newest news about them.
The calls
GET /v1/{sport}/competitors → competitor_id, competitor_name, competitor_type
GET /v1/{sport}/event-results?competitor_id=… → event_id, division, finish_position, points, status
GET /v1/{sport}/events → event_id, event_name, start_date
GET /v1/pressbox/players?search=… (or /teams?search=…) → slug, name, type, articles_url (free)
GET /v1/pressbox/players/{slug}/articles?limit=5 → id, title, url, source_name, created_at, tags (1 credit)/competitors has no name filter, so the program pages through it and matches the name itself. Rosters
are small enough for this (the largest, WSL, is about 12,700 rows, or 128 pages at limit=100).
Pressbox is a separate news feed with its own slugs. There is no link between a warehouse competitor_id
and a Pressbox slug, so the program looks the slug up by name. Use /v1/pressbox/players for athletes and
/v1/pressbox/teams for teams.
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 "smx"
NAME = sys.argv[2] if len(sys.argv) > 2 else "Jett Lawrence"
def get(path: str, **params) -> dict:
while True:
res = requests.get(f"{BASE_URL}{path}", headers=HEADERS, params=params, 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()
return res.json()
def all_rows(path: str, **params):
token = None
while True:
body = get(path, **params, limit=100, **({"page_token": token} if token else {}))
yield from body["data"]
token = body.get("next_page_token")
if not token:
return
# 1. Find the competitor by name.
needle = NAME.casefold()
matches = [
c for c in all_rows(f"/v1/{SPORT}/competitors")
if needle in (c.get("competitor_name") or "").casefold()
]
if not matches:
sys.exit(f"No {SPORT} competitor matches {NAME!r}")
competitor = matches[0]
print(f"{competitor['competitor_name']} ({competitor['competitor_type']}, {competitor['competitor_id']})")
# 2. Their finish at every event, oldest first.
events = {e["event_id"]: e for e in all_rows(f"/v1/{SPORT}/events")}
finishes = list(all_rows(f"/v1/{SPORT}/event-results", competitor_id=competitor["competitor_id"]))
finishes.sort(key=lambda r: str(events.get(r["event_id"], {}).get("start_date") or ""))
wins = sum(1 for r in finishes if r["finish_position"] == 1)
print(f"{len(finishes)} event finishes, {wins} wins\n")
for r in finishes:
event = events.get(r["event_id"], {})
points = f" {r['points']} pts" if r.get("points") is not None else "" # null for hlr, sometimes elsewhere
print(f" {event.get('start_date') or '----------'} P{r['finish_position']} "
f"[{r['division'] or '-'}] {event.get('event_name') or r['event_id']}{points}")
# 3. News from Pressbox: look up the slug (free), then fetch articles (1 credit).
lookup = "teams" if competitor["competitor_type"] == "team" else "players"
tags = get(f"/v1/pressbox/{lookup}", search=competitor["competitor_name"], limit=5)["data"]
if tags:
slug = tags[0]["slug"]
articles = get(f"/v1/pressbox/{lookup}/{slug}/articles", limit=5)["data"]
print(f"\nLatest news for Pressbox tag '{slug}':")
for a in articles:
print(f" {a['created_at']} {a['title']} ({a['source_name']})\n {a['url']}")
else:
print("\nNo Pressbox tag found for this name.")const BASE_URL = 'https://platform-api.altsportsleagues.ai';
const headers = { Authorization: `Bearer ${process.env.ASD_API_KEY}` };
const SPORT = process.argv[2] ?? 'smx';
const NAME = process.argv[3] ?? 'Jett Lawrence';
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;
division: string | null;
finish_position: number | null;
points: number | string | null; // null for hlr (see meta.absent_columns), sometimes elsewhere
};
type PressboxTag = { slug: string; name: string | null; type: string | null; articles_url: string };
type Article = {
id: string;
title: string;
url: string;
source_name: string | null;
created_at: string | null;
};
async function get<T>(path: string, params: Record<string, string> = {}): Promise<T> {
for (;;) {
const res = await fetch(`${BASE_URL}${path}?${new URLSearchParams(params)}`, { headers });
if (res.status === 429) {
// keys allow 10 requests a minute: wait and retry
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()}`);
return res.json() as Promise<T>;
}
}
async function collect<T>(path: string, params: Record<string, string> = {}): Promise<T[]> {
const rows: T[] = [];
let token: string | null | undefined;
do {
const body = await get<{ data: T[]; next_page_token?: string | null }>(path, {
...params,
limit: '100',
...(token ? { page_token: token } : {}),
});
rows.push(...body.data);
token = body.next_page_token;
} while (token);
return rows;
}
// 1. Find the competitor by name.
const needle = NAME.toLowerCase();
const competitor = (await collect<Competitor>(`/v1/${SPORT}/competitors`)).find((c) =>
(c.competitor_name ?? '').toLowerCase().includes(needle),
);
if (!competitor) throw new Error(`No ${SPORT} competitor matches "${NAME}"`);
console.log(`${competitor.competitor_name} (${competitor.competitor_type}, ${competitor.competitor_id})`);
// 2. Their finish at every event, oldest first.
const events = await collect<Event>(`/v1/${SPORT}/events`);
const finishes = await collect<EventResult>(`/v1/${SPORT}/event-results`, { competitor_id: competitor.competitor_id });
const eventsById = new Map(events.map((e) => [e.event_id, e]));
const date = (r: EventResult) => eventsById.get(r.event_id)?.start_date ?? '';
finishes.sort((a, b) => date(a).localeCompare(date(b)));
const wins = finishes.filter((r) => r.finish_position === 1).length;
console.log(`${finishes.length} event finishes, ${wins} wins\n`);
for (const r of finishes) {
const event = eventsById.get(r.event_id);
const points = r.points != null ? ` ${r.points} pts` : '';
console.log(
` ${event?.start_date ?? '----------'} P${r.finish_position} [${r.division ?? '-'}] ` +
`${event?.event_name ?? r.event_id}${points}`,
);
}
// 3. News from Pressbox: look up the slug (free), then fetch articles (1 credit).
const lookup = competitor.competitor_type === 'team' ? 'teams' : 'players';
const { data: tags } = await get<{ data: PressboxTag[] }>(`/v1/pressbox/${lookup}`, {
search: competitor.competitor_name ?? NAME,
limit: '5',
});
if (tags.length > 0) {
const slug = tags[0].slug;
const { data: articles } = await get<{ data: Article[] }>(
`/v1/pressbox/${lookup}/${encodeURIComponent(slug)}/articles`,
{ limit: '5' },
);
console.log(`\nLatest news for Pressbox tag '${slug}':`);
for (const a of articles) console.log(` ${a.created_at} ${a.title} (${a.source_name})\n ${a.url}`);
} else {
console.log('\nNo Pressbox tag found for this name.');
}Watch out
- Pressbox is not enabled yet. Step 3 currently fails with
500 internal_error. Skip it, or wrap it in a try block, until Pressbox is live. /competitorsrejects asearchparameter. Spine routes return400 invalid_requestfor any parameter they do not accept, so match names in your own code as shown.- Name matching is fuzzy on both sides. A substring match can hit several competitors, and the
Pressbox lookup is a case-insensitive substring match on tag name and slug. Show the candidates to a
person, or check the Pressbox tag's
name, before you treat the first match as the right one. - Pressbox articles cost 1 credit per call. The
/playersand/teamslookups are free. - MASL competitors are teams. For
masl, use/v1/pressbox/teams. The program picks the route fromcompetitor_type. pointscan benull. HLR has no points data at all (meta.absent_columnslists it), and other sports can have null totals on some rows. Treatnullas unknown, never as zero.