Skip to navigation

Python SDK

Install statpad, call the REST API with typed responses, and handle errors, retries and timeouts.

statpad is the Python client for the Statpad REST API. It has a method for every endpoint and a type for every schema. The source and its README are at statpad-dev/statpad-python. For TypeScript, use the TypeScript SDK.

Install

pip install statpad

The SDK needs Python 3.10 or newer. It sends requests with httpx.

It has two clients with the same methods: Statpad, which is synchronous, and AsyncStatpad, whose methods are coroutines, for asyncio and Trio. Both read your key from STATPAD_API_KEY when you don’t pass one:

from statpad import Statpad
statpad = Statpad()
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())

Close a client to close its connections: Statpad with with Statpad() as statpad: or statpad.close(), and AsyncStatpad with async with AsyncStatpad() as statpad: or await statpad.close(). Neither closes an http_client you pass in.

Call Statpad from your server. The API doesn’t accept requests from browsers, and a key in a web page or an app is readable by anyone who has it.

Options

OptionDefaultWhat it does
api_keySTATPAD_API_KEYYour API key. The client sends it as Authorization: Bearer <key>. Without a key, the client raises ValueError.
base_urlhttps://api.statpad.devThe API’s address.
timeout10 seconds to connect, 30 for each read, write and pool waitHow long httpx waits for each network operation: seconds for all of them, an httpx.Timeout for each one, or None to wait forever.
max_retries2How many times to retry a failed request.
http_clientA new httpx.ClientThe client that sends the requests, for proxies, event hooks or tests. Pass an httpx.AsyncClient to AsyncStatpad.

Methods

Path parameters are positional, in the order the path names them. Query parameters are keyword-only, with the same names as in the API Reference, except from, a Python keyword, which is from_.

Each method returns an APIResponse. data is the parsed body, and response is the raw httpx.Response. status_code, headers, etag, not_modified and rate_limit read from it:

game = statpad.games.get_game("nfl", game_id)
print(game.status_code, game.data["game"]["status"])

The client groups its methods the same way as the API Reference:

AttributeMethods
leagueslist_leagues
gameslist_games, get_game, list_game_roster
play_by_playlist_plays, list_play_groups
statisticsget_box_score, list_player_stats, list_leaders
teamslist_teams, get_team, get_team_roster, get_depth_chart
playersget_player, list_player_stats
league_newslist_injuries, list_transactions
changeslist_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. Time parameters take a string or a datetime.datetime with a time zone. A datetime without one raises ValueError, because the client won’t guess its zone:

import datetime
now = datetime.datetime.now(datetime.timezone.utc)
games = statpad.games.list_games("nba", from_=now, to=now + datetime.timedelta(hours=24)).data

statpad.types has a type for every schema, such as Game, LiveState, Change and ErrorCode:

from statpad.types import Game

They’re TypedDicts and Literal aliases, so data holds the plain dicts and lists the JSON decodes to, and mypy or Pyright checks the keys you read. Timestamps stay RFC 3339 strings. An enum value the API adds later, such as a new play type, reaches you as a string instead of failing to parse.

For an endpoint this version has no method for yet, statpad.get(path, path_params=..., query=...) sends a GET with the client’s key, retries and errors.

Pagination

paginate takes a list method and its arguments. It requests each next page until next_cursor is None, and yields whole pages, so you keep each page’s teams, players and seq:

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"])

With AsyncStatpad, use paginate_async and async for.

list_game_changes pages by after_seq, so paginate doesn’t accept it: mypy and Pyright reject it, and at run time it raises TypeError. Lists, pagination and dates covers both kinds of paging.

Errors

An error response raises a StatpadError, or the subclass for its code. Branch on the class or the code, which are stable. title and detail are for people and can change:

errors.py
from statpad import Statpad, StatpadError
statpad = Statpad(timeout=10)
try:
statpad.games.get_game("nfl", "01a1d60f-0000-7000-8000-000000000000")
except StatpadError as err:
print(err.status, err.code, err.detail)
404 not_found No game 01a1d60f-0000-7000-8000-000000000000 in nfl.

