RapidAPI Notes
Working with RapidAPI to understand API.
Covid19 RapidAPI Example
The example API data used in class can be found here.
As I was still getting comfortable with APIs, the only real modification I made to this (aside from the key) was adding another part of the output about Japan's COVID stats.
"""
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': "f9dc4c060fmsh192fef0e86699c6p109981jsn882369c51285", #my own key
'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
# 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)
#print(response.json())
for country in countries: # countries is a list
if country["country_name"] == "Japan": # this filters for USA
for key, value in country.items(): # this finds key, value pairs in country
print(key, value)
# 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": "jcmbea0fa2ff5msh7f14bf69be38ca6p175482jsn6c4988114560", # place your key here
"X-RapidAPI-Host": "coinranking1.p.rapidapi.com"
}
response = requests.request("GET", url, headers=headers, params=querystring)
print(response.text)
# 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"
"""
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
"""
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": "f9dc4c060fmsh192fef0e86699c6p109981jsn882369c51285",
"X-RapidAPI-Host": "coinranking1.p.rapidapi.com"
}
response = requests.request("GET", url, headers=headers, params=querystring)
json = response.json()
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!")
Personal Use of RapidAPI
On RapidAPI, I found some data taken from speedrun.com, the internet's primary speedrunning forum site and hub for video game speedrunning world records.
To clarify, speedrunning is the practice of attempting to beat or complete certain goals in video games as fast as possible. This can be a challenge as minor as buying Mario some boxers to wear in Super Mario Odyssey (Nipple%) or as gargantuan as completing every shrine and side quest in The Legend of Zelda: Breath of the Wild (BotW 100%); and it can be as short as just over a minute (Pokémon Red and Blue any%) and as long as multiple days (in segments with certain restrictions).
This API included a LOT of data, so I decided it would be best to curate it based on user input so that it wasn't TOO bloated. Plus, this shows additional fluency with reading and displaying json
-ified data.
import requests
url = "https://speedrun1.p.rapidapi.com/forum"
headers = {
"X-RapidAPI-Key": "f9dc4c060fmsh192fef0e86699c6p109981jsn882369c51285",
"X-RapidAPI-Host": "speedrun1.p.rapidapi.com"
}
response = requests.request("GET", url, headers=headers)
speedrun = response.json()
#print(response.text)
def print_data(d_rec): #plagiar-inspired by lists and dictionaries lesson
print('"' + d_rec["forum"] + '"')
print("\t", "Game:", d_rec["game"])
print("\t", "URL:", d_rec["url"])
print()
def recursive_loop(i): #could print all forum posts, but that's TONS of content
if i < len(speedrun):
record = speedrun[i]
print_data(record)
recursive_loop(i + 1)
def print_name(d_rec): #see name_check
print(d_rec["game"])
def name_check(i): #this function showed me which games were in this API
if i < len(speedrun):
record = speedrun[i]
print_name(record)
name_check(i + 1)
#Showing all posts would be too much, so let's narrow it down to certain games
z = 0 #see reccheckloop function
gamelist = [ #these 11 games are featured in the api, in that order (popularity-based)
"legend_of_zelda_breath_of_the_wild", #format used by the dictionaries here
"super_mario_sunshine",
"super_mario_odyssey",
"mario_kart_8_delux",
"celeste",
"portal",
"hollow_knight",
"super_mario_brothers",
"minecraft",
"super_mario_world",
"super_mario_64"
] #THEIR INDEXES ARE IMPORTANT! SEE BELOW
validinputs = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"]
def print_forum(f_rec): #see use below
print('Post Title and Info: "' + f_rec["forum"] + '"')
print("\tURL: " + f_rec["url"])
print("")
def reccheckloop(i):
global z #pulls z = 0
record = speedrun[z] #starts with the first dictionary of the API
if record["game"] == gamelist[i]: #checks if forum pertains to chosen game
print_forum(record) #prints post name (includes info) and URL below
if (z + 1) < len(speedrun): #(z + 1) necessary because z starts at 0, "len" doesn't
z += 1 #only increases if it wouldn't cause an index error when looped
else:
return #once all posts have been checked, the program ends here
reccheckloop(i) #repeat
def selection_check(): #gets user input and ensures its validity
msg = input("Please input an integer found in the list below.")
if msg in validinputs: #variance with inputs makes using a list optimal
print("\n-------------------- " + msg + " --------------------\n")
reccheckloop(int(msg) - 1) #subtracts 1 because pertinent list is zero-based
else:
print("Invalid response.")
selection_check() #repeats input check if user input is invalid
def game_select():
print("Which speed game would you like to see forum posts for?")
print("\t1. The Legend of Zelda: Breath of the Wild (Wii U/Switch)")
print("\t2. Super Mario Sunshine (GameCube)")
print("\t3. Super Mario Odyssey (Switch)")
print("\t4. Mario Kart 8 Deluxe (Switch)")
print("\t5. Celeste (Console & PC)")
print("\t6. Porta (Console & PC)")
print("\t7. Hollow Knight (Console & PC)")
print("\t8. Super Mario Bros. (NES)")
print("\t9. Minecraft (PC)")
print("\t10. Super Mario World (SNES)")
print("\t11. Super Mario 64 (N64)")
selection_check()
print("\n-------------------- END --------------------")
game_select()