FastAPI 可透過 Header 讀取請求標頭,並透過 Depends 進行依賴注入(Dependency Injection),適用於 API Token 驗證、身份驗證、請求處理 等場景。
0
0
0
3
| 1 | from fastapi import FastAPI, Header, HTTPException |
| 2 | |
| 3 | app = FastAPI() |
| 4 | |
| 5 | @app.get("/secure-data") |
| 6 | async def secure_data(api_key: str = Header(None)): |
| 7 | if api_key != "my_secure_token": |
| 8 | raise HTTPException(status_code=401, detail="無效的 API 金鑰") |
| 9 | return {"message": "驗證成功,提供安全數據"} |