How to Query the Yahoo Fantasy Football API in .NET
October 4, 2011 1 Comment
As technical co-commissioner of my Keeper Fantasy Football league, I perform a good deal of administrative duties during the offseason. I have to sort through all the player transactions from the season to determine which NFL players are eligible to be kept within our league rules. One year, at the end of the 2010 season, I waited too long to gather this data. I normally click through the Yahoo Website to see all the historical transaction data necessary. However, after a certain point in the year, Yahoo removes access to the year’s information.
Luckily, in late 2009, Yahoo opened up their Fantasy Football API. Therefore, I was able to implement a .NET solution to retrieve the data I needed. Below are the steps I took.
The goal of our solution will be to create a simple ASP.NET Web Forms application that authenticates to Yahoo and then enables us to query the API.
Perhaps the most difficult hurdle to overcome is authentication. Yahoo uses a web standard called OAuth, which is a “simple, secure, and quick way to publish and access protected data”. You can find out more about it here, as I do not plan to delve into the low-level details of this protocol. The difficulty I found was that there are not many examples of .NET applications using this technology on the web.
To help us authenticate, we will leverage a .NET library called DevDefined OAuth.
- Create a new Web Forms solution and add a reference to this project or compiled dll.
In our next step, we will create a simple button (named AuthenticateButton) in the Default.aspx page to kick off the authentication process.
- Create a click event handler for your button. Enter the following code in the code-behind:
string requestUrl = “https://api.login.yahoo.com/oauth/v2/get_request_token”;
string userAuthorizeUrl = “https://api.login.yahoo.com/oauth/v2/request_auth”;
string accessUrl = “https://api.login.yahoo.com/oauth/v2/get_token”;
string callBackUrl = “http://domain.com/Query.aspx”;
protected void AuthenticateButton_Click(object sender, EventArgs e)
{
var consumerContext = new OAuthConsumerContext
{
ConsumerKey = “[provided by yahoo]”,
SignatureMethod = SignatureMethod.HmacSha1,
ConsumerSecret = “[provided by yahoo]”
};
var session = new OAuthSession(consumerContext, requestUrl, userAuthorizeUrl, accessUrl, callBackUrl);
// get a request token from the provider
IToken requestToken = session.GetRequestToken();
// generate a user authorize url for this token (which you can use in a redirect from the current site)
string authorizationLink = session.GetUserAuthorizationUrlForToken(requestToken, callBackUrl);
Session[“oAuthSession”] = session;
Session[“oAuthToken”] = requestToken;
Response.Redirect(authorizationLink);
}
To obtain your ConsumerKey and ConsumerSecret strings to place into the above code, go Yahoo’s Developer Projects Site and create a project. When creating your project, enter the Application URL (e.g. http://domain.com) and App Domain (e.g. domain.com) of the deployed location of your web site. Also, make sure to enable access to the Yahoo Fantasy Football API.
Take a look at the value in the callBackUrl string above. This needs to be edited to be an address on your web site. As part of the authentication process, Yahoo calls back to a URL on your site and therefore requires your site to be accessible from the public web.
- Add a new web page to your project named “Query.aspx”
- Place the below code in your Page_Load event handler
protected void Page_Load(object sender, EventArgs e)
{
OAuthSession session = (OAuthSession)Session[“oAuthSession”];
IToken requestToken = (IToken)Session[“oAuthToken”];
// exchange a request token for an access token
string oauth_verifier = Request.QueryString[“oauth_verifier”];
if (!String.IsNullOrEmpty(oauth_verifier))
{
IToken accessToken = session.ExchangeRequestTokenForAccessToken(requestToken, oauth_verifier);
Session[“oAuthSession”] = session;
}
}
Now that we are finished implementing the authentication code we can write the query submission logic.
- Add a textbox (named QueryTextBox), a label (named ResultsLabel), and a button (named QueryButton) to the Query.aspx page
- Add a click event handler for your button. Enter the following code in the code-behind:
protected void QueryButton_Click(object sender, EventArgs e)
{
string query = QueryTextBox.Text;
IConsumerRequest responseText = ((OAuthSession)Session[“oAuthSession”]).Request().Get().ForUrl(“http://fantasysports.yahooapis.com/fantasy/v2/” + query);
ResultsLabel.Text = responseText.ToString();
}
You are now ready to query the Yahoo Fantasy Football API. Here is how you use it.
- Load the page by navigating to http://domain.com (replace “domain” with your website domain name).
- Click the Authenticate button
- Yahoo’s site will guide you through the steps to login to your Fantasy Football account and redirect to your site when finished.
- Enter an API Query into the text box and click “Submit Query.”
There are definitely improvements that can be made to our sample application. For instance, the results output from our query are not easily readable, but they can be simply output to an xml document or some other format for reading.
The amount of data that can be extracted from the API is huge and can be leveraged for some very creative purposes. For more information about the query syntax as well as available data, see the Fantasy Sports API Documentation.
You can download the code for the sample application.
Lastly, below are some resourceful links:
http://github.com/buildmaster/oauth-mvc.net
http://oauth.googlecode.com/svn/code/csharp/
http://blog.techcle.com/2010/03/20/simple-oauth-integration-for-twitter-in-asp-net-mvc/
http://www.codeproject.com/KB/cs/Delicious-OAuth-API.aspx
http://code.google.com/p/devdefined-tools/w/list
http://developer.yahoo.com/fantasysports/
http://developer.yahoo.net/forum/index.php?showforum=122