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': "fe79b3687bmshe4d5f96190e00c5p14dc84jsnde81577c9e6c",
    '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": "fe79b3687bmshe4d5f96190e00c5p14dc84jsnde81577c9e6c",  # 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"

for coin in json["data"]["coins"]:
	print(f'{coin["symbol"]} {coin["name"]} {coin["price"]}')
BTC Bitcoin 19480.094920571948
ETH Ethereum 1326.2739797012734
USDT Tether USD 1.0005906201939905
USDC USDC 1.000796478844496
BNB Binance Coin 281.1541773820596
XRP XRP 0.5203111827768135
BUSD Binance USD 1.0013023019092655
ADA Cardano 0.42423118065732485
SOL Solana 32.797721933455726
DOGE Dogecoin 0.06218753916984209
DOT Polkadot 6.335758740808434
MATIC Polygon 0.817513705467937
SHIB Shiba Inu 0.000011059411658594
DAI Dai 1.000587839458817
TRX TRON 0.062440970388428337
WETH Wrapped Ether 1324.2296021586974
UNI Uniswap 6.547304508815042
AVAX Avalanche 16.830567667121453
WBTC Wrapped BTC 19476.549254903497
CAKE PancakeSwap 4.56253725382758
ATOM Cosmos 13.11169516066699
OKB OKB 15.704769979991314
LTC Litecoin 53.00460096582705
FTT FTX Token 24.28948638056076
ETC Ethereum Classic 27.24498045714858
XMR Monero 146.85425459379428
XLM Stellar 0.1258368833320945
ALGO Algorand 0.33737015155278194
BCH Bitcoin Cash 117.02372314445903
BTCB Bitcoin BEP2 19480.45280429421
CRO Cronos 0.10725758291626851
NEAR NEAR Protocol 3.5163695095408265
LUNC Terra Classic 0.000294490417317802
WEMIX WEMIX TOKEN 1.789438046354266
ENS EnergySwap 17.546655865308566
FLOW Flow 1.6867449119728115
FIL Filecoin 5.427443470102646
ICP Internet Computer (DFINITY) 5.895879473416911
VET VeChain 0.023065169863900115
MANA Decentraland 0.692808752823511
IMX Immutable X 0.7365257284322817
HBAR Hedera 0.06018058130914208
QNT Quant 148.93388347910738
FRAX Frax 1.0007582291562658
EGLD Elrond 54.845974248401035
XTZ Tezos 1.4127841057946406
CHZ Chiliz 0.2146500107791076
SAND The Sandbox 0.8312050216117796
LDO Lido DAO Token 1.4832811499010896
EOS EOS 1.1266777460450925

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.

Hacks

Find and use an API as part of your project. An API and a little coding logic will be a big step toward getting meaningful data for a project. There are many API providers, find one that might work for your project to complete this hack. When picking an API you are looking for something that will work with either JavaScript Fetch or Python Request. Here are some samples, these are not qualified in any way.

Show API and format results in either Web Page or Jupyter Notebook. Ultimately, I will expect that we do APIs in backend (Python/Flask). However, for this Hack you can pick your preference. We will discuss pros and cons in next API tech talk.

import requests

url = "https://reddit34.p.rapidapi.com/getPopularPosts"

querystring = {"sort":"new"}

headers = {
	"X-RapidAPI-Key": "fe79b3687bmshe4d5f96190e00c5p14dc84jsnde81577c9e6c",
	"X-RapidAPI-Host": "reddit34.p.rapidapi.com"
}

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

# print(response.text)
json = response.json()

for post in json["data"]["posts"]:
    print(f'{post["title"]} by {post["author"]} {post["permalink"]}')
