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 is a 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 necessaryparams
andheaders
information 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
cafes
withpandas
'sDataFrame()
function. The listings are under the"businesses"
key indata
. - Print the dataframe's
dtypes
to see what information you're getting.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
api_url = "https://api.yelp.com/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)
This exercise is part of the course
Streamlined Data Ingestion with pandas
Learn to acquire data from common file formats and systems such as CSV files, spreadsheets, JSON, SQL databases, and APIs.
Learn how to work with JSON data and web APIs by exploring a public dataset and getting cafe recommendations from Yelp. End by learning some techniques to combine datasets once they have been loaded into data frames.
Exercise 1: Introduction to JSONExercise 2: Load JSON dataExercise 3: Work with JSON orientationsExercise 4: Introduction to APIsExercise 5: Get data from an APIExercise 6: Set API parametersExercise 7: Set request headersExercise 8: Working with nested JSONsExercise 9: Flatten nested JSONsExercise 10: Handle deeply nested dataExercise 11: Combining multiple datasetsExercise 12: Concatenate dataframesExercise 13: Merge dataframesExercise 14: Wrap-upWhat is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.