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

## how to get data from each site
"""
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

url = "https://corona-virus-world-and-india-data.p.rapidapi.com/api"

headers = {
	"X-RapidAPI-Key": "947170cc21msh533b44751737465p1dc810jsn1c522f8542f5",
	"X-RapidAPI-Host": "corona-virus-world-and-india-data.p.rapidapi.com"
}

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

## change to .json()
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 is a list
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)
## have different data paterns which need to be found out before being able to use the data

Digital Coin Example

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

## how to get data from each site
"""
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

url = "https://google-translate1.p.rapidapi.com/language/translate/v2/detect"

payload = "q=English%20is%20hard%2C%20but%20detectably%20so"
headers = {
	"content-type": "application/x-www-form-urlencoded",
	"Accept-Encoding": "application/gzip",
	"X-RapidAPI-Key": "947170cc21msh533b44751737465p1dc810jsn1c522f8542f5",
	"X-RapidAPI-Host": "google-translate1.p.rapidapi.com"
}

response = requests.request("POST", url, data=payload, headers=headers)

print(response.text)
## change to .json()
print(response.text)


# print("Languages")
# lang = response.json().get('languages')  # turn response to json() so we can extract "world_total"
# for key, value in lang.items():  # this finds key, value pairs in country
#     print(key, value)

# print()

# # # This code looks for USA in "countries_stats"
# # print("Country Totals")
# # ## countries is a list
# # 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)
# # ## have different data paterns which need ot be found out before being able to use the data

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!")
import requests

url = "https://dictionary-by-api-ninjas.p.rapidapi.com/v1/dictionary"

input("Which word do you want to search")
querystring = {"word": input()}

headers = {
	"X-RapidAPI-Key": "947170cc21msh533b44751737465p1dc810jsn1c522f8542f5",
	"X-RapidAPI-Host": "dictionary-by-api-ninjas.p.rapidapi.com"
}

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

print(response.json) ## changed .text to .json

word = response.json().get('word') ## gets the word
define = response.json().get('definition') ## gets the definition

print("Word: " + word)
print ("Definition: " + define)
<bound method Response.json of <Response [200]>>
Word: pie
Definition: 1. An article of food consisting of paste baked with something in it or under it; as, chicken pie; venison pie; mince pie; apple pie; pumpkin pie. 2. See Camp, n., 5. [Prov. Eng.] Halliwell. Pie crust, the paste of a pie.

1. (Zoöl.) (a) A magpie. (b) Any other species of the genus Pica, and of several allied genera. [Written also pye.] 2. (R. C. Ch.)  The service book. 3. (Pritn.)  Type confusedly mixed. See Pi. By cock and pie, an adjuration equivalent to "by God and the service book." Shak. -- Tree pie (Zoöl.), any Asiatic bird of the genus Dendrocitta, allied to the magpie. -- Wood pie. (Zoöl.) See French pie, under French.

See Pi.