開始使用免費開始

使用 requests 套件傳送 JSON

就像你可以從 API 回應中取得 JSON 文字一樣,你也可以在發送 POST 或 PUT 請求時把 JSON 文字傳給 API。當你在 request.post()request.put() 方法中使用 json 參數時,requests 函式庫會自動幫你加入必要的標頭與編碼。很方便!

來試試看吧!你知道嗎?用對 /playlists API 的 POST 請求,可以一次建立多個播放清單。 只要把一個播放清單陣列(每個都有 Name 屬性)傳給 API,它就會一次建立全部。

本練習屬於課程

Python API 入門

檢視課程

練習說明

  • 將變數 playlists 作為引數傳給 requests.post() 方法,讓它自動以 JSON 形式送出。
  • 從 API 取得所有播放清單的清單。
  • 透過列印 JSON 文字來檢視這個 GET 請求的回應。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

playlists = [{"Name":"Rock ballads"}, {"Name":"My favorite songs"}, {"Name":"Road Trip"}]

# POST the playlists array to the API using the json argument
requests.post('http://localhost:3000/playlists/', ____=____)

# Get the list of all created playlists
response = requests.____('http://localhost:3000/playlists')

# Print the response text to inspect the JSON text
print(response.____)
編輯並執行程式碼