Skip to content

About

Official Python SDK for TheRundown sports data API: real-time odds from 25+ sportsbooks, scores, schedules, player props and live WebSocket streams.

Topics

Resources

Contributing

Stars

2 stars

Watchers

0 watching

Forks

Repository files navigation

TheRundown Python SDK

PyPI version CI Python 3.9+ Typed License: MIT

The official Python SDK for TheRundown sports data API: real-time odds from 25+ sportsbooks, scores, schedules, player props, futures and live WebSocket streams.

  • Every REST endpoint of the API, V2 and legacy V1, with typed parameters and typed responses
  • A sync client and an async client with the same methods
  • Live WebSocket streams with typed messages, automatic reconnect and resubscribe
  • Retries with exponential backoff and jitter, timeouts, and typed errors
  • Usage and rate-limit headers on every response
  • Fully type annotated (py.typed), Python 3.9 and later

Full API documentation: docs.therundown.io

Install

pip install therundown

Quickstart

  1. Get an API key at therundown.io/api.
  2. Put it in the THERUNDOWN_API_KEY environment variable.
  3. Make your first call:
from datetime import date

from therundown import TheRundown

client = TheRundown()  # reads THERUNDOWN_API_KEY

# Today's NBA games with moneyline, spread and total main lines from two sportsbooks.
result = client.events.list(
    4, date.today(), market_ids=[1, 2, 3], affiliate_ids=[19, 23], main_line=True
)

for event in result.data.events or []:
    away = next((team.name for team in event.teams or [] if team.is_away), None)
    home = next((team.name for team in event.teams or [] if team.is_home), None)
    print(f"{away} at {home}, {event.event_date}")

    for market in event.markets or []:
        for participant in market.participants or []:
            for line in participant.lines or []:
                selection = " ".join(part for part in (participant.name, line.value) if part)
                for affiliate_id, price in (line.prices or {}).items():
                    print(f"  {market.name} | {selection} | book {affiliate_id}: {price.price}")

print(f"Data points used by this call: {result.response.datapoints}")

Sport IDs, sportsbook (affiliate) IDs and market IDs are listed in the reference tables, and the SDK can fetch them too: client.sports.list(), client.reference.affiliates() and client.markets.list().

Async

AsyncTheRundown has the same resources and methods. Every call is awaited:

import asyncio
from datetime import date

from therundown import AsyncTheRundown


async def main() -> None:
    async with AsyncTheRundown() as client:
        nba, nfl = await asyncio.gather(
            client.events.list(4, date.today(), market_ids=[1], main_line=True),
            client.events.list(2, date.today(), market_ids=[1], main_line=True),
        )
        print(len(nba.data.events or []), "NBA events,", len(nfl.data.events or []), "NFL events")


asyncio.run(main())

Authentication

The client reads the key from the api_key argument or, when that is left out, from the THERUNDOWN_API_KEY environment variable.

import os

from therundown import TheRundown

client = TheRundown(os.environ["MY_RUNDOWN_KEY"])
print(client.has_api_key)  # True or False; the key itself is never exposed
print(client)  # the key is not part of the repr

By default the key travels in the X-TheRundown-Key request header. The API also accepts it as a key query parameter, which you can select with auth="query":

from therundown import TheRundown

client = TheRundown(auth="query")
print(len(client.sports.list().data.sports or []), "sports")

Keep the key on your server. Do not ship it in client-side code, and do not commit it. The SDK never logs the key and removes it from error messages and URLs. A few endpoints, such as client.sports.list() and the client.public resource, need no key at all.

Responses

Every call returns an APIResult with two attributes. data is the typed response body, a pydantic model. response describes the HTTP response, including the usage figures the API sends in headers:

from datetime import date

from therundown import TheRundown

client = TheRundown()
result = client.events.list(4, date.today(), market_ids=[1], main_line=True)

print(len(result.data.events or []), "events")
print(result.response.status)  # 200
print(result.response.request_id)  # an id to quote to support
print(result.response.tier)  # your plan
print(result.response.datapoints)  # data points this call used
usage = result.response
print(
    usage.datapoints_remaining, "of", usage.datapoints_limit, "left this", usage.datapoints_period
)
print(result.response.rate_limit)  # requests per second for your key
print(result.response.headers["content-type"])  # every header is available