I wish they had a brass knuckle type weapon or knuckle wrap that deals unarmed damage, potentially paired with Truffle Tussle to boost unarmed attacks. 🤷‍♂️ by SirRealest https://www.reddit.com/r/GroundedGame/comments/xz2y72/i_wish_they_had_a_brass_knuckle_type_weapon_or/
:: ding dong :: Hello! We would like to share with you what Entertainment Weekly calls “the funniest musical of all time.” Make it your mission to see The Book of Mormon on Broadway. Get your tickets today! by BookofMormonBroadway https://www.reddit.com/user/BookofMormonBroadway/comments/w3o5sq/ding_dong_hello_we_would_like_to_share_with_you/
Available to help with heists, setups, etc. Looking to make some 💰 however I can. I'm rank 340. Bogdan used to be my go to for money so it stays ready to run for b2b. but I'm up for helping with whatever. by WreckItRob559 https://www.reddit.com/r/HeistTeams/comments/xz2y71/available_to_help_with_heists_setups_etc_looking/
Taking a shit saved my life but this time the guy nutte'd instead by unlikely_suspicious https://www.reddit.com/r/copypasta/comments/xz2y6z/taking_a_shit_saved_my_life_but_this_time_the_guy/
mega gyarados raid on me 5387 8897 5456 by Dangerous_Raccoon_58 https://www.reddit.com/r/PokemonGoRaids/comments/xz2y6w/mega_gyarados_raid_on_me_5387_8897_5456/
Made some slashers. by Classicstupidtomtor4 https://www.reddit.com/r/HeroForgeMinis/comments/xz2y6n/made_some_slashers/
If Only... by M_i_c_K https://www.reddit.com/r/walkaway/comments/xz2y6l/if_only/
Something werid happened by Statement-Famous https://www.reddit.com/r/Twitch/comments/xz2y6j/something_werid_happened/
rocket emojo x3 by Dre_Dede https://www.reddit.com/r/691/comments/xz2y6f/rocket_emojo_x3/
Columbia City man arrested for child pornography by MugShots https://www.reddit.com/r/ArrestStories/comments/xz2y6c/columbia_city_man_arrested_for_child_pornography/
Is the Space Adenture Set really selling for $100AUD?? by bigdaddyborg https://www.reddit.com/r/lego/comments/xz2y6b/is_the_space_adenture_set_really_selling_for/
The new Obey 10F sports car has a lot of things going for it: air intake slots, titanium valvetrain, a muscular engine. Combine with a suite of customizations, and you’ve got an excellent value proposition. Now available from Legendary Motorsport. by rockstargames https://www.reddit.com/user/rockstargames/comments/xx9uta/the_new_obey_10f_sports_car_has_a_lot_of_things/
H: Apparel, Masks, Weapons, Flux, Caps W: AA/25aim .50cal by Chief_Crossbow https://www.reddit.com/r/Market76/comments/xz2y67/h_apparel_masks_weapons_flux_caps_w_aa25aim_50cal/
Which b-side should have been on Amnesiac? by something-outside-74 https://www.reddit.com/r/radiohead/comments/xz2y5w/which_bside_should_have_been_on_amnesiac/
Can we appreciate how consistent codfish is 🔥 consistent yearly upload schedule, things you love to see by Capidapi https://www.reddit.com/r/beatbox/comments/xz2y5t/can_we_appreciate_how_consistent_codfish_is/
Prevent mold after flooding- primitive cabin by Donexodus https://www.reddit.com/r/preppers/comments/xz2y5q/prevent_mold_after_flooding_primitive_cabin/
What’s a red flag that sounds silly but is actually pretty indicative? by lostsaucestolen https://www.reddit.com/r/AskReddit/comments/xz2y5p/whats_a_red_flag_that_sounds_silly_but_is/
[Game Thread] #21 Washington - Arizona State | 10/8/2022, 1:00pm (Pac-12) by rHuskiesBot https://www.reddit.com/r/huskies/comments/xz2y5o/game_thread_21_washington_arizona_state_1082022/
Guys help by Sarthak2712 https://www.reddit.com/r/FingMemes/comments/xz2y5m/guys_help/
Clive Barker is ALIVE??? by LiquidRedneckYT https://www.reddit.com/r/MandelaEffect/comments/xz2y5f/clive_barker_is_alive/
Discover the award-winning stories that move you on HBO Max. by hbomax https://www.reddit.com/user/hbomax/comments/xv56mu/discover_the_awardwinning_stories_that_move_you/
Our DM`s cat. I guess I`m no longer the cleric now by _elizaneg https://www.reddit.com/r/CatsPlayingDnd/comments/xz2y5e/our_dms_cat_i_guess_im_no_longer_the_cleric_now/
People 28+, would you be in a relationship with someone 10 years your junior? Why or why not? by pepperpeppington https://www.reddit.com/r/AskReddit/comments/xz2y58/people_28_would_you_be_in_a_relationship_with/
Dale Wilson by actbob1000 https://www.reddit.com/r/dalewilson/comments/xz2y56/dale_wilson/
Raffle prize I completed for a follower on Twitter. by ZekZebZab https://www.reddit.com/r/blender/comments/xz2y54/raffle_prize_i_completed_for_a_follower_on_twitter/
This years yard sale harvest for the Dark Gods of Milwaukee. by On_The_Fourth_Floor https://www.reddit.com/r/RedLetterMedia/comments/xz2y50/this_years_yard_sale_harvest_for_the_dark_gods_of/
Please by VARGVIKERNES2929 https://www.reddit.com/r/ShadowBan/comments/xz2y4z/please/
Naruto - Road of Naruto「AMV」- Through It All ♫ by ItsukiAMV https://www.reddit.com/r/AMVSchannels/comments/xz2y4y/naruto_road_of_narutoamv_through_it_all/