# MLB Stats API (`gentle_cloud/mlb-stats-api`) Actor

Extract baseball data from MLB official free API. Get teams, standings, game schedules/scores, and detailed player statistics for any season.

- **URL**: https://apify.com/gentle_cloud/mlb-stats-api.md
- **Developed by:** [Monkey Coder](https://apify.com/gentle_cloud) (community)
- **Categories:** Developer tools, Other
- **Features:** Limited permissions
- **Stats:** 120 total users, 2 monthly users, 100.0% runs succeeded, 1 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.50 / 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.

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

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
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.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## 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.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## ⚾ MLB Stats API

Extract comprehensive baseball data from MLB's official free API. Get teams, standings, game schedules with scores, and detailed player statistics for any season.

### Why use this Actor

Use this Actor when you need structured MLB data without wrestling with unofficial scrapers or brittle HTML parsing. It’s useful for research, dashboards, sports monitoring, and quick season comparisons.

### 🔧 Features

- **Teams** — List all 30 MLB teams with venue, league, division info
- **Standings** — Division standings with W/L record, winning percentage, games back, run differential
- **Schedule / Scores** — Game schedules and final scores for any date or full season
- **Player Stats** — Detailed hitting and pitching statistics for any team's roster

### 📊 Modes

| Mode | Description | Key Fields |
|------|-------------|------------|
| `teams` | All 30 MLB teams | name, abbreviation, league, division, venue |
| `standings` | Division standings | team, wins, losses, pct, games_back, streak |
| `schedule` | Game schedule & scores | away_team, home_team, scores, winner, venue |
| `player_stats` | Player statistics | name, position, avg/hr/rbi (hitting) or era/wins/k (pitching) |

### 🚀 How to Use

1. Select a **Mode** from the dropdown
2. Set the **Season** year (defaults to current year)
3. For `schedule` mode: optionally enter a **Date** (YYYY-MM-DD)
4. For `player_stats` mode: optionally enter a **Team ID**
5. Click **Start** to run

#### Common Team IDs

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

### 📦 Sample Output (Standings)

```json
{
    "division": "American League East",
    "team": "New York Yankees",
    "wins": 82,
    "losses": 55,
    "pct": ".599",
    "games_back": "-",
    "division_rank": "1",
    "runs_scored": 580,
    "runs_allowed": 478,
    "run_diff": 102,
    "streak": "W3",
    "season": "2025",
    "mode": "standings",
    "index": 1,
    "fetched_at": "2025-07-15T12:00:00+00:00"
}
```

### 📦 Sample Output (Player Stats — Hitting)

```json
{
    "player_id": 660271,
    "name": "Shohei Ohtani",
    "number": "17",
    "position": "DH",
    "stat_group": "hitting",
    "team": "Los Angeles Dodgers",
    "games": 120,
    "at_bats": 450,
    "hits": 130,
    "avg": ".289",
    "home_runs": 40,
    "rbi": 95,
    "ops": "1.012",
    "season": "2025",
    "mode": "player_stats",
    "index": 1,
    "fetched_at": "2025-07-15T12:00:00+00:00"
}
```

### 🚀 Quick Start

1. Choose a mode: `teams`, `standings`, `schedule`, or `player_stats`.
2. For schedules, use a date like `2025-07-15`.
3. For player stats, optionally provide a team ID (e.g. `147` for the Yankees).
4. Run the Actor and verify that each item includes `index`, `mode`, and `fetched_at`.

### 🔍 Verification Steps

- Test `teams` mode first to confirm the API is reachable.
- Run `standings` mode and check that division rows appear in the dataset.
- For `schedule`, verify the date filter returns games for the requested day.
- For `player_stats`, start with a small roster and confirm stats fields are populated.

### 🧪 Example Inputs

**Teams**

```json
{ "mode": "teams", "season": "2025" }
```

**Schedule**

```json
{ "mode": "schedule", "season": "2025", "date": "2025-07-15" }
```

**Player stats**

```json
{ "mode": "player_stats", "season": "2025", "team_id": 147, "stat_type": "hitting" }
```

### 📝 Notes

- **No API key required** — MLB Stats API is completely free and public
- Player stats mode makes individual API calls per player (may take 30-60 seconds for a full roster)
- Schedule without a date returns the full season schedule (can be large)
- All data comes directly from MLB's official `statsapi.mlb.com` API

### 💡 Troubleshooting

- Use `YYYY-MM-DD` for the schedule date field.
- If you get no results, check that the season is valid and the mode is set correctly.
- For roster stats, try a known team ID first (like `147` for the Yankees).
- If `player_stats` feels slow, start with a single team to confirm the pipeline before larger runs.

# Actor input Schema

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

Data mode: 'teams' (list all teams), 'standings' (division standings), 'schedule' (game schedule/scores), 'player_stats' (roster + individual stats)

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

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

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

Game date for schedule mode (format: YYYY-MM-DD). Leave empty to get full season schedule.

## `team_id` (type: `string`):

MLB team ID for player_stats mode. Common IDs: NYY=147, LAD=119, BOS=111, CHC=112, HOU=117, ATL=144, PHI=143, SD=135, NYM=121, SF=137. Leave empty for NYY default.

## `stat_type` (type: `string`):

Type of player stats to fetch: 'hitting' (batters only), 'pitching' (pitchers only), 'all' (full roster)

## Actor input object example

```json
{
  "mode": "standings",
  "season": 2025,
  "date": "",
  "team_id": "",
  "stat_type": "hitting"
}
```

# 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": "standings",
    "season": 2025,
    "date": "",
    "team_id": "",
    "stat_type": "hitting"
};

// Run the Actor and wait for it to finish
const run = await client.actor("gentle_cloud/mlb-stats-api").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": "standings",
    "season": 2025,
    "date": "",
    "team_id": "",
    "stat_type": "hitting",
}

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

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).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": "standings",
  "season": 2025,
  "date": "",
  "team_id": "",
  "stat_type": "hitting"
}' |
apify call gentle_cloud/mlb-stats-api --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,gentle_cloud/mlb-stats-api"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/ToDC6ydulO79igDoX/builds/0L9oENZ5p9MthRBFI/openapi.json
