Its that time of year!

Its that time of year again. The time when we dust off the old ESPN fantasy football API R code and fix everything that broke in the last year.

Here’s what I hope to show over the next few posts.

  1. How to access your ESPN public fantasy football league’s data.
  2. How to organize that data and create a few interesting displays.
  3. How to create a dashboard to supplement your league’s fun.

My ultimate goal is to build this into a package on Github. I’ve got that started, but its currently a work in progress.

All this code and more is located at my github.

And a special thanks to my friend and collaborator Jim Pleuss who really enhanced so much of this project!

A little background

This ESPN API exploration is a fun annual process. I first started doing this in 2018. In 2019, after some hacking and some updates, I posted about how to access public leagues, how to access private leagues using reticulate and python, and how to access private leagues in R. I went so far last year as to build a dashboard with the data to further analyze my league.

Well, in 2020, ESPN changed their some of their end points. After a lot of exploration and the help of Chrome’s inspect tool, I present code to access ESPN’s API. This should work for any league. If you find it does not work for your league, I’d be happy to take a pull request or two to handle more nuances.

How to access the API

In the function below, you provide arguments for your leagueID and the week of the information you would like to extract.

To find your leagueID, look at the URL of your fantasy football home page on ESPN.

The output of this function will be a JSON file. I provide code to explore the JSON file as well.

library(tidyverse)
library(gt)

get_data <- function(leagueID = leagueID, per_id = per_id){
base = "http://fantasy.espn.com/apis/v3/games/ffl/seasons/"
year = "2020"
mid = "/segments/0/leagues/"
tail = str_c("?view=mDraftDetail",
             "&view=mLiveScoring",
             "&view=mMatchupScore,",
             "&view=mPendingTransactions",
             "&view=mPositionalRatings",
             "&view=mRoster",
             "&view=mSettings",
             "&view=mTeam",
             "&view=modular",
             "&view=mNav",
             "&view=mMatchupScore",
             "&scoringPeriodId="
             )

url = paste0(base,year,mid,leagueID,tail,per_id)

ESPNGet <- httr::GET(url = url)
ESPNRaw <- rawToChar(ESPNGet$content)
ESPNFromJSON <- jsonlite::fromJSON(ESPNRaw)

return(ESPNFromJSON)

}

leagueID <- 89417258
per_id <- 2

ESPNFromJSON <- get_data(leagueID = leagueID, per_id = per_id)

We’ll can explore the data using the listviewer package. You can peruse the data from this JSON below.

ESPNFromJSON %>% listviewer::jsonedit()