APIキー認証

FastAPI を使った AI のプロダクション環境へのデプロイ

Matt Eckerle

Software and Data Engineering Leader

APIを保護する理由

 

 

  • 不正なユーザーのアクセスを防ぐ
  • APIキー認証でエンドポイントを保護する

安全な金庫

FastAPI を使った AI のプロダクション環境へのデプロイ

APIキーの仕組み

 

  • APIのデジタルパスワードに相当する
  • リクエストヘッダーで送信される
  • エンドポイントへのアクセス前に検証される

APIキーの仕組みを説明するフロー図

FastAPI を使った AI のプロダクション環境へのデプロイ

APIKeyHeaderを理解する

from fastapi import FastAPI
from fastapi.security import APIKeyHeader
header_scheme = APIKeyHeader(

name="X-API-Key",
auto_error=True
)
FastAPI を使った AI のプロダクション環境へのデプロイ

エンドポイントの認証

from fastapi.security import APIKeyHeader
from fastapi import Depends, HTTPException


header_scheme = APIKeyHeader(name="X-API-Key", auto_error=True) API_SECRET_KEY = "your-secret-key"
@app.get("/items/") def read_items( api_key: str = Depends(header_scheme) ):
if api_key != API_SECRET_KEY: raise HTTPException( status_code=403, detail="Invalid API key")
return {"api_key": api_key}
  • ApiKeyHeader
  • Dependsでヘッダースキームを追加
  • HTTPExceptionで例外を処理
  • APIキーヘッダーとシークレットキーを定義
  • test_api_keyでAPIキーを検証
  • キーがAPI_SECRET_KEYと一致しない場合に403を発生
FastAPI を使った AI のプロダクション環境へのデプロイ

アプリの認証

def verify_api_key(api_key: str = Depends(header_scheme)):
    if api_key != API_KEY:
        raise HTTPException(status_code=403,  detail="Invalid API key")
    return api_key

app = FastAPI( dependencies=[Depends(verify_api_key)] )
@app.post("/predict") def predict_sentiment(text: str):
return { "text": text, "sentiment": "positive", "status": "success" }
FastAPI を使った AI のプロダクション環境へのデプロイ

エンドポイントのテスト

無効なAPIキーのコマンド:

curl -X POST \
  http://localhost:8000/predict \
  -H "X-API-Key: wrong-key" \
  -H "Content-Type: application/json" \
  -d '{"text": "This product is amazing!"}'

有効なAPIキーのコマンド:

curl -X POST \
  http://localhost:8000/predict \
  -H "X-API-Key: your-secret-key" \
  -H "Content-Type: application/json" \
  -d '{"text": "This product is amazing!"}'

無効なキーの出力:

{"detail":"Invalid API key"}

 

 

有効なキーの出力:

{"text":"This product is amazing!",
 "sentiment":"positive",
 "status":"success"}
FastAPI を使った AI のプロダクション環境へのデプロイ

練習しましょう!

FastAPI を使った AI のプロダクション環境へのデプロイ

Preparing Video For Download...