GDub
GDub

Reputation: 638

How do you access the NFL's API's?

I've been trying to access or find away to access data from NFL.com, but have not found it yet. There is public documentation on these sites:

https://api.nfl.com/docs/identity/oauth2/index.html

but these docs do not tell you how to get a client id or client secret.

I've also tried:

http://api.fantasy.nfl.com/v2/docs

The documentation says that you need to send an email to [email protected] to get the app key. I sent an email a while ago and a follow up and I've received no responses.

You can send requests to these API's and they will respond telling you that you have invalid credentials.

Have you had any success with this? Am I doing something wrong? Are these sites out of date?

EDIT: I emailed them on 10/30/2015

Upvotes: 27

Views: 30220

Answers (3)

leat
leat

Reputation: 1467

You can replicate the experience of generating a client JWT token in Nfl.com by opening chrome inspector and going to nfl.com then clearing your application local storage and your network console, refreshing the page and then just watching the responses come across the line and how it issues a token.

I'd argue they probably have a bit of a security gap in how they issue tokens because they sent their clientId and clientSecret to the end user which is later posted back to the server create a JWT, when they should probably have some sort of end point that gens a token and also has some site origin protections, but hey makes consumption of the API a bit easier.

Usage:

        using (var client = await WebClientFactory.Create())
        {
            foreach (var week in all)
            {
                var url = $"https://api.nfl.com/football/v1/games?season={year}&seasonType=REG&week={week}&withExternalIds=true";
                var content = await client.DownloadStringTaskAsync(url);

                var obj = JsonConvert.DeserializeObject<SeasonStripV2>(content);

               // do so0mething here
            }
        }

The meat and potatoes:

public class WebClientFactory
{
    static WebClientFactory()
    {
        ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) =>
        {
            Console.WriteLine(er);
            // I had some cert troubles you may need to fiddle with this if you get a 405
            // if (c.Subject?.Trim() == "CN=clubsweb.san1.nfl.com")
            // {
            //     return true;
            // }
            
            Console.WriteLine(c);
            return false;
        };
    }
    public static async Task<WebClient> Create()
    {
        var clientInfo = new
                         {
                             clientId = "e535c7c0-817f-4776-8990-56556f8b1928",
                             clientKey = "4cFUW6DmwJpzT9L7LrG3qRAcABG5s04g",
                             clientSecret = "CZuvCL49d9OwfGsR",
                             deviceId = "1259aca6-3793-4391-9dc3-2c4b4c96abc5",
                             useRefreshToken = false
                         };

        var clientUploadInfo = JsonConvert.SerializeObject(clientInfo);
        var webRequest = WebRequest.CreateHttp("https://api.nfl.com/identity/v1/token/client");
        webRequest.Accept = "*/*";
        webRequest.ContentType = "application/json";
        webRequest.Method = WebRequestMethods.Http.Post;
        await WriteBody(webRequest, clientUploadInfo);
        var result = await GetResult(webRequest);
        var tokenWrapper = JsonConvert.DeserializeObject<RootV2>(result);

        var client = new WebClient();
        client.Headers.Add("Authorization", $"Bearer {tokenWrapper.accessToken}");
        return client;
    }

    private static async Task WriteBody(HttpWebRequest webRequest, string clientUploadInfo)
    {
        using (var stream = webRequest.GetRequestStream())
        {
            using (var sw = new StreamWriter(stream))
            {
                await sw.WriteAsync(clientUploadInfo);
            }
        }
    }

    private static async Task<string> GetResult(HttpWebRequest webRequest)
    {
        using (var response = await webRequest.GetResponseAsync())
        {
            return await GetResult((HttpWebResponse) response);
        }
    }

    private static async Task<string> GetResult(HttpWebResponse webResponse)
    {
        using (var stream = webResponse.GetResponseStream())
        {
            using (StreamReader sr = new StreamReader(stream))
            {
                return await sr.ReadToEndAsync();
            }
        }
    }
    private class RootV2
    {
        public string accessToken { get; set; }
        public int expiresIn { get; set; }
        public object refreshToken { get; set; }
    }
}

Note you can also getting a token by calling this endpoint:

POST "https://api.nfl.com/v1/reroute"
BODY: "device_id=5cb798ec-82fc-4ba0-8055-35aad432c492&grant_type=client_credentials"

and add these headers:

 client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
 client.Headers["X-Domain-Id"] = "100";

Upvotes: 0

Oleg Kozynenko
Oleg Kozynenko

Reputation: 77

Hooks Data provides a real-time API for major US sports including NFL.

1) Get API KEY here: https://www.hooksdata.io/signup?invite=SM4555

2) Subscribe to soccer games:

curl -H "Content-type: application/json" -d '{
"query": "SELECT * FROM NFLGames WHERE away_team.team_name = 'New England Patriots' OR home_team.team_name = 'New England Patriots' AND start_datetime.countdown = 3600"}' 'http://api.hooksdata.io/v1/subscriptions'

DOCS: https://www.hooksdata.io/docs/api/datasources/nflgames/

3) Optional: Add a Webhooks URL where you want to get the data: https://www.hooksdata.io/webhooks

4) Pull the data using fetch endpoint https://www.hooksdata.io/docs/api/api-reference/#query-datasource

5) Get all the data in JSON:

{
"matches_count": 1,
"results": [
    {
        "_entity_type": "NFLGame",
        "_id": "NFLGame_400999173",
        "away_score": null,
        "away_team": {
            "_entity_type": "NFLTeam",
            "_id": "NFLTeam_NE",
            "acronym": "NE",
            "division": "AFC East",
            "id": "NFLTeam_NE",
            "team_name": "New England Patriots"
        },
        "game_id": "400999173",
        "home_score": null,
        "home_team": {
            "_entity_type": "NFLTeam",
            "_id": "NFLTeam_PHI",
            "acronym": "PHI",
            "division": "NFC East",
            "id": "NFLTeam_PHI",
            "team_name": "Philadelphia Eagles"
        },
        "link": "http://espn.go.com/nfl/game?gameId=400999173",
        "start_datetime": null,
        "status": "FUTURE"
    }
]

}

Upvotes: -4

synthrom
synthrom

Reputation: 430

While I haven't had any success with api.nfl.com, I am able to get some data from the api.fantasy.nfl.com. You should have read access to all of the /players/* endpoints (e.g. http://api.fantasy.nfl.com/v1/players/stats?statType=seasonStats&season=2010&week=1&format=json). I would think you need an auth token for the league endpoints and the write endpoints.

How long ago did you email them?

EDIT: I emailed the NFL and this is what they had to say: "We've passed your API request along to our product and strategy teams. NFL.com Fantasy APIs are available on a per-use, case-by- case basis for NFL partners. Our team reviews other requests, but our APIs are typically not available for external usage otherwise."

Upvotes: 26

Related Questions