as_dict = result.data.model_dump(by_alias=True, exclude_unset=True)  # back to a plain dict
print(list(as_dict))

Response fields are optional in the types because the API leaves out fields that have no value. Fields the SDK does not know yet are kept on the model, so an API addition never breaks your code. Prices are numbers or strings: the odds_format parameter decides which.

Pagination

Endpoints that page have an ..._all method that returns an iterator and fetches pages as you go:

from therundown import TheRundown

client = TheRundown()

# Every NFL futures competition, fetched 25 at a time.
for competition in client.futures.list_all(2, limit=25):
    print(competition.event_id, competition.event_date, len(competition.markets or []), "markets")

With the async client, use async for. The plain method (client.futures.list) returns one page and its cursor if you would sooner page by hand.

Polling for changes

Load prices once, then ask only for what changed since. The first call hands you a cursor and each later call hands you the next one:

from datetime import date

from therundown import TheRundown

client = TheRundown()

# Load today's NBA moneylines, spreads and totals once, and keep the cursor that comes with them.
snapshot = client.events.list(4, date.today(), market_ids=[1, 2, 3])
meta = snapshot.data.meta
if meta is None or meta.delta_last_id is None:
    raise SystemExit("this response has no cursor")

# Later: what changed since the snapshot. This call takes market IDs as written, so 41, 42 and
# 43 add the live versions of the three markets.
changes = client.markets.delta(
    last_id=meta.delta_last_id,
    sport_id=4,
    market_ids=[1, 2, 3, 41, 42, 43],
    affiliate_visibility_token=meta.affiliate_visibility_token,
)
for change in (changes.data.deltas or [])[:10]:
    print(change.participant_name, change.line, change.previous_price, "->", change.price)

if changes.data.meta is not None:
    print("more waiting:", changes.data.meta.has_more)

For the next call pass the delta_last_id and the affiliate_visibility_token from changes.data.meta. While has_more is true, more rows are waiting. If reset_required is true, load a fresh snapshot and start from its cursor. Start polling from a snapshot only when snapshot.response.data_delay_seconds is 0. To have changes pushed to you instead, use the WebSocket streams.

Errors

Every error the SDK raises extends TheRundownError. An error status from the API raises an APIError subclass that carries the status, the API's message and code, the response headers and a request id:

Class When
BadRequestError 400: a parameter is invalid
AuthenticationError 401: the key is missing or not valid
PermissionDeniedError 403: the plan does not include the request
NotFoundError 404: no such resource
RateLimitError 429: a rate limit or data point limit was reached
ServerError 500 and above
APIConnectionError no response arrived (network, DNS, TLS)
APITimeoutError the request timed out
MissingAPIKeyError the call needs a key and the client has none
InvalidArgumentError an argument failed validation before any request
from therundown import APIError, AuthenticationError, RateLimitError, TheRundown

client = TheRundown()

try:
    client.events.get("not-a-real-event-id")
except AuthenticationError:
    print("Check the API key")
except RateLimitError as error:
    print(f"Limit reached ({error.limit_type}); retry after {error.retry_after} s")
except APIError as error:
    # An unknown event id answers 400 with a message that says so.
    print(error.status, error.message, error.request_id)

PermissionDeniedError also tells you what would unlock the request: feature, required_tier and upgrade_url.

Retries and timeouts

The client retries a failed call up to 2 times, with exponential backoff and jitter. It retries connection errors, timeouts, 408, 500, 502, 503, 504 and rate-limit 429 responses, and it honors Retry-After. It does not retry other 4xx responses or a 429 that reports a daily or monthly data point limit.

Each attempt times out after 30 seconds. Both settings can be changed for the client or for one call:

from therundown import RetryOptions, TheRundown

client = TheRundown(
    max_retries=4,
    timeout=10.0,
    retry=RetryOptions(initial_delay=0.25, max_delay=4.0),
)

# For one call:
result = client.sports.dates(4, max_retries=0, timeout=5.0)
print(result.response.retries)  # how many retries this response took

