statpad

The Python client for Statpad, a live sports data API. It covers schedules, live game state, play-by-play, box scores, rosters, injuries, transactions and season leaders.
Install
pip install statpad
The package needs Python 3.10 or later. It sends requests with httpx and has a synchronous client, Statpad, and an asynchronous one, AsyncStatpad, for asyncio and Trio.
Call Statpad from your server. The API doesn't allow requests from browsers, and a key shipped in a web page or mobile app is readable by anyone who opens it.
Quickstart
Create an API key on the Keys page of your Statpad account and put it in your environment as STATPAD_API_KEY. This script prints the NBA games that start in the next 24 hours:
import datetime
from statpad import Statpad
statpad = Statpad() # reads STATPAD_API_KEY
now = datetime.datetime.now(datetime.timezone.utc)
page = statpad.games.list_games("nba", from_=now, to=now + datetime.timedelta(hours=24)).data
teams = {team["id"]: team for team in page["teams"]}
for game in page["data"]:
away, home = teams[game["away_team_id"]], teams[game["home_team_id"]]
print(
f"{away['market']} {away['name']} at {home['market']} {home['name']}, {game['scheduled_at']}"
)
A list response includes the teams or players its items refer to, so one request has everything you need to print the page.
The asynchronous client has the same methods, as coroutines:
import asyncio
from statpad import AsyncStatpad
async def main() -> None:
async with AsyncStatpad() as statpad:
leagues = (await statpad.leagues.list_leagues()).data
print([league["alias"] for league in leagues["data"]])
asyncio.run(main())
What the client covers
Each method returns an APIResponse. Its data is the parsed body and its response is the raw httpx.Response; status_code, headers, etag, not_modified and rate_limit read from it. Path parameters are positional, in the order the path names them, and query parameters are keyword-only, with the names in the API reference. The one exception is from, a Python keyword, which is from_.
| Attribute |
Methods |
leagues |
list_leagues |
games |
list_games, get_game, list_game_roster |
play_by_play |
list_plays, list_play_groups |
statistics |
get_box_score, list_player_stats, list_leaders |
teams |
list_teams, get_team, get_team_roster, get_depth_chart |
players |
get_player, list_player_stats |
league_news |
list_injuries, list_transactions |
changes |
list_game_changes, list_changed_entities |
list_player_stats is in two groups. Both call the same endpoint.
Date parameters take a string or a datetime.date, and time parameters take a string or a datetime.datetime with a time zone. The client raises ValueError for a naive datetime rather than guess its zone.
statpad.types has a type for every schema in the API, such as Game, LiveState, Change and ErrorCode:
from statpad.types import Game
They are TypedDicts and Literal aliases, so data is the plain dicts and lists the JSON decodes to, with no copying or validation, and mypy or Pyright checks the keys you read. Timestamps stay ISO 8601 strings. A value the API adds to an enum later, such as a new play type, reaches you as the string it is instead of failing to parse.
Pagination
List methods return one page at a time. paginate requests each next page until the list runs out:
from statpad import paginate
for page in paginate(statpad.play_by_play.list_plays, "nfl", game_id):
for play in page["data"]:
print(play["description"])
It passes your arguments through and adds each page's next_cursor as cursor. It yields whole pages instead of single items, because each page also carries the teams or players its items refer to. It accepts only methods that page by cursor, so mypy and Pyright reject list_game_changes, which pages by sequence number, and at run time it raises TypeError. With AsyncStatpad, use paginate_async and async for.
Errors
A request that gets an error response from the API raises a StatpadError, or the subclass for its code. Branch on the class or the code, which stay stable. The title and detail fields are for people and can change.
A 2xx response whose body isn't JSON also raises a StatpadError, with that 2xx status and no code. This happens when something other than the API answers, such as a captive portal or a proxy's sign-in page.
A failure before there is a response, such as a refused connection, a failed DNS lookup or a timeout, raises the httpx exception once the retries run out. They all subclass httpx.TransportError, and timeouts subclass httpx.TimeoutException.
from statpad import NotFoundError
try:
statpad.games.get_game("nfl", game_id)
except NotFoundError:
print("No such game")
These are the codes most applications handle:
code |
Status |
Class |
What to do |
unauthorized |
401 |
UnauthorizedError |
The key is missing, unknown or revoked. Check it on the Keys page. |
forbidden |
403 |
ForbiddenError |
The key works, but your plan doesn't include this league or feature. An unknown league alias also returns forbidden. |
not_found |
404 |
NotFoundError |
The game, team or player doesn't exist in that league. |
resync_required |
410 |
ResyncRequiredError |
The changes feed no longer holds the position you asked for. Read the game again, as shown in Following a live game. |
rate_limited |
429 |
RateLimitedError |
You sent requests faster than your plan allows. The client retries these and raises only when its retries run out. |
quota_exhausted |
429 |
QuotaExhaustedError |
Your account used this billing period's request allowance. resets_at says when the next period starts. |
bad_request (BadRequestError), internal (InternalError) and unavailable (UnavailableError) have classes too. The errors page lists every code. Each error also has status, type, retry_after, min_seq, the parsed body and the raw response. Include request_id when you report a problem to Statpad.
Retries and timeouts
The client retries 500 and 503 responses whatever their body, 429 responses unless the code is quota_exhausted, and network errors and timeouts, up to two times. It waits the number of seconds in the Retry-After header when that is a usable number, and otherwise backs off exponentially with random jitter. It never retries quota_exhausted, because the allowance comes back only when the billing period renews. Every Statpad endpoint is a read, so a retry never repeats a write.
The timeouts are httpx's, applied per operation: 10 seconds to connect, and 30 seconds for each read, write and wait for a pooled connection. They aren't a deadline for the whole call, because the read timeout restarts with each chunk of the response and a timed-out attempt is retried. Pass max_retries to change the retry limit, or 0 to turn retries off, and timeout to change the timeouts: seconds for all four, an httpx.Timeout, or None to wait forever. with_options changes either for some calls, sharing the client's connections:
statpad = Statpad(timeout=10, max_retries=3)
statpad.with_options(timeout=2, max_retries=0).games.get_game("nfl", game_id)
Following a live game
Every change to a game has a sequence number, seq. A game read returns the seq it reflects, and changes.list_game_changes returns the changes after a given seq, oldest first. Read the game once, then poll for changes:
import time
from statpad import ResyncRequiredError
seq = statpad.games.get_game("nfl", game_id).data["seq"]
while True:
try:
page = statpad.changes.list_game_changes("nfl", game_id, after_seq=seq).data
for change in page["data"]:
apply_change(change)
seq = change["seq"]
if seq < page["head_seq"]:
continue
except ResyncRequiredError:
seq = statpad.games.get_game("nfl", game_id).data["seq"]
time.sleep(5)
apply_change stands for your own code. Each change carries the entity's full current state, so applying the same change twice is harmless. When seq is behind head_seq, the loop requests the next page without waiting. If you need changes as they happen instead of every few seconds, use the WebSocket stream described in the docs. This package doesn't include a stream client yet.
Conditional requests
Reads of a game, its plays, roster and box score, and of teams, players and injuries return an ETag header. Pass it back as if_none_match, and if nothing changed the API answers 304 with no body. The client doesn't raise on a 304. It returns data as None and not_modified as True:
first = statpad.statistics.get_box_score("nfl", game_id)
following = statpad.statistics.get_box_score("nfl", game_id, if_none_match=first.etag)
box_score = following.data or first.data
When you pass if_none_match, the method's return type makes data optional, so mypy and Pyright remind you to handle the 304. A 304 counts against your allowance like any other successful request, but it saves the transfer.
Rate limits
rate_limit reads the RateLimit-Policy and RateLimit headers. It is None when the response has neither:
usage = statpad.leagues.list_leagues().rate_limit
if usage:
print(f"{usage.remaining} of {usage.limit} requests left, resetting in {usage.reset} seconds")
See Rate limits for how the allowance works.
Configuration
| Option |
Default |
Description |
api_key |
STATPAD_API_KEY |
Your Statpad API key. The client sends it as Authorization: Bearer <key>. It raises ValueError when there is none. |
base_url |
https://api.statpad.dev |
The API's address. |
timeout |
30 seconds, 10 to connect |
httpx's connect, read, write and pool timeouts. |
max_retries |
2 |
How many times to retry a failed request. |
http_client |
A new httpx.Client |
The client to send requests through, for proxies, event hooks or tests. Pass an httpx.AsyncClient to AsyncStatpad. |
Use with Statpad() or call close(), or async with AsyncStatpad() or await close(), to close the client's connections. It doesn't close an http_client you pass.
statpad.get(path, path_params=..., query=...) sends a GET to any API path with the client's key, retries and errors, for an endpoint this version doesn't have a method for yet.
Versioning
The package follows semantic versioning. Until 1.0, a minor release can include breaking changes, so pin a minor version, such as statpad~=0.1.0.
Support
Report bugs in GitHub issues. For questions about the API, your account or your data, see the Statpad docs. To change the package itself, read CONTRIBUTING.md.
License
MIT