用參數組合 URL
你可以透過 URL 的路徑與查詢參數來微調 API 請求。讓我們用 requests 套件學習如何運用 HTTP 動詞、URL 路徑與參數。
在這個練習中,你會再次對「Lyrics API」發出請求,但這次不是取得今日歌詞,而是改為請求「random lyrics API」。接著,你會加入查詢參數,限定特定歌手,並包含曲名。下面提供你組合正確 URL 需要的細節。
| Component | Value |
|---|---|
| Protocol | http |
| Domain | localhost |
| Port | 3000 |
| Path | /lyrics/random |
| Artist filter parameter | artist |
| Include track parameter | include_track |
已為你方便起見預先匯入 requests 函式庫。
本練習屬於課程
Python API 入門
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Construct the URL string and pass it to the requests.get() function
response = requests.get('http://localhost:____/____/____')
print(response.text)