Skip to main content

MLB — ESPN web API (v3)

sportsdataverse.mlb — 5 endpoints.

espn_mlb_player_overview​

ESPN endpoint.

Endpoint URL: GET https://site.web.api.espn.com/apis/common/v3/sports/baseball/mlb/athletes/{athlete_id}/overview

Valid URL: https://site.web.api.espn.com/apis/common/v3/sports/baseball/mlb/athletes/4239/overview

API ParameterPythonPatternRequiredNullableDescription
athlete_idathlete_idYathlete_id path parameter.

Returns​

return_parsed=True (default) — a tidy polars.DataFrame with the columns below; pass return_as_pandas=True for a pandas.DataFrame.

col_nametypedescription
athlete_idintegerUnique ESPN athlete identifier.
athlete_display_namecharacterAthlete display name (full).
athlete_short_namecharacterAthlete short display name.
athlete_positioncharacter
athlete_jerseycharacterAthlete jersey.
athlete_team_idinteger
athlete_team_abbreviationcharacter
split_namecharacterSplit name (typically "All Splits").
split_categorycharacter
games_playedcharacterGames played.
avg_minutescharacter
field_goal_pctcharacter
three_point_pctcharacter
free_throw_pctcharacter
avg_reboundscharacter
avg_assistscharacter
avg_blockscharacter
avg_stealscharacter
avg_foulscharacter
avg_turnoverscharacter
avg_pointscharacter

return_parsed=False — the raw JSON Dict payload, unparsed.

Raises​

ExceptionDescription
NoDataErrorThe host answered 404 -- the requested resource does not exist.
ValueErrorThe host answered 400 / 422 -- the request is wrong; retrying cannot help.
AssetFetchErrorThe fetch failed (a non-2xx answer or a connection failure after retries, e.g. 401/403/429/5xx, or an empty or unreadable 200 body) -- the answer is unknown, not empty.

Example​

espn_mlb_player_overview(athlete_id='4239')

espn_mlb_player_stats_v3​

ESPN endpoint.

Endpoint URL: GET https://site.web.api.espn.com/apis/common/v3/sports/baseball/mlb/athletes/{athlete_id}/stats

Valid URL: https://site.web.api.espn.com/apis/common/v3/sports/baseball/mlb/athletes/39832/stats

API ParameterPythonPatternRequiredNullableDescription
athlete_idathlete_idYathlete_id path parameter.
seasonseasonYSeason year (e.g. 2024).

Returns​

return_parsed=True (default) — a tidy polars.DataFrame with the columns below; pass return_as_pandas=True for a pandas.DataFrame.

