0% found this document useful (0 votes)
15 views6 pages

Introduction to Fruityvice API in Python

This document is a hands-on lab guide for creating and using APIs in Python, specifically focusing on REST APIs and the Pandas library. It provides step-by-step instructions for accessing NBA data to analyze the performance of the Golden State Warriors against the Toronto Raptors. The lab includes code snippets for data manipulation and visualization using Python libraries such as Pandas and Matplotlib.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views6 pages

Introduction to Fruityvice API in Python

This document is a hands-on lab guide for creating and using APIs in Python, specifically focusing on REST APIs and the Pandas library. It provides step-by-step instructions for accessing NBA data to analyze the performance of the Golden State Warriors against the Toronto Raptors. The lab includes code snippets for data manipulation and visualization using Python libraries such as Pandas and Matplotlib.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

2/8/25, 5:36 AM PY0101EN-5.

1_Intro_API

Hands-on Lab: Introduction to API


Estimated time needed: 15 minutes

Objectives
After completing this lab you will be able to:

Create and use APIs in Python

Introduction
An 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 Contents

Pandas is an API
REST APIs
Quiz

Pandas is an API
Pandas is actually set of software components , much of which is not even written in Python.

In [ ]: import pandas as pd
import [Link] as plt

You create a dictionary, this is just data.

In [ ]: dict_={'a':[11,21,31],'b':[12,22,32]}

[Link] 1/6
2/8/25, 5:36 AM PY0101EN-5.1_Intro_API

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.

In [ ]: df=[Link](dict_)
type(df)

When you call the method head the dataframe communicates with the API displaying the
first few rows of the dataframe.

In [ ]: [Link]()

When you call the method mean , the API will calculate the mean and return the value.

In [ ]: [Link]()

REST APIs
Rest APIs 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 to determine the 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 will handle a lot of the details, such a
Endpoints and Authentication.

It's quite simple to use the nba api to make a request for a specific team. 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 .

[Link] 2/6
2/8/25, 5:36 AM PY0101EN-5.1_Intro_API

In [ ]: !pip install nba_api

In [ ]: from nba_api.[Link] import teams


import [Link] as plt

In [ ]: 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

The method get_teams() returns a list of dictionaries.

In [ ]: nba_teams = teams.get_teams()

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:

In [ ]: nba_teams[0:3]

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.

In [ ]: dict_nba_team=one_dict(nba_teams)
df_teams=[Link](dict_nba_team)
df_teams.head()

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:

In [ ]: df_warriors=df_teams[df_teams['nickname']=='Warriors']
df_warriors

We can use the following line of code to access the first column of the DataFrame:

In [ ]: id_warriors=df_warriors[['id']].values[0][0]
# we now have an integer that can be used to request the Warriors information
id_warriors

The function "League Game Finder " will make an API call, it's in the module
[Link] .

In [ ]: from nba_api.[Link] import leaguegamefinder

[Link] 3/6
2/8/25, 5:36 AM PY0101EN-5.1_Intro_API

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 game finder .

In [ ]: # Since [Link] does not allow api calls from Cloud IPs and Skills Ne
# The following code is commented out, you can run it on jupyter labs on your own c
# gamefinder = [Link](team_id_nullable=id_warriors)

We can see the json file by running the following line of code.

In [ ]: # Since [Link] does not allow api calls from Cloud IPs and Skills Ne
# The following code is commented out, you can run it on jupyter labs on your own c
# gamefinder.get_json()

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 won by that
amount of points. The column MATCHUP has 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.

In [ ]: # Since [Link] does not allow api calls from Cloud IPs and Skills Ne
# The following code is comment out, you can run it on jupyter labs on your own com
# games = gamefinder.get_data_frames()[0]
# [Link]()

You can download the dataframe from the API call for Golden State and run the rest like a
video.

In [ ]: import requests

filename = "[Link]

def download(url, filename):


response = [Link](url)
if response.status_code == 200:
with open(filename, "wb") as f:
[Link]([Link])

download(filename, "Golden_State.pkl")

In [ ]: file_name = "Golden_State.pkl"
games = pd.read_pickle(file_name)
[Link]()

[Link] 4/6
2/8/25, 5:36 AM PY0101EN-5.1_Intro_API

We can create two dataframes, one for the games that the Warriors faced the raptors at
home, and the second for away games.

