API Key Authentication

FastAPI के साथ प्रोडक्शन में AI डिप्लॉय करना

Matt Eckerle

Software and Data Engineering Leader

APIs को सुरक्षित क्यों करें?

 

 

  • अनधिकृत यूज़र्स को रोकें
  • API key authentication से API endpoints सुरक्षित करें

एक सुरक्षित तिजोरी

FastAPI के साथ प्रोडक्शन में AI डिप्लॉय करना

API keys कैसे काम करते हैं

 

  • हमारी API के लिए डिजिटल पासवर्ड जैसा
  • रिक्वेस्ट हेडर्स में भेजा जाता है
  • एंडपॉइंट्स तक पहुँच से पहले वेरिफ़ाई होता है

API keys कैसे काम करते हैं, इसका फ़्लो डायग्राम

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 हेडर स्कीम जोड़ता है
  • exceptions के लिए HTTPException
  • API key हेडर और secret key तय करता है
  • test_api_key से API keys वेलिडेट करता है
  • key 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 key के साथ कमांड:

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 key के साथ कमांड:

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!"}'

गलत key का आउटपुट:

{"detail":"Invalid API key"}

 

 

सही key का आउटपुट:

{"text":"This product is amazing!",
 "sentiment":"positive",
 "status":"success"}
FastAPI के साथ प्रोडक्शन में AI डिप्लॉय करना

अभ्यास करते हैं!

FastAPI के साथ प्रोडक्शन में AI डिप्लॉय करना

Preparing Video For Download...