col_nametypedescription
categorycharacterESPN stat category the row belongs to (e.g., basketball "averages" / "totals" / "miscellaneous", NFL "passing", MLB "career-batting"). The stat columns after position are named from each category's own names list, so they differ by sport, and the other categories' columns are null on a row.
split_namecharacterSeason label of the row (e.g., "2010-11") on the Web v3 payload, or "Career" on the row built from the category's career totals; the split's name on payloads that ship named splits.
split_categorycharacterCategory of a named split; null on the Web v3 per-season rows.
split_valuecharacterValue of a named split; null on the Web v3 per-season rows.
seasonintegerSeason end year of the row (e.g., 2011 for 2010-11); null on the "Career" row.
team_idintegerESPN team id (Int64) the athlete played that season for; a traded player has one row per team. Null on the "Career" row.
positioncharacterPosition abbreviation the athlete was listed at for that season and team (e.g., "G"); null on the "Career" row.
games_playedcharacterGames played (GP), as ESPN ships it (a string).
at_batscharacterAt bats (AB), plate appearances minus walks, hit-by-pitches and sacrifices.
runscharacterRuns scored (R).
hitscharacterHits (H), singles through home runs.
doublescharacterDoubles (2B), two-base hits.
triplescharacterTriples (3B), three-base hits.
home_runscharacterHome runs (HR).
rb_ischaracterRuns batted in (RBI); ESPN's stat key RBIs, snake-cased.
walkscharacterWalks (BB), bases on balls.
hit_by_pitchcharacterTimes hit by a pitch (HBP).
strikeoutscharacterStrikeouts (SO).
stolen_basescharacterStolen bases (SB).
caught_stealingcharacterTimes caught stealing (CS).
avgcharacterBatting average (AVG), hits / at bats.
on_base_pctcharacterOn-base percentage (OBP), (hits + walks + hit-by-pitches) / plate appearances.
slug_avgcharacterSlugging percentage (SLG), total bases / at bats.
opscharacterOn-base plus slugging (OPS).
warbrcharacterWins above replacement (WAR); ESPN's stat key WARBR, snake-cased.
plate_appearancescharacterPlate appearances (PA).
pitchescharacterPitches seen (P).
pitches_per_plate_appearancecharacterPitches seen per plate appearance (P/PA).
extra_base_hitscharacterExtra-base hits (XBH), doubles plus triples plus home runs.
total_basescharacterTotal bases (TB), 1 per single, 2 per double, 3 per triple, 4 per home run.
intentional_walkscharacterIntentional walks (IBB).
gid_pscharacterGrounded into double play (GIDP); ESPN's stat key GIDPs, snake-cased.
sac_hitscharacterSacrifice bunts (SH).
sac_fliescharacterSacrifice flies (SF).
stolen_base_pctcharacterStolen-base success percentage (SB%).
off_warbrcharacterOffensive wins above replacement (OWAR); ESPN's stat key offWARBR, snake-cased.
runs_createdcharacterRuns created (RC), an estimate of the runs a batter produced.
runs_created_per27_outscharacterRuns created per 27 outs (RC/27).
isolated_powercharacterIsolated power (ISOP), slugging percentage minus batting average.
secondary_avgcharacterSecondary average (SECA), extra bases from hits plus walks and stolen bases, per at bat.
at_bats_per_home_runcharacterAt bats per home run (AB/HR).
walks_per_plate_appearancecharacterWalks per plate appearance (BB/PA).
walk_to_strikeout_ratiocharacterWalks per strikeout (BB/K).
ground_ballscharacterGround-ball outs (GO).
fly_ballscharacterFly-ball outs (FO).
ground_to_fly_ratiocharacterGround outs per fly out (GO/FO).

return_parsed=False — the raw JSON Dict payload, unparsed.

Raises​

ExceptionDescription
NoDataErrorThe host answered 404 -- the requested resource does not exist.
ValueErrorThe host answered 400 / 422 -- the request is wrong; retrying cannot help.
AssetFetchErrorThe fetch failed (a non-2xx answer or a connection failure after retries, e.g. 401/403/429/5xx, or an empty or unreadable 200 body) -- the answer is unknown, not empty.

Example​

espn_mlb_player_stats_v3(athlete_id='39832')

espn_mlb_player_gamelog​

ESPN endpoint.

Endpoint URL: GET https://site.web.api.espn.com/apis/common/v3/sports/baseball/mlb/athletes/{athlete_id}/gamelog

Valid URL: https://site.web.api.espn.com/apis/common/v3/sports/baseball/mlb/athletes/4239/gamelog

API ParameterPythonPatternRequiredNullableDescription
athlete_idathlete_idYathlete_id path parameter.
seasonseasonYSeason year (e.g. 2024).

Returns​

return_parsed=True (default) — a tidy polars.DataFrame with the columns below; pass return_as_pandas=True for a pandas.DataFrame.

