# MLB Stats Scraper (`crawlerbros/mlb-stats-scraper`) Actor

Scrape the official MLB Stats API, comprehensive baseball data including teams, players, schedules, standings, and detailed statistics. Official MLB data source, no authentication required.

- **URL**: https://apify.com/crawlerbros/mlb-stats-scraper.md
- **Developed by:** [Crawler Bros](https://apify.com/crawlerbros) (community)
- **Categories:** Developer tools, Automation, Other
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 7 bookmarks
- **User rating**: 5.00 out of 5 stars

## Pricing

from $3.00 / 1,000 results

This Actor is paid per event and usage. You are charged both the fixed price for specific events and for Apify platform usage.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

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

## What's an Apify Actor?

Actors are a software tools running on the Apify platform, for all kinds of web data extraction and automation use cases.
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.

In JavaScript/TypeScript projects, use official [JavaScript/TypeScript client](https://docs.apify.com/api/client/js.md):

```bash
npm install apify-client
```

In Python projects, use official [Python client library](https://docs.apify.com/api/client/python.md):

```bash
pip install apify-client
```

In shell scripts, use [Apify CLI](https://docs.apify.com/cli/docs.md):

````bash
# MacOS / Linux
curl -fsSL https://apify.com/install-cli.sh | bash
# Windows
irm https://apify.com/install-cli.ps1 | iex
```bash

In AI frameworks, you might use the [Apify MCP server](https://docs.apify.com/platform/integrations/mcp.md).

If your project is in a different language, use 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

Access comprehensive baseball data from the **official MLB Stats API** — teams, players, schedules, standings, and detailed statistics. No authentication required. Official MLB data source updated in real-time during the season.

### Features

- **Teams** — list all 30 MLB teams with league, division, venue, and location info
- **Players** — get full rosters for any team, or all active players in the league
- **Schedule** — fetch game schedules by date, date range, or team
- **Standings** — current division standings with win/loss records, GB, and streak info
- **Player Stats** — hitting, pitching, or fielding statistics for any player by season
- **Game Details** — detailed linescore, run/hit/error totals, and inning-by-inning data for any game

### Input Parameters

| Parameter | Type | Description |
|-----------|------|-------------|
| `mode` | Select | `teams`, `players`, `schedule`, `standings`, `playerStats`, `gameDetails` |
| `season` | Integer | MLB season year (default: current year) |
| `teamId` | Integer | MLB team ID (e.g. 147 = Yankees, 111 = Red Sox) |
| `playerId` | Integer | MLB player ID (e.g. 660271 = Juan Soto) |
| `gamePk` | Integer | Game primary key (required for mode=gameDetails) |
| `date` | Text | Game date as YYYY-MM-DD (mode=schedule) |
| `fromDate` | Text | Start date for schedule range |
| `toDate` | Text | End date for schedule range |
| `leagueId` | Select | `AL`, `NL`, or `both` (mode=standings) |
| `statGroup` | Select | `hitting`, `pitching`, or `fielding` (mode=playerStats) |
| `gameType` | Select | `R` (Regular), `S` (Spring), `P` (Playoffs), `W` (World Series), etc. |
| `maxItems` | Integer | Maximum records to return (1–10,000, default 100) |

### Output Fields

#### Teams mode
| Field | Description |
|-------|-------------|
| `teamId` | MLB team identifier |
| `name` | Full team name |
| `abbreviation` | 2–3 letter abbreviation (e.g. NYY) |
| `teamName` | Short team name (e.g. Yankees) |
| `locationName` | City/location name |
| `leagueName` | American League or National League |
| `divisionName` | Division name (e.g. AL East) |
| `venueName` | Home stadium name |
| `active` | Whether the team is active |
| `mlbUrl` | Official MLB team page URL |

#### Players mode
| Field | Description |
|-------|-------------|
| `playerId` | MLB player identifier |
| `fullName` | Player's full name |
| `primaryNumber` | Jersey number |
| `birthDate` | Date of birth |
| `birthCity` | City of birth |
| `birthCountry` | Country of birth |
| `height` | Player height |
| `weight` | Player weight (lbs) |
| `primaryPosition` | Primary fielding position |
| `currentTeam` | Current team name |
| `batSide` | Batting side (Left/Right/Switch) |
| `pitchHand` | Throwing hand |
| `mlbUrl` | Official MLB player page URL |

#### Schedule mode
| Field | Description |
|-------|-------------|
| `gamePk` | Game primary key |
| `gameDate` | Full game date/time (ISO 8601) |
| `homeTeam` | Home team name |
| `awayTeam` | Away team name |
| `homeScore` | Home team runs scored |
| `awayScore` | Away team runs scored |
| `status` | Game status (Final, In Progress, Postponed, etc.) |
| `venue` | Stadium name |

#### Standings mode
| Field | Description |
|-------|-------------|
| `teamName` | Team name |
| `divisionName` | Division name |
| `wins` | Total wins |
| `losses` | Total losses |
| `pct` | Winning percentage |
| `divisionRank` | Rank within division |
| `gamesBack` | Games behind division leader |
| `streakCode` | Current streak (e.g. W5, L2) |

#### Player Stats mode
| Field | Description |
|-------|-------------|
| `playerId` | MLB player identifier |
| `season` | Season year |
| `gamesPlayed` | Games played |
| `homeRuns` | Home runs |
| `rbi` | Runs batted in |
| `avg` | Batting average |
| `obp` | On-base percentage |
| `slg` | Slugging percentage |
| `ops` | On-base plus slugging |
| `era` | Earned run average (pitchers) |
| `whip` | Walks plus hits per inning pitched |
| `wins` | Pitcher wins |

### Example Use Cases

**Get all 30 MLB teams for 2024:**
```json
{
  "mode": "teams",
  "season": 2024,
  "maxItems": 30
}
````

**Get New York Yankees roster:**

```json
{
  "mode": "players",
  "teamId": 147,
  "season": 2024
}
```

**Get July 4th 2024 schedule:**

```json
{
  "mode": "schedule",
  "date": "2024-07-04",
  "gameType": "R"
}
```

**Get 2024 AL East standings:**

```json
{
  "mode": "standings",
  "season": 2024,
  "leagueId": "AL"
}
```

**Get Juan Soto 2024 hitting stats:**

```json
{
  "mode": "playerStats",
  "playerId": 660271,
  "season": 2024,
  "statGroup": "hitting"
}
```

### Common Team IDs

| Team | ID | Team | ID |
|------|----|------|----|
| New York Yankees | 147 | New York Mets | 121 |
| Boston Red Sox | 111 | Los Angeles Dodgers | 119 |
| Chicago Cubs | 112 | San Francisco Giants | 137 |
| Houston Astros | 117 | Atlanta Braves | 144 |
| Los Angeles Angels | 108 | Philadelphia Phillies | 143 |

### Data Source

All data is sourced from the [official MLB Stats API](https://statsapi.mlb.com/api/v1/) — the same data feed used by MLB.com, the Statcast system, and major sports analytics platforms. The API is completely free and requires no authentication.

### FAQs

**Q: How current is the data?**
A: Schedule, scores, and standings update in real-time during games. Player stats may have slight delays.

**Q: What seasons are available?**
A: Historical data goes back to 1876. Not all stats are available for very old seasons.

**Q: How do I find a player's ID?**
A: Use mode=players to list all players. Player IDs are also visible in MLB.com profile URLs (e.g. mlb.com/player/660271).

**Q: What game types are available?**
A: Regular Season (R), Spring Training (S), Playoffs (P), World Series (W), League Championship (L), and All-Star (A).

**Q: Is there a cost to use this scraper?**
A: No. The official MLB Stats API is free and public. This scraper uses only standard Apify datacenter proxies (included in the free tier).

**Q: Can I get historical standings?**
A: Yes — provide the `season` parameter (e.g. `season: 2020`) for any past season.

# Actor input Schema

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

What to fetch from the MLB Stats API.

## `season` (type: `integer`):

MLB season year (e.g. 2024). Defaults to current season.

## `teamId` (type: `integer`):

MLB team ID (e.g. 147 = Yankees, 111 = Red Sox). Used in modes: players, schedule.

## `playerId` (type: `integer`):

MLB player ID (e.g. 660271 = Juan Soto). Required for mode=playerStats.

## `gamePk` (type: `integer`):

MLB game primary key (e.g. 745456). Required for mode=gameDetails.

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

Game date for mode=schedule (e.g. '2024-07-04').

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

Start date for schedule range (e.g. '2024-04-01').

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

End date for schedule range (e.g. '2024-09-30').

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

Filter standings by league (mode=standings).

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

Type of stats to retrieve (mode=playerStats).

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

Filter schedule by game type.

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

Hard cap on emitted records.

## Actor input object example

```json
{
  "mode": "teams",
  "season": 2024,
  "leagueId": "both",
  "statGroup": "hitting",
  "gameType": "R",
  "maxItems": 100
}
```

# Actor output Schema

## `mlbData` (type: `string`):

Dataset containing all scraped MLB records (teams, players, games, standings, or stats).

# 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 = {
    "mode": "teams",
    "season": 2024,
    "leagueId": "both",
    "statGroup": "hitting",
    "gameType": "R",
    "maxItems": 100
};

// Run the Actor and wait for it to finish
const run = await client.actor("crawlerbros/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 = {
    "mode": "teams",
    "season": 2024,
    "leagueId": "both",
    "statGroup": "hitting",
    "gameType": "R",
    "maxItems": 100,
}

# Run the Actor and wait for it to finish
run = client.actor("crawlerbros/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 '{
  "mode": "teams",
  "season": 2024,
  "leagueId": "both",
  "statGroup": "hitting",
  "gameType": "R",
  "maxItems": 100
}' |
apify call crawlerbros/mlb-stats-scraper --silent --output-dataset

```

## MCP server setup

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

```

## OpenAPI specification

```json
{
    "openapi": "3.0.1",
    "info": {
        "title": "MLB Stats Scraper",
        "description": "Scrape the official MLB Stats API, comprehensive baseball data including teams, players, schedules, standings, and detailed statistics. Official MLB data source, no authentication required.",
        "version": "1.0",
        "x-build-id": "kVnBk2RVseqwfm3to"
    },
    "servers": [
        {
            "url": "https://api.apify.com/v2"
        }
    ],
    "paths": {
        "/acts/crawlerbros~mlb-stats-scraper/run-sync-get-dataset-items": {
            "post": {
                "operationId": "run-sync-get-dataset-items-crawlerbros-mlb-stats-scraper",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for its completion, and returns Actor's dataset items in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        },
        "/acts/crawlerbros~mlb-stats-scraper/runs": {
            "post": {
                "operationId": "runs-sync-crawlerbros-mlb-stats-scraper",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor and returns information about the initiated run in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK",
                        "content": {
                            "application/json": {
                                "schema": {
                                    "$ref": "#/components/schemas/runsResponseSchema"
                                }
                            }
                        }
                    }
                }
            }
        },
        "/acts/crawlerbros~mlb-stats-scraper/run-sync": {
            "post": {
                "operationId": "run-sync-crawlerbros-mlb-stats-scraper",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for completion, and returns the OUTPUT from Key-value store in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        }
    },
    "components": {
        "schemas": {
            "inputSchema": {
                "type": "object",
                "required": [
                    "mode"
                ],
                "properties": {
                    "mode": {
                        "title": "Mode",
                        "enum": [
                            "teams",
                            "players",
                            "schedule",
                            "standings",
                            "playerStats",
                            "gameDetails"
                        ],
                        "type": "string",
                        "description": "What to fetch from the MLB Stats API.",
                        "default": "teams"
                    },
                    "season": {
                        "title": "Season (year)",
                        "minimum": 1876,
                        "maximum": 2100,
                        "type": "integer",
                        "description": "MLB season year (e.g. 2024). Defaults to current season.",
                        "default": 2024
                    },
                    "teamId": {
                        "title": "Team ID",
                        "minimum": 100,
                        "maximum": 999,
                        "type": "integer",
                        "description": "MLB team ID (e.g. 147 = Yankees, 111 = Red Sox). Used in modes: players, schedule."
                    },
                    "playerId": {
                        "title": "Player ID",
                        "minimum": 100000,
                        "maximum": 9999999,
                        "type": "integer",
                        "description": "MLB player ID (e.g. 660271 = Juan Soto). Required for mode=playerStats."
                    },
                    "gamePk": {
                        "title": "Game PK",
                        "minimum": 1,
                        "maximum": 999999999,
                        "type": "integer",
                        "description": "MLB game primary key (e.g. 745456). Required for mode=gameDetails."
                    },
                    "date": {
                        "title": "Date (YYYY-MM-DD)",
                        "type": "string",
                        "description": "Game date for mode=schedule (e.g. '2024-07-04')."
                    },
                    "fromDate": {
                        "title": "From date (YYYY-MM-DD)",
                        "type": "string",
                        "description": "Start date for schedule range (e.g. '2024-04-01')."
                    },
                    "toDate": {
                        "title": "To date (YYYY-MM-DD)",
                        "type": "string",
                        "description": "End date for schedule range (e.g. '2024-09-30')."
                    },
                    "leagueId": {
                        "title": "League",
                        "enum": [
                            "both",
                            "AL",
                            "NL"
                        ],
                        "type": "string",
                        "description": "Filter standings by league (mode=standings).",
                        "default": "both"
                    },
                    "statGroup": {
                        "title": "Stat group",
                        "enum": [
                            "hitting",
                            "pitching",
                            "fielding"
                        ],
                        "type": "string",
                        "description": "Type of stats to retrieve (mode=playerStats).",
                        "default": "hitting"
                    },
                    "gameType": {
                        "title": "Game type",
                        "enum": [
                            "R",
                            "S",
                            "P",
                            "W",
                            "L",
                            "A"
                        ],
                        "type": "string",
                        "description": "Filter schedule by game type.",
                        "default": "R"
                    },
                    "maxItems": {
                        "title": "Max items",
                        "minimum": 1,
                        "maximum": 10000,
                        "type": "integer",
                        "description": "Hard cap on emitted records.",
                        "default": 100
                    }
                }
            },
            "runsResponseSchema": {
                "type": "object",
                "properties": {
                    "data": {
                        "type": "object",
                        "properties": {
                            "id": {
                                "type": "string"
                            },
                            "actId": {
                                "type": "string"
                            },
                            "userId": {
                                "type": "string"
                            },
                            "startedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "finishedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "status": {
                                "type": "string",
                                "example": "READY"
                            },
                            "meta": {
                                "type": "object",
                                "properties": {
                                    "origin": {
                                        "type": "string",
                                        "example": "API"
                                    },
                                    "userAgent": {
                                        "type": "string"
                                    }
                                }
                            },
                            "stats": {
                                "type": "object",
                                "properties": {
                                    "inputBodyLen": {
                                        "type": "integer",
                                        "example": 2000
                                    },
                                    "rebootCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "restartCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "resurrectCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "computeUnits": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "options": {
                                "type": "object",
                                "properties": {
                                    "build": {
                                        "type": "string",
                                        "example": "latest"
                                    },
                                    "timeoutSecs": {
                                        "type": "integer",
                                        "example": 300
                                    },
                                    "memoryMbytes": {
                                        "type": "integer",
                                        "example": 1024
                                    },
                                    "diskMbytes": {
                                        "type": "integer",
                                        "example": 2048
                                    }
                                }
                            },
                            "buildId": {
                                "type": "string"
                            },
                            "defaultKeyValueStoreId": {
                                "type": "string"
                            },
                            "defaultDatasetId": {
                                "type": "string"
                            },
                            "defaultRequestQueueId": {
                                "type": "string"
                            },
                            "buildNumber": {
                                "type": "string",
                                "example": "1.0.0"
                            },
                            "containerUrl": {
                                "type": "string"
                            },
                            "usage": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "integer",
                                        "example": 1
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "usageTotalUsd": {
                                "type": "number",
                                "example": 0.00005
                            },
                            "usageUsd": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "number",
                                        "example": 0.00005
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
```
