Развёртывание ИИ в производственной среде с помощью FastAPI
Matt Eckerle
Software and Data Engineering Leader


from fastapi import FastAPI from fastapi.security import APIKeyHeader header_scheme = APIKeyHeader(name="X-API-Key",auto_error=True)
from fastapi.security import APIKeyHeader from fastapi import Depends, HTTPExceptionheader_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}
ApiKeyHeaderDepends добавляет схему заголовкаHTTPException для обработки исключенийtest_api_key403, если ключ не совпадает с API_SECRET_KEYdef 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_keyapp = FastAPI( dependencies=[Depends(verify_api_key)] )@app.post("/predict") def predict_sentiment(text: str):return { "text": text, "sentiment": "positive", "status": "success" }
Команда с неверным 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