Created
October 26, 2021 07:39
-
-
Save CaptainZidgel/758721ef51c64db3c2e7d670764f9c72 to your computer and use it in GitHub Desktop.
Get roster list containing jersey numbers and player names from a NHL API gameid. (You could modify to get other fields if you wanted to).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Get roster reports from NHL's official API | |
#https://gitlab.com/dword4/nhlapi/-/tree/master/ | |
#https://www.kevinsidwar.com/iot/2017/7/1/the-undocumented-nhl-stats-api | |
import requests | |
class Person: #I don't have any reason for making this a class besides dot notation | |
def __init__(self, n, name): | |
self.n = n | |
self.name = name | |
class Team: | |
def __init__(self, _id, name, roster, whomst): | |
self.id = _id | |
self.name = name | |
self.roster = roster | |
self.home = True if whomst == "home" else False | |
ROOT = "https://statsapi.web.nhl.com" | |
GAMES_ENDPOINT = ROOT + "/api/v1/game/" | |
GAMES_APPEND = "/feed/live" #ENDPOINT + gameid + APPEND = :) | |
test_gid="2015020597" | |
def GetRosters(gid): | |
''' | |
Enter Game ID, receive dict containing two teamnames, each teamname entry is a Team object | |
containing an id, name, roster, and home bool field. | |
the roster field is a list of Person objects, each Person object has two fields: n (jersey number) and name (first/last) | |
''' | |
r = requests.get(GAMES_ENDPOINT+gid+GAMES_APPEND) | |
j = r.json()["gameData"] | |
j_teams = j["teams"] | |
season = j["game"]["season"] | |
f_teams = {} | |
#the players section in j["gameData"] doesn't include what team the player was ON during the game!!!! | |
#just the CURRENT team! what the CRINGE! holy CRINGE! im NOT pogging! | |
#so we must urghghhgh make another 2 api requests hahahaha whatever | |
for loc, t in j_teams.items(): #loc = 'away'/'home' | |
team = [] | |
endpoint = ROOT + t["link"] + "/roster" | |
m = requests.get(endpoint, params = {"season": season}) | |
for x in m.json()["roster"]: | |
try: | |
person = Person(x.get("jerseyNumber"), x["person"]["fullName"]) | |
team.append(person) | |
except KeyError: | |
print("keyerr", x, endpoint) | |
f_teams[t["teamName"]] = Team(t["id"], t["name"], team, loc) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment