開始使用免費開始

使用金鑰驗證保護 API

你正在建置一個安全的 API,需要實作 API 金鑰驗證。API 會在每個請求的 X-API-Key 標頭中尋找金鑰,並與預先定義的密鑰比對。你將使用 FastAPI 內建的安全性功能來實作這個驗證系統。

FastAPIHTTPException 類別已經預先匯入。

本練習屬於課程

使用 FastAPI 將 AI 佈署到生產環境

檢視課程

練習說明

  • 從 FastAPI 匯入用來處理相依性的必要函式。
  • 建立一個 API 金鑰標頭的執行個體,作為相依性以驗證請求中的傳入 API 金鑰。
  • 完成 verify_api_key 函式,將傳入的 api_key 與預先定義的密鑰比對。
  • 當請求帶入無效金鑰時,拋出一個 HTTP 例外。

動手互動練習

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

# Import the function that handles dependencies
from fastapi import ____
from fastapi.security import APIKeyHeader

# Create the API key instance
api_key_header = ____(name="X-API-Key")
API_KEY = "your_secret_key"

# Pass the APIKeyHeader instance and verify against input api_key
def verify_api_key(api_key: str = Depends(____)):
    if api_key != ____:  
      	# Raise the HTTP exception here
        raise ____(status_code=403, detail="Invalid API Key")  
    return api_key
編輯並執行程式碼