toddrob99 / MLB-StatsAPI

Python wrapper for MLB Stats API
GNU General Public License v3.0
533 stars 100 forks source link

player_stat_data doesn't actually return stats. Better way? #68

Closed bennettcolecohen closed 2 years ago

bennettcolecohen commented 2 years ago

Hi - I'm trying to compile previous season stats by looking up player id using the player_stat_data, but the stats value on that lookup is always empty. I have data on a game by game basis but don't want to manually calculate that

Minimum Example: statsapi.player_stat_data('645277', group="hitting", type = 'season')

NOTE: type = 'career' does work but that isn't what is needed.

return this object. Note how 'stats' is just an empty list

{'id': 645277, 'first_name': 'Ozzie', 'last_name': 'Albies', 'active': True, 'current_team': 'Atlanta Braves', 'position': '2B', 'nickname': 'Bolly', 'last_played': None, 'mlb_debut': '2017-08-01', 'bat_side': 'Switch', 'pitch_hand': 'Right', 'stats': []}

toddrob99 commented 2 years ago

It's returning the current season stats, which the API is defaulting to 2022. The statsapi.player_stat_data() method does not include a way to specify the season, but the API endpoint does.

In order to retrieve the same data for a prior season, you will need to make the API call using statsapi.get() instead. If you like the way statsapi.player_stat_data() returns the data, you can duplicate that function and add the season to line 1115.

"hydrate": "stats(group=" + group + ",type=" + type + "),currentTeam", to "hydrate": "stats(group=" + group + ",type=" + type + ",season=2021),currentTeam",

The resulting API URL is https://statsapi.mlb.com/api/v1/people/645277?hydrate=stats(group=hitting,type=season,season=2021),currentTeam.

toddrob99 commented 2 years ago

Oh, and if you just want to know how to get the raw data from the API and parse it out yourself, you can still refer to how statsapi.player_stat_data() is building the statsapi.get() call and include the season.

params = {
    "personId": personId,
    "hydrate": "stats(group=" + group + ",type=" + type + ",season=2021),currentTeam",
}
r = statsapi.get("person", params)