Python, RapidAPI Terms

APIs and tooling like Jupyter docs allows many opportunities in fields like Data Science. As more and more developers use APIs, they build standards in how you setup a client, send requests and receive information...

Covid19 RapidAPI Example

To begin the API journey. You need to find an API provider.

  • RapidAPI is a great option. You must setup and account, but there are many free options.
  • Goto this page for starters, the Corona virus World and India data- Under Code Snippets pick Python - Requests

RapidAPI, you will select Python Requests type of code to work with you Notebook.

  • The url is the endpoint to which the API is directed
  • The headers is a dictionary data structure to send special messaging to the endpoint
  • The requests.request() python function is used to send a request and retrieve their responses
  • The response variable receives result of of the request in JSON text

Next step, is to format the response according to your data science needs

"""
Requests is a HTTP library for the Python programming language. 
The goal of the project is to make HTTP requests simpler and more human-friendly. 
"""
import requests

"""
RapidAPI is the world's largest API Marketplace. 
Developers use Rapid API to discover and connect to thousands of APIs. 
"""
url = "https://corona-virus-world-and-india-data.p.rapidapi.com/api"
headers = {
    'x-rapidapi-key': "6fa44ed3a2msh483515e3beca32dp153a87jsn04ee72a909e0",
    'x-rapidapi-host': "corona-virus-world-and-india-data.p.rapidapi.com"
}

# Request Covid Data
response = requests.request("GET", url, headers=headers)
# print(response.text)  # uncomment this line to see raw data

# print(response.json[])

# This code looks for "world data"
print("World Totals")
world = response.json().get('world_total')  # turn response to json() so we can extract "world_total"
for key, value in world.items():  # this finds key, value pairs in country
    print(key, value)

print()

# This code looks for USA in "countries_stats"
print("Country Totals")
countries = response.json().get('countries_stat')
for country in countries:  # countries is a list
    if country["country_name"] == "USA":  # this filters for USA
        for key, value in country.items():  # this finds key, value pairs in country
            print(key, value)
World Totals
total_cases 509,268,964
new_cases 204,268
total_deaths 6,242,509
new_deaths 630
total_recovered 461,827,849
active_cases 41,198,606
serious_critical 42,510
total_cases_per_1m_population 65,334
deaths_per_1m_population 800.9
statistic_taken_at 2022-04-24 11:18:01

Country Totals
country_name USA
cases 82,649,779
deaths 1,018,316
region 
total_recovered 80,434,925
new_deaths 0
new_cases 0
serious_critical 1,465
active_cases 1,196,538
total_cases_per_1m_population 247,080
deaths_per_1m_population 3,044
total_tests 1,000,275,726
tests_per_1m_population 2,990,303

Digital Coin Example

This example provides digital coin feedback (ie Bitcoin). It include popularity, price, symbols, etc.

  • A valid X-RapidAPI-Key is required. Look in code for link to RapidAPI page
  • Read all comments in code for further guidance
# RapidAPI page https://rapidapi.com/Coinranking/api/coinranking1/
 
# Begin Rapid API Code
import requests
 
url = "https://coinranking1.p.rapidapi.com/coins"
querystring = {"referenceCurrencyUuid":"yhjMzLPhuIDl","timePeriod":"24h","tiers[0]":"1","orderBy":"marketCap","orderDirection":"desc","limit":"50","offset":"0"}
headers = {
   "X-RapidAPI-Key": "6fa44ed3a2msh483515e3beca32dp153a87jsn04ee72a909e0",  # place your key here
   "X-RapidAPI-Host": "coinranking1.p.rapidapi.com"
}
 
response = requests.request("GET", url, headers=headers, params=querystring)
# End Rapid API Code
json = response.json()  # convert response to python json object
 
# Observe data from an API.  This is how data transports over the internet in a "JSON" text form
# - The JSON "text" is formed in dictionary {} and list [] divisions
# - To read the result, Data Scientist of  Developer converts JSON into human readable form
# - Review the first line, look for the keys --  "status" and "data"
 
for coin in json["data"]["coins"]: # json is calling the data
   print (f'{coin["price"]} {coin["symbol"]} {coin["name"]}') #this is the way the data is formatted
