Skip to main content

Crate mlb_api

Crate mlb_api 

Source
Expand description

§The Rust MLB API Wrapper

This project and its author are not affiliated with MLB or any MLB team. This crate wraps the existing MLB Stats API, which is subject to the notice posted at http://gdx.mlb.com/components/copyright.txt.

§Usage

Endpoints are most commonly used using their module’s builder functions.

use mlb_api::sport::SportId;
use mlb_api::request::RequestUrlBuilderExt;
use mlb_api::schedule::{self, ScheduleResponse, ScheduleDate};
 
let response: ScheduleResponse = schedule::request()
    .sport_id(SportId::MLB)
    .build_and_get()
    .await?;
 
let [date]: [ScheduleDate; 1] = response.dates.try_into()?;

Play Streams are the recommended way to process live games

use mlb_api::game::PlayStream;
 
let game: ScheduleGame = ...;
 
PlayStream::new(game.game_id).run(|event, _meta, _data| { ... }).await?;

Use single_stat! for simple stats requests and make your own hydrations for more complicated requests

use mlb_api::single_stat;
use mlb_api::person::{self, PeopleResonse};

let season_hitting = single_stat!( Season + Hitting for 660_271 ).await?;
let sabermetrics_pitching = single_stat!( Sabermetrics + Pitching for 660_271; with |builder| builder.season(2024) ).await?;

person_hydrations! {
    struct PersonDisplayHydrations {
        nicknames,
        stats: { [Season, Sabermetrics] = [Hitting, Pitching] },
    }
}

let response: PeopleResponse = person::request_with_hydrations::<PersonDisplayHydrations>(660_271).await?;

§Endpoints

This API contains wrappers / bindings for all known public MLB API endpoints (unless incomplete), the table of which can be seen below. Additional information can be found at https://github.com/toddrob99/MLB-StatsAPI/wiki/Endpoints (thanks Todd Roberts)

Stars hightlight the most popular and used endpoints

EndpointDescription
attendanceTeam attendance data by season
awardsList of all awards, Cy Young, MVP, etc.
conferenceConferences, like divisions but not
divisionNames, has a wildcard or not, playoff teams
draftDraft rounds, players, etc.
live_feedboxscore, linescore, plays, and misc
diff_patchJSON diff patch for live feed
timestampsList of timestamps for game plays & play events
changesGames that underwent scheduling changes (?)
context_metricsVarious metrics for game plays & play events
win_probabilityWin Probability calculations for games
boxscoreBoxscore summary for game, includes stats
contentEditorial content regarding games
linescoreLinescore for games
playsPlay by Play Data on a game
uniformsGame Uniforms
paceAverage game durations and league stat totals
home_run_derbyHome Run Derby stats
leagueLeague data, AL, NL, divisions contained, etc.
all_starASG data
personA person, lots of data here
free_agentsFree agents in any given year
person_statsPlayer stats for a single game
jobsList of all people with a job, ex: scorer, ump
jobs::umpireList of all umpires
jobs::datacastersList of all datacasters
jobs::official_scorersList of all official scorers
scheduleAll games played within a certain date range
schedule::tiedAll games that ended tied (?)
schedule::postseasonPostseason schedule
schedule::postseason::seriesPostseason series schedule
seasonDate ranges for season states: reg, post, spring
sportList of sports, MLB, AAA, AA, A+, etc.
playersList of all players in a sport and season
standingsStandings information for teams
statsStats data
stats::leadersLeague leaders in specific stats
teamTeam data
team::historyHistory of a team, such as Brooklyn & LA Dodgers
team::statsStats for a team
team::affiliatesMinor league affiliate teams
team::alumniAlumni for a team
team::coachesList of coaches on a team
team::personnelPersonnel on a team
team::leadersStat leaders per team
team::rosterRoster players on a team
team::uniformsUniforms a team wears
transactionsTrades, IL moves, etc.
venueYankee Stadium, Dodger Stadium, Fenway Park, etc.
metaMetadata endpoints, typically cached or enums

