Skip to main content

Python client for ESPN's public API

Project description

espn-sports-api

PyPI CI Python License Open In Colab Deepnote

Python client for ESPN's public API. No authentication required for most endpoints.

Installation

uv add espn-sports-api

or with pip:

pip install espn-sports-api

Quick Start

from espn_sports_api import NFL, NBA, Soccer, SeasonType, quick_scores

# One-liner for today's scores
scores = quick_scores("nba")

# Get today's NFL scores
nfl = NFL()
scores = nfl.today()

# Get NBA team roster
nba = NBA()
roster = nba.team_roster("lal")

# Get Premier League table
epl = Soccer(league="epl")
table = epl.standings()

Supported Sports

Sport Class Leagues
Football NFL, NCAAF, CFL, XFL NFL, College Football, CFL, XFL
Basketball NBA, NCAAB, WomensNCAAB, WNBA NBA, College Basketball, WNBA
Baseball MLB, CollegeBaseball MLB, College Baseball
Hockey NHL NHL
Soccer Soccer 90+ leagues worldwide
MMA UFC UFC
Golf Golf PGA, LPGA, European Tour
Racing Racing F1, NASCAR, IndyCar
Tennis Tennis ATP, WTA

Common Methods

All sport classes share these methods:

# Scoreboard with filtering
sport.scoreboard(dates="20240115")       # By date
sport.scoreboard(season=2024, week=10)   # By season/week
sport.scoreboard(seasontype=SeasonType.POSTSEASON)  # or raw int: 1=pre, 2=reg, 3=post

# Teams
sport.teams()                  # All teams
sport.team("NYY")              # Team details
sport.team_roster("NYY")       # Team roster
sport.team_schedule("NYY")     # Team schedule
sport.team_injuries("NYY")     # Team injuries

# League-wide data
sport.injuries()               # All injuries
sport.transactions()           # Trades, signings, IR moves
sport.statistics()             # League statistics
sport.leaders()                # Statistical leaders
sport.venues()                 # Stadium information
sport.franchises()             # Franchise data
sport.events()                 # All games
sport.positions()              # All positions

# Other
sport.standings()              # Standings
sport.news()                   # News articles
sport.event("401547417")       # Game details
sport.playbyplay("401547417")  # Play-by-play data
sport.athlete("12345")         # Athlete profile
sport.athlete_stats("12345")   # Athlete statistics
sport.seasons(2024)            # Season information

# Date convenience methods
sport.today()                  # Today's games
sport.yesterday()              # Yesterday's games
sport.tomorrow()               # Tomorrow's games
sport.live()                   # In-progress games only
sport.on_date(date(2024,12,25)) # Games on specific date
sport.date_range(start, end)   # Games in date range
sport.for_week(10, season=2024) # Games for specific week

College Conference Filtering

Filter college sports by conference:

from espn_sports_api import NCAAF, NCAAB, NCAAFConference, Conferences

# By string name
ncaaf = NCAAF()
sec_games = ncaaf.scoreboard(conference="SEC")
big_ten = ncaaf.scoreboard(conference="Big Ten")

# By enum (type-safe)
ncaab = NCAAB()
games = ncaab.scoreboard(conference=NCAABConference.BIG_EAST)

# Lookup conference IDs
Conferences.get("ncaaf", "SEC")          # Returns 8
Conferences.get("ncaab", "Big Ten")      # Returns 7
Conferences.list_all("ncaaf")            # All NCAAF conferences

Betting Odds

Extract odds from scoreboard responses:

from espn_sports_api import NFL, Odds

nfl = NFL()
scoreboard = nfl.scoreboard()

# Get all odds
all_odds = Odds.from_scoreboard(scoreboard)
for game in all_odds:
    print(f"{game.away_team} @ {game.home_team}")
    if game.spread:
        print(f"  Spread: {game.spread.favorite} {game.spread.spread}")
    if game.moneyline:
        print(f"  ML: {game.moneyline.home_odds}/{game.moneyline.away_odds}")
    if game.total:
        print(f"  O/U: {game.total.over_under}")

# Or get specific data
spreads = Odds.spreads(scoreboard)
moneylines = Odds.moneylines(scoreboard)
totals = Odds.totals(scoreboard)

Data Models

Parse API responses into dataclasses:

from espn_sports_api import NFL, parse_injuries, parse_teams

nfl = NFL()

# Parse injuries - models have readable __str__ methods
injury_response = nfl.injuries()
injuries = parse_injuries(injury_response)
for injury in injuries:
    print(injury)  # "John Doe (QB, Patriots): Questionable - Ankle"

# Parse teams
teams_response = nfl.teams()
teams = parse_teams(teams_response)
for team in teams:
    print(f"{team.name} ({team.abbreviation})")

Available models: Venue, Broadcast, Weather, Injury, Transaction, Athlete, Team

Soccer Leagues

90+ leagues supported:

from espn_sports_api import Soccer

