開始使用免費開始

使用 requests 進行 Basic Authentication

Basic Authentication 是最簡單的網路 API 驗證方式。它的運作就像登入網站一樣。為了取得存取權限,你需要在每一次請求中一併傳送個人的使用者名稱與密碼。API 會用這組使用者名稱與密碼來識別你,並授權你存取所請求的資料。

我們先來看看當驗證失敗時,伺服器會如何回應,接著再用「Basic Authentication」把它修正。

你需要知道的事:

  1. requests 套件已經匯入好了。
  2. 你可以使用使用者名稱 [email protected] 和密碼 Warp_ExtrapolationsForfeited2 來進行驗證。

本練習屬於課程

Python API 入門

檢視課程

動手互動練習

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

response = requests.get('http://localhost:3000/albums')

# Check if the status code on the response object matches a successful response
if(response.____ == ____):
    print("Success!")
# Check if the status code indicates a failed authentication attempt
elif(response.____ == ____):
    print('Authentication failed')
else:
    print('Another error occurred')
編輯並執行程式碼