開始使用免費開始

使用 requests 進行 API key 驗證

以 API key 為基礎的驗證與 Basic Authentication 類似,但你必須在經過驗證的請求中,透過請求標頭或 URL 參數加入一組唯一的 API key。讓我們來試試這兩種做法。

你需要知道:

  1. 已經匯入 requests 套件。
  2. 使用 API key/token 8apDFHaNJMxy8Kt818aa6b4a0ed0514b5d3 進行驗證。

本練習屬於課程

Python API 入門

檢視課程

動手互動練習

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

# Create a dictionary containing the API key using the correct key-value combination
params = {____: ____}
# Add the dictionary to the requests.get() call using the correct function argument
response = requests.get('http://localhost:3000/albums', ____=params)

if(response.status_code == 200):
    print("Success!")
elif(response.status_code == 401):
    print('Authentication failed')
else:
    print('Another error occurred')
編輯並執行程式碼