设置请求头
许多 API 要求用户提供通过注册获得的 API key。密钥通常放在请求头中,而不是作为参数传递。
Yelp API 文档说明:"若要使用 API Key 对 API 调用进行身份验证,请将 Authorization HTTP 头的值设置为 Bearer api_key。"
您将创建一个字典,把这条信息传给 get(),调用 API 获取纽约市评分最高的咖啡馆,并解析响应。
已加载 pandas(简称 pd)和 requests。API 端点保存在 api_url,密钥在 api_key。请求参数在字典 params 中。
本练习是课程的一部分
使用 pandas 高效导入数据
练习说明
- 创建字典
headers,将格式化后的密钥字符串传给"Authorization"头的值。 - 使用
get()携带必要的请求头和参数,向 Yelp API(api_url)发起请求。将结果保存为response。 - 从
response中提取 JSON 数据,保存为data。 - 将
data中"businesses"的值加载为数据框cafes,并打印names列。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Create dictionary that passes Authorization and key string
headers = {____: "Bearer {}".format(____)}
# Query the Yelp API with headers and params set
response = ____
# Extract JSON data from response
data = ____
# Load "businesses" values to a dataframe and print names
cafes = ____
print(cafes.name)