In [ ]: games_home=games[games['MATCHUP']=='GSW vs. TOR']


games_away=games[games['MATCHUP']=='GSW @ TOR']

We can calculate the mean for the column PLUS_MINUS for the dataframes games_home
and games_away :

In [ ]: games_home['PLUS_MINUS'].mean()

In [ ]: games_away['PLUS_MINUS'].mean()

We can plot out the PLUS MINUS column for the dataframes games_home and
games_away . We see the warriors played better at home.

In [ ]: fig, ax = [Link]()

games_away.plot(x='GAME_DATE',y='PLUS_MINUS', ax=ax)
games_home.plot(x='GAME_DATE',y='PLUS_MINUS', ax=ax)
[Link](["away", "home"])
[Link]()

Quiz
Calculate the mean for the column PTS for the dataframes games_home and
games_away :

In [ ]: # Write your code below and press Shift+Enter to execute

Click here for the solution

Authors:
Joseph Santarcangelo

Joseph Santarcangelo has a PhD in Electrical Engineering, his research focused on using
machine learning, signal processing, and computer vision to determine how videos impact
human cognition. Joseph has been working for IBM since he completed his PhD. <!---

Change Log

[Link] 5/6
2/8/25, 5:36 AM PY0101EN-5.1_Intro_API

Date (YYYY-MM-
Version Changed By Change Description
DD)

Abhishek Minor formatting updates and some


2023-11-09 2.2
Gagneja instructional updates

2020-09-09 2.1 Malika Singla Spell Check

2020-08-26 2.0 Lavanya Moved lab to course repo in GitLab

---!>

© IBM Corporation 2023. All rights reserved.

In [ ]:

[Link] 6/6

Common questions

Powered by AI

The 'get_data_frames()' method converts the API response into a DataFrame containing various game statistics. The 'PLUS_MINUS' column specifically indicates game outcomes, showing whether the Warriors won or lost by the margin of the score. A positive value means a win by that score margin, while a negative value signifies a loss by the same margin .

The 'MATCHUP' column indicates the teams playing in a game with the format showing the initials of the teams and a symbol to differentiate the venue. 'vs' signifies a home game, and '@' indicates an away game. For instance, 'GSW vs. TOR' indicates the Warriors played at home against the Raptors, while 'GSW @ TOR' indicates an away game .

Instructional updates, such as formatting and clarifying explanations, directly improve comprehension by making technical content more accessible and logically organized. The change log indicates ongoing refinements aimed at reducing confusion, which is especially important when teaching complex subjects like APIs where clear steps and rationale support learning outcomes .

The process involves retrieving a list of teams as dictionaries using the 'get_teams()' method. Each team has a unique 'id' used as a key. By converting this list to a DataFrame and filtering by the team's nickname, such as 'Warriors', you can extract its unique ID. This ID is crucial for making further API requests to retrieve specific data about that team .

The League Game Finder uses a unique team ID to make HTTP requests for historical game data, providing it in a structured DataFrame format. However, a limitation noted is its inaccessibility from cloud environments due to restrictions on API calls, necessitating use on local machines for execution .

The 'one_dict' function initializes a dictionary with keys from the first dictionary in a list, then appends values of each key across all dictionaries to lists in a new dictionary. This structure is converted into a DataFrame, enabling streamlined access and manipulation of structured data, which is critical for efficient use of APIs by standardizing data input formats .

Pandas acts as an API by converting data into DataFrames which then communicate with the API for data manipulations. For instance, methods like 'head()' or 'mean()' on a DataFrame internally use the API to generate outputs such as the first few rows of data or calculating the mean .

Machine learning can process large datasets efficiently to uncover patterns, while data visualization allows for clear insights into performance trends. Using the NBA API, historical game data can be modeled to predict future game outcomes, and visualizing metrics like 'PLUS_MINUS' helps interpret performance over time, revealing strengths and weaknesses in different contexts .

REST APIs facilitate communication by sending requests via HTTP messages, typically containing JSON files with instructions for operations. The responses are also communicated via HTTP messages and usually returned in JSON format .

JSON files provide a lightweight format for data interchange that REST APIs utilize for inputs, which include data operations or commands sent over HTTP in Python applications. The API interprets these JSON instructions and processes them, returning outputs also formatted as JSON files to be used or further processed by the application .

You might also like