§Usage & Appendix

  1. Use PlayStream for obtaining live updates on games.
  2. Use single_stat! for simple stat requests rather than making person_hydrations! and PersonRequest yourself.
  3. Use as_complete_or_request and the numerous crate::*_hydrations! items to obtain additional information in requests, try to minimize request quantity.
  4. The precache function allows caching commonly requested values before usage to make as_complete_or_request faster to use.
  5. Supply SeasonIds to requests to not have them break when the year changes.

Modules§

all_star
Unimplemented as you can only get data as the ASG is ongoing.
attendance
Attendance for games and seasons.
awards
An award, such as the Cy Young, MVP, etc.
cache
The caching feature of mlb-api
conference
A conference, like in NCAA Baseball.
division
A division, like the AL East or NL West.
draft
Draft endpoint data. Picks, rounds, etc.
game
The thing you’re most likely here for.
home_run_derby
Needs to be a home run derby for me to implement this one
hydrations
General hydrations types for the hydrations system
jobs
Jobs data.
league
Leagues; AL, NL, etc.
meta
An abstraction over endpoints that contain fixed data, such as GameTypes, JobTypes, etc.
person
A description of a person in baseball.
request
Handles the request portion of the code
schedule
Schedules, typically the main entrypoint to navigate through games.
season
Data about important dates in a season for a specific SportId.
sport
Different “sports”; MLB, AAA, AA, A+, A, Rookieball, etc.
standings
Standings of a team, wins, losses, etc
stats
The Stats API
team
Endpoints related to teams; roster, history, affiliates, etc.
transactions
Roster transactions; calling someone up, free agent signings, etc.
venue
Venues; Yankee Stadium, Rogers Centre, Dodger Stadium, etc.

Macros§

person_hydrations
Creates hydrations for a person
roster_hydrations
Creates hydrations for a RosterRequest.
schedule_hydrations
Creates hydrations for a schedule
single_stat
Shorthand function for getting a single [StatType] and [StatGroup] for a specific player.
sports_hydrations
Creates hydrations for a sport
standings_hydrations
Creates hydrations for a standings request
stats_hydrations
Generates stat data types to be used in requests.
team_hydrations
Creates hydrations for a team
venue_hydrations
Creates hydrations for a venue

Structs§

ExternalReference
More generalized than social media, includes retrosheet, fangraphs, (+ some socials), etc.
FieldInfo
Various information regarding a field.
HomeAway
General type that represents two fields where one is home and one is away
Location
Street address, city, etc.
MLBError
Represents an error parsing an HTTP request
RGBAColor
rgba({red}, {green}, {blue}) into a type
ResourceUsage
TimeZoneData
Data regarding a timezone, uses chrono_tz.
TrackingSystem
Tracking equipment, Hawk-Eye, PitchFx, etc.
TrackingSystemVendor
A vendor for specific tracking concepts, such as Hawk-Eye for skeletal data.
TrackingSystemVendorId

Enums§

Copyright
The copyright at the top of every request
DayHalf
AM/PM
Gender
Gender
Handedness
Handedness
HandednessParseError
Error for handedness parsing
HeatmapTemperature
Used in HittingHotColdZones and PitchingHotColdZones.
HeightMeasurement
Measurement of a person’s height
HeightMeasurementParseError
Error for [<HeightMeasurement as FromStr>::from_str]
IntegerOrFloatStat
Stat that is either an integer or float.
PlayerPool
General filter for players in requests
RGBAColorFromStrError
Spec: rgba({red}, {green}, {blue})
RoofType
Different types of roof setups.
TeamSide
TurfType
Different types of turf.

Functions§

deserialize_team_side_from_is_home
deserialize_time_delta_from_hms
Errors
from_str
Deserializes a type using its FromStr implementation.
from_yes_no
Deserializes a "Y" or "N" into a bool
try_from_str
Try to deserialize a type using its FromStr implementation, fallback to None if it doesn’t work.

Type Aliases§

NaiveDateRange
Represents a range from one date to another (inclusive on both ends)