# MLB Stats Scraper — Teams, Players, Games, Standings & Leaders (`memo23/mlb-stats-scraper`) Actor

MLB scraper on the official Stats API — teams, full rosters with player bios, schedules and results, live standings, season hitting/pitching/fielding stats, game box scores and league leaders. Multi-season in one run, flat rows for CSV. No key, no proxies, from $0.004 per row.

- **URL**: https://apify.com/memo23/mlb-stats-scraper.md
- **Developed by:** [Muhamed Didovic](https://apify.com/memo23) (community)
- **Categories:** Automation, AI, Agents
- **Stats:** 12 total users, 11 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $4.00 / 1,000 results

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/platform/actors/running/actors-in-store#pay-per-event

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.
Actors are written with capital "A".

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.
The best way to integrate Actors is as follows.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).

# README

## MLB Stats Scraper — Teams, Players, Games, Standings & Leaders

Pull **Major League Baseball data straight from the official MLB Stats API** — all 30 teams, full rosters with player bios, schedules and final scores, live division standings, season hitting/pitching/fielding lines, game box scores, and league leaderboards. Seven modes, one actor. No API key, no login, no proxies. Rows come out flat, so the same record reads cleanly as JSON or as a CSV column set.

### Why use this scraper?

- **Seven datasets in one actor** — teams, players, schedule, standings, player stats, game details, leaders. No juggling separate scrapers per endpoint.
- **Several seasons in a single run** — ask for `[2024, 2025, 2026]` and get all three in one dataset, tagged by season. Historical data reaches back to 1876.
- **Player bios included** — roster rows are hydrated with birth date, age, birthplace, height, weight, bats/throws and MLB debut, not just a name and a jersey number.
- **Flat rows, not nested blobs** — the API buries values four levels deep (`teams.home.team.name`); every row here is one level, so Excel and CSV work without post-processing.
- **League leaderboards** — home runs, batting average, ERA, strikeouts, saves and any other category the API exposes, ranked with player, team and value.
- **Official source** — data comes from MLB's own statsapi.mlb.com, updated live during the season.
- **No proxies, no keys** — the endpoints are public, which keeps runs fast and cheap.

### Supported modes

| Mode | One row per | Key fields |
|---|---|---|
| `teams` | Club | id, name, abbreviation, league, division, venue, first year of play |
| `players` | Player on a roster | name, jersey, position, status, birth date, age, birthplace, height, weight, bats/throws, debut |
| `schedule` | Game | gamePk, date, status, both teams, both scores, winner, venue, records, series info |
| `standings` | Team season record | wins, losses, pct, games back, division/league rank, streak, run differential, magic number |
| `playerStats` | Player season line | full hitting/pitching/fielding stat block (40+ metrics), team, games played |
| `gameDetails` | Team in a game | runs, hits, doubles, triples, HR, RBI, walks, strikeouts, errors, innings pitched, ERA inputs |
| `leaders` | Ranked player | category, rank, value, player, team, league |

### Use cases

| Audience | What they use it for |
|---|---|
| Fantasy baseball tools | Nightly stat pulls for scoring, projections and waiver-wire ranking |
| Sports betting & modelling | Historical results, run differentials and box scores for backtesting |
| Sports media & newsletters | Standings tables, leaderboards and game recaps without manual entry |
| Data science / ML | Multi-season training sets with consistent schemas |
| Apps & dashboards | A dependable feed for schedule widgets, team pages and player cards |

### How it works

1. **Pick a mode** — teams, players, schedule, standings, player stats, game details or leaders.
2. **Set the scope** — seasons, and optionally team ids, player ids, game ids, a date or a date range.
3. **The actor calls the official API** — requests run in a bounded pool with retry and backoff, so a transient error never fails the run.
4. **Rows are flattened** — nested API objects become one-level records with domain-correct names.
5. **Emit** — one clean row per entity to your dataset, exportable as JSON, CSV or Excel.

### Input configuration

