### Phillies 40-Man Roster on 2018 Opening Day Source: https://github.com/toddrob99/mlb-statsapi/wiki/Examples Retrieves the 2018 season start date using `statsapi.get('season')` and then fetches the Phillies' 40-man roster for that opening day using `statsapi.roster()`. ```python print('Phillies 40-man roster on opening day of the 2018 season:\n%s' % statsapi.roster(143,'40Man',date=statsapi.get('season',{'seasonId':2018,'sportId':1})['seasons'][0]['regularSeasonStartDate'])) ``` -------------------------------- ### Install and Upgrade MLB-StatsAPI Source: https://github.com/toddrob99/mlb-statsapi/wiki/Home Instructions for installing the MLB-StatsAPI package from PyPI using pip, and how to upgrade to the latest version. ```bash pip install MLB-StatsAPI python -m pip install MLB-StatsAPI ``` ```bash pip install --upgrade MLB-StatsAPI python -m pip install --upgrade MLB-StatsAPI ``` -------------------------------- ### statsapi.notes() and Endpoint Parameter Requirements Source: https://github.com/toddrob99/mlb-statsapi/wiki/Function:-notes Provides details on using the `statsapi.notes()` function to get information about API endpoints, including required parameters and hints. Explains how multiple parameter requirements are structured and differentiates between path and query parameters with URL examples. ```APIDOC statsapi.notes(endpoint) - Retrieves notes for a specified API endpoint. - The result includes a list of required parameters and hints for some endpoints. - Example required_params structure for endpoints with multiple independent requirements: 'required_params': [['teamId'], ['leagueId'], ['leagueListid']] - Path parameters are part of the URL itself, e.g., `teamId` in `/api/v1/teams/143`. - Query parameters are appended after a question mark, e.g., `hydrate` in `/api/v1/teams/143?hydrate=league`. - Parameter passing for `statsapi.get()` is the same for both path and query parameters. ``` -------------------------------- ### Get Top 10 Pitchers by Career ERA Source: https://github.com/toddrob99/mlb-statsapi/wiki/Function:-league_leaders Example of fetching the top 10 pitchers based on their career earned run average (ERA). This demonstrates using 'earnedRunAverage' for `leaderCategories`, 'pitching' for `statGroup`, and 'career' for `statType`. ```python print( statsapi.league_leaders('earnedRunAverage',statGroup='pitching',limit=10,statType='career') ) ``` -------------------------------- ### Get Top 5 Team Leaders in Walks (Python Example) Source: https://github.com/toddrob99/mlb-statsapi/wiki/Function:-team_leaders Example demonstrating how to use the team_leaders function to find the top 5 players with the most walks for a specific team and season. ```Python import statsapi import datetime # Print the top 5 team leaders in walks for the 2008 Phillies print(statsapi.team_leaders(143,'walks',limit=5,season=2008)) ``` -------------------------------- ### Example MLB StatsAPI Query Source: https://github.com/toddrob99/mlb-statsapi/wiki/Function:-get Demonstrates a typical call to the `statsapi.get` function to retrieve data for a specific team. ```Python import statsapi # Get data for the Philadelphia Phillies (teamId=143) phillies_data = statsapi.get('team', {'teamId': 143}) # The 'phillies_data' variable will contain the JSON response from the API. ``` -------------------------------- ### Scoring Plays from Marlins @ Phillies Game (4/28/2019) Source: https://github.com/toddrob99/mlb-statsapi/wiki/Examples Prints a list of scoring plays for a specific game (ID 567074) using the `statsapi.game_scoring_plays()` function. ```python print( statsapi.game_scoring_plays(567074) ) ``` -------------------------------- ### Example: Print National League Standings Source: https://github.com/toddrob99/mlb-statsapi/wiki/Function:-standings Demonstrates how to call the statsapi.standings function to fetch and print the standings for the National League on a specific date. ```python print( statsapi.standings(leagueId=104,date='09/27/2008') ) ``` -------------------------------- ### Get Games and Print Summary Source: https://github.com/toddrob99/mlb-statsapi/wiki/Function:-schedule Demonstrates how to fetch game data using the statsapi.schedule function and then iterate through the results to print the 'summary' field for each game. ```python games = statsapi.schedule(start_date='07/01/2018',end_date='07/31/2018',team=143,opponent=121) for x in games: print(x['summary']) ``` -------------------------------- ### Get Team Affiliates Source: https://github.com/toddrob99/mlb-statsapi/wiki/Endpoints Retrieves affiliate information for teams. Requires teamIds. Supports version, teamIds, sportId, season, hydrate, and fields parameters. ```APIDOC Endpoint: teams_affiliates URL: https://statsapi.mlb.com/api/{ver}/teams/affiliates Required Parameters: * teamIds All Parameters: * ver * teamIds * sportId * season * hydrate * fields ``` -------------------------------- ### Get Team Personnel Source: https://github.com/toddrob99/mlb-statsapi/wiki/Endpoints Retrieves personnel information for a team. Requires teamId. Supports version, teamId, date, and fields parameters. ```APIDOC Endpoint: team_personnel URL: https://statsapi.mlb.com/api/{ver}/teams/{teamId}/personnel Required Parameters: * teamId All Parameters: * ver * teamId * date * fields ``` -------------------------------- ### Example: Print Full Box Score Source: https://github.com/toddrob99/mlb-statsapi/wiki/Function:-boxscore Demonstrates how to call the `statsapi.boxscore` function to print the complete box score for a specific game. ```python print( statsapi.boxscore(565997) ) ``` -------------------------------- ### MLB Standings on July 4, 2018 Source: https://github.com/toddrob99/mlb-statsapi/wiki/Examples Retrieves and prints the MLB standings for a specific date, July 4, 2018, using the `statsapi.standings()` function with the `date` parameter. ```python print(statsapi.standings(date='07/04/2018')) ``` -------------------------------- ### Top 10 All-Time Career Leaders in Doubles Source: https://github.com/toddrob99/mlb-statsapi/wiki/Examples Retrieves the top 10 all-time career leaders in doubles for hitting statistics using `statsapi.league_leaders()`. ```python print(statsapi.league_leaders('doubles',statGroup='hitting',statType='career',limit=10)) ``` -------------------------------- ### Get Team Coaches Source: https://github.com/toddrob99/mlb-statsapi/wiki/Endpoints Retrieves coaching staff for a team. Requires teamId. Supports version, teamId, season, date, and fields parameters. ```APIDOC Endpoint: team_coaches URL: https://statsapi.mlb.com/api/{ver}/teams/{teamId}/coaches Required Parameters: * teamId All Parameters: * ver * teamId * season * date * fields ``` -------------------------------- ### Get Game Content - MLB StatsAPI Source: https://github.com/toddrob99/mlb-statsapi/wiki/Endpoints Fetches content related to a specific MLB game, identified by gamePk. Supports filtering by highlight limit. ```APIDOC Endpoint: game_content URL: https://statsapi.mlb.com/api/{ver}/game/{gamePk}/content Required Parameters: * gamePk All Parameters: * ver * gamePk * highlightLimit ``` -------------------------------- ### Get Team Roster Source: https://github.com/toddrob99/mlb-statsapi/wiki/Endpoints Retrieves the roster for a team. Requires teamId. Supports version, teamId, rosterType, season, date, hydrate, and fields parameters. ```APIDOC Endpoint: team_roster URL: https://statsapi.mlb.com/api/{ver}/teams/{teamId}/roster Required Parameters: * teamId All Parameters: * ver * teamId * rosterType * season * date * hydrate * fields ``` -------------------------------- ### Python: Get Info for Teams in a City Source: https://github.com/toddrob99/mlb-statsapi/wiki/Function:-lookup_team Shows how to iterate through the results of `statsapi.lookup_team` when searching by location (e.g., 'ny') and print details for each team found. ```python for team in statsapi.lookup_team('ny'): print(team) ``` -------------------------------- ### Get Season Data Source: https://github.com/toddrob99/mlb-statsapi/wiki/Endpoints Retrieves season-specific data. Requires seasonId and sportId. Supports version, seasonId, sportId, and fields parameters. ```APIDOC Endpoint: season URL: https://statsapi.mlb.com/api/{ver}/seasons/{seasonId} Required Parameters: * seasonId * sportId All Parameters: * ver * seasonId * sportId * fields ``` -------------------------------- ### Get Team Details Source: https://github.com/toddrob99/mlb-statsapi/wiki/Endpoints Retrieves specific details for a team. Requires teamId. Supports version, teamId, season, sportId, hydrate, and fields parameters. ```APIDOC Endpoint: team URL: https://statsapi.mlb.com/api/{ver}/teams/{teamId} Required Parameters: * teamId All Parameters: * ver * teamId * season * sportId * hydrate * fields ``` -------------------------------- ### Get Teams History Source: https://github.com/toddrob99/mlb-statsapi/wiki/Endpoints Retrieves the history of teams. Requires teamIds. Supports version, teamIds, startSeason, endSeason, and fields parameters. ```APIDOC Endpoint: teams_history URL: https://statsapi.mlb.com/api/{ver}/teams/history Required Parameters: * teamIds All Parameters: * ver * teamIds * startSeason * endSeason * fields ``` -------------------------------- ### Get Game Play By Play - MLB StatsAPI Source: https://github.com/toddrob99/mlb-statsapi/wiki/Endpoints Fetches the play-by-play data for a specific MLB game, identified by gamePk. Supports filtering by timecode and requesting specific fields. ```APIDOC Endpoint: game_playByPlay URL: https://statsapi.mlb.com/api/{ver}/game/{gamePk}/playByPlay Required Parameters: * gamePk All Parameters: * ver * gamePk * timecode * fields ``` -------------------------------- ### Get Standings Source: https://github.com/toddrob99/mlb-statsapi/wiki/Endpoints Retrieves league standings for a given season. Requires leagueId. Supports version, leagueId, season, standingsTypes, date, hydrate, and fields parameters. ```APIDOC Endpoint: standings URL: https://statsapi.mlb.com/api/{ver}/standings Required Parameters: * leagueId All Parameters: * ver * leagueId * season * standingsTypes * date * hydrate * fields ``` -------------------------------- ### Get Game Uniforms - MLB StatsAPI Source: https://github.com/toddrob99/mlb-statsapi/wiki/Endpoints Retrieves uniform information for specified MLB games. Requires one or more gamePks. Supports filtering by fields. ```APIDOC Endpoint: game_uniforms URL: https://statsapi.mlb.com/api/{ver}/uniforms/game Required Parameters: * gamePks All Parameters: * ver * gamePks * fields ``` -------------------------------- ### Basic Usage of MLB-StatsAPI Source: https://github.com/toddrob99/mlb-statsapi/wiki/Home Demonstrates how to import the MLB-StatsAPI package and use the `schedule` function to retrieve game schedules for a specific date range and team. ```python import statsapi sched = statsapi.schedule(start_date='07/01/2018',end_date='07/31/2018',team=143,opponent=121) ``` -------------------------------- ### Get Top 10 All-Time Career Triples Leaders Source: https://github.com/toddrob99/mlb-statsapi/wiki/Function:-league_leaders Example of fetching the top 10 players with the most career triples. This illustrates using 'triples' for `leaderCategories`, 'hitting' for `statGroup`, `sportId`, and 'career' for `statType`. ```python print( statsapi.league_leaders('triples',statGroup='hitting',limit=10,sportId=1,statType='career') ) ``` -------------------------------- ### Get Top 5 Hitters by OPS in 2018 Source: https://github.com/toddrob99/mlb-statsapi/wiki/Function:-league_leaders Example of retrieving the top 5 batters by On-Base Plus Slugging (OPS) for the 2018 season. This showcases filtering by `leaderCategories`, `statGroup`, `limit`, and `season`. ```python print( statsapi.league_leaders('onBasePlusSlugging',statGroup='hitting',limit=5,season=2018) ) ``` -------------------------------- ### Get Game Highlights Source: https://github.com/toddrob99/mlb-statsapi/wiki/Function:-game_highlights Retrieves highlight video links for a given game using its unique game primary key (gamePk). Requires the `statsapi` library. Returns a list of highlight objects, each containing a title, description, and URL. ```APIDOC statsapi.game_highlights(gamePk) - Retrieves highlight video links for a given game. - Parameters: - gamePk: The primary key of the game (integer). - Returns: A list of highlight objects, each containing title, description, and URL. ``` ```Python print( statsapi.game_highlights( statsapi.last_game(143) ) ) ``` -------------------------------- ### Philadelphia Phillies Games Won in July 2008 Source: https://github.com/toddrob99/mlb-statsapi/wiki/Examples Fetches all games for July 2008 using `statsapi.schedule()`, filters for Phillies wins, and prints the linescore for each winning game using `statsapi.linescore()`. ```python for x in [y for y in statsapi.schedule(team=143,start_date='07/01/2008',end_date='07/31/2008') if y.get('winning_team','')=='Philadelphia Phillies']: print('%s\nWinner: %s, Loser: %s\n%s\n\n' % (x['game_date'], x['winning_team'], x['losing_team'], statsapi.linescore(x['game_id']))) ``` -------------------------------- ### Get Top 10 Players with Most Errors in 2017 (AL) Source: https://github.com/toddrob99/mlb-statsapi/wiki/Function:-league_leaders Example of finding the top 10 players who committed the most errors in the 2017 season within the American League. This demonstrates using 'errors' for `leaderCategories`, 'fielding' for `statGroup`, `season`, and `leagueId`. ```python print( statsapi.league_leaders('errors',statGroup='fielding',limit=10,season=2017,leagueId=103) ) ``` -------------------------------- ### Get Chase Utley's Career Hitting Stats Source: https://github.com/toddrob99/mlb-statsapi/wiki/Function:-player_stats Example demonstrating how to retrieve Chase Utley's career hitting statistics. It first looks up the player's ID using the `sports_players` endpoint and then calls `player_stats` with the appropriate parameters. ```python print( statsapi.player_stats(next(x['id'] for x in statsapi.get('sports_players',{'season':2008,'gameType':'W'})['people'] if x['fullName']=='Chase Utley'), 'hitting', 'career') ) ``` -------------------------------- ### Get Game Pace Data (Python) Source: https://github.com/toddrob99/mlb-statsapi/wiki/Function:-game_pace_data Retrieves pace of game data for a specified MLB season, returning the results as a Python dictionary. The function accepts a 'season' parameter (defaults to the current year) and 'sportId' (defaults to 1). It is recommended to explicitly provide the 'season' parameter for predictable results, especially around the start of a new season. Data is available for seasons dating back to 1999. ```python import datetime # Example usage: # statsapi.game_pace_data(season=2023, sportId=1) # The season parameter will default to the current calendar year if not provided. # It's best to include the season parameter explicitly. statsapi.game_pace_data(season=datetime.now().year, sportId=1) ``` -------------------------------- ### Get Games and Print Decisions Source: https://github.com/toddrob99/mlb-statsapi/wiki/Function:-schedule Shows how to retrieve game data and extract specific details like the game date, game number, winning pitcher, and losing pitcher for each game in the schedule. ```python games = statsapi.schedule(start_date='07/01/2018',end_date='07/31/2018',team=143,opponent=121) for x in games: print("%s Game %s - WP: %s, LP: %s" % (x['game_date'],x['game_num'],x['winning_pitcher'],x['losing_pitcher'])) ``` -------------------------------- ### Get Stats Leaders Source: https://github.com/toddrob99/mlb-statsapi/wiki/Endpoints Retrieves statistical leaders. Requires leaderCategories. Supports version, leaderCategories, playerPool, leaderGameTypes, statGroup, season, leagueId, sportId, hydrate, limit, fields, and statType parameters. Note: If excluding season parameter to get all time leaders, include statType=statsSingleSeason or you will likely not get any results. ```APIDOC Endpoint: stats_leaders URL: https://statsapi.mlb.com/api/{ver}/stats/leaders Required Parameters: * leaderCategories All Parameters: * ver * leaderCategories * playerPool * leaderGameTypes * statGroup * season * leagueId * sportId * hydrate * limit * fields * statType Note: If excluding season parameter to get all time leaders, include statType=statsSingleSeason or you will likely not get any results. ``` -------------------------------- ### Get Next Game for Team Source: https://github.com/toddrob99/mlb-statsapi/wiki/Function:-next_game Retrieves the `gamePk` for the next unstarted game for a given team. This function takes a `teamId` as input. ```Python statsapi.next_game(teamId) ``` -------------------------------- ### Get Conferences - MLB StatsAPI Source: https://github.com/toddrob99/mlb-statsapi/wiki/Endpoints Retrieves information about MLB conferences. The endpoint can be called without parameters to get a list of conferences. Supports filtering by conferenceId and season. ```APIDOC Endpoint: conferences URL: https://statsapi.mlb.com/api/{ver}/conferences Required Parameters: * None All Parameters: * ver * conferenceId * season * fields ``` -------------------------------- ### Get Team Roster API Source: https://github.com/toddrob99/mlb-statsapi/wiki/Function:-roster Retrieves the roster for a specified team. Supports filtering by roster type and date. Default roster type is 'active'. Date format should be MM/DD/YYYY. ```APIDOC statsapi.roster(teamId, rosterType=None, season=datetime.now().year, date=None) Parameters: - teamId (int): The unique identifier for the team. - rosterType (str, optional): The type of roster to retrieve (e.g., 'active', 'depthChart'). Defaults to None, which implies 'active' if not specified. - season (int, optional): The season year for the roster. Defaults to the current year. - date (str, optional): A specific date to retrieve the roster for, in 'MM/DD/YYYY' format. Defaults to None. Notes: - To get a list of available rosterTypes, call the meta endpoint with type=rosterTypes. - The default rosterType is 'active'. - Example date format: '04/24/2019'. Example Usage: # Print the current Phillies active roster: print( statsapi.roster(143) ) ``` -------------------------------- ### Top 5 Phillies Team Leaders in Walks (2008) Source: https://github.com/toddrob99/mlb-statsapi/wiki/Examples Fetches the top 5 team leaders for the Philadelphia Phillies in the 'walks' category for the 2008 season using `statsapi.team_leaders()`. ```python print(statsapi.team_leaders(143,'walks',limit=5,season=2008)) ``` -------------------------------- ### Configure MLB-StatsAPI Logging Source: https://github.com/toddrob99/mlb-statsapi/wiki/Home Shows how to set up Python's logging module to capture debug messages from the MLB-StatsAPI. This involves getting the 'statsapi' logger, setting its level, and adding a stream handler with a custom formatter. ```python import logging logger = logging.getLogger('statsapi') logger.setLevel(logging.DEBUG) rootLogger = logging.getLogger() rootLogger.setLevel(logging.DEBUG) ch = logging.StreamHandler() formatter = logging.Formatter("%(asctime)s - %(levelname)8s - %(name)s(%(thread)s) - %(message)s") ch.setFormatter(formatter) rootLogger.addHandler(ch) ``` -------------------------------- ### Get Game Context Metrics - MLB StatsAPI Source: https://github.com/toddrob99/mlb-statsapi/wiki/Endpoints Retrieves context metrics for a specific MLB game, identified by gamePk. This can be used to get current win probability for each team. Supports filtering by timecode. ```APIDOC Endpoint: game_contextMetrics URL: https://statsapi.mlb.com/api/{ver}/game/{gamePk}/contextMetrics Required Parameters: * gamePk All Parameters: * ver * gamePk * timecode * fields Note: If you only want the current win probability for each team, try the game_contextMetrics endpoint instad. ``` -------------------------------- ### Get Latest Season Data Source: https://github.com/toddrob99/mlb-statsapi/wiki/Function:-latest_season Retrieves the latest season data for a specified sport ID. The default sport ID is 1 (MLB). The function returns a dictionary containing season details, including the 'seasonId'. ```python season_data = statsapi.latest_season() print(season_data['seasonId']) ``` -------------------------------- ### Get Team's Last Game PK using statsapi Source: https://github.com/toddrob99/mlb-statsapi/wiki/Function:-last_game This function retrieves the gamePk for the most recent completed game for a specified team. It takes a `teamId` as input and returns the game's primary key. ```Python statsapi.last_game(teamId) ``` -------------------------------- ### List Sports Source: https://github.com/toddrob99/mlb-statsapi/wiki/Endpoints Retrieves a list of supported sports. No required parameters. Supports version, sportId, and fields parameters. ```APIDOC Endpoint: sports URL: https://statsapi.mlb.com/api/{ver}/sports Required Parameters: * *None* All Parameters: * ver * sportId * fields ``` -------------------------------- ### Get Game Scoring Plays Function Source: https://github.com/toddrob99/mlb-statsapi/wiki/Function:-game_scoring_plays Retrieves a text-formatted list of scoring plays for a specified MLB game. The function takes a game primary key (`gamePk`) as input. Note: This method was reported as broken as of 7/25/2020 due to changes in the `schedule` endpoint, with a fix available in v0.1.9. For raw data, consider `game_scoring_play_data`. ```APIDOC statsapi.game_scoring_plays(gamePk) - Retrieves a text-formatted list of scoring plays for a given game. - Parameters: - gamePk: The primary key (ID) of the game (e.g., integer). - Returns: - A string containing a formatted list of scoring plays. - Notes: - This method is broken as of 7/25/2020 due to a change in the schedule endpoint. - Update to v0.1.9 for a fix. - To retrieve the data used to build the formatted text, see Function: game_scoring_play_data. Example Usage: print( statsapi.game_scoring_plays(567074) ) ``` -------------------------------- ### people_freeAgents API Endpoint Source: https://github.com/toddrob99/mlb-statsapi/wiki/Endpoints Fetches a list of free agents. Requires a league ID and supports filtering by order, hydration, and fields. ```APIDOC Endpoint: people_freeAgents URL: https://statsapi.mlb.com/api/{ver}/people/freeAgents Required Parameters: - leagueId: The ID of the league. All Parameters: - ver: API version. - leagueId: The ID of the league. - order: Specifies the order of results. - hydrate: Specifies related data to include. - fields: Comma-separated list of fields to return. ```