Track Your Favorite NBA Team’s Performance with API-NBA

- Posted in Tutorials by

If you are a die-hard NBA fan then how about taking a closer look at your favorite team’s performance. With the NBA API hosted on RapidAPI, you can do that and more.

The NBA API is a treasure trove of data. From seasons to leagues, and teams to players, it can spew out a lot of data for you to consume. So why not put this basketball sports API into action and show you how to extract some meaningful information from this data.

In this blog post, we are going to build a quick chart of NBA team performance during a season. The language of choice is Python and we will leverage the Seaborn charting library to build a plot of an NBA team’s standing during a season.

enter image description here

The NBA API console can be accessed here.

enter image description here

As you can see from the endpoints, this API has lots and lots of options for getting information specific to seasons, leagues, teams, players and games. The API also supports separate endpoints for fetching data related to standings and statistics for games and players.

Lets’s leverage the rich dataset offered by the NBA API to build a performance dashboard for tracking teams.

How to get access to the NBA API

1. Sign Up for a RapidAPI User Account

To begin using the NBA API, you’ll first need to sign up for a free RapidAPI developer account.

RapidAPI is the world’s largest API marketplace, with over 10,000 APIs and over 1,000,000 developers. Our goal is to help developers find and connect to APIs to help them build amazing apps.

Once you sign up, you will get a single API key with which you can gain access to all our APIs

2. Navigate to the NBA API Console

Search for “API-NBA” in the search bar, or you can also directly access the API Console here.

enter image description here

3. Subscribe to the NBA API

Once you have successfully navigated to the NBA API console page, click on the “pricing” tab and subscribe to the basic plan. (hint: It’s free to use up to 1000 requests/day)

enter image description here

How much does the NBA API Cost?

API-Sports has now made the API completely free to use.

How To Use the NBA API with Python

You will now learn how to use the NBA API with Python to build a team standings chart for each NBA season.

Before we get into the code level details, let’s test this API to explore the options.

NBA API Endpoints Overview

Log on to your RapidAPI account. Once you are in the NBA API console page, you can see the listing of the API endpoints.

enter image description here

Click on the “/seasons/” endpoint and hit the “Test Endpoint” button.

enter image description here

You will get the API response containing the NBA season years whose data can be fetched from this API.

enter image description here

Similarly, the other endpoints categories can be used to retrieve data about teams, players and games.

The last two endpoint categories, “standings” and “statistics” are very interesting. They provide comparison data about team standings as well as historic data about a player’s career or a team’s performance since its inception.

enter image description here

Getting the NBA Team Standings Data

You can test the “/standings/” endpoint, to get the ranking of each team for a particular season.

enter image description here

For ‘standard’ league and ‘2018’ season, the API response looks like:

enter image description here

The expanded data shown for one team shows you detailed insights. You will get to know about the team’s performance during the season along with some key indicators, such as the number of wins, losses, last ten wins/loss counts and winning streak, etc.

We will use this data to write a short Python program that renders a comparative standings chart for an NBA season.

The code snippet for calling the API using Python is available as part of the console. Choose “Python” > “Unirest” under the “Code Snippet” tab and you can see the sample code.

enter image description here

How to Build a Team Standings Chart App for the NBA Season

Building the standings chart is a fun and easy way to analyze the performance of your favorite NBA team. So let’s get started with the coding now. Follow along with the steps below to build your own charting app from the NBA API using Python.

But first, you have to set up the programming environments with the requisite tools and libraries that we will be using in this app.

Prerequisites

Here is what you need in terms of the Python runtime.

  • Python 2.7
  • Pip ( any recent version of pip that ships with Python 2.7)

Now, you also need to install the libraries that will be used in this app.

Python Libraries

Seaborn

Seaborn is a Python visualization library that works on top of the popular matplotlib library. This will render the data and display it as a chart.

To install Seaborn, run the following command within your Python 2.7 runtime:

pip install seaborn

Unirest

unirest is a lightweight HTTP library. You will use this to invoke the NBA API endpoints.

To install the Python version of this library, invoke the pip command as follows:

pip install unirest

Pandas

Pandas is a data analysis library for Python. It is used to prepare and hold the team performance data returned from the NBA API. It is the default choice of data storage buffer for Seaborn.

pip install pandas

Coding the NBA Performance Chart App

It’s time to exercise your Python coding chops. Open your favorite code editor and follow along with the steps below to build the code.

1. Import the libraries

First up, you need to import the python modules that are used in this app.

Here is the list of all imports:

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import unirest
import matplotlib.ticker as ticker

2. Initialize the Global Data

You need to define some global data to store configurations as well as transient data. Extend the code below the import statements with these global declarations:

unirest.timeout(15) # 5s timeout
RAPIDAPI_KEY  = "<YOUR_RAPIDAPI_KEY>" 
RAPIDAPI_HOST = "<YOUR_RAPIDAPI_ENDPOINT>"
season_string = ""
inputdata = dict()
inputdata["Teams"] = list()
inputdata["Result"] = list()
inputdata["Win-Loss"] = list()

Don’t forget to replace the placeholders and with your own subscription specific values displayed in the code snippet within the API console.

3. Call the API to Fetch Team Standings

def fetchStandingData(year):

  response = unirest.get("https://api-nba-v1.p.rapidapi.com/standings/standard/" + year,
    headers={
      "X-RapidAPI-Host": RAPIDAPI_HOST,
      "X-RapidAPI-Key": RAPIDAPI_KEY

    }
  )

  if(response.code == 200):
    return response.body
  else:

    return None

In this function, you will pass the season year as an argument and call the API to get the entire standings data for all teams during that season.

4. Call the API to Fetch Team Data

