使用 urllib 發送 API 請求
在這門課中,你會使用一個「Music Catalog」應用程式的 API。這個 API 有多種功能。你會先從「Lyrics API」開始,它能讓你擷取「今日歌詞」中的一句歌詞。
在發送第一個 API 請求之前,你需要知道 API 的存取位置。這個位置也稱為 URL(Uniform Resource Locator 的縮寫)。URL 會告訴 Python 要把 API 請求送到哪裡。Lyrics API 的 URL 如下:http://localhost:3000/lyrics/。
現在就用內建的 Python 模組 urllib,對 Lyrics API 發送第一個請求吧。
本練習屬於課程
Python API 入門
練習說明
- 對回應物件使用
read函式,從回應物件讀取回應資料。 - 使用
decode函式,依正確的編碼將回應資料解碼為字串。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
from urllib.request import urlopen
with urlopen('http://localhost:3000/lyrics/') as response:
# Use the correct function to read the response data from the response object
data = response.____()
encoding = response.headers.get_content_charset()
# Decode the response data so you can print it as a string later
string = data.____(encoding)
print(string)