19224.447593601126 BTC Bitcoin
1308.199551212318 ETH Ethereum
1.0000523455427062 USDT Tether USD
1.0002524530884096 USDC USDC
274.74450631272896 BNB Binance Coin
0.5211455214949348 XRP XRP
1.000171247381502 BUSD Binance USD
0.4139552402915634 ADA Cardano
32.454134482189296 SOL Solana
0.06054842848035766 DOGE Dogecoin
6.354403003989721 DOT Polkadot
0.835383532602989 MATIC Polygon
0.000010736474729842 SHIB Shiba Inu
0.999891639898776 DAI Dai
0.06351970963448027 TRX TRON
1308.950203374039 WETH Wrapped Ether
6.352808919826807 UNI Uniswap
16.582266591683975 AVAX Avalanche
4.534812109996118 CAKE PancakeSwap
16.097275035337095 OKB OKB
12.790865904079196 ATOM Cosmos
53.16388872968613 LTC Litecoin
23.87294802061375 FTT FTX Token
25.39839861266645 ETC Ethereum Classic
146.14913616438486 XMR Monero
0.1256703462070973 XLM Stellar
0.32924309203358804 ALGO Algorand
113.34545922204282 BCH Bitcoin Cash
19245.95077301717 BTCB Bitcoin BEP2
0.10541410004274888 CRO Cronos
3.4418393654122696 NEAR NEAR Protocol
0.000293866408536083 LUNC Terra Classic
1.742193550502613 WEMIX WEMIX TOKEN
1.6497345409755526 FLOW Flow
16.524231414902868 ENS EnergySwap
5.292418584086171 FIL Filecoin
0.02320353209595045 VET VeChain
155.68731956157967 QNT Quant
0.6842150594079114 MANA Decentraland
5.624430651470011 ICP Internet Computer (DFINITY)
0.05983121896177806 HBAR Hedera
0.7083305292153628 IMX Immutable X
0.9998613493400573 FRAX Frax
57.322221492067925 EGLD Elrond
1.398063181968517 XTZ Tezos
0.8232983748529789 SAND The Sandbox
0.20047738370702253 CHZ Chiliz
1.340424033760174 LDO Lido DAO Token
5.222843346525186 HT Huobi Token
74.84882436943164 AAVE Aave
import requests

url = "https://americanfootballapi.p.rapidapi.com/api/american-football/search/brady"

querystring = {"sort":"new"}

headers = {
	"X-RapidAPI-Key": "6fa44ed3a2msh483515e3beca32dp153a87jsn04ee72a909e0",
	"X-RapidAPI-Host": "americanfootballapi.p.rapidapi.com"
}

response = requests.request("GET", url, headers=headers, params=querystring)

print(response.text)
json = response.json().get('results')  # convert response to python json object
 
# Observe data from an API.  This is how data transports over the internet in a "JSON" text form
# - The JSON "text" is formed in dictionary {} and list [] divisions
# - To read the result, Data Scientist of  Developer converts JSON into human readable form
# - Review the first line, look for the keys --  "status" and "data"

