Skip to content

Commit 4658baa

Browse files
authored
Merge pull request #162 from toddrob99/develop
Features: - New uniform endpoints `game_uniforms` and `team_uniforms` (#154) - `schedule()` supports the `season` argument to get an entire season's games at once (#149) - `player_stats()` and `player_stats_data()` support the `season` argument to get previous seasons of stats (#161) - `get()` now accepts a `requests_kwargs` dict which are passed as extra arguments to `requests.get()` (#159) Bug fixes: - Fixed the offseason behavior of the `latest_season()` function to return the upcoming season, not just whatever the most recent in MLB's data is (#157) - `schedule()` supports passing `include_series_status=False` to not request the series status from the endpoint, which can fail when requesting schedules covering large periods of time (#158)
2 parents e949dcd + 2093203 commit 4658baa

File tree

3 files changed

+79
-22
lines changed

3 files changed

+79
-22
lines changed

statsapi/__init__.py

Lines changed: 39 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,8 @@ def schedule(
4949
sportId=1,
5050
game_id=None,
5151
leagueId=None,
52+
season=None,
53+
include_series_status=True,
5254
):
5355
"""Get list of games for a given date/range and/or team/opponent."""
5456
if end_date and not start_date:
@@ -78,16 +80,20 @@ def schedule(
7880
if leagueId:
7981
params.update({"leagueId": leagueId})
8082

83+
if season:
84+
params.update({"season": season})
85+
8186
hydrate = (
8287
"decisions,probablePitcher(note),linescore,broadcasts,game(content(media(epg)))"
8388
)
84-
if date == "2014-03-11" or (str(start_date) <= "2014-03-11" <= str(end_date)):
85-
# For some reason the seriesStatus hydration throws a server error on 2014-03-11 only (checked back to 2000)
86-
logger.warning(
87-
"Excluding seriesStatus hydration because the MLB API throws an error for 2014-03-11 which is included in the requested date range."
88-
)
89-
else:
90-
hydrate += ",seriesStatus"
89+
if include_series_status:
90+
if date == "2014-03-11" or (str(start_date) <= "2014-03-11" <= str(end_date)):
91+
# For some reason the seriesStatus hydration throws a server error on 2014-03-11 only (checked back to 2000)
92+
logger.warning(
93+
"Excluding seriesStatus hydration because the MLB API throws an error for 2014-03-11 which is included in the requested date range."
94+
)
95+
else:
96+
hydrate += ",seriesStatus"
9197
params.update(
9298
{
9399
"sportId": str(sportId),
@@ -1116,9 +1122,11 @@ def game_pace_data(season=datetime.now().year, sportId=1):
11161122
return r
11171123

11181124

1119-
def player_stats(personId, group="[hitting,pitching,fielding]", type="season"):
1125+
def player_stats(
1126+
personId, group="[hitting,pitching,fielding]", type="season", season=None
1127+
):
11201128
"""Get current season or career stats for a given player."""
1121-
player = player_stat_data(personId, group, type)
1129+
player = player_stat_data(personId, group, type, season)
11221130

11231131
stats = ""
11241132
stats += player["first_name"]
@@ -1154,15 +1162,22 @@ def player_stats(personId, group="[hitting,pitching,fielding]", type="season"):
11541162

11551163

11561164
def player_stat_data(
1157-
personId, group="[hitting,pitching,fielding]", type="season", sportId=1
1165+
personId, group="[hitting,pitching,fielding]", type="season", sportId=1, season=None
11581166
):
11591167
"""Returns a list of current season or career stat data for a given player."""
1168+
1169+
if season is not None and "season" not in type:
1170+
raise ValueError(
1171+
"The 'season' parameter is only valid when using the 'season' type."
1172+
)
1173+
11601174
params = {
11611175
"personId": personId,
11621176
"hydrate": "stats(group="
11631177
+ group
11641178
+ ",type="
11651179
+ type
1180+
+ (",season=" + str(season) if season else "")
11661181
+ ",sportId="
11671182
+ str(sportId)
11681183
+ "),currentTeam",
@@ -1209,15 +1224,9 @@ def latest_season(sportId=1):
12091224
all_seasons = get("season", params)
12101225
return next(
12111226
(
1212-
x
1213-
for x in all_seasons.get("seasons", [])
1214-
if x.get("seasonStartDate")
1215-
and x.get("seasonEndDate")
1216-
and (
1217-
x["seasonStartDate"]
1218-
< datetime.today().strftime("%Y-%m-%d")
1219-
< x["seasonEndDate"]
1220-
)
1227+
s
1228+
for s in all_seasons.get("seasons", [])
1229+
if (datetime.today().strftime("%Y-%m-%d") < s.get("seasonEndDate", ""))
12211230
),
12221231
all_seasons["seasons"][-1],
12231232
)
@@ -1574,6 +1583,7 @@ def meta(type, fields=None):
15741583
"awards",
15751584
"baseballStats",
15761585
"eventTypes",
1586+
"freeGameTypes",
15771587
"gameStatus",
15781588
"gameTypes",
15791589
"hitTrajectories",
@@ -1588,12 +1598,15 @@ def meta(type, fields=None):
15881598
"positions",
15891599
"reviewReasons",
15901600
"rosterTypes",
1601+
"runnerDetailTypes",
1602+
"scheduleTypes",
15911603
"scheduleEventTypes",
15921604
"situationCodes",
15931605
"sky",
15941606
"standingsTypes",
15951607
"statGroups",
15961608
"statTypes",
1609+
"violationTypes",
15971610
"windDirection",
15981611
]
15991612
if type not in types:
@@ -1640,7 +1653,7 @@ def notes(endpoint):
16401653
return msg
16411654

16421655

1643-
def get(endpoint, params={}, force=False):
1656+
def get(endpoint, params={}, force=False, *, request_kwargs={}):
16441657
"""Call MLB StatsAPI and return JSON data.
16451658
16461659
This function is for advanced querying of the MLB StatsAPI,
@@ -1763,8 +1776,13 @@ def get(endpoint, params={}, force=False):
17631776
+ note
17641777
)
17651778

1779+
if len(request_kwargs):
1780+
logger.debug(
1781+
"Including request_kwargs in requests.get call: {}".format(request_kwargs)
1782+
)
1783+
17661784
# Make the request
1767-
r = requests.get(url)
1785+
r = requests.get(url, **request_kwargs)
17681786
if r.status_code not in [200, 201]:
17691787
r.raise_for_status()
17701788
else:

statsapi/endpoints.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -404,6 +404,25 @@
404404
"query_params": ["timecode", "fields"],
405405
"required_params": [[]],
406406
},
407+
"game_uniforms": {
408+
"url": BASE_URL + "{ver}/uniforms/game",
409+
"path_params": {
410+
"ver": {
411+
"type": "str",
412+
"default": "v1",
413+
"leading_slash": False,
414+
"trailing_slash": False,
415+
"required": True,
416+
}
417+
},
418+
"query_params": [
419+
"gamePks",
420+
"fields",
421+
],
422+
"required_params": [
423+
["gamePks"],
424+
],
425+
},
407426
"gamePace": {
408427
"url": BASE_URL + "{ver}/gamePace",
409428
"path_params": {
@@ -1285,6 +1304,26 @@
12851304
"required_params": [["season", "group"]],
12861305
"note": "Use meta('statGroups') to look up valid values for group, meta('statTypes') for valid values for stats, and meta('situationCodes') for valid values for sitCodes. Use sitCodes with stats=statSplits.",
12871306
},
1307+
"team_uniforms": {
1308+
"url": BASE_URL + "{ver}/uniforms/team",
1309+
"path_params": {
1310+
"ver": {
1311+
"type": "str",
1312+
"default": "v1",
1313+
"leading_slash": False,
1314+
"trailing_slash": False,
1315+
"required": True,
1316+
}
1317+
},
1318+
"query_params": [
1319+
"teamIds",
1320+
"season",
1321+
"fields",
1322+
],
1323+
"required_params": [
1324+
["teamIds"],
1325+
],
1326+
},
12881327
"transactions": {
12891328
"url": BASE_URL + "{ver}/transactions",
12901329
"path_params": {

statsapi/version.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
#!/usr/bin/env python
22

3-
VERSION = "1.8.1"
3+
VERSION = "1.9.0"

0 commit comments

Comments
 (0)