
Security News
Attackers Are Hunting High-Impact Node.js Maintainers in a Coordinated Social Engineering Campaign
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.
mlb-stats-api
Advanced tools
Node.js Library for calling the MLB Stats API
npm install mlb-stats-api --save
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();
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);
}
}
// 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/');
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.)// 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' }
});
// 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();
// 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 } });
// 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();
// 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
}
});
// Get current standings
await mlbStats.getStandings({ params: { leagueId: 103 } });
// Get standings for specific date
await mlbStats.getStandings({
params: {
leagueId: 103,
date: '2024-07-01'
}
});
// Get stat leaders
await mlbStats.getStatsLeaders({
params: {
leaderCategories: 'homeRuns',
season: 2024
}
});
// Get stats
await mlbStats.getStats({
params: {
stats: 'season',
group: 'hitting',
season: 2024
}
});
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
}
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
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);
}
}
# Run all tests
npm test
# Run tests with coverage
npm run test:coverage
# Run tests in watch mode
npm run test:watch
# Check code style
npm run lint
# Fix code style issues
npm run lint:fix
This package includes comprehensive TypeScript definitions. Import types as needed:
import type {
TeamsResponse,
GameFeedResponse,
ScheduleResponse,
Team,
Game,
Player
} from 'mlb-stats-api/types';
For detailed information about available parameters and response formats, see the Official MLB Stats API Documentation.
MIT
Contributions are welcome! Please feel free to submit a Pull Request.
FAQs
Node JS Library for consuming MLB's official stats API
We found that mlb-stats-api demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.

Security News
Axios compromise traced to social engineering, showing how attacks on maintainers can bypass controls and expose the broader software supply chain.

Security News
Node.js has paused its bug bounty program after funding ended, removing payouts for vulnerability reports but keeping its security process unchanged.