# Major leagues
epl = Soccer(league="epl")
la_liga = Soccer(league="la_liga")
bundesliga = Soccer(league="bundesliga")
serie_a = Soccer(league="serie_a")
ligue_1 = Soccer(league="ligue_1")
mls = Soccer(league="mls")

# Cups and competitions
champions_league = Soccer(league="champions_league")
europa_league = Soccer(league="europa_league")
fa_cup = Soccer(league="fa_cup")
copa_libertadores = Soccer(league="copa_libertadores")
world_cup = Soccer(league="world_cup")

# International
liga_mx = Soccer(league="liga_mx")
eredivisie = Soccer(league="eredivisie")
scottish_premiership = Soccer(league="scottish_premiership")
j_league = Soccer(league="j_league")

# All available leagues
print(Soccer.available_leagues())

# Filter leagues by region
print(Soccer.list_leagues("eng"))  # English leagues only

# Cross-league scoreboard
all_scores = Soccer.all_leagues_scoreboard(dates="20240115")

Racing

from espn_sports_api import Racing

f1 = Racing(series="f1")
nascar = Racing(series="nascar")
indycar = Racing(series="indycar")

standings = f1.standings()
schedule = f1.schedule(season=2024)

Fantasy Leagues

from espn_sports_api import FantasyFootball

# Public league
league = FantasyFootball(league_id=123456, season=2024)

# Private league (requires cookies)
league = FantasyFootball(
    league_id=123456,
    season=2024,
    swid="{YOUR-SWID}",
    espn_s2="YOUR_ESPN_S2_COOKIE"
)

teams = league.teams()
matchups = league.matchups(week=1)
standings = league.standings()

Caching

Enable response caching for faster repeated requests:

from espn_sports_api import ESPNClient, NFL
from pathlib import Path

# Memory cache with 5-minute TTL
client = ESPNClient(cache_ttl=300)
nfl = NFL(client=client)

# First request hits the API
scores = nfl.scoreboard()  # ~300ms

# Second request uses cache
scores = nfl.scoreboard()  # ~0ms

# Clear cache when needed
client.clear_cache()

# Disk cache for persistence across sessions
client = ESPNClient(cache_ttl=3600, cache_dir=Path("./cache"))

Context Manager

with NFL() as nfl:
    scores = nfl.scoreboard()

Examples

See the examples/ directory for scripts and an interactive notebook:

python examples/scripts/nfl_example.py
python examples/scripts/soccer_epl_example.py

Error Handling

All API errors raise typed exceptions:

from espn_sports_api import NFL, ESPNNotFoundError, ESPNRateLimitError, ESPNTimeoutError

nfl = NFL()
try:
    nfl.athlete("invalid_id")
except ESPNNotFoundError:
    print("Athlete not found")
except ESPNRateLimitError:
    print("Rate limited, back off")
except ESPNTimeoutError:
    print("Request timed out")

Exception hierarchy: ESPNApiError (base) > ESPNNotFoundError, ESPNRateLimitError, ESPNServerError, ESPNTimeoutError, ESPNResponseError.

Automatic retries (3x with backoff) are enabled by default for 429 and 5xx responses.

API Reference

ESPN's public API doesn't require authentication. Base URLs:

  • site.api.espn.com - Scoreboards, teams, standings, news, injuries, transactions
  • sports.core.api.espn.com - Athletes, venues, franchises, events, leaders
  • site.web.api.espn.com - Athlete statistics
  • lm-api-reads.fantasy.espn.com - Fantasy leagues

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

espn_sports_api-0.4.1.tar.gz (68.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

espn_sports_api-0.4.1-py3-none-any.whl (31.1 kB view details)

Uploaded Python 3

File details

Details for the file espn_sports_api-0.4.1.tar.gz.

File metadata

  • Download URL: espn_sports_api-0.4.1.tar.gz
  • Upload date:
  • Size: 68.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for espn_sports_api-0.4.1.tar.gz
Algorithm Hash digest
SHA256 99e68eded782fbd02d9774717137b1a2f43e195f9023adbc5cd9947a61bba597
MD5 657c496a2857c7feb7e8eb6834f6ec74
BLAKE2b-256 d19175e4a8a5bc8972a55ca33cb893ea06cbbba498fef8acfae59242899ca7d4

See more details on using hashes here.

Provenance

The following attestation bundles were made for espn_sports_api-0.4.1.tar.gz:

Publisher: publish.yml on fenneh/espn-sports-api

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file espn_sports_api-0.4.1-py3-none-any.whl.

File metadata

File hashes

Hashes for espn_sports_api-0.4.1-py3-none-any.whl
Algorithm Hash digest
SHA256 a1ec6aa84e071d1166ae6a285dad7fdf62df67371eb32e82d490d9ae5607523a
MD5 da4f6dd9ab1bee1591cb8b2f42d14e9b
BLAKE2b-256 c684cc28e499a2c6bc57b047c4981c3451ebc7725be9718362005017af73ba48

See more details on using hashes here.

Provenance

The following attestation bundles were made for espn_sports_api-0.4.1-py3-none-any.whl:

Publisher: publish.yml on fenneh/espn-sports-api

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page