使用 requests 進行 Basic Authentication
Basic Authentication 是最簡單的網路 API 驗證方式。它的運作就像登入網站一樣。為了取得存取權限,你需要在每一次請求中一併傳送個人的使用者名稱與密碼。API 會用這組使用者名稱與密碼來識別你,並授權你存取所請求的資料。
我們先來看看當驗證失敗時,伺服器會如何回應,接著再用「Basic Authentication」把它修正。
你需要知道的事:
requests套件已經匯入好了。- 你可以使用使用者名稱
[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')