> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://statpad.dev/docs/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://statpad.dev/docs/_mcp/server.

# Python SDK

> Install and use statpad, the Python client for the Statpad REST API. Covers the sync and async clients, the return shape, method groups, pagination, errors, retries, timeouts, conditional requests and versioning.

`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](https://github.com/statpad-dev/statpad-python). For TypeScript, use the [TypeScript SDK](/docs/sdk).

## Install

```bash
pip install statpad
```

The SDK needs Python 3.10 or newer. It sends requests with [httpx](https://www.python-httpx.org).

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:

```python
from statpad import Statpad

statpad = Statpad()
```

```python
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

| Option        | Default                                                      | What it does                                                                                                                          |
| ------------- | ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- |
| `api_key`     | `STATPAD_API_KEY`                                            | Your API key. The client sends it as `Authorization: Bearer <key>`. Without a key, the client raises `ValueError`.                    |
| `base_url`    | `https://api.statpad.dev`                                    | The API's address.                                                                                                                    |
| `timeout`     | 10 seconds to connect, 30 for each read, write and pool wait | How long httpx waits for each network operation: seconds for all of them, an `httpx.Timeout` for each one, or `None` to wait forever. |
| `max_retries` | `2`                                                          | How many times to retry a failed request.                                                                                             |
| `http_client` | A new `httpx.Client`                                         | The 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](/docs/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`](#rate-limits) read from it:

```python
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:

| 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`. 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:

```python
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`:

```python
from statpad.types import Game
```

They're `TypedDict`s 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`:

```python
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](/docs/pagination) 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`**

```python title="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)
```

```text
404 not_found No game 01a1d60f-0000-7000-8000-000000000000 in nfl.
```

Each code the REST API sends has its own class:

| `code`            | Status | Class                 |
| ----------------- | ------ | --------------------- |
| `bad_request`     | 400    | `BadRequestError`     |
| `unauthorized`    | 401    | `UnauthorizedError`   |
| `forbidden`       | 403    | `ForbiddenError`      |
| `not_found`       | 404    | `NotFoundError`       |
| `resync_required` | 410    | `ResyncRequiredError` |
| `rate_limited`    | 429    | `RateLimitedError`    |
| `quota_exhausted` | 429    | `QuotaExhaustedError` |
| `internal`        | 500    | `InternalError`       |
| `unavailable`     | 503    | `UnavailableError`    |

So you can catch only the one you handle:

```python
from statpad import NotFoundError

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

A `StatpadError` also has these fields:

| Field         | What it holds                                                    |
| ------------- | ---------------------------------------------------------------- |
| `status`      | The HTTP status.                                                 |
| `request_id`  | The request's id. Include it when you report a problem.          |
| `retry_after` | The seconds from the `Retry-After` header, when there is one.    |
| `resets_at`   | With `quota_exhausted`, when the next period's allowance starts. |
| `min_seq`     | With `resync_required`, the oldest seq the stream still holds.   |
| `body`        | The parsed problem body.                                         |
| `response`    | The 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](/docs/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:

```python
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`**

```python title="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:

```text
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:

```python
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](/docs/get-started/rate-limits) explains the allowance and the headers.

## The stream

The SDK has no stream client yet. Use any WebSocket library, such as [`websockets`](https://websockets.readthedocs.io), and the types in `statpad.types` for the messages' contents. The [Quickstart](/docs/quickstart#follow-it-live) builds a stream client, and [Live updates](/docs/streaming) 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:

```bash
pip install "statpad~=0.1.0"
```