Use Official MLB Team, Schedule & Stat Line Scraper with Python
Get baseball data from MLB's own public Stats API: season hitting, pitching, and fielding lines, team rosters, game schedules and scores, or live division standings. No authentication required.
1. Choose the data you need
Review the published README for supported collection modes, examples, and limits. The recipe below uses the current published input definition.
2. Prepare a source-based input
This JSON contains published prefills and required-field defaults. Review every value for your task before running it; it is not a promise of successful collection.
{
"gamePks": [],
"gameType": "R",
"includeStats": false,
"includeTeamTotals": false,
"leaderCategory": "homeRuns",
"leagueId": "both",
"maxItems": 3,
"mode": "getPlayers",
"playerIds": [],
"referenceType": "venues",
"rosterType": "active",
"seasons": [],
"statGroup": "hitting",
"statType": "season",
"teamIds": []
}
Download input.example.json and save your reviewed copy as input.json.
| Field | Type | Required | Description |
|---|---|---|---|
mode | string | required | What to fetch. Nine modes cover teams, players/rosters, player stats, game logs, schedules, standings, box scores, leaders, and reference data. |
seasons | array | optional | Season years, e.g. 2024 or 2025. Leave empty for the current season. Stats cover 1876 onward; schedules cover 1901 onward. Multiple seasons can be fetched in one run (mode=getTeams, getPlayers, getPlayerStats, getSchedule, getStandings, getLeaders, getReference). |
teamIds | array | optional | Filter by MLB team IDs (147 = Yankees), team names (Yankees), abbreviations (NYY), or team URLs (https://www.mlb.com/yankees). Leave empty for all teams. Used by teams, players, player stats, schedule, standings, box score, and leaders modes. |
playerIds | array | optional | MLB player IDs, e.g. 660271 for Shohei Ohtani. Used by players, player stats, and game log modes. Use Search query to find a player ID by name. |
gamePks | array | optional | MLB game IDs (gamePk), e.g. 822974. Used by mode=getBoxscore. Leave empty to derive games from seasons, dates, or teams. |
startDate | string | optional | Start date in YYYY-MM-DD format. Used by schedule, box score, and player stats (statType=byDateRange). A single date can be set in either date field. |
endDate | string | optional | End date in YYYY-MM-DD format. Used by schedule, box score, and player stats (statType=byDateRange). |
statGroup | string | optional | Which stat category to return for players, player stats, game logs, box scores, and leaders. |
statType | string | optional | Scope for mode=getPlayerStats. Season, career, and date-range stats work for the whole player pool; season-by-season, month, day-of-week, and home/away splits require playerIds or teamIds. |
rosterType | string | optional | Which roster to return for mode=getPlayers when teamIds is set. |
searchQuery | string | optional | Find players by name for mode=getPlayers, e.g. Ohtani or Aaron Judge. Returns up to 50 matching players. |
leagueId | string | optional | Filter standings and leaders to the American League, National League, or both. |
gameType | string | optional | Filter games and stats by game type. Regular season is R; other codes include spring training (S), wild card (F), division series (D), league championship (L), World Series (W), and All-Star (A). |
leaderCategory | string | optional | Stat category for mode=getLeaders. Choose a category that belongs to the selected stat group, e.g. homeRuns, battingAverage, or runsBattedIn for hitting; earnedRunAverage, strikeouts, or saves for pitching; fieldingPercentage or errors for fielding. |
referenceType | string | optional | Which reference dataset to return for mode=getReference. |
includeStats | boolean | optional | For mode=getPlayers, attach each player's season stats for the selected stat group. |
includeTeamTotals | boolean | optional | For mode=getBoxscore, add one team-total record per side per game, including the inning-by-inning line score. |
maxItems | integer | optional | Hard cap on the number of records returned (1–10,000). |
3. Start an Actor run
Set APIFY_TOKEN in your environment. Python 3.10 or newer is sufficient; this recipe uses no third-party packages.
Execution may incur charges. Review current pricing on Apify. The request asks for a 120-second timeout and a charge limit; these settings are subject to Apify’s pricing and do not guarantee an all-inclusive spending cap.
import json
import os
import urllib.request
# Save the schema-derived example as input.json; review and edit it first.
with open("input.json", encoding="utf-8") as stream:
actor_input = json.load(stream)
token = os.environ["APIFY_TOKEN"]
request = urllib.request.Request(
"https://api.apify.com/v2/acts/rg2FBxNB1s8X13GRi/runs?timeout=120&maxTotalChargeUsd=0.50",
data=json.dumps(actor_input).encode("utf-8"),
headers={"Authorization": "Bearer " + token, "Content-Type": "application/json"},
method="POST",
)
# This starts a potentially billable run. Do not automatically retry this POST.
with urllib.request.urlopen(request, timeout=40) as response:
run = json.load(response)["data"]
print("Run ID:", run["id"])
print("Status:", run["status"])
# Inspect and download results in Apify Console once the run succeeds.
4. Inspect the actual results
Open the run in Apify Console and wait for a successful completion. Use the published output schema to locate results and the dataset schema to understand declared views. Missing or optional record fields must not be treated as guaranteed values.
One record per MLB team, player, stat line, game, standing, leader, box-score line, venue, league, division, or season calendar row, sourced from the official MLB Stats API.
Questions before you run
Which inputs are required?
The published required fields are mode
What does this guide verify?
The fields, prefills, and schema links are rendered from the published build. This is a usage recipe, not a paid live extraction test. Source availability and collection results can vary.
What if the run request times out?
Check Apify Console before retrying. The first request may already have created a run. Do not automatically repeat a run-creation POST.
Generated from source build cCMwmOrwZkNoObEE3 and its README and schemas. Source changes regenerate this guide; no third-party editorial claims are inferred.