使用 requests 套件接收 JSON
當你從 API 請求 JSON 資料時,requests 函式庫可輕鬆將 API 回傳的 JSON 字串解碼為 Python 物件。在本練習中,你需要先向 API 以 JSON 格式請求資料,然後將回應解碼為 Python 物件,最後擷取並印出 album 的 Title 屬性。
注意:requests 套件已為你匯入,且由於 albums API 需要驗證,正確的標頭已經替你加入。
本練習屬於課程
Python API 入門
練習說明
- 加上正確的標頭,向 API 請求 JSON。
- 將 JSON 回應解碼為 album 物件。
- 印出 album 的
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(____)