| Field | Type | Default | Notes |
|---|---|---|---|
| `mode` | select | `teams` | Which dataset to pull (see the table above) |
| `seasons` | array | current year | One or more seasons, e.g. `["2026"]` or `["2024","2025"]` |
| `teamIds` | array | all 30 | MLB team ids, e.g. `119` Dodgers, `147` Yankees. Run `teams` once to collect them |
| `playerIds` | array | rosters | Player-stats mode: specific players by person id |
| `gamePks` | array | schedule | Game-details mode: specific games by gamePk |
| `date` / `fromDate` / `toDate` | string | — | `YYYY-MM-DD`; a single day or a range for schedule and game details |
| `leagueId` | select | `both` | Standings: American, National or both |
| `statGroup` | select | `hitting` | Player stats and leaders: hitting, pitching or fielding |
| `gameType` | select | `R` | Regular season, spring training, postseason, World Series, LCS or All-Star |
| `leaderCategories` | array | `homeRuns` | Leaders: e.g. `battingAverage`, `earnedRunAverage`, `strikeouts`, `saves` |
| `maxItems` | integer | 1000 | Hard cap on rows returned and charged |

#### Example input

```json
{
    "mode": "playerStats",
    "seasons": ["2026"],
    "teamIds": ["119"],
    "statGroup": "hitting",
    "maxItems": 40
}
```

### Output samples

**Standings row**

```json
{
    "recordType": "standing",
    "season": 2026,
    "teamId": 139,
    "team": "Rays",
    "league": "American League",
    "division": "American League East",
    "wins": 66,
    "losses": 46,
    "winningPercentage": ".589",
    "gamesBack": "-",
    "divisionRank": 1,
    "streak": "W1",
    "runDifferential": 88,
    "magicNumber": "E"
}
```

**Game row**

```json
{
    "recordType": "game",
    "gamePk": 823431,
    "officialDate": "2026-08-03",
    "status": "Final",
    "awayTeam": "Washington Nationals",
    "awayScore": 3,
    "homeTeam": "Philadelphia Phillies",
    "homeScore": 6,
    "winningTeam": "Philadelphia Phillies",
    "venueName": "Citizens Bank Park",
    "url": "https://www.mlb.com/gameday/823431"
}
```

### Key output fields

| Field | Meaning |
|---|---|
| `recordType` | Which mode produced the row — handy when you merge several runs |
| `teamId` / `playerId` / `gamePk` | Official MLB ids, stable across seasons and joins |
| `season` | The season the row belongs to, so multi-season runs stay separable |
| `url` | Deep link to the team, player or gameday page on mlb.com |
| `winningTeam` | Computed from the final score, `null` while a game is unfinished |
| `statGroup` | Hitting, pitching or fielding — set on stat and leader rows |

### FAQ

**What does a run cost?** $0.004 per row plus a $0.005 run start. All 30 teams is about $0.13; a full league leaderboard costs a few cents.

**Do I need an API key or proxies?** No. The MLB Stats API is public, so runs need no key, no login and no proxy spend.

**How far back does the data go?** To 1876 for most modes. Coverage of individual stat categories thins out for the earliest seasons — that's the source data, not the actor.

**How do I find a team or player id?** Run `teams` once for every club id, or `players` for a roster with person ids. Then pass them into the other modes.

**Can I pull a whole season of games?** Yes — choose `schedule`, set the season, and leave the date fields empty. Raise `maxItems` since a full season is about 2,430 games.

**Is this affiliated with MLB?** No. It reads a public endpoint that MLB operates. See the disclaimer below.

### Support

