### Get Gamepace Metrics (HTTP Request) Source: https://github.com/zero-sum-seattle/python-mlb-statsapi/wiki/Data-Types:-Gamepace Example HTTP GET request to the MLB Stats API endpoint for retrieving pace of game metrics for a given season. ```http https://statsapi.mlb.com/api/v1/gamePace?season=2018 ``` -------------------------------- ### Install and Initialize Python MLB Stats API Source: https://github.com/zero-sum-seattle/python-mlb-statsapi/blob/main/README.md This snippet shows how to install the python-mlb-statsapi library using pip and how to initialize the main MLB API object for use. ```python import mlbstatsapi # Install the library: # python3 -m pip install python-mlb-statsapi # Initialize the MLB API object: mlb = mlbstatsapi.Mlb() ``` -------------------------------- ### Install Python MLB Stats API Source: https://github.com/zero-sum-seattle/python-mlb-statsapi/wiki/Home Installs the python-mlb-statsapi package from the test PyPI repository. This command is used to set up the library for use in a Python environment. ```python python3 -m pip install -i https://test.pypi.org/simple/ python-mlb-statsapi ``` -------------------------------- ### Get Game Source: https://github.com/zero-sum-seattle/python-mlb-statsapi/wiki/Data-Types:-Game Retrieves general information about a specific game. ```APIDOC ## GET /api/v1.1/game/{game_id} ### Description Returns general information about a specific game. This endpoint can also return a snapshot of data at a specific timecode and allow filtering of returned fields. ### Method GET ### Endpoint `/api/v1.1/game/{game_id}` ### Parameters #### Path Parameters - **game_id** (string/int) - Required - Game id number #### Query Parameters - **timecode** (string) - Optional - Use this parameter to return a snapshot of the data at the specified time. Format: YYYYMMDD_HHMMSS - **fields** (string) - Optional - Comma delimited list of specific fields to be returned. Format: topLevelNode, childNode, attribute ### Request Example ```https https://statsapi.mlb.com/api/v1.1/game/534196?fields=game.status ``` ### Response #### Success Response (200) - **gameData** (object) - Contains detailed information about the game. #### Response Example ```json { "gameData": { "game": { "pk": 534196, "status": { "abstractGameState": "Final", "detailedState": "Final" } } } } ``` ``` -------------------------------- ### Get MLB Schedule Data with Python Source: https://github.com/zero-sum-seattle/python-mlb-statsapi/wiki/Data-Types:-Schedule Retrieves MLB schedule information for a given date using the python-mlb-statsapi library. This function takes a date string as input and returns a Schedule object containing details about games played on that date. It requires the mlbstatsapi library to be installed. The output includes the total number of items, events, games, and games in progress, along with a list of dates, each containing its own game information. ```python import mlbstatsapi mlb = mlbstatsapi.Mlb() schedule = mlb.get_schedule('2022-10-13') print(schedule) dates = schedule.dates for date in dates: for game in date.games: print(game.teams.home) print(game.teams.away) ``` -------------------------------- ### Get Game Play By Play Source: https://github.com/zero-sum-seattle/python-mlb-statsapi/wiki/Data-Types:-Game Retrieves the play-by-play data for a specific game. ```APIDOC ## GET /api/v1.1/game/{game_id}/playByPlay ### Description Returns the play-by-play data for a specific game. This endpoint can also return a snapshot of data at a specific timecode and allow filtering of returned fields. ### Method GET ### Endpoint `/api/v1.1/game/{game_id}/playByPlay` ### Parameters #### Path Parameters - **game_id** (string/int) - Required - Game id number #### Query Parameters - **timecode** (string) - Optional - Use this parameter to return a snapshot of the data at the specified time. Format: YYYYMMDD_HHMMSS - **fields** (string) - Optional - Comma delimited list of specific fields to be returned. Format: topLevelNode, childNode, attribute ### Request Example ```https https://statsapi.mlb.com/api/v1.1/game/534196/playByPlay?timecode=20230101_120000 ``` ### Response #### Success Response (200) - **playByPlay** (object) - Contains the play-by-play data for the game. #### Response Example ```json { "playByPlay": { "gameId": "534196", "plays": [] } } ``` ``` -------------------------------- ### Get Player and Team IDs and Stats (Python) Source: https://github.com/zero-sum-seattle/python-mlb-statsapi/blob/main/README.md Demonstrates how to retrieve player and team IDs by name, and then fetch their respective statistics. It covers getting hitting stats for a player and pitching stats for a team for a specific season. ```python import mlbstatsapi mlb = mlbstatsapi.Mlb() # Get Player ID and Stats player_id = mlb.get_people_id("Ty France") print(f"Ty France ID: {player_id}") stats = ['season', 'seasonAdvanced'] groups = ['hitting'] params = {'season': 2022} player_stats = mlb.get_player_stats(player_id[0], stats, groups, **params) print(f"Ty France Stats (2022): {player_stats}") # Get Team ID and Stats team_id = mlb.get_team_id("Oakland Athletics") print(f"Oakland Athletics ID: {team_id}") stats = ['season', 'seasonAdvanced'] groups = ['pitching'] params = {'season': 2022} team_stats = mlb.get_team_stats(team_id[0], stats, groups, **params) print(f"Oakland Athletics Pitching Stats (2022): {team_stats}") ``` -------------------------------- ### MLB Stats API Endpoint Example Source: https://github.com/zero-sum-seattle/python-mlb-statsapi/wiki/Data-Types:-Season An example of a direct API query to the MLB stats API to retrieve season data. This URL fetches all seasons for a specified sport ID (1 for MLB). ```http https://statsapi.mlb.com/api/v1/seasons?sportId=1 ``` -------------------------------- ### Get Venues Source: https://github.com/zero-sum-seattle/python-mlb-statsapi/wiki/Data-Types:-Venue Retrieves venue information based on specified IDs, sports, season, or fields. ```APIDOC ## GET /api/v1/venues ### Description Return all venues or filter by venueIds, sportIds, season, or specific fields. ### Method GET ### Endpoint /api/v1/venues ### Parameters #### Query Parameters - **venueIds** (int/list) - Optional - Insert venueId to return venue directorial information based venueId. - **sportIds** (string/int) - Optional - Insert sportIds to return venue directorial information based a given sport(s). For a list of all sports: https://statsapi.mlb.com/api/v1/sports - **season** (string/int) - Optional - Insert year to return venue directorial information for a given season. - **fields** (string) - Optional - Comma delimited list of specific fields to be returned. Format: topLevelNode, childNode, attribute ### Request Example ```json { "venueIds": [15] } ``` ### Response #### Success Response (200) - **id** (int) - The unique identifier for the venue. - **link** (string) - A relative link to the venue resource. - **name** (string) - The name of the venue. - **fieldInfo** (object) - Information about the field dimensions and characteristics. - **active** (boolean) - Indicates if the venue is currently active. #### Response Example ```json { "venues": [ { "id": 31, "link": "/api/v1/venues/31", "name": "PNC Park", "fieldInfo": { "capacity": 38753, "turfType": "Grass", "roofType": "Open", "leftLine": 325, "left": 389, "leftCenter": 410, "center": 399, "rightCenter": 375, "rightLine": 320 }, "active": true } ] } ``` ``` -------------------------------- ### GET /api/v1.1/game/{game_id}/feed/live Source: https://github.com/zero-sum-seattle/python-mlb-statsapi/wiki/Data-Types:-Game Retrieves live feed data for a specific game, including play-by-play and other game details. ```APIDOC ## GET /api/v1.1/game/{game_id}/feed/live ### Description Returns live feed data for a specific game, including play-by-play and other game details. This endpoint can also return a snapshot of data at a specific timecode and allow filtering of returned fields. ### Method GET ### Endpoint `/api/v1.1/game/{game_id}/feed/live` ### Parameters #### Path Parameters - **game_id** (string/int) - Required - Game id number #### Query Parameters - **timecode** (string) - Optional - Use this parameter to return a snapshot of the data at the specified time. Format: YYYYMMDD_HHMMSS - **fields** (string) - Optional - Comma delimited list of specific fields to be returned. Format: topLevelNode, childNode, attribute ### Request Example ```https https://statsapi.mlb.com/api/v1.1/game/534196/feed/live?timecode=20230101_120000&fields=game.teams ``` ### Response #### Success Response (200) - **gameData** (object) - Contains detailed information about the game. - **liveData** (object) - Contains live statistics and status of the game. #### Response Example ```json { "gameData": { "game": { "pk": 534196 } }, "liveData": { "plays": { "allPlays": [] } } } ``` ``` -------------------------------- ### Get Venue ID Source: https://github.com/zero-sum-seattle/python-mlb-statsapi/wiki/Data-Types:-Venue Retrieves the venue ID based on the venue name. ```APIDOC ## POST /api/v1/venues/getVenueId ### Description Return venue id based on venue name. ### Method POST ### Endpoint /api/v1/venues/getVenueId ### Parameters #### Request Body - **venue_name** (string) - Required - The name of the venue. - **search_key** (string) - Optional - The key to use for searching the venue name. ### Request Example ```json { "venue_name": "PNC Park" } ``` ### Response #### Success Response (200) - **venue_ids** (list) - A list of venue IDs matching the provided name. #### Response Example ```json { "venue_ids": [31] } ``` ``` -------------------------------- ### Get Team ID and Details using Python MLB Stats API Source: https://github.com/zero-sum-seattle/python-mlb-statsapi/wiki/Data-Types:-Team This snippet demonstrates how to get a team's ID and then retrieve detailed team information using the `mlbstatsapi` library. It requires initializing the `Mlb` client and then calling `get_team_id` followed by `get_team`. ```python >>> import mlbstatsapi >>> >>> mlb = mlbstatsapi.Mlb() >>> >>> team_id = mlb.get_team_id("Seattle Mariners") >>> print(team_id) [136] >>> >>> team = mlb.get_team(team_ids[0]) >>> print(team) Team(id=136, link=/api/v1/teams/136, name=Seattle Mariners, springleague=League(id=114, link=/api/v1/league/114, name=Cactus League), allstarstatus=N, season=2022, venue=Venue(id=680, link=/api/v1/venues/680, name=T-Mobile Park), springvenue=Venue(id=2530, link=/api/v1/venues/2530, name=None), teamcode=sea, filecode=sea, abbreviation=SEA, teamname=Mariners, locationname=Seattle, firstyearofplay=1977, league=League(id=103, link=/api/v1/league/103, name=American League), division=Division(id=200, link='/api/v1/divisions/200', name='American League West', season=None, nameshort=None, abbreviation=None, league=None, sport=None, haswildcard=None, sortorder=None, numplayoffteams=None, active=None), sport=Sport(id=1, link=/api/v1/sports/1), shortname=Seattle, franchisename=Seattle, clubname=Mariners, active=True) >>> ``` -------------------------------- ### Get Game Box Score Source: https://github.com/zero-sum-seattle/python-mlb-statsapi/wiki/Data-Types:-Game Retrieves the box score for a specific game. ```APIDOC ## GET /api/v1.1/game/{game_id}/boxscore ### Description Returns the box score for a specific game. This endpoint can also return a snapshot of data at a specific timecode and allow filtering of returned fields. ### Method GET ### Endpoint `/api/v1.1/game/{game_id}/boxscore` ### Parameters #### Path Parameters - **game_id** (string/int) - Required - Game id number #### Query Parameters - **timecode** (string) - Optional - Use this parameter to return a snapshot of the data at the specified time. Format: YYYYMMDD_HHMMSS - **fields** (string) - Optional - Comma delimited list of specific fields to be returned. Format: topLevelNode, childNode, attribute ### Request Example ```https https://statsapi.mlb.com/api/v1.1/game/534196/boxscore?timecode=20230101_120000 ``` ### Response #### Success Response (200) - **boxScore** (object) - Contains the box score data for the game. #### Response Example ```json { "boxScore": { "teams": { "home": { "players": [], "batters": [], "pitchers": [], "coaches": [] }, "away": { "players": [], "batters": [], "pitchers": [], "coaches": [] } } } } ``` ``` -------------------------------- ### Get Gamepace Metrics (Python) Source: https://github.com/zero-sum-seattle/python-mlb-statsapi/wiki/Data-Types:-Gamepace Retrieves pace of game metrics for a specified season. Supports filtering by team, league, sport, date, and other criteria. Requires the mlbstatsapi library. ```python import mlbstatsapi mlb = mlbstatsapi.Mlb() mlb.get_gamepace(season = 2018) ``` -------------------------------- ### GET /api/v1/gamePace Source: https://github.com/zero-sum-seattle/python-mlb-statsapi/wiki/Data-Types:-Gamepace Retrieves pace of game metrics for a specified season and optionally filters by team, league, date, and other criteria. ```APIDOC ## GET /api/v1/gamePace ### Description Returns a Gamepace. This endpoint allows you to fetch pace of game metrics for a given season and apply various filters. ### Method GET ### Endpoint /api/v1/gamePace ### Parameters #### Query Parameters - **season** (int) - Required - Insert year to return a directory of pace of game metrics for a given season. - **teamIds** (int) - Optional - Insert a teamIds to return directory of pace of game metrics for a given team. Format '110' or '110,147'. - **leagueId** (int) - Optional - Insert leagueIds to return a directory of pace of game metrics for a given league. Format '103' or '103,104'. - **leagueListId** (string) - Optional - Insert a unique League List Identifier to return a directory of pace of game metrics for a specific league listId. - **sportId** (int) - Optional - Insert a sportId to return a directory of pace of game metrics for a specific sport. Format '11' or '1,11'. - **gameType** (string) - Optional - Insert gameType(s) to return a directory of pace of game metrics for a specific gameType. For a list of all gameTypes, refer to the API documentation. - **date** (string) - Optional - Insert date to return a directory of pace of game metrics for a particular date range. Format: MM/DD/YYYY. Must be coupled with endDate. - **endDate** (string) - Optional - Insert date to return a directory of pace of game metrics for a particular date range. Format: MM/DD/YYYY. Must be coupled with startDate. - **venueIds** (int) - Optional - Insert venueId to return a directory of pace of game metrics for a particular venueId. - **orgType** (string) - Optional - Insert an orgType to return a directory of pace of game metrics based on team, league or sport. Available values : T- TEAM, L- LEAGUE, S- SPORT. - **includeChildren** (bool) - Optional - Insert includeChildren to return a directory of pace of game metrics for all child teams in a given parent sport. - **fields** (string) - Optional - Comma delimited list of specific fields to be returned. Format: topLevelNode, childNode, attr. ### Request Example ```https https://statsapi.mlb.com/api/v1/gamePace?season=2018&teamIds=110 ``` ### Response #### Success Response (200) - **gamePace** (array) - An array of game pace objects, each containing metrics like gameDuration, pitchDuration, and more. #### Response Example ```json { "gamePace": [ { "gameDuration": "3:05:15", "pitchDuration": "0:03:10", "teamId": 110, "teamName": "New York Yankees", "season": "2018" } ] } ``` ``` -------------------------------- ### Get Schedule Source: https://github.com/zero-sum-seattle/python-mlb-statsapi/wiki/Data-Types:-Schedule Retrieves schedule objects for a specified date or date range, with options to filter by sport, team, league, game Pks, venue IDs, and game types. ```APIDOC ## GET /api/v1/schedule ### Description Returns a schedule object for a given date or date range. ### Method GET ### Endpoint /api/v1/schedule ### Parameters #### Query Parameters - **date** (string) - Required - The specific date for which to retrieve the schedule (e.g., 'YYYY-MM-DD'). - **start_date** (string) - Required - The start date for the schedule range (e.g., 'YYYY-MM-DD'). - **end_date** (string) - Required - The end date for the schedule range (e.g., 'YYYY-MM-DD'). - **sport_id** (string/int) - Required - The ID of the sport for which to retrieve the schedule. Defaults to 1. - **team_id** (string/int) - Optional - The ID of the team for which to retrieve the schedule. - **leagueId** (string) - Required - The ID of the league to filter schedules. - **gamePks** (string) - Required - Comma-separated game primary keys to filter schedules. - **venueIds** (string) - Required - Comma-separated venue IDs to filter schedules. - **gameTypes** (string) - Required - Comma-separated game types to filter schedules. For a list of game types, see: https://statsapi.mlb.com/api/v1/gameTypes ### Request Example ```python import mlbstatsapi mlb = mlbstatsapi.Mlb() schedule = mlb.get_schedule('2022-10-13', sportId=1) print(schedule) ``` ### Response #### Success Response (200) - **totalItems** (int) - The total number of items in the schedule. - **totalEvents** (int) - The total number of events in the schedule. - **totalGames** (int) - The total number of games in the schedule. - **totalGamesInProgress** (int) - The total number of games currently in progress. - **dates** (array) - An array of date objects, each containing schedule information for that date. - **date** (string) - The date of the schedule information. - **totalGames** (int) - The total number of games on this date. - **games** (array) - An array of game objects for the date. - **gamePk** (int) - The primary key for the game. - **link** (string) - The API link to the game details. - **teams** (object) - Contains home and away team information. - **home** (object) - Home team details. - **team** (object) - Team information. - **id** (int) - Team ID. - **link** (string) - API link to the team. - **name** (string) - Team name. - **leagueRecord** (object) - Team's league record. - **wins** (int) - Number of wins. - **losses** (int) - Number of losses. - **pct** (string) - Winning percentage. - **away** (object) - Away team details (similar structure to home team). #### Response Example ```json { "totalItems": 2, "totalEvents": 0, "totalGames": 2, "totalGamesInProgress": 0, "dates": [ { "date": "2022-10-13", "totalGames": 2, "games": [ { "gamePk": 660829, "link": "/api/v1/game/660829/feed/live", "teams": { "away": { "leagueRecord": { "wins": 0, "losses": 2, "pct": ".000", "ties": null }, "score": 0, "team": { "id": 136, "name": "Seattle Mariners", "link": "/api/v1/teams/136" } }, "home": { "leagueRecord": { "wins": 2, "losses": 0, "pct": "1.000", "ties": null }, "score": 3, "team": { "id": 117, "name": "Houston Astros", "link": "/api/v1/teams/117" } } } } ] } ] } ``` ``` -------------------------------- ### Get Standings API Source: https://github.com/zero-sum-seattle/python-mlb-statsapi/wiki/Data-Types:-Standings Retrieves standings information for a specified league and season. Additional parameters can filter by standings type and date. ```APIDOC ## GET /api/v1/standings ### Description Retrieves standings information for a specified league and season. This endpoint allows fetching standings based on league ID, season, standings type, and a specific date. ### Method GET ### Endpoint /api/v1/standings ### Parameters #### Query Parameters - **leagueId** (string/int) - Required - Insert leagueId to return all standings based on a particular standingType for a specific league. - **season** (string) - Required - Insert year to return all standings based on a particular year. - **standingsTypes** (string) - Optional - Insert standingType to return all standings based on a particular year. Find standingTypes at https://statsapi.mlb.com/api/v1/standingsTypes - **date** (string) - Required - Insert date to return standing information for on a particular date. Format: MM/DD/YYYY ### Request Example ```json { "example": "https://statsapi.mlb.com/api/v1/standings?leagueId=103&season=2018&date=09/20/2023" } ``` ### Response #### Success Response (200) - **eliminationnumber** (str) - The number of games the team needs to win or the number of games their opponents need to lose in order to be eliminated from playoff contention. - **wildcardeliminationnumber** (str) - The number of games the team needs to win or the number of games their opponents need to lose in order to be eliminated from wild card contention. - **wins** (int) - The number of wins of the team. - **losses** (int) - The number of losses of the team. - **rundifferential** (int) - The run differential of the team (runs scored minus runs allowed). - **winningpercentage** (str) - The winning percentage of the team. - **wildcardrank** (str) - The rank of the team in the wild card race. - **wildcardleader** (bool) - A flag indicating whether the team is the leader in the wild card race. - **magicnumber** (str) - The number of games the team needs to win or the number of games their opponents need to lose in order to clinch a spot in the playoffs. - **clinchindicator** (str) - Clinch indicator. #### Response Example ```json { "example": "[Actual JSON response containing standings data]" } ``` ``` -------------------------------- ### Get Play-by-Play Data using Python MLB StatsAPI Source: https://github.com/zero-sum-seattle/python-mlb-statsapi/wiki/Data-Types:-Game Fetches the play-by-play data for a given MLB game ID. This function allows filtering by timecode and specific fields. ```Python import mlbstatsapi mlb = mlbstatsapi.Mlb() # Example: Get play-by-play for game ID 534196 play_by_play = mlb.get_game_play_by_play(game_id=534196) # Example: Get play-by-play at a specific timecode # play_by_play_at_time = mlb.get_game_play_by_play(game_id=534196, timecode='20230101_120000') # Example: Get specific fields # play_by_play_specific_fields = mlb.get_game_play_by_play(game_id=534196, fields='game,plays,result') ``` -------------------------------- ### Get All Leagues Source: https://github.com/zero-sum-seattle/python-mlb-statsapi/wiki/Data-Types:-League Retrieves a list of all available leagues, with options to filter by league ID, sport ID, or season. ```APIDOC ## GET /api/v1/leagues ### Description Returns a list of all available leagues. This endpoint allows filtering by specific league IDs, sport IDs, and seasons. ### Method GET ### Endpoint /api/v1/leagues ### Parameters #### Query Parameters - **leagueId** (string) - Optional - leagueId(s) to return league information for specific leagues. Format '103,104' - **sportId** (string) - Optional - Insert sportId to return league information for a specific sport. For a list of all sportIds: http://statsapi.mlb.com/api/v1/sports - **season** (string) - Optional - Insert year(s) to return league information for a specific season. - **fields** (string) - Optional - Comma delimited list of specific fields to be returned. Format: topLevelNode, childNode, attribute ### Request Example ```json { "leagueId": "103,104", "sportId": "1", "season": "2022" } ``` ### Response #### Success Response (200) - **Leagues** (array) - A list of league objects, each containing information about a specific league. #### Response Example ```json [ { "id": 103, "link": "/api/v1/league/103", "name": "American League", "abbreviation": "AL", "nameShort": "American", "seasonState": "postseason", "hasWildcard": true, "hasSplitSeason": false, "numGames": 162, "hasPlayoffPoints": false, "numTeams": 15, "numWildcardTeams": 2, "sport": { "id": 1, "link": "/api/v1/sports/1" }, "sortOrder": 21, "active": true } ] ``` ``` -------------------------------- ### Get Game Data using Python MLB StatsAPI Source: https://github.com/zero-sum-seattle/python-mlb-statsapi/wiki/Data-Types:-Game Retrieves general information for a specific MLB game using its unique ID. Supports optional parameters for specific timecodes and fields to be returned. ```Python import mlbstatsapi mlb = mlbstatsapi.Mlb() mlb.get_game(game_id = 534196) ``` -------------------------------- ### Get Specific MLB Season Details using Python mlbstatsapi Source: https://github.com/zero-sum-seattle/python-mlb-statsapi/wiki/Data-Types:-Season This example shows how to retrieve detailed information for a specific MLB season using its ID. After initializing the mlbstatsapi client, it fetches the season data for the year 2022 and prints the comprehensive Season object, which includes start and end dates for various parts of the season, wildcard status, and other relevant details. ```python >>> import mlbstatsapi >>> >>> mlb = mlbstatsapi.Mlb() >>> >>> season = mlb.get_season(season_id=2022) >>> >>> print(season) Season(seasonid=2022, haswildcard=True, preseasonstartdate=2022-01-01, preseasonenddate=2022-03-16, seasonstartdate=2022-03-17, springstartdate=2022-03-17, springenddate=2022-04-06, regularseasonstartdate=2022-04-07, lastdate1sthalf=2022-07-17, allstardate=2022-07-19, firstdate2ndhalf=2022-07-21, regularseasonenddate=2022-10-05, postseasonstartdate=2022-10-07, postseasonenddate=2022-11-05, seasonenddate=2022-11-05, offseasonstartdate=2022-11-06, offseasonenddate=2022-12-31, seasonlevelgamedaytype=P, gamelevelgamedaytype=P, qualifierplateappearances=3.1, qualifieroutspitched=6000.0) ``` -------------------------------- ### Get Team Information Source: https://github.com/zero-sum-seattle/python-mlb-statsapi/blob/main/README.md Retrieves detailed information about a specific MLB team using its ID. The process involves first getting the team's ID by its name, then using that ID to fetch the full team object. The example prints the team's ID and name. ```python import mlbstatsapi mlb = mlbstatsapi.Mlb() team_ids = mlb.get_team_id("Seattle Mariners") team_id = team_ids[0].id team = mlb.get_team(team_id) print(team.id) print(team.name) ``` -------------------------------- ### Get Game Pace Metrics Source: https://github.com/zero-sum-seattle/python-mlb-statsapi/blob/main/README.md Retrieves game pace metrics for a specified season. This function helps in understanding the tempo of games within a particular MLB season. It requires the `mlbstatsapi` library to be installed and configured. ```python import mlbstatsapi mlb = mlbstatsapi.Mlb() season = 2021 gamepace = mlb.get_gamepace(season) ``` -------------------------------- ### Initialize and Use Python MLB Stats API Source: https://github.com/zero-sum-seattle/python-mlb-statsapi/wiki/Home Demonstrates how to import the mlbstatsapi library, create an MLB instance, and use it to retrieve a team ID. This is a basic example of interacting with the API. ```python import mlbstatsapi mlb = mlbstatsapi.Mlb() oak_id = mlb.get_team_id("Oakland Athletics") print (oak_id) >>>[133] ``` -------------------------------- ### Fetch Player Stats with python-mlb-statsapi Source: https://github.com/zero-sum-seattle/python-mlb-statsapi/wiki/Data-Types:-Stats This Python code demonstrates how to fetch player statistics using the python-mlb-statsapi library. It retrieves both season and career hitting and pitching stats for a given player ID and iterates through the splits to print stat details. Dependencies include the 'mlbstatsapi' library. ```python >>> mlb = mlbstatsapi.Mlb() >>> >>> player_id = mlb.get_people_id("Ty France")[0] >>> >>> stats = ['season', 'career'] >>> groups = ['hitting', 'pitching'] >>> >>> stat_dict = mlb.get_player_stats(player_id, stats=stats, groups=groups ) >>> season_hitting_stat = stat_dict['hitting']['season'] >>> career_pitching_stat = stat_dict['pitching']['career'] >>> >>> for split in season_hitting_stat.splits: ... for k, v in split.stat.__dict__.items(): ... print(k, v) ... >>> for split in career_pitching_stat.splits: ... for k, v in split.stat.__dict__.items(): ... print(k, v) ... ``` -------------------------------- ### League Statistics Source: https://github.com/zero-sum-seattle/python-mlb-statsapi/wiki/Data-Types:-Gamepace Provides aggregate statistics for the league, including game counts, time metrics, and performance indicators. ```APIDOC ## League Statistics ### Description Retrieves aggregate statistics for the league, such as total games played, time metrics per game/pitch, and various performance ratios. ### Method GET ### Endpoint /api/v1/stats/league ### Query Parameters - **season** (str) - Optional - The season for which to retrieve stats (e.g., '2023'). ### Response #### Success Response (200) - **totalPitches** (int) - The total number of pitches thrown in the league. - **totalGames** (int) - The total number of games played in the league. - **total7InningGames** (int) - The total number of 7-inning games played in the league. - **total9InningGames** (int) - The total number of 9-inning games played in the league. - **totalExtraInningGames** (int) - The total number of extra inning games played in the league. - **timePerGame** (str) - The average time spent per game in the league. - **timePerPitch** (str) - The average time spent per pitch in the league. - **timePerHit** (str) - The average time spent per hit in the league. - **timePerRun** (str) - The average time spent per run scored in the league. - **timePerPlateAppearance** (str) - The average time spent per plate appearance in the league. - **timePer9Innings** (str) - The average time spent per 9 innings played in the league. - **timePer77PlateAppearances** (str) - The average time spent per 7-7 plate appearances in the league. - **totalExtraInningTime** (str) - The total amount of time spent on extra inning games in the league. - **timePer7InningGame** (str) - The average time spent per 7-inning game in the league. - **total7InningGamesCompletedEarly** (int) - The total number of 7-inning games completed early in the league. - **timePer7InningGameWithoutExtraInnings** (str) - The average time spent per 7-inning game without extra innings in the league. - **total7InningGamesScheduled** (int) - The total number of 7-inning games scheduled in the league. - **total7InningGamesWithoutExtraInnings** (int) - The total number of 7-inning games played without extra innings in the league. - **total9InningGamesCompletedEarly** (int) - The total number of 9-inning games completed early in the league. - **total9InningGamesWithoutExtraInnings** (int) - The total number of 9-inning games played without extra innings. - **total9InningGamesScheduled** (int) - The total number of 9 inning games scheduled. - **hitsPerRun** (float) - The number of hits per run. - **pitchesPerPitcher** (float) - The number of pitches thrown per pitcher. - **season** (str) - The season number. - **team** (object) - Information about the team. - **id** (int) - The ID number of the team. - **name** (str) - The name of the team. - **link** (str) - The API link of the team. - **league** (object) - Information about the league. - **id** (int) - The ID number of the league. - **name** (str) - The name of the league. - **link** (str) - The link of the league. - **sport** (object) - Information about the sport. - **id** (int) - The ID number of the sport. - **code** (str) - The sport code. - **link** (str) - The link of the sport. - **prportalcalculatedfields** (object) - Calculated fields for a league. - **total7InningGames** (int) - The total number of 7-inning games played. - **total9InningGames** (int) - The total number of 9-inning games played. - **totalExtraInningGames** (int) - The total number of extra-inning games played. ### Response Example ```json { "totalPitches": 123456, "totalGames": 2430, "total7InningGames": 50, "total9InningGames": 2380, "totalExtraInningGames": 100, "timePerGame": "02:45:00", "timePerPitch": "00:00:04", "timePerHit": "00:05:30", "timePerRun": "00:15:00", "timePerPlateAppearance": "00:04:00", "timePer9Innings": "02:40:00", "timePer77PlateAppearances": "00:03:50", "totalExtraInningTime": "100:00:00", "timePer7InningGame": "02:15:00", "total7InningGamesCompletedEarly": 5, "timePer7InningGameWithoutExtraInnings": "02:10:00", "total7InningGamesScheduled": 55, "total7InningGamesWithoutExtraInnings": 45, "total9InningGamesCompletedEarly": 10, "total9InningGamesWithoutExtraInnings": 2370, "total9InningGamesScheduled": 2380, "hitsPerRun": 1.5, "pitchesPerPitcher": 100.5, "season": "2023", "team": { "id": 15, "name": "Seattle Mariners", "link": "/api/v1/teams/15" }, "league": { "id": 1, "name": "MLB", "link": "/api/v1/league/1" }, "sport": { "id": 1, "code": "mlb", "link": "/api/v1/sports/1" }, "prportalcalculatedfields": { "total7InningGames": 50, "total9InningGames": 2380, "totalExtraInningGames": 100 } } ``` ``` -------------------------------- ### Stats Reference Source: https://github.com/zero-sum-seattle/python-mlb-statsapi/wiki/Data-Types:-Stats Provides a reference for available stat types and their descriptions. These can be used in conjunction with the `get_stats` endpoint. ```APIDOC ## Stats Reference ### Description This section details the available stat types that can be requested using the `get_stats` endpoint. Each stat type supports specific stat groups and may have associated parameter requirements. ### Stat Types - **season** (string) - A season stat, supports stat groups hitting, pitching, fielding, and catching. Requires use of season param. - **seasonAdvanced** (string) - A seasonAdvanced stat, supports stat groups hitting, pitching, fielding, and catching. - **career** (string) - A career stat, supports stat groups hitting, pitching, fielding, and catching. - **careerAdvanced** (string) - A career advanced stat, supports stat groups hitting, pitching, fielding, and catching. - **winLoss** (string) - A winLoss stat, supports stat groups hitting, pitching. - **winLossPlayoffs** (string) - A winloss playoff stat, supports stat groups hitting, pitching. - **homeAndAway** (string) - A homeandaway stat, supports stat groups hitting, pitching. - **homeAndAwayPlayoffs** (string) - A winLoss stat, supports stat groups hitting, pitching. - **careerRegularSeason** (string) - A homeandaway playoffs stat, supports stat groups hitting, pitching. - **careerPlayoffs** (string) - A career playoff stat, supports stat groups hitting, pitching. - **statsSingleSeason** (string) - A season stat, supports stat groups hitting, pitching, fielding, and catching. - **yearByYear** (string) - A yearbyyear stat, supports stat groups hitting, pitching, fielding, and catching. - **yearByYearPlayoffs** (string) - A yearByYearPlayoffs stat, supports stat groups hitting, pitching, fielding, and catching. - **opponentsFaced** (string) - A opponentsFaced stat, supports stat groups hitting, pitching. - **sabermetrics** (string) - A sabermetrics stat, supports stat groups hitting, pitching. - **gameLog** (string) - A gameLog stat, supports stat groups hitting, pitching. - **pitchLog** (string) - A pitchLog stat, supports stat groups hitting, pitching. - **playLog** (string) - A playLog stat, supports stat groups hitting, pitching. - **vsPlayer** (string) - A vsPlayer stat, supports stat groups hitting, pitching. Requires use of opposingPlayerId param. - **vsTeam** (string) - A vsTeam stat, supports stat groups hitting, pitching. Requires use of opposingTeamId param. ### Stat Groups - **hitting** (string) - Hitting stat group. - **pitching** (string) - Pitching stat group. - **fielding** (string) - Fielding stat group. - **catching** (string) - Catching stat group. ``` -------------------------------- ### Get Venue by Name (Python) Source: https://github.com/zero-sum-seattle/python-mlb-statsapi/blob/main/README.md Fetches venue details using the venue's name. It first gets the venue ID and then uses that ID to retrieve the venue object. The output includes the venue's ID and name. Requires `mlbstatsapi`. ```python >>> mlb = mlbstatsapi.Mlb() >>> vevue_ids = mlb.get_venue_id('PNC Park') >>> venue_id = venue_ids[0] >>> venue = mlb.get_team(venue.id) >>> print(venue.id) >>> print(venue.name) ```