for post in json: # countries in a list
	for posts in post["entity"]:
		if posts["country"].get("name") == "USA":
			for key, value in post.items():
				print(key, value)
{"results":[{"entity":{"category":null,"country":{"alpha2":"US","name":"USA"},"disabled":null,"displayInverseHomeAwayTeams":null,"firstName":"","gender":null,"id":853680,"lastName":"","name":"Tom Brady","nameCode":null,"national":null,"position":"QB","ranking":null,"shortName":"T. Brady","slug":"brady-tom","sport":null,"team":{"country":{"alpha2":"US","name":"USA"},"disabled":false,"gender":"M","id":4388,"name":"Tampa Bay Buccaneers","nameCode":"TB","national":false,"ranking":null,"shortName":"Tampa Bay Buccaneers","slug":"tampa-bay-buccaneers","sport":{"id":63,"name":"American football","slug":"american-football"},"teamColors":{"primary":"#d50a0a","secondary":"#34302b","text":"#34302b"},"type":0,"userCount":14077},"teamColors":null,"type":null,"userCount":10394},"score":1274827,"type":"player"},{"entity":{"category":null,"country":{"alpha2":null,"name":null},"disabled":null,"displayInverseHomeAwayTeams":null,"firstName":"","gender":null,"id":1132339,"lastName":"","name":"Brady Christensen","nameCode":null,"national":null,"position":"OT","ranking":null,"shortName":"B. Christensen","slug":"christensen-brady","sport":null,"team":{"country":{"alpha2":"US","name":"USA"},"disabled":null,"gender":"M","id":4415,"name":"Carolina Panthers","nameCode":"CAR","national":false,"ranking":null,"shortName":"Carolina Panthers","slug":"carolina-panthers","sport":{"id":63,"name":"American football","slug":"american-football"},"teamColors":{"primary":"#3a84c5","secondary":"#07141e","text":"#07141e"},"type":0,"userCount":2480},"teamColors":null,"type":null,"userCount":2},"score":205,"type":"player"},{"entity":{"category":null,"country":{"alpha2":"US","name":"USA"},"disabled":null,"displayInverseHomeAwayTeams":null,"firstName":null,"gender":null,"id":887887,"lastName":null,"name":"Brady Sheldon","nameCode":null,"national":null,"position":"LB","ranking":null,"shortName":"B. Sheldon","slug":"sheldon-brady","sport":null,"team":{"country":{"alpha2":null,"name":null},"disabled":true,"gender":null,"id":273134,"name":"No team","nameCode":"NTE","national":false,"ranking":null,"shortName":"No team","slug":"no-team","sport":{"id":63,"name":"American football","slug":"american-football"},"teamColors":{"primary":"#52b030","secondary":"#52b030","text":"#ffffff"},"type":0,"userCount":0},"teamColors":null,"type":null,"userCount":0},"score":0,"type":"player"},{"entity":{"category":null,"country":{"alpha2":null,"name":null},"disabled":null,"displayInverseHomeAwayTeams":null,"firstName":null,"gender":null,"id":984311,"lastName":null,"name":"Tyre Brady","nameCode":null,"national":null,"position":"WR","ranking":null,"shortName":"T. Brady","slug":"brady-tyre","sport":null,"team":{"country":{"alpha2":null,"name":null},"disabled":true,"gender":null,"id":273134,"name":"No team","nameCode":"NTE","national":false,"ranking":null,"shortName":"No team","slug":"no-team","sport":{"id":63,"name":"American football","slug":"american-football"},"teamColors":{"primary":"#52b030","secondary":"#52b030","text":"#ffffff"},"type":0,"userCount":0},"teamColors":null,"type":null,"userCount":0},"score":0,"type":"player"}]}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/Users/jameshunter/vscode/james-fastpage/_notebooks/2022-10-06-PBL-python_rapidapi.ipynb Cell 7 in <cell line: 22>()
     <a href='vscode-notebook-cell:/Users/jameshunter/vscode/james-fastpage/_notebooks/2022-10-06-PBL-python_rapidapi.ipynb#W6sZmlsZQ%3D%3D?line=21'>22</a> for post in json: # countries in a list
     <a href='vscode-notebook-cell:/Users/jameshunter/vscode/james-fastpage/_notebooks/2022-10-06-PBL-python_rapidapi.ipynb#W6sZmlsZQ%3D%3D?line=22'>23</a> 	for posts in post["entity"]:
---> <a href='vscode-notebook-cell:/Users/jameshunter/vscode/james-fastpage/_notebooks/2022-10-06-PBL-python_rapidapi.ipynb#W6sZmlsZQ%3D%3D?line=24'>25</a> 		if posts["country"].get("name") == "USA":
     <a href='vscode-notebook-cell:/Users/jameshunter/vscode/james-fastpage/_notebooks/2022-10-06-PBL-python_rapidapi.ipynb#W6sZmlsZQ%3D%3D?line=25'>26</a> 			for key, value in post.items():
     <a href='vscode-notebook-cell:/Users/jameshunter/vscode/james-fastpage/_notebooks/2022-10-06-PBL-python_rapidapi.ipynb#W6sZmlsZQ%3D%3D?line=26'>27</a> 				print(key, value)

TypeError: string indices must be integers

Formatting Digital Coin example

JSON text transferred from the API in the previous cell was converted to a Python Dictionary called json. The "coins" in the dictionary contain a list of the most relevant data. Look at the code and comments to see how the original text is turned into something understandable. Additionally, there are error check to make sure we are starting the code with the expectation that the API was run correctly.

"""
This cell is dependent on valid run of API above.
- try and except code is making sure "json" was properly run above
- inside second try is code that is used to process Coin API data

Note.  Run this cell repeatedly to format data without re-activating API
"""

try:
    print("JSON data is Python type: " + str(type(json)))
    try:
        # Extracting Coins JSON status, if the API worked
        status = json.get('status')
        print("API status: " + status)
        print()
        
        # Extracting Coins JSON data, data about the coins
        data = json.get('data')
        
        # Procedural abstraction of Print code for coins
        def print_coin(c):
            print(c["symbol"], c["price"])
            print("Icon Url: " + c["iconUrl"])
            print("Rank Url: " + c["coinrankingUrl"])

        # Coins data was observed to be a list
        for coin in data['coins']:
            print_coin(coin)
            print()
            
    except:
        print("Did you insert a valid key in X-RapidAPI-Key of API cell above?")
        print(json)
except:
    print("This cell is dependent on running API call in cell above!")
JSON data is Python type: <class 'dict'>
Did you insert a valid key in X-RapidAPI-Key of API cell above?
{'message': 'You are not subscribed to this API.'}

Go deeper into APIs

Web Development vs Jupyter Notebook. A notebook is certainly a great place to start. But, for your end of Trimester project we want you to build the skill to reference and use APIs within your Project. Here are some resources to get you started with this journey.