EDIT: ESPN readjusted their Fantasy API come v3 in at an early stage 2019, so several v2 code from this write-up no longer works. Don’t concern we’re ~ above it:
Check that out.
You are watching: How to find league id espn fantasy football
Fantasy football season approacheth. Your heart longs to analyze the scoring distribution in your league by week, by team, through player — to finally quantitatively inquiry the predictive power of projected points — to check your hypothesis that you got an unfair slate of opponents in the pre-playoff weeks … and also yet you recognize not how. Copy-paste data indigenous a webpage? do some expert-level net scraping?
You’re in luck. ESPN has actually an accessible, despite undocumented, API for their Fantasy soccer database. This means you can query a question choose “what was the score of the week 1 game between ABC and XYZ” directly with a acquire request and some JSON fiddling, no internet “scraping” required.
Since the API is mysteriously undocumented, in this blog I’ll write down everything I’ve learned around the API, exactly how to access different parts of it, and how to do that in Python and R. In a follow-on post, I’ll present how to get boxscores, and then exactly how to address private leagues. Here’s a boxplot fine produce:
Before we obtain started, permit the reader note there’s currently a Python package the end there that carry out a most what i describe listed below in a clean way: espnff. Therefore you can skip the hassle and also just usage this fantastic work. My feeling is: I’d fairly bake my own janky cake with all the toppings I want than purchase the tasty much more attractive cake from the store.
You should likewise check the end my friend Dusty Turner’s excellent post about ESPN Fantasy scraping in R, and also this Reddit discussion about the ESPN Fantasy API.
CAVEAT: your organization needs to it is in “public”, or you need to figure out how to send session cookies or login remotely, see end of this post.
Looking at scores (in Python)
Let’s begin with Python. Making use of the inquiry package because that our obtain request, stop tap right into the ESPN Fantasy API with the scoreboard endpoint:
import requestsscores = for mainly in range(1, 17): r = requests.get("http://games.espn.com/ffl/api/v2/scoreboard", params="leagueId": 123456, "seasonId": 2017, "matchupPeriodId": week) scores
Let’s walk through this line by line. Income the request package. Initialize a dict dubbed scores to organize score information. Loop over weeks 1-16. Execute a acquire request come the API in ~ http://games.espn.com/ffl/api/v2/ through the endpoint scoreboard, and also with parameters for the organization ID, season, and matchup period. To find your organization ID, examine the URL when you’re on your league’s page. Note: if we don’t point out the matchup period, it will default to the critical week. Finally, store that week’s score info in scores as a dict in JSON format.
The gain request above, through parameters, is basically equivalent come if you entered the following URL right into a browser:
and then conserved the resulting text (which an alert is in a JSON format).
It is precious poking approximately this nested collection of information. This is an abbreviation sample that scores<1>:
There is a ton of details stored here already, and we’re just using one endpoint! We’ll emphasis on scores for now, yet at the end of this post, I’ll point out some other potential right here such as those playerIDs (i.e. The football player on every team, through week!).
To extract the very first matchup of week 1, we would execute scores<1><"scoreboard"><"matchups"><0>. To extract the house score for this matchup, we would index deeper and call scores<1><"scoreboard"><"matchups"><0><"teams"><0><"score">. To make a clean table of all the team IDs, names, and also scores for every weeks, we deserve to do
df = <>for vital in scores: temp = scores
I’d like to begin visualizing this details with matplotlib, and to do our lives less complicated let’s lug numpy, pandas and also seaborn to the mix.
%matplotlib inlineimport matplotlib.pyplot as pltimport pandas as pdimport numpy as npimport seaborn together sns
(The matplotlib inline is part magic to acquire inline plots in a Jupyter notebook, omit if you room working in one more setting.)
Now we can save ours table as a pandas DataFrame, let’s take a look at it:
df = pd.DataFrame(df, columns=<"Week", "HomeAbbrev", "AwayAbbrev", "HomeScore", "AwayScore">)df.head()
Let’s eliminate the (let’s admit, completely arbitrary) home-away distinction and just gain a dataframe of every scores by team. Let’s also include a categorical variable form for even if it is the video game was continual season or playoff.
df = (df<<"Week", "HomeAbbrev", "HomeScore">> .rename(columns="HomeAbbrev": "Abbrev", "HomeScore": "Score") .append(df<<"Week", "AwayAbbrev", "AwayScore">> .rename(columns="AwayAbbrev": "Abbrev", "AwayScore": "Score")) )df<"Type"> = pd.Series(<"Regular" if w14 else "Playoff" because that w in df<"Week">>)
To safeguard the innocent, ns renamed all the teams “A”, “B”, “C”, … here’s my df.head()
If you adjust violinplot to boxplot in the above code, you’ll gain the image at the start of this blog.
A few stories here: high scorers space unsurprisingly in higher standing than low scorers. Consistency no seem to issue much, as there are high variance groups at top and bottom. Yet playoff power absolutely does issue for the playoff groups (in this case, optimal 4) — in fact, Player D entered the playoffs as optimal seed and also finished 4th. Player E had actually the best playoff performance but had too numerous mediocre games in the continuous season. All story as old as time.
Doing the in R
I thought around redoing the above procedure in R, however realized
DTDusty already did it better: inspect out his blog end here. This is a teaser pic, whose filename allow the reader note is dusty_fantasy.png …
Other endpoints, exclusive leagues…
Another rabbit hole to discover is the various other “endpoints” come the API besides scoreboard. Here’s number of that I know about:leagueSettings playerInfo scoreboard player/news recentActivity leagueSchedules teams rosterInfo schedule polls messageboard condition teams/pendingMoveBatches tweets story livescoring (doesn’t seem to be functioning right) boxscore
Each the these deserve to be appended to the ESPN API URL and also be explored.
I’m most interested in boxscore which contains the weekly clues by player. However, it just returns the full information if you are logged into an account, which I’ve been unable to carry out through a obtain request. Try it: log in in to your ESPN account, and then enter the API URL
with your league ID. All the wanted info will certainly pop up. Now shot through a gain request and you’ll gain basically an empty dict. This shows there is some cookie/swid/other stuff being passed behind the scenes because that this endpoint. That is possible to send espn_s2 cookies, swid, and other details in the get request, but I haven’t acquired these to work. If did you do it cracked the password on this, you re welcome let me know.
See more: Why Did Howard Jones Leave Kse, Howard Jones (American Musician)
EDIT: ns think it be as basic as including a teamId parameter, but more to monitor in a later post …
EDIT2: the was: examine out the follow-on short articles on just how to gain boxscores, and then exactly how to attend to private leagues.
Hope this has been enjoyable, great luck this season!created on June 27th, 2018 by Steven Morse
developed by Steven Morse v Jekyll and the Lagrange template