To share connection settings such as proxies, pass your own httpx.Client (or httpx.AsyncClient for the async client) as http_client.

WebSocket streams

Streams deliver price changes in real time, with sub-second odds updates. WebSocket access needs an Ultra plan or higher; see plans.

Open a stream in a with block and read it with for. The SDK keeps it connected: it watches for heartbeats, reconnects with backoff after a dropped connection and subscribes again. Leaving the with block closes the connection.

Markets stream

One message per price change, filtered by sport, event, market and sportsbook:

from therundown import TheRundown

client = TheRundown()

with client.stream.markets(sport_ids=[2, 4], market_ids=[1, 2, 3], main_line=True) as stream:
    count = 0
    for message in stream:
        if message.type == "market_price":
            update = message.data
            print(update.event_id, update.market_id, update.affiliate_id, update.line, update.price)
            count += 1
            if count == 10:
                break

Multiplexed stream

One connection that carries several subscriptions: markets, scores, plays, stats, live and futures. Ask for a snapshot to receive the current state first, then live updates:

from datetime import date

from therundown import TheRundown
from therundown.stream import EventsSnapshotFrame, MarketPriceDelta, ScoreDelta

client = TheRundown()

with client.stream.multiplexed() as stream:
    stream.subscribe("scores", sport_ids=[4], date=date.today(), snapshot=True)
    stream.subscribe("markets", sport_ids=[4], market_ids=[1, 2, 3], main_line=True)

    updates = 0
    for frame in stream:
        if isinstance(frame, EventsSnapshotFrame):
            print("snapshot:", len(frame.data.events or []), "events")
        elif isinstance(frame, ScoreDelta):
            score = frame.data.data
            print("score:", score.event_id, score.score_away, score.score_home, score.display_clock)
        elif isinstance(frame, MarketPriceDelta):
            update = frame.data.data
            print("price:", update.event_id, update.market_id, update.line, update.price)
            updates += 1
            if updates == 10:
                break

subscribe() returns when the server accepts the subscription and raises a StreamActionError when it refuses, for example because the plan allows no more subscriptions. The returned handle can unsubscribe(), ask for a fresh snapshot() or resync() after a gap.

Async streams

The async client has the same streams. Use async with and async for:

import asyncio

from therundown import AsyncTheRundown


async def main() -> None:
    async with AsyncTheRundown() as client:
        async with client.stream.markets(sport_ids=[4], market_ids=[1], main_line=True) as stream:
            count = 0
            async for message in stream:
                if message.type == "market_price":
                    print(message.data.event_id, message.data.affiliate_id, message.data.price)
                    count += 1
                    if count == 5:
                        break


asyncio.run(main())

Good to know:

  • Reconnects. After a reconnect the stream sends every subscription again. A plays subscription with event_ids resumes from the last play it delivered, so no play is lost. For prices, stream.last_delta_id is the position to pass to client.markets.delta() to fetch what you missed.
  • Gaps. Pass on_gap to learn when a subscription skipped updates, then call stream.resync(id).
  • When a stream ends. The loop raises when the stream cannot go on: AuthenticationError or PermissionDeniedError for a refused key or plan, RateLimitError when the plan's connection limit is reached, and StreamClosedError when the server says not to reconnect.
  • Slow consumers. Messages wait in a buffer while your loop is busy. If more than max_buffered_messages (65,536 by default) pile up, the loop raises a StreamBufferOverflowError.
  • Usage. Pass usage_frames=60 to receive a usage message with your data point totals every 60 seconds.
  • Closing. Use the with block: it closes the connection when the block ends, however it ends. A stream read without with stays open until you call stream.close().
  • Legacy V1. client.stream.v1() opens the V1 stream for existing integrations.

The WebSocket guide and the WebSocket reference describe the protocol, channels and per-plan limits.

More examples

Best available moneyline price for an upcoming game, across sportsbooks:

from datetime import date

from therundown import TheRundown

client = TheRundown()

schedule = client.events.list(
    4, date.today(), market_ids=[1], main_line=True, event_status="STATUS_SCHEDULED"
)
events = schedule.data.events or []
if events and events[0].event_id:
    best = client.odds.best_line_for_event(events[0].event_id, market_id=1).data
    if best.best:
        print("best:", best.best.price, "at", best.best.affiliate_name)
    for price in best.all or []:
        print(price.affiliate_name, price.price, price.updated_at)

