從 API 取得資料
在這個練習中,你會使用 requests.get() 查詢 Yelp Business Search API,找出 New York City 的咖啡館。requests.get() 需要指定要取得資料的 URL。Yelp API 也需要搜尋參數與授權標頭,分別透過 params 與 headers 關鍵字引數傳入。
你需要用回應物件的 json() 方法擷取資料,然後傳給 pandas 的 DataFrame() 函式來建立 dataframe。請注意,所需資料位於字典鍵 "businesses" 之下。
pandas(縮寫為 pd)與 requests 已經載入。授權資料在字典 headers 中,所需的 API 參數則存放在 params。
本練習屬於課程
使用 pandas 的精實資料導入
練習說明
- 使用
requests.get()透過 Yelp API(api_url)取得 New York City 咖啡館的資料。必要的params與headers資訊已提供。 - 用回應物件的
json()方法擷取 JSON 資料,並指派給data。 - 使用
pandas的DataFrame()函式,將咖啡館清單載入到 dataframecafes。清單位於data的"businesses"鍵下。 - 列印 dataframe 的
dtypes,看看你取得了哪些資訊。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
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)