Each code the REST API sends has its own class:

codeStatusClass
bad_request400BadRequestError
unauthorized401UnauthorizedError
forbidden403ForbiddenError
not_found404NotFoundError
resync_required410ResyncRequiredError
rate_limited429RateLimitedError
quota_exhausted429QuotaExhaustedError
internal500InternalError
unavailable503UnavailableError

So you can catch only the one you handle:

from statpad import NotFoundError
try:
statpad.games.get_game("nfl", game_id)
except NotFoundError:
print("No such game")

A StatpadError also has these fields:

FieldWhat it holds
statusThe HTTP status.
request_idThe request’s id. Include it when you report a problem.
retry_afterThe seconds from the Retry-After header, when there is one.
resets_atWith quota_exhausted, when the next period’s allowance starts.
min_seqWith resync_required, the oldest seq the stream still holds.
bodyThe parsed problem body.
responseThe raw httpx.Response.

A 2xx response whose body isn’t JSON also raises a StatpadError, with that status and no code. This happens when something other than the API answers, such as a captive portal.

A failure before there’s a response, such as a refused connection, a failed DNS lookup or a timeout, doesn’t raise a StatpadError. It raises the httpx exception after the retries run out. Each one subclasses httpx.TransportError, and timeouts subclass httpx.TimeoutException.

Errors lists every code.

Retries and timeouts

The client retries these failures:

  • 429, unless its code is quota_exhausted
  • 500 and 503, whatever the body says
  • Network errors and timeouts

It retries up to max_retries times, 2 by default, so a request makes at most 3 attempts. Between attempts, it waits the seconds in Retry-After. When there’s no Retry-After, or it isn’t a number of seconds, it backs off exponentially with random jitter. Set max_retries=0 to turn retries off.

It never retries quota_exhausted. The allowance comes back only when the period renews.

Every endpoint is a read, so a retry never repeats a write.

The client passes timeout to httpx, which applies it to each network operation rather than to the whole request: 10 seconds to connect, and 30 seconds for each read, each write and the wait for a connection from the pool. The read timeout covers the wait for each chunk of the response, so a response that keeps arriving slowly doesn’t time out. A number sets all four, and an httpx.Timeout sets each one. When an operation times out, the client retries the request like any network error. It sets no deadline for the whole call.

with_options returns a client with a different timeout or retry limit that shares the original’s connections, for the calls that need it:

statpad = Statpad(timeout=10, max_retries=3)
statpad.with_options(timeout=2, max_retries=0).games.get_game("nfl", game_id)

Conditional requests

Reads of a game, its plays, drives, roster and box score return an ETag. So do reads of teams, players, team rosters, depth charts and injuries. Pass it back as if_none_match, and the client sends it in If-None-Match. 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:

etag.py
import sys
from statpad import Statpad
statpad = Statpad()
game_id = sys.argv[1]
first = statpad.statistics.get_box_score("nfl", game_id)
following = statpad.statistics.get_box_score("nfl", game_id, if_none_match=first.etag)
print(following.status_code, following.not_modified)
box = following.data or first.data
print(len(box["players"]))

For a recorded NFL game whose box score hasn’t changed, it prints:

304 True
68

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 saves the transfer, but it still counts as one request against your allowance.

Rate limits

rate_limit reads the RateLimit-Policy and RateLimit headers into limit, window, remaining and reset. It’s 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")

A QuotaExhaustedError carries resets_at, when the next period’s allowance starts. Rate limits explains the allowance and the headers.

The stream

The SDK has no stream client yet. Use any WebSocket library, such as websockets, and the types in statpad.types for the messages’ contents. The Quickstart builds a stream client, and Live updates adds backoff, dead-connection checks and error handling.

Versioning

The SDK follows semantic versioning. Until 1.0, a minor release can include breaking changes, so pin the minor version:

pip install "statpad~=0.1.0"