- **Found a bug or need another field?** Open a ticket on the **Issues** tab of this actor.
- Author's website: [muhamed-didovic.github.io](https://muhamed-didovic.github.io/)
- Email: <muhamed.didovic@gmail.com>
- More scrapers: [apify.com/memo23](https://apify.com/memo23)

### Additional Services

- Request customization or a whole dataset: <muhamed.didovic@gmail.com>
- For API access to this scraper (no Apify fee, usage fee only), get in touch at the same address.

### Explore More Scrapers

Other data feeds from the same author: [Gumroad](https://apify.com/memo23/gumroad-scraper), [Etsy](https://apify.com/memo23/etsy-scraper), [OfferUp](https://apify.com/memo23/offerup-marketplace-scraper), [Clutch.co](https://apify.com/memo23/apify-clutch-cheerio), [ZipRecruiter](https://apify.com/memo23/ziprecruiter-scraper-ppe), [Instagram Transcript](https://apify.com/memo23/instagram-transcript-cheerio) — full catalog at [apify.com/memo23](https://apify.com/memo23).

### ⚠️ Disclaimer

This actor reads publicly available data from MLB's own statsapi.mlb.com endpoints. It is not affiliated with, endorsed by, or sponsored by Major League Baseball or any MLB club. All trademarks belong to their respective owners. MLB data is provided for informational purposes; check MLB's terms before redistributing it commercially, and use the extracted data in compliance with applicable law.

### SEO Keywords

MLB scraper, MLB Stats API, baseball data scraper, MLB standings scraper, MLB schedule scraper, baseball statistics API, MLB player stats, MLB box score scraper, league leaders baseball, fantasy baseball data, sports data scraper, MLB roster scraper, baseball analytics dataset, MLB game results, sabermetrics data

# Actor input Schema

## `mode` (type: `string`):

Which dataset to pull. Teams = all 30 clubs. Players = full rosters with bios. Schedule = games and results. Standings = division tables. Player stats = season hitting/pitching/fielding lines. Game details = box-score totals per team. Leaders = league leaderboards by category.

## `seasons` (type: `array`):

One or more seasons to pull, e.g. \[2026] or \[2024, 2025, 2026]. Defaults to the current season. Historical data goes back to 1876.

## `teamIds` (type: `array`):

Limit to specific teams by MLB team id, e.g. 119 (Dodgers), 147 (Yankees), 111 (Red Sox). Leave empty for all 30 teams. Run the Teams mode once to get every id.

## `playerIds` (type: `array`):

Player stats mode: pull only these players by MLB person id (e.g. 660271 for Shohei Ohtani). Leave empty to use the rosters of the selected teams.

## `gamePks` (type: `array`):

Game details mode: pull only these games by gamePk. Leave empty to use the schedule for the chosen date, range or season.

## `date` (type: `string`):

Schedule / game details for one day, in YYYY-MM-DD format, e.g. 2026-08-03.

## `fromDate` (type: `string`):

Start of a date range (YYYY-MM-DD). Use together with To date.

## `toDate` (type: `string`):

End of a date range (YYYY-MM-DD). Use together with From date.

## `leagueId` (type: `string`):

Standings mode: restrict to the American or National League.

## `statGroup` (type: `string`):

Which statistics to return in Player stats and Leaders modes.

## `gameType` (type: `string`):

Which games to include in Schedule and Game details modes.

## `leaderCategories` (type: `array`):

Leaders mode: which leaderboards to pull, e.g. homeRuns, battingAverage, runsBattedIn, stolenBases, strikeouts, earnedRunAverage, wins, saves.

## `maxItems` (type: `integer`):

Hard cap on how many rows the run returns (and is charged for).

## Actor input object example

```json
{
  "mode": "teams",
  "seasons": [
    "2026"
  ],
  "leagueId": "both",
  "statGroup": "hitting",
  "gameType": "R",
  "leaderCategories": [
    "homeRuns"
  ],
  "maxItems": 1000
}
```

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "seasons": [
        "2026"
    ],
    "leaderCategories": [
        "homeRuns"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("memo23/mlb-stats-scraper").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "seasons": ["2026"],
    "leaderCategories": ["homeRuns"],
}

# Run the Actor and wait for it to finish
run = client.actor("memo23/mlb-stats-scraper").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print("💾 Check your data here: https://console.apify.com/storage/datasets/" + run["defaultDatasetId"])
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "seasons": [
    "2026"
  ],
  "leaderCategories": [
    "homeRuns"
  ]
}' |
apify call memo23/mlb-stats-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "command": "npx",
            "args": [
                "mcp-remote",
                "https://mcp.apify.com/?tools=memo23/mlb-stats-scraper",
                "--header",
                "Authorization: Bearer <YOUR_API_TOKEN>"
            ]
        }
    }
}

```

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/Y7sIohmZYz8fd5O0V/builds/iDn8Svaw78OeCmWWz/openapi.json
