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
| Endpoint | Description |
|---|---|
attendance | Team attendance data by season |
awards | List of all awards, Cy Young, MVP, etc. |
conference | Conferences, like divisions but not |
division | Names, has a wildcard or not, playoff teams |
draft | Draft rounds, players, etc. |
live_feed ⭐ | boxscore, linescore, plays, and misc |
diff_patch | JSON diff patch for live feed |
timestamps | List of timestamps for game plays & play events |
changes | Games that underwent scheduling changes (?) |
context_metrics | Various metrics for game plays & play events |
win_probability | Win Probability calculations for games |
boxscore | Boxscore summary for game, includes stats |
content | Editorial content regarding games |
linescore | Linescore for games |
plays | Play by Play Data on a game |
uniforms | Game Uniforms |
pace | Average game durations and league stat totals |
home_run_derby | Home Run Derby stats |
league | League data, AL, NL, divisions contained, etc. |
all_star | ASG data |
person ⭐ | A person, lots of data here |
free_agents | Free agents in any given year |
person_stats | Player stats for a single game |
jobs | List of all people with a job, ex: scorer, ump |
jobs::umpire | List of all umpires |
jobs::datacasters | List of all datacasters |
jobs::official_scorers | List of all official scorers |
schedule ⭐ | All games played within a certain date range |
schedule::tied | All games that ended tied (?) |
schedule::postseason | Postseason schedule |
schedule::postseason::series | Postseason series schedule |
season | Date ranges for season states: reg, post, spring |
sport | List of sports, MLB, AAA, AA, A+, etc. |
players ⭐ | List of all players in a sport and season |
standings | Standings information for teams |
stats | Stats data |
stats::leaders | League leaders in specific stats |
team ⭐ | Team data |
team::history | History of a team, such as Brooklyn & LA Dodgers |
team::stats | Stats for a team |
team::affiliates | Minor league affiliate teams |
team::alumni | Alumni for a team |
team::coaches | List of coaches on a team |
team::personnel | Personnel on a team |
team::leaders | Stat leaders per team |
team::roster | Roster players on a team |
team::uniforms | Uniforms a team wears |
transactions | Trades, IL moves, etc. |
venue | Yankee Stadium, Dodger Stadium, Fenway Park, etc. |
meta | Metadata endpoints, typically cached or enums |
§Usage & Appendix
- This API defaults to using
reqwestandtokiofor non-blocking IO, there is aureqfeature to switch toureqandparking_lotfor blocking IO. - Use
PlayStreamfor obtaining live updates on games. - Use
single_stat!for simple stat requests rather than makingperson_hydrations!andPersonRequestyourself. - Use
as_complete_or_requestand the numerouscrate::*_hydrations!items to obtain additional information in requests, try to minimize request quantity. - The
precachefunction allows caching commonly requested values before usage to makeas_complete_or_requestfaster to use. - 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; uses [
::ureq] or::reqwestfor blocking or non-blocking networking. - 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§
- External
Reference - More generalized than social media, includes retrosheet, fangraphs, (+ some socials), etc.
- Field
Info - Various information regarding a field.
- Home
Away - 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
- RGBA
Color rgba({red}, {green}, {blue})into a type- Resource
Usage - Time
Zone Data - Data regarding a timezone, uses
chrono_tz. - Tracking
System - Tracking equipment, Hawk-Eye, PitchFx, etc.
- Tracking
System Vendor - A vendor for specific tracking concepts, such as Hawk-Eye for skeletal data.
- Tracking
System Vendor Id
Enums§
- Copyright
- The copyright at the top of every request
- DayHalf
- AM/PM
- Gender
- Gender
- Handedness
- Handedness
- Handedness
Parse Error - Error for handedness parsing
- Heatmap
Temperature - Used in
HittingHotColdZonesandPitchingHotColdZones. - Height
Measurement - Measurement of a person’s height
- Height
Measurement Parse Error - Error for [
<HeightMeasurement as FromStr>::from_str] - Integer
OrFloat Stat - Stat that is either an integer or float.
- Player
Pool - General filter for players in requests
- RGBA
Color From StrError - Spec:
rgba({red}, {green}, {blue}) - Roof
Type - Different types of roof setups.
- Team
Side - Turf
Type - Different types of turf.
Functions§
- deserialize_
team_ side_ from_ is_ home - deserialize_
time_ delta_ from_ hms - Errors
- from_
str - Deserializes a type using its
FromStrimplementation. - from_
yes_ no - Deserializes a
"Y"or"N"into abool - try_
from_ str - Try to deserialize a type using its
FromStrimplementation, fallback toNoneif it doesn’t work.
Type Aliases§
- Naive
Date Range - Represents a range from one date to another (inclusive on both ends)