col_nametypedescription
season_type_idinteger
season_type_namecharacter
categorycharacterCategory label.
event_idintegerUnique ESPN event/game identifier.
event_datecharacterEvent date-time in ISO 8601 (e.g. '2017-07-11T00:00:00Z').
home_awaycharacterVenue label for the team ('home' or 'away').
scorecharacterRunning score (away-home) after the play.
opponent_idintegerUnique identifier for opponent.
opponent_abbreviationcharacterOpponent abbreviation.
opponent_display_namecharacterDisplay name.
game_resultcharacterGame result (W/L).
game_processedcharacter
stat_0character
stat_1character
stat_2character
stat_3character
stat_4character
stat_5character
stat_6character
stat_7character
stat_8character
stat_9character
stat_10character
stat_11character
stat_12character
stat_13character

return_parsed=False — the raw JSON Dict payload, unparsed.

Raises​

ExceptionDescription
NoDataErrorThe host answered 404 -- the requested resource does not exist.
ValueErrorThe host answered 400 / 422 -- the request is wrong; retrying cannot help.
AssetFetchErrorThe fetch failed (a non-2xx answer or a connection failure after retries, e.g. 401/403/429/5xx, or an empty or unreadable 200 body) -- the answer is unknown, not empty.

Example​

espn_mlb_player_gamelog(athlete_id='4239')

espn_mlb_player_splits​

ESPN endpoint.

Endpoint URL: GET https://site.web.api.espn.com/apis/common/v3/sports/baseball/mlb/athletes/{athlete_id}/splits

Valid URL: https://site.web.api.espn.com/apis/common/v3/sports/baseball/mlb/athletes/4239/splits

API ParameterPythonPatternRequiredNullableDescription
athlete_idathlete_idYathlete_id path parameter.
seasonseasonYSeason year (e.g. 2024).

Returns​

return_parsed=True (default) — a tidy polars.DataFrame with the columns below; pass return_as_pandas=True for a pandas.DataFrame.

col_nametypedescription
descriptionscharacter
display_namecharacterDisplay name.
display_namescharacter
filterscharacter
labelscharacter
namescharacterAssociated detail names for the type.
split_categoriescharacter

return_parsed=False — the raw JSON Dict payload, unparsed.

Raises​

ExceptionDescription
NoDataErrorThe host answered 404 -- the requested resource does not exist.
ValueErrorThe host answered 400 / 422 -- the request is wrong; retrying cannot help.
AssetFetchErrorThe fetch failed (a non-2xx answer or a connection failure after retries, e.g. 401/403/429/5xx, or an empty or unreadable 200 body) -- the answer is unknown, not empty.

Example​

espn_mlb_player_splits(athlete_id='4239')

espn_mlb_leaders​

ESPN endpoint.

Endpoint URL: GET https://site.web.api.espn.com/apis/common/v3/sports/baseball/mlb/statistics/byathlete

Valid URL: https://site.web.api.espn.com/apis/common/v3/sports/baseball/mlb/statistics/byathlete?limit=50&page=1

API ParameterPythonPatternRequiredNullableDescription
categorycategoryYLeaderboard population: the athletes ranked in that category, whose values it fills (other categories come back null). Football takes <group>:<category> (offense:passing, offense:rushing, offense:receiving, defense:defensive, scoring:scoring); a bare passing is rejected with HTTP 400 (ValueError). Basketball takes the bare name (offensive).
seasonseasonYSeason year (e.g. 2024).
seasontypeseason_typeYSeason phase: 1=preseason, 2=regular season, 3=postseason.
limitlimitYMaximum number of items to return.
pagepageYpage query parameter.
sortsortYSort key <category>.<statName>:<asc|desc>, the names in the payload's categories (passing.passingYards:desc, offensive.avgPoints:desc). A stat without its category is rejected with HTTP 400 (ValueError).

Returns​

return_parsed=True (default) — a tidy polars.DataFrame with the columns below; pass return_as_pandas=True for a pandas.DataFrame.