Price history for an event:

from datetime import date

from therundown import TheRundown

client = TheRundown()

schedule = client.events.list(4, date.today(), market_ids=[1], main_line=True)
events = schedule.data.events or []
if events and events[0].event_id:
    history = client.markets.history(
        events[0].event_id, market_ids=[1], affiliate_ids=[19], limit=20
    ).data
    for change in history.history or []:
        print(change.updated_at, change.line, change.price)

Anything the SDK has no method for yet can go through client.request(), which applies the same auth, retries and errors:

from therundown import TheRundown

client = TheRundown()
result = client.request("GET", "/api/v2/sports", keyless=True)
print(len(result.data["sports"]), "sports")

Migrating from the earlier code in this repository

Before version 1.0.0 this repository held an unpublished rundown package. It was never on PyPI, and the rundown project there is unrelated. Version 1.0.0 replaces it with the therundown package described above. If you installed the old code from GitHub, it stays available at the legacy-rundown tag:

pip install "git+https://github.com/TheRundown/therundown-python@legacy-rundown"

Use Python 3.9 for the old code. On Python 3.12 its pinned PyYAML 5.4 fails to build.

To move to the new package, change the import and the calls:

Earlier code Version 1.0.0
from rundown import TheRundownClient from therundown import TheRundown
TheRundownClient(api_key, timeout=30.0) TheRundown(api_key, timeout=30.0)
client.list_sports_dates(sport_ids=[1, 2]) client.sports.dates_for_sports(sport_ids=[1, 2]).data
client.get_events(1, "2026-10-03", market_ids=[1], main_line=True) client.events.list(1, "2026-10-03", market_ids=[1], main_line=True).data
client.last_response result.response on the value each call returns
requests.HTTPError therundown.APIError and its subclasses
requests.Timeout, requests.ConnectionError therundown.APITimeoutError, therundown.APIConnectionError

What changes in behavior:

  • Calls return an APIResult. Its data is a typed model, not a dict. result.data.model_dump(by_alias=True, exclude_unset=True) gives the dict the earlier client returned.
  • Failed calls are retried up to 2 times by default. Pass max_retries=0 to turn that off.
  • The HTTP library is httpx, not requests.

The older V1 client in rundown.rundown (Rundown) maps to the client.v1 resources and their V2 successors:

Rundown method Version 1.0.0
sports() client.sports.list()
dates(sport) client.sports.dates(sport_id)
sportsbooks() client.reference.affiliates()
teams(sport) client.sports.teams(sport_id)
events(sport, date) client.events.list(sport_id, date), or client.v1.events.list(sport_id, date) for the V1 shape
opening_lines(sport, date) client.events.openers(sport_id, date) or client.v1.events.openers(sport_id, date)
closing_lines(sport, date) client.events.closing(sport_id, date) or client.v1.events.closing(sport_id, date)
events_delta(last_id) client.events.delta(last_id=...) or client.v1.events.delta(last_id=...)
event(event_id) client.events.get(event_id) or client.v1.events.get(event_id)
moneyline(line_id), spread(line_id), total(line_id) client.v1.lines.moneyline(line_id), client.v1.lines.spread(line_id), client.v1.lines.total(line_id)
schedule(sport) client.v1.sports.schedule(sport_id)

The V1 client's RapidAPI keys and its local YAML tables of sports and sportsbooks are gone: the client talks to https://therundown.io with a TheRundown API key, and client.sports.list() and client.reference.affiliates() return the current tables.

Requirements

  • Python 3.9 or later. The SDK is tested on Python 3.9 through 3.14.
  • Dependencies: httpx, pydantic 2, websockets, anyio and typing-extensions.

Links

Questions about the API or your account: support@therundown.io. Bugs in this SDK: open an issue.

License

MIT

About

Official Python SDK for TheRundown sports data API: real-time odds from 25+ sportsbooks, scores, schedules, player props and live WebSocket streams.

Topics

Resources

Contributing

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages