<jupyter_start><jupyter_text>Using APIs and JSON Data  ObjectivesYou will be able to:* Make an API call to Yelp   Agenda* Build up an API Call* Look at the results<jupyter_code>import requests
import json<jupyter_output><empty_output><jupyter_text>For more information about the request package you can use the following resources:**Tutorial:** https://realpython.com/python-requests/**Package Documentation:** https://requests.readthedocs.io/en/master/ ![](quota.png) Let's do a search of businesses on the Yelp API.<jupyter_code>import sys
print(sys.path)
# set theurl and endpoint we want to hit
url =  'https://api.yelp.com/v3/businesses/search'<jupyter_output><empty_output><jupyter_text>Now that you have an API key, let's enter set that information here so that we can do our searches. Once you have the `api_key` variable, place int in our header.<jupyter_code>client_id = ____
api_key = ____
from  keys  import  client_id, api_key
print(api_key)
headers = {
        'Authorization': 'Bearer {}'.format(api_key),
    }<jupyter_output><empty_output><jupyter_text>We now need to determine our parameters we want to pass.  You must give a specific search term, location and one other paramter to limit your search. Remember you can search the API documenation to find another parameter to limit your search.  https://www.yelp.com/developers/documentation/v3/get_startedrequests is allowing us to do this. So user doesn't have to enter them into the url<jupyter_code># what type of business do you want to search
term = 'Thai'

#where do you want to perform this search
location = 'Queens'

# what is your other parameter you want to search against
radius = 1000

url_params = {
                "term": term.replace(' ', '+'),
                "location": location.replace(' ', '+'),
                "categories" : categories,
                "limit": 50,
    
            }

url_params<jupyter_output><empty_output><jupyter_text>Now that we have all of the parts necessary for an API call, let's put them together.<jupyter_code>response = requests.get(url, headers=headers, params=url_params)

url
response.status_code<jupyter_output><empty_output><jupyter_text>The ResponseThe response of a GET request often has some valuable information, known as a payload, in the message body. Using the attributes and methods of Response, you can view the payload in a variety of different formats.To see the response’s content in bytes, you use `.content`You will often want to convert them into a string using a character encoding such as UTF-8. Response will do that for you when you access `.text`The response is actually serialized JSON content. To get a dictionary, you could take the str you retrieved from `.text` and deserialize it using `json.loads()`. However, a simpler way to accomplish this task is to use `.json()`:<jupyter_code>response.text
json.loads(response.text)

response.json()<jupyter_output><empty_output><jupyter_text>Using one of the methods above load the response data and assign it to a variable `data`.<jupyter_code>data = response.json()<jupyter_output><empty_output><jupyter_text>What are the keys in this dictionary and the datatypes of their values.<jupyter_code># your code here
for k,v in data.items():
    print(k)
    print(type(v))<jupyter_output>businesses
<class 'list'>
total
<class 'int'>
region
<class 'dict'><jupyter_text>How many results did our query return?<jupyter_code>data.total<jupyter_output><empty_output><jupyter_text>How many businesses were returned from the API call?<jupyter_code>data.businesses #to view
len(data.businesses)<jupyter_output><empty_output><jupyter_text>Parsing the ResultsThere are a lot of key-value pairs for each business. Many of which we do not care about. Let's create a simple parser of this data that will return a list with the name, display_address, and one other data point of your choice. First we want to assign one of the businesses to the `business` variable. Once we cna properly parse oonne business  we can use a loop to do them all.<jupyter_code>business = data['businesses'][0]
business<jupyter_output><empty_output><jupyter_text>Rember we want the following pieces of information:name, display_address, and one other data point of your choice<jupyter_code>#This is from before because it had to be a tuple. Can still be one though
#You need to pull the id*******. It is needed for reviews.
biz_tuple = ()
biz_tuple<jupyter_output><empty_output><jupyter_text>Now that we know how to do this for one business. Let create a function that recieves the list of businesses and returns a list of tuples with the important information.<jupyter_code>def parse_data(list_of_data):
    # create a container to hold our parsed data
    parsed_Data = []
    # loop through our business and 
    for business in list_of_data:
    # parse each individual business into a tuple
        biz_tuple = (business['id'], etc...)
    # add each individual business tuple to our data container
        parsed_data.append(biz_tuple)
    # return the container with all of the parsed results
    return parsed_data
parsed_results = parse_data(data['businesses'])<jupyter_output><empty_output><jupyter_text>Take the parsed results and put them in a Dataframe.<jupyter_code>#THE BREAK: KeyError 'price'. The business didn't have a price key
#pd.Dataframe, name the parsed data *parsed_data, columns = ['column1', 'column2', etc]
#then append this to the main dataframe<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.08040293040293041, 'fraction_numerical': 0.002197802197802198, 'mean_word_length': 4.903783783783783, 'pattern_counts': {'":': 3, '<': 59, '<?xml version=': 0, '>': 59, 'https://': 4, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '14', 'dir': 'jupyter-structured-clean-dedup', 'id': '233441', 'license': 'MIT', 'n_tokens_mistral': 1603, 'n_tokens_neox': 1568, 'n_words': 641, 'path': 'Phase_1/ds-apis-nbz32-main/API_Calls_Practice.ipynb', 'repo_name': 'ismizu/ds-east-042621-lectures', 'size': '5460'}