The standings API endpoint returns all the data with numeric team ids that are internally defined by the API. You have to convert the team ids to the team name so that the chart looks more readable. There is a separate endpoint, ‘/teams/’, for that. You need another function to call this API and retrieve the teams’ full name.

def fetchTeamNames(teamId):
  response = unirest.get("https://api-nba-v1.p.rapidapi.com/teams/teamId/" + teamId,
    headers={
      "X-RapidAPI-Host": RAPIDAPI_HOST,
      "X-RapidAPI-Key": RAPIDAPI_KEY
    }
  )
  if(response.code == 200):
    return response.body["api"]["teams"][0]["fullName"]
  else:
    return None

5. Parse the Team Standings Data

We now move on to the main function of the program.

The program will first take the user input for the season and then parse the standings data.

if __name__ == "__main__":

  try:
    while len(season_string) <= 2:
      season_string = raw_input("Enter the NBA Season: ")

    response = fetchStandingData(season_string)

    if (None != response): 

      standings_data = response["api"]["standings"] 

      for team_data in standings_data:

        team_name =  fetchTeamNames(team_data["teamId"])

        inputdata["Teams"].append(team_name)
        inputdata["Result"].append("Win")
        inputdata["Win-Loss"].append(int(team_data["win"]))



        inputdata["Teams"].append(team_name)
        inputdata["Result"].append("Loss")
           inputdata["Win-Loss"].append(int(team_data["loss"]))

        print "Team name: " + team_name
        print "Wins: " + team_data["win"]
        print "Loss: " + team_data["loss"]
        print "n"

      df = pd.DataFrame(inputdata)

The parsing logic extracts the count of wins and losses for each team, prints it and populates it in the inputdata dictionary.

Subsequently, it is loaded in the Pandas data frame variable df. The inputdata also contains an additional list for storing the string “win” and “loss” against each count to label the data.

6. Plot the Chart

Now you can load the inputdata into the Seaborn catplot( ) function to display the bar chart.

sns.set(style="darkgrid")

ax = sns.catplot(x="Teams", y="Win-Loss", hue="Result",data=df,kind="bar",height=4,aspect=2)

plt.xticks(
    rotation=45, 
    horizontalalignment='right',
    fontweight='light',
    fontsize='xx-small'  
)

plt.tight_layout()
plt.show()

Take a closer look at catplot( ) function. It accepts the df buffer and defines the kind of chart as “bar”.

This is how the standings chart looks like for the 2018 NBA season. Each team is represented by a blue and a red bar to indicate their win and loss counts during the season.

enter image description here

Voila! You are now done. Here is the complete program in case you want to refer to it:

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import unirest
import matplotlib.ticker as ticker


unirest.timeout(15) # 5s timeout

RAPIDAPI_KEY  = "<YOUR_RAPIDAPI_KEY>" 
RAPIDAPI_HOST = "<YOUR_RAPIDAPI_ENDPOINT>"

season_string = ""

inputdata = dict()
inputdata["Teams"] = list()
inputdata["Result"] = list()
inputdata["Win-Loss"] = list()




def fetchStandingData(year):

  response = unirest.get("https://api-nba-v1.p.rapidapi.com/standings/standard/" + year,
    headers={
      "X-RapidAPI-Host": RAPIDAPI_HOST,
      "X-RapidAPI-Key": RAPIDAPI_KEY

    }
  )

  if(response.code == 200):
    return response.body
  else:

    return None

def fetchTeamNames(teamId):

  response = unirest.get("https://api-nba-v1.p.rapidapi.com/teams/teamId/" + teamId,
    headers={
      "X-RapidAPI-Host": RAPIDAPI_HOST,
      "X-RapidAPI-Key": RAPIDAPI_KEY
    }
  )

  if(response.code == 200):
    return response.body["api"]["teams"][0]["fullName"]
  else:

    return None

if __name__ == "__main__":

  try:
    while len(season_string) <= 2:
      season_string = raw_input("Enter the NBA Season: ")

    response = fetchStandingData(season_string)

    if (None != response): 

      standings_data = response["api"]["standings"] 

      for team_data in standings_data:

        team_name =  fetchTeamNames(team_data["teamId"])

        inputdata["Teams"].append(team_name)
        inputdata["Result"].append("Win")
        inputdata["Win-Loss"].append(int(team_data["win"]))



        inputdata["Teams"].append(team_name)
        inputdata["Result"].append("Loss")
        inputdata["Win-Loss"].append(int(team_data["loss"]))

        print "Team name: " + team_name
        print "Wins: " + team_data["win"]
        print "Loss: " + team_data["loss"]
        print "n"

      df = pd.DataFrame(inputdata)

      sns.set(style="darkgrid")

      ax = sns.catplot(x="Teams", y="Win-Loss", hue="Result",data=df,kind="bar",height=4,aspect=2)

      plt.xticks(
          rotation=45, 
          horizontalalignment='right',
          fontweight='light',
          fontsize='xx-small'  
      )

      plt.tight_layout()
      plt.show()

  except Exception as e:
    print "Error"   
    print e

Get the Live NBA Team Standings Now

The good part about this API is that it can also fetch data for a live game.

Moreover, if you want to follow the current season, then you can call this program to get the 2019 season standings as of now.

Note: At the time of this writing, the NBA API only returns data for the 2018 and 2019 seasons. Querying the program for seasons before 2018 will not return any data and the chart will not be displayed.

Wrapping Up

We have shown you yet another powerful way of analyzing data from APIs. You can extend this program to cover things like performance standings for teams within leagues and players within teams. For those of you who consider themselves as data science nerds, you can explore the “/statistics/” API endpoint to get more granular details about each game and player.

Signing off now, until we are back soon with yet another interesting API tutorial powered by RapidAPI.

This tutorial is taken from RapidAPI and written by Shyam Purkayastha.