使用 requests 套件
使用 urllib 來整合 API 可能會讓程式碼變得冗長而複雜,因為你需要自己處理許多額外事項,例如編碼與解碼回應。
作為 urllib 的替代方案,requests Python 套件提供更簡單的方式來整合 API。requests 內建了許多功能,讓你的程式碼更容易撰寫與閱讀。讓我們用 requests 套件再做一次相同的練習。
跟前一題一樣,Lyrics API 的 URL 是 http://localhost:3000/lyrics。
本練習屬於課程
Python API 入門
練習說明
- 匯入
requests套件。 - 將 URL
http://localhost:3000/lyrics傳入requests.get方法。 - 列印回應的文字內容。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import the requests package
import ____
# Pass the API URL to the get function
response = requests.get(____)
# Print out the text attribute of the response object
print(response.____)