NHL API: Get Schedule
Introduction
The NHL has a publicly accessible Application Programming Interface (or API) that allows users to obtain a lot of useful data (including detailed play-by-play data). There are a couple of obstacles though: 1) the NHL API does not come with a user manual; and 2) the NHL API is most easily accessed using a programming language such as R or Python. To help you overcome those obstacles I’m writing articles that provide the code (in the R programming language) for functions that pull data from the NHL API.
In this article I provide a function that pulls schedule data.
The Data
Before I provide the code, here’s a sample of the data.
game_id: 2022030245
season: 20222023
game_type: P
date: 2023-05-12
home_team_id: 54
home_team: Vegas Golden Knights
away_team_id: 22
away_team: Edmonton Oilers
The Code
Here’s the code for the function that pulls the above data.
# This function pulls the NHL schedule for a specified time period
# The date format is "YYYY-MM-DD" (include the quotation marks)
# The default setting is to pull data for ONLY the regular season
# To pull data for ALL GAMES enter "FALSE" for reg_szn (include the quotation marks)
get_schedule <- function(start_date, end_date, reg_szn = "TRUE") {
# Generate the appropriate URL based on reg_szn TRUE/FALSE
sched_url <- ifelse(reg_szn == "FALSE", paste0("https://statsapi.web.nhl.com/api/v1/schedule?startDate=", start_date, "&endDate=", end_date), paste0("https://statsapi.web.nhl.com/api/v1/schedule?startDate=", start_date, "&endDate=", end_date, "&gameType=R"))
# Pull and clean schedule data for the specified time period
sched_site <- read_json(sched_url)
sched_dates <- sched_site$dates %>%
tibble() %>%
unnest_wider(1) %>%
unnest_longer(games) %>%
unnest_wider(games) %>%
unnest_wider(teams) %>%
unnest_wider(away) %>%
select(-link) %>%
unnest_wider(team) %>%
rename(away_team_id = id) %>%
rename(away_team = name) %>%
select(-link, -leagueRecord, -score) %>%
unnest_wider(home) %>%
unnest_wider(team) %>%
rename(home_team_id = id) %>%
rename(home_team = name) %>%
select(game_id = gamePk,
season,
game_type = gameType,
date,
home_team_id,
home_team,
away_team_id,
away_team)
sched_dates$date <- as.Date(sched_dates$date)
return(sched_dates)
}
Get It On GitHub
I’ve created a public repository on GitHub where I’ll be sharing my functions for accessing the NHL’s API. You can go to the repository by clicking here.
The End Of The Article
That’s the end of this article. Follow me on twitter to be notified about new content.
Cheers,
Mark (18 Skaters)