Skip to main content

mlb_api/requests/game/
boxscore.rs

1//! Various live information & collection stats about the ongoing game.
2//!
3//! Teams have pitching, hitting, and fielding stats, rosters, batting orders, etc.
4//!
5//! Lists of umpires, top performers, etc.
6
7use std::fmt::Display;
8
9use bon::Builder;
10use fxhash::FxHashMap;
11use serde::{Deserialize, de::IgnoredAny};
12use serde_with::{serde_as, DefaultOnError};
13
14use crate::{Copyright, HomeAway, game::{BattingOrderIndex, GameId, LabelledValue, Official, PlayerGameStatusFlags, SectionedLabelledValues}, meta::NamedPosition, person::{Ballplayer, JerseyNumber, NamedPerson, PersonId}, request::RequestURL, stats::{StatTypeStats, stat_types::__BoxscoreStatTypeStats}, team::{NamedTeam, Team, TeamId, roster::RosterStatus}};
15
16/// See [`self`]
17#[derive(Debug, Deserialize, PartialEq, Clone)]
18#[serde(rename_all = "camelCase")]
19#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
20pub struct Boxscore {
21    #[serde(default)]
22    pub copyright: Copyright,
23    #[serde(rename = "info")]
24    pub misc: Vec<LabelledValue>,
25    pub top_performers: Option<[TopPerformer; 3]>,
26    pub pitching_notes: Vec<String>,
27    pub teams: HomeAway<TeamWithGameData>,
28    pub officials: Vec<Official>,
29}
30
31impl Boxscore {
32    /// Returns a [`PlayerWithGameData`] if present in the baseball game.
33    pub fn find_player_with_game_data(&self, id: PersonId) -> Option<&PlayerWithGameData> {
34        self.teams.home.players.get(&id).or_else(|| self.teams.away.players.get(&id))
35    }
36}
37
38/// One of three "top performers" of the game, measured by game score.
39///
40/// Originally an enum but the amount of two-way-players that exist make it pointlessly annoying and easy to break.
41#[derive(Debug, Deserialize, PartialEq, Clone)]
42#[serde(rename_all = "camelCase")]
43#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
44pub struct TopPerformer {
45    pub player: PlayerWithGameData,
46    pub game_score: usize,
47    #[serde(rename = "type")]
48    pub player_kind: String,
49
50    #[doc(hidden)]
51    #[serde(rename = "pitchingGameScore", default)]
52    pub __pitching_game_score: IgnoredAny,
53    #[doc(hidden)]
54    #[serde(rename = "hittingGameScore", default)]
55    pub __hitting_game_score: IgnoredAny,
56}
57
58/// A person with some potentially useful information regarding their performance in the current game.
59#[derive(Debug, Deserialize, PartialEq, Clone)]
60#[serde(from = "__PlayerWithGameDataStruct")]
61#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
62pub struct PlayerWithGameData {
63	pub person: NamedPerson,
64	pub boxscore_name: String,
65	pub jersey_number: Option<JerseyNumber>,
66	pub position: NamedPosition,
67	pub status: RosterStatus,
68	pub stats: BoxscoreStatCollection,
69	/// Uses the active game's [`GameType`], not the regular season stats.
70	pub season_stats: BoxscoreStatCollection,
71	pub game_status: PlayerGameStatusFlags,
72	pub all_positions: Vec<NamedPosition>,
73	pub batting_order: Option<BattingOrderIndex>,
74
75	pub __parent_team_id: IgnoredAny,
76}
77
78#[doc(hidden)]
79#[serde_as]
80#[derive(Deserialize)]
81#[serde(rename_all = "camelCase")]
82#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
83struct __PlayerWithGameDataStruct {
84	person: __NamedPersonWithBoxscoreName,
85	#[serde(default)]
86	#[serde_as(deserialize_as = "DefaultOnError")]
87	jersey_number: Option<JerseyNumber>,
88	position: NamedPosition,
89	status: RosterStatus,
90	stats: BoxscoreStatCollection,
91	season_stats: BoxscoreStatCollection,
92	game_status: PlayerGameStatusFlags,
93	#[serde(default)]
94	all_positions: Vec<NamedPosition>,
95	batting_order: Option<BattingOrderIndex>,
96
97    #[doc(hidden)]
98    #[serde(rename = "parentTeamId", default)]
99	__parent_team_id: IgnoredAny,
100}
101
102#[derive(Deserialize)]
103#[serde(rename_all = "camelCase")]
104struct __NamedPersonWithBoxscoreName {
105    id: PersonId,
106    full_name: String,
107    boxscore_name: String,
108}
109
110impl From<__PlayerWithGameDataStruct> for PlayerWithGameData {
111    fn from(__PlayerWithGameDataStruct {
112        person,
113        jersey_number,
114        position,
115        status,
116        stats,
117        season_stats,
118        game_status,
119        all_positions,
120        batting_order,
121        __parent_team_id
122    }: __PlayerWithGameDataStruct) -> Self {
123        Self {
124            person: NamedPerson { full_name: person.full_name, id: person.id },
125            boxscore_name: person.boxscore_name,
126            jersey_number,
127            position,
128            status,
129            stats,
130            season_stats,
131            game_status,
132            all_positions,
133            batting_order,
134            __parent_team_id
135        }
136    }
137}
138
139/// A team with some potentially useful information regarding their performance in the current game.
140#[derive(Debug, Deserialize, PartialEq, Clone)]
141#[serde(rename_all = "camelCase")]
142#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
143pub struct TeamWithGameData {
144    pub team: NamedTeam,
145    pub team_stats: BoxscoreStatCollection,
146    #[serde(deserialize_with = "super::deserialize_players_cache")]
147    pub players: FxHashMap<PersonId, PlayerWithGameData>,
148    pub batters: Vec<PersonId>,
149    pub pitchers: Vec<PersonId>,
150    pub bench: Vec<PersonId>,
151    pub bullpen: Vec<PersonId>,
152    pub batting_order: [PersonId; 9],
153    #[serde(rename = "info")]
154    pub sectioned_labelled_values: Vec<SectionedLabelledValues>,
155    #[serde(rename = "note")]
156    pub notes: Vec<LabelledValue>,
157}
158
159/// Hitting, Pitching, and Fielding stats.
160#[allow(private_interfaces, reason = "the underlying type is pub")]
161#[serde_as]
162#[derive(Debug, Deserialize, PartialEq, Clone)]
163#[serde(rename_all = "camelCase")]
164#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
165pub struct BoxscoreStatCollection {
166    #[serde(rename = "batting")]
167    #[serde_as(deserialize_as = "DefaultOnError")]
168    pub hitting: <__BoxscoreStatTypeStats as StatTypeStats>::Hitting,
169    #[serde_as(deserialize_as = "DefaultOnError")]
170    pub fielding: <__BoxscoreStatTypeStats as StatTypeStats>::Fielding,
171    #[serde_as(deserialize_as = "DefaultOnError")]
172    pub pitching: <__BoxscoreStatTypeStats as StatTypeStats>::Pitching,
173}
174
175#[derive(Builder)]
176#[builder(derive(Into))]
177pub struct BoxscoreRequest {
178    #[builder(into)]
179    id: GameId,
180}
181
182impl<S: boxscore_request_builder::State + boxscore_request_builder::IsComplete> crate::request::RequestURLBuilderExt for BoxscoreRequestBuilder<S> {
183    type Built = BoxscoreRequest;
184}
185
186impl Display for BoxscoreRequest {
187    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
188        write!(f, "http://statsapi.mlb.com/api/v1/game/{}/boxscore", self.id)
189    }
190}
191
192impl RequestURL for BoxscoreRequest {
193    type Response = Boxscore;
194}
195
196#[cfg(test)]
197mod tests {
198    use crate::TEST_YEAR;
199    use crate::game::BoxscoreRequest;
200    use crate::meta::GameType;
201    use crate::request::RequestURLBuilderExt;
202    use crate::schedule::ScheduleRequest;
203    use crate::season::{Season, SeasonsRequest};
204    use crate::sport::SportId;
205
206    #[tokio::test]
207    async fn ws_gm7_2025_boxscore() {
208        let _ = BoxscoreRequest::builder().id(813_024).build_and_get().await.unwrap();
209    }
210
211    #[tokio::test]
212	async fn postseason_boxscore() {
213		let [season]: [Season; 1] = SeasonsRequest::builder().season(TEST_YEAR).sport_id(SportId::MLB).build_and_get().await.unwrap().seasons.try_into().unwrap();
214		let postseason = season.postseason.expect("Expected the MLB to have a postseason");
215		let games = ScheduleRequest::<()>::builder().date_range(postseason).sport_id(SportId::MLB).build_and_get().await.unwrap();
216		let games = games.dates.into_iter().flat_map(|date| date.games).filter(|game| game.game_type.is_postseason()).map(|game| game.game_id).collect::<Vec<_>>();
217		let mut has_errors = false;
218		for game in games {
219			if let Err(e) = BoxscoreRequest::builder().id(game).build_and_get().await {
220			    dbg!(e);
221			    has_errors = true;
222			}
223		}
224		assert!(!has_errors, "Has errors.");
225	}
226
227	#[cfg_attr(not(feature = "_heavy_tests"), ignore)]
228    #[tokio::test]
229    async fn regular_season_boxscore() {
230        let [season]: [Season; 1] = SeasonsRequest::builder().season(TEST_YEAR).sport_id(SportId::MLB).build_and_get().await.unwrap().seasons.try_into().unwrap();
231        let regular_season = season.regular_season;
232        let games = ScheduleRequest::<()>::builder().date_range(regular_season).sport_id(SportId::MLB).build_and_get().await.unwrap();
233        let games = games.dates.into_iter().flat_map(|date| date.games).filter(|game| game.game_type == GameType::RegularSeason).collect::<Vec<_>>();
234        let mut has_errors = false;
235        for game in games {
236            if let Err(e) = BoxscoreRequest::builder().id(game.game_id).build_and_get().await {
237                dbg!(e);
238                has_errors = true;
239            }
240        }
241        assert!(!has_errors, "Has errors.");
242    }
243}