npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

mlb-stats-api

v2.0.0

Published

Node JS Library for consuming MLB's official stats API

Readme

mlb-stats-api

Node.js Library for calling the MLB Stats API

npm npm License

Features

  • Complete MLB Stats API coverage - Access all endpoints of the official MLB Stats API
  • TypeScript support - Full type definitions included for better development experience
  • Modern Node.js - Built for Node.js 18+ with native ES6+ features
  • Zero dependencies - Lightweight with no external runtime dependencies
  • Promise-based - Modern async/await support
  • Well tested - Comprehensive test suite covering all endpoints

Install

npm install mlb-stats-api --save

Quick Start

JavaScript (CommonJS)

const MLBStatsAPI = require('mlb-stats-api');
const mlbStats = new MLBStatsAPI();

async function getGameData() {
    try {
        // Get current teams
        const teams = await mlbStats.getTeams({ params: { sportId: 1 } });
        console.log(teams.data.teams);
        
        // Get today's games
        const schedule = await mlbStats.getSchedule({ 
            params: { 
                sportId: 1, 
                date: new Date().toISOString().split('T')[0] 
            } 
        });
        console.log(schedule.data.dates);
        
        // Get live game feed (if game is in progress)
        const gameFeed = await mlbStats.getGameFeed({ 
            pathParams: { gamePk: 634197 } 
        });
        console.log(gameFeed.data);
    } catch (error) {
        console.error('Error fetching MLB data:', error.message);
    }
}

getGameData();

TypeScript

import MLBStatsAPI from 'mlb-stats-api';
import type { TeamsResponse, ScheduleResponse, GameFeedResponse } from 'mlb-stats-api/types';

const mlbStats = new MLBStatsAPI();

async function getTypedGameData(): Promise<void> {
    try {
        // TypeScript provides full intellisense and type checking
        const teams = await mlbStats.getTeams({ params: { sportId: 1 } });
        const teamsData: TeamsResponse = teams.data;
        
        const schedule = await mlbStats.getSchedule({ 
            params: { 
                sportId: 1, 
                date: '2024-07-01' 
            } 
        });
        const scheduleData: ScheduleResponse = schedule.data;
        
        const gameFeed = await mlbStats.getGameFeed({ 
            pathParams: { gamePk: 634197 } 
        });
        const gameData: GameFeedResponse = gameFeed.data;
        
        console.log(`Found ${teamsData.teams.length} teams`);
        console.log(`Found ${scheduleData.totalGames} games`);
    } catch (error) {
        console.error('Error:', error);
    }
}

Constructor Options

// Use default MLB Stats API host
const mlbStats = new MLBStatsAPI();

// Use custom host (for testing or alternative endpoints)
const mlbStats = new MLBStatsAPI('https://custom-api.example.com/api/');

Making Requests

Each method accepts an options object with the following properties:

  • params - Query parameters (optional)
  • pathParams - Path parameters for endpoints that require them (like game IDs, team IDs, etc.)

Basic Usage

// Simple request with no parameters
const awards = await mlbStats.getAwards();

// Request with query parameters
const teams = await mlbStats.getTeams({ 
    params: { 
        sportId: 1, 
        season: 2024 
    } 
});

// Request with path parameters
const team = await mlbStats.getTeam({ 
    pathParams: { teamId: 111 } 
});

// Request with both path and query parameters
const teamRoster = await mlbStats.getTeamRoster({ 
    pathParams: { teamId: 111 },
    params: { rosterType: 'active' }
});

Available Endpoints

Teams

// Get all teams
await mlbStats.getTeams({ params: { sportId: 1 } });

// Get specific team
await mlbStats.getTeam({ pathParams: { teamId: 111 } });

// Get team roster
await mlbStats.getTeamRoster({ pathParams: { teamId: 111 } });

// Get team stats
await mlbStats.getTeamsStats();

// Get team history
await mlbStats.getTeamsHistory();

Games

// Get live game feed
await mlbStats.getGameFeed({ pathParams: { gamePk: 634197 } });

// Get game boxscore
await mlbStats.getGameBoxscore({ pathParams: { gamePk: 634197 } });

// Get game linescore
await mlbStats.getGameLinescore({ pathParams: { gamePk: 634197 } });

// Get play-by-play
await mlbStats.getGamePlayByPlay({ pathParams: { gamePk: 634197 } });

Schedule

// Get today's games
await mlbStats.getSchedule({ 
    params: { 
        sportId: 1, 
        date: '2024-07-01' 
    } 
});

// Get date range
await mlbStats.getSchedule({ 
    params: { 
        sportId: 1, 
        startDate: '2024-07-01',
        endDate: '2024-07-07'
    } 
});

// Get postseason schedule
await mlbStats.getSchedulePostseason();

Players

// Get people/players
await mlbStats.getPeople({ params: { personIds: '660271' } });

// Get specific person
await mlbStats.getPerson({ pathParams: { personId: 660271 } });

// Get player stats for specific game
await mlbStats.getPersonStats({ 
    pathParams: { 
        personId: 660271, 
        gamePk: 634197 
    } 
});

Standings

// Get current standings
await mlbStats.getStandings({ params: { leagueId: 103 } });

// Get standings for specific date
await mlbStats.getStandings({ 
    params: { 
        leagueId: 103, 
        date: '2024-07-01' 
    } 
});

Stats

// Get stat leaders
await mlbStats.getStatsLeaders({ 
    params: { 
        leaderCategories: 'homeRuns',
        season: 2024 
    } 
});

// Get stats
await mlbStats.getStats({ 
    params: { 
        stats: 'season',
        group: 'hitting',
        season: 2024 
    } 
});

Response Format

All API responses follow this structure:

interface APIResponse {
    status: number;          // HTTP status code
    statusText: string;      // HTTP status message
    headers: object;         // Response headers
    data: any;              // Parsed JSON response data
    json(): Promise<any>;   // Method to get JSON data
    text(): Promise<string>; // Method to get raw text
}

Example Response Handling

const response = await mlbStats.getTeams({ params: { sportId: 1 } });

console.log('Status:', response.status);           // 200
console.log('Teams:', response.data.teams);        // Array of team objects
console.log('Headers:', response.headers);         // Response headers

// Alternative ways to access data
const jsonData = await response.json();            // Same as response.data
const rawText = await response.text();             // Raw response text

Error Handling

The library throws errors for failed requests that you should handle:

try {
    const response = await mlbStats.getGameFeed({ 
        pathParams: { gamePk: 'invalid-id' } 
    });
    console.log(response.data);
} catch (error) {
    console.error('Request failed:', error.message);
    
    if (error.response) {
        console.error('Status:', error.response.status);
        console.error('Data:', error.response.data);
    }
}

Development

Running Tests

# Run all tests
npm test

# Run tests with coverage
npm run test:coverage

# Run tests in watch mode
npm run test:watch

Linting

# Check code style
npm run lint

# Fix code style issues
npm run lint:fix

TypeScript Support

This package includes comprehensive TypeScript definitions. Import types as needed:

import type { 
    TeamsResponse, 
    GameFeedResponse, 
    ScheduleResponse,
    Team,
    Game,
    Player 
} from 'mlb-stats-api/types';

API Documentation

For detailed information about available parameters and response formats, see the Official MLB Stats API Documentation.

License

MIT

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.