col_nametypedescription
sort_orderintegerPosition of the athlete in ESPN's leaderboard order (the requested category or sort), counted across pages: (page - 1) * limit + position on the page. A position, not a rank: tied athletes still count up; ESPN's per-stat ranks stay in the raw payload (return_parsed=False).
athlete_idintegerESPN id of the athlete, the key the athlete endpoints (athlete_overview, athlete_stats) take.
athlete_uidcharacterESPN composite athlete uid (s:<sport>~l:<league>~a:<athlete id>), kept as text.
athlete_display_namecharacterAthlete's full display name.
athlete_short_namecharacterAthlete's abbreviated name (e.g. 'B. Nix').
athlete_first_namecharacterAthlete's first name.
athlete_last_namecharacterAthlete's last name.
athlete_positioncharacterAthlete's position abbreviation (e.g. QB, G, C).
athlete_statuscharacterAthlete's ESPN status name (e.g. Active, Inactive) as ESPN reports it at request time, not for the requested season.
team_idintegerESPN id of the team the athlete played for in the requested season.
team_abbreviationcharacterAbbreviation of the athlete's team in the requested season (ESPN teamShortName, e.g. ORE).
team_namecharacterNickname of the athlete's team in the requested season (ESPN teamName, e.g. Ducks).
batting_games_playeddoubleGames Played (ESPN 'batting' category).
batting_at_batsdoubleAt Bats (ESPN 'batting' category): The number of times a batter comes up to bat not counting walks and sacrifices.
batting_runsdoubleRuns (ESPN 'batting' category): The number of runs scored.
batting_hitsdoubleHits (ESPN 'batting' category): The number of hits.
batting_avgdoubleBatting Average (ESPN 'batting' category): The average number of times the batter reached successfully on base due to a hit: hits / atBats.
batting_doublesdoubleDoubles (ESPN 'batting' category): The number of times that a batter reaches second base as the result of a hit without an error being committed.
batting_triplesdoubleTriples (ESPN 'batting' category): The number of hits that result in the batter reaching 3rd base without the aid of an error.
batting_home_runsdoubleHome Runs (ESPN 'batting' category): The number of hits that allowed the batter to round the bases and score without the aid of an error of the defense.
batting_rb_isdoubleRuns Batted In (ESPN 'batting' category): The number of runs scored by a batter's play.
batting_total_basesdoubleTotal Bases (ESPN 'batting' category): The number of bases calculated as 1 for a 1B, 2 for a 2B, 3 for a 3B and 4 for a HR.
batting_walksdoubleWalks (ESPN 'batting' category): The number of times a batter reaches base on four balls.
batting_strikeoutsdoubleStrikeouts (ESPN 'batting' category): The number of times a player strikes out.
batting_stolen_basesdoubleStolen Bases (ESPN 'batting' category): The number of bases stolen.
batting_on_base_pctdoubleOn Base Percentage (ESPN 'batting' category): The ratio of the number of times the batter reached base per plate appearnce: (hits + walks + hbp / plateAppearances).
batting_slug_avgdoubleSlugging Percentage (ESPN 'batting' category): Slugging percentage is a metric that is meant to measuring how many bases the hitter safely advances to after making contact with the ball: (totalBases / atBats).
batting_opsdoubleOBP Pct + SLG Pct (ESPN 'batting' category): The average calculated by adding up on-base percentage and slugging percentage.
batting_warbrdoubleWins Above Replacement (ESPN 'batting' category).
pitching_games_playeddoubleGames Played (ESPN 'pitching' category).
pitching_games_starteddoubleGames Started (ESPN 'pitching' category): The number of games started by a pitcher.
pitching_quality_startsdoubleQuality Starts (ESPN 'pitching' category): The number of quality starts for a pitcher.
pitching_eradoubleEarned Run Average (ESPN 'pitching' category): The average number of runs a pitcher yields per 9 innings thrown.
pitching_winsdoubleWins (ESPN 'pitching' category): The number of times the pitcher was attributed with a win.
pitching_lossesdoubleLosses (ESPN 'pitching' category): The number of losses for a pitcher.
pitching_savesdoubleSaves (ESPN 'pitching' category): The number of times a pitcher enters and finishes the game without surrendering the lead in a save opportunity.
pitching_holdsdoubleHolds (ESPN 'pitching' category): The number of times a pitcher enters the game with the lead, gets at least an out and leaves the game wihtout having given up the lead.
pitching_inningsdoubleInnings pitched (ESPN 'pitching' category): The number of innings pitched.
pitching_hitsdoubleHits (ESPN 'pitching' category): The number of hits surrendered by a pitcher.
pitching_earned_runsdoubleEarned runs (ESPN 'pitching' category): The number of earned runs surrendered by a pitcher.
pitching_home_runsdoubleHome Runs (ESPN 'pitching' category): The number of times a pitcher has allowed a home run.
pitching_walksdoubleWalks (ESPN 'pitching' category): The number of times a pitcher surrenders a base on balls.
pitching_strikeoutsdoubleStrikeouts (ESPN 'pitching' category): The number of times the pitcher struck out a batter.
pitching_strikeouts_per_nine_inningsdoubleStrikeouts Per 9 Innings (ESPN 'pitching' category): The average number of strikeouts for a pitcher per 9 innings.
pitching_whipdoubleWalks Plus Hits Per Inning Pitched (ESPN 'pitching' category): The number representing walks plus hits divided by innings pitched.
pitching_warbrdoubleWins Above Replacement (ESPN 'pitching' category).
fielding_games_playeddoubleGames Played (ESPN 'fielding' category).
fielding_games_starteddoubleGames Started (ESPN 'fielding' category): The number of games started by a fielder.
fielding_full_innings_playeddoubleFull Innings (ESPN 'fielding' category): The number of fully completed innings by a fielder.
fielding_total_chancesdoubleTotal Chances (ESPN 'fielding' category): The number of chances a fielder has to make an out calculated by assists plus putouts plus errors.
fielding_putoutsdoublePutouts (ESPN 'fielding' category): The number of times the fielder tags or forces the out of a baserunner.
fielding_assistsdoubleAssists (ESPN 'fielding' category): The number of times a fielder is involved in an out when the fielder is not the putouter.
fielding_fielding_pctdoubleFielding Percentage (ESPN 'fielding' category): The percentage of plays made by a fielder given the total number of chances.
fielding_errorsdoubleErrors (ESPN 'fielding' category): The number of times a fielder fails to make the play they are expected to make.
fielding_double_playsdoubleDouble Plays (ESPN 'fielding' category): The number of double plays a fielder has been a part of as either the assister or putouter.
fielding_range_factordoubleRange Factor (ESPN 'fielding' category): The estimation of how much field a fielder can cover.
fielding_def_warbrdoubleDefensive Wins Above Replacement (ESPN 'fielding' category).
fielding_passed_ballsdoublePassed Balls (ESPN 'fielding' category): The number of times the ball is dropped or passes by the catcher.
fielding_catcher_stolen_bases_alloweddoubleStolen Bases Allowed (ESPN 'fielding' category): The number of stolen bases that a catcher allows.
fielding_catcher_caught_stealingdoubleCaught Stealing (ESPN 'fielding' category): The number of times a catcher throws a baserunner trying to steal a base.
fielding_catcher_caught_stealing_pctdoubleCaught Stealing Percentage (ESPN 'fielding' category): The percentage of baserunners caught by the catcher given the total number of steal attempts.

return_parsed=False — the raw JSON Dict payload, unparsed.

Raises​

ExceptionDescription
NoDataErrorThe host answered 404 -- the requested resource does not exist.
ValueErrorThe host answered 400 / 422 -- the request is wrong; retrying cannot help.
AssetFetchErrorThe fetch failed (a non-2xx answer or a connection failure after retries, e.g. 401/403/429/5xx, or an empty or unreadable 200 body) -- the answer is unknown, not empty.

Example​

espn_mlb_leaders()