使用 requests 包接收 JSON
当从 API 请求 JSON 数据时,requests 库可以非常轻松地将从 API 接收到的 JSON 字符串解码回 Python 对象。本练习中,您需要先向 API 请求 JSON 格式的数据,然后将响应解码为 Python 对象,从中获取并打印相册的 Title 属性。
注意:已为您导入 requests 包。由于 albums API 需要认证,正确的请求头已预先添加。
本练习是课程的一部分
Python 中的 API 入门
练习说明
- 添加正确的头部以从 API 请求 JSON。
- 将 JSON 响应解码为相册对象。
- 打印相册的
Title属性。
交互式实操练习
通过完成这段示例代码来试试这个练习。
headers = {
'Authorization': 'Bearer ' + API_TOKEN,
# Add a header to request JSON formatted data
____: ____
}
response = requests.get('http://localhost:3000/albums/1/', headers=headers)
# Get the JSON data as a Python object from the response object
album = ____
# Print the album title
print(____)