<jupyter_start><jupyter_text>Application Programming InterfaceEstimated time needed: **15** minutes ObjectivesAfter completing this lab you will be able to:-   Create and Use APIs in Python  IntroductionAn API lets two pieces of software talk to each other. Just like a function,  you don’t have to know how the API works only its inputs and outputs.  An essential type of API is a REST API that allows you to access resources via the internet. In this lab, we will review the Pandas Library  in the context of an API, we will also review a basic REST API    Table of ContentsPandas is an APIREST APIs Basics  Quiz on Tuples<jupyter_code>!pip install nba_api<jupyter_output><empty_output><jupyter_text>Pandas is an API  You will use this function in the lab:<jupyter_code>def one_dict(list_dict):
    keys=list_dict[0].keys()
    out_dict={key:[] for key in keys}
    for dict_ in list_dict:
        for key, value in dict_.items():
            out_dict[key].append(value)
    return out_dict<jupyter_output><empty_output><jupyter_text>Pandas is an API  Pandas is actually set of software components , much of  which is not even written in Python.<jupyter_code>import pandas as pd
import matplotlib.pyplot as plt<jupyter_output><empty_output><jupyter_text>You create a dictionary, this is just data.<jupyter_code>dict_={'a':[11,21,31],'b':[12,22,32]}<jupyter_output><empty_output><jupyter_text>When you create a Pandas object with the Dataframe constructor in API lingo, this is an "instance". The data in the dictionary is passed along to the pandas API. You then use the dataframe to communicate with the API.<jupyter_code>df=pd.DataFrame(dict_)
type(df)<jupyter_output><empty_output><jupyter_text>When you call the method head the dataframe communicates with the API displaying the first few rows of the dataframe.<jupyter_code>df.head()<jupyter_output><empty_output><jupyter_text>When you call the method mean,the API will calculate the mean and return the value.<jupyter_code>df.mean()<jupyter_output><empty_output><jupyter_text>REST APIs Rest API’s function by sending a request,  the request is communicated via HTTP message. The HTTP message usually contains a JSON file. This contains instructions for what operation we would like the service or resource to perform. In a similar manner, API returns a response, via an HTTP message, this response is usually contained within a JSON.In this lab, we will use the NBA API to determine how well the Golden State Warriors performed against the Toronto Raptors. We will use the API do the determined number of points the Golden State Warriors won or lost by for each game. So if the value is three, the Golden State Warriors won by three points. Similarly it the  Golden State Warriors lost  by two points the result will be negative two. The API is relatively will handle a lot of the details such a Endpoints and Authentication  In the nba api to make a request for a specific team, it's quite simple, we don't require a JSON all we require is an id. This information is stored locally in the API we import the module teams<jupyter_code>from nba_api.stats.static import teams
import matplotlib.pyplot as plt
#https://pypi.org/project/nba-api/<jupyter_output><empty_output><jupyter_text>The method get_teams() returns a list of dictionaries  the dictionary key id has a unique identifier for each team as a value<jupyter_code>nba_teams = teams.get_teams()<jupyter_output><empty_output><jupyter_text>The dictionary key id has a unique identifier for each team as a value, let's look at the first three elements of the list:<jupyter_code>nba_teams[0:3]<jupyter_output><empty_output><jupyter_text>To make things easier, we can convert the dictionary to a table. First, we use the function one dict, to create a dictionary. We use the common keys for each team as the keys,  the value is a list; each element of the list corresponds to the values for each team.We then convert the dictionary to a dataframe, each row contains the information for a different team.<jupyter_code>dict_nba_team=one_dict(nba_teams)
df_teams=pd.DataFrame(dict_nba_team)
df_teams.head()<jupyter_output><empty_output><jupyter_text>Will use the team's nickname to find the unique id, we can see the row that contains the warriors by using the column nickname as follows:<jupyter_code>df_warriors=df_teams[df_teams['nickname']=='Warriors']
df_warriors<jupyter_output><empty_output><jupyter_text>we can use the following line of code to access the first column of the dataframe:<jupyter_code>id_warriors=df_warriors[['id']].values[0][0]
#we now have an integer that can be used   to request the Warriors information 
id_warriors<jupyter_output><empty_output><jupyter_text>The function "League Game Finder " will make an API call, its in the module stats.endpoints<jupyter_code>from nba_api.stats.endpoints import leaguegamefinder<jupyter_output><empty_output><jupyter_text>The parameter team_id_nullable is the unique ID for the warriors. Under the hood, the NBA API is making a HTTP request.  The information requested is provided and is transmitted via an HTTP response this is assigned to the object gamefinder.<jupyter_code># Since https://stats.nba.com does lot allow api calls from Cloud IPs and Skills Network Labs uses a Cloud IP.
# The following code is comment out, you can run it on jupyter labs on your own computer.
# gamefinder = leaguegamefinder.LeagueGameFinder(team_id_nullable=id_warriors)<jupyter_output><empty_output><jupyter_text>we can see the json file by running the following line of code.<jupyter_code># Since https://stats.nba.com does lot allow api calls from Cloud IPs and Skills Network Labs uses a Cloud IP.
# The following code is comment out, you can run it on jupyter labs on your own computer.
# gamefinder.get_json()<jupyter_output><empty_output><jupyter_text>The game finder object has a method get_data_frames(), that returns a dataframe.  If we view the dataframe, we can see it contains information about all the games the Warriors played.  The PLUS_MINUS column contains information on the score, if the value is negative the Warriors lost by that many points, if the value is positive, the warriors one by that amount of points. The column MATCHUP had the team the Warriors were playing, GSW stands for Golden State Warriors and TOR means Toronto Raptors; vs signifies it was a home game and the @ symbol means an away game.<jupyter_code># Since https://stats.nba.com does lot allow api calls from Cloud IPs and Skills Network Labs uses a Cloud IP.
# The following code is comment out, you can run it on jupyter labs on your own computer.
# games = gamefinder.get_data_frames()[0]
# games.head()<jupyter_output><empty_output><jupyter_text>you can download the dataframe from the API call for Golden State and run the rest like a video.<jupyter_code>! wget https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Chapter%205/Labs/Golden_State.pkl
file_name = "Golden_State.pkl"
games = pd.read_pickle(file_name)
games.head()<jupyter_output><empty_output><jupyter_text>We can create two dataframes, one  for the games that the Warriors faced the raptors at home and the second for away games.<jupyter_code>games_home=games [games ['MATCHUP']=='GSW vs. TOR']
games_away=games [games ['MATCHUP']=='GSW @ TOR']<jupyter_output><empty_output><jupyter_text>We can calculate the mean for the column  PLUS_MINUS for the dataframes  games_home and  games_away:<jupyter_code>games_home.mean()['PLUS_MINUS']
games_away.mean()['PLUS_MINUS']<jupyter_output><empty_output><jupyter_text>We can plot out the PLUS MINUS column for  for the dataframes  games_home and  games_away.We see the warriors played better at home.<jupyter_code>fig, ax = plt.subplots()

games_away.plot(x='GAME_DATE',y='PLUS_MINUS', ax=ax)
games_home.plot(x='GAME_DATE',y='PLUS_MINUS', ax=ax)
ax.legend(["away", "home"])
plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.06835123183828175, 'fraction_numerical': 0.0035375868603916612, 'mean_word_length': 5.737021276595745, 'pattern_counts': {'":': 0, '<': 85, '<?xml version=': 0, '>': 85, 'https://': 5, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '21', 'dir': 'jupyter-structured-clean-dedup', 'id': '14849', 'license': 'MIT', 'n_tokens_mistral': 2412, 'n_tokens_neox': 2335, 'n_words': 979, 'path': 'Python for AI and DataScience/PY0101EN-5.1_Intro_API.ipynb', 'repo_name': 'amitkrishna/IBM-DataScience', 'size': '7915'}