Skip to main content

statpad

CI License: MIT

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

Metadata

Release files for statpad 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for statpad 0.1.0
File Size Uploaded Provenance Actions
statpad-0.1.0.tar.gz 224.2 kB With provenance Details for statpad-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for statpad 0.1.0
File Interpreter ABI Platform Actions
statpad-0.1.0-py3-none-any.whl Python 3 none any Details for statpad-0.1.0-py3-none-any.whl

Total release size: 255.8 kB

Release files / statpad-0.1.0.tar.gz

Download URL statpad-0.1.0.tar.gz
Size 224.2 kB
Tags Source
SHA-256 checksum
How to use checksums
1fc993cbba80b4c4f1a623d379fa1c164a8627b27c823a955c2e25e2395bde04
BLAKE2b-256 checksum
How to use checksums
50018dd71bc8a091f4eb1e3f30661b5661b654edac73e1abe79d2b0f5b717300
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.

Transparency log

Release files / statpad-0.1.0-py3-none-any.whl

Download URL statpad-0.1.0-py3-none-any.whl
Size 31.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
8682f04cf4e421fd837e0a215b36d90fca8d460d8cc3b9965c4f8d4f9f4b9b52
BLAKE2b-256 checksum
How to use checksums
7ca7d38783d72679535d7f07e55d5a11164f06116c9d24ca4a25e102bbf84b49
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.

Transparency log

Security for statpad 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for statpad-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page