Autentikasi Kunci API

Menerapkan AI ke Produksi dengan FastAPI

Matt Eckerle

Software and Data Engineering Leader

Mengapa mengamankan API?

 

 

  • Hentikan pengguna tidak sah
  • Amankan endpoint API dengan autentikasi kunci API

Sebuah brankas yang aman

Menerapkan AI ke Produksi dengan FastAPI

Cara kerja kunci API

 

  • Seperti kata sandi digital untuk API kita
  • Dikirim dalam header permintaan
  • Diverifikasi sebelum mengakses endpoint

Diagram alur yang menjelaskan cara kerja kunci API

Menerapkan AI ke Produksi dengan FastAPI

Memahami APIKeyHeader

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

name="X-API-Key",
auto_error=True
)
Menerapkan AI ke Produksi dengan FastAPI

Mengautentikasi endpoint

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 menambahkan skema header
  • HTTPException untuk pengecualian
  • Mendefinisikan header kunci API dan kunci rahasia
  • Memvalidasi kunci API dengan test_api_key
  • Melempar 403 jika kunci tidak cocok dengan API_SECRET_KEY
Menerapkan AI ke Produksi dengan FastAPI

Mengautentikasi aplikasi

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" }
Menerapkan AI ke Produksi dengan FastAPI

Menguji endpoint

Perintah dengan kunci API tidak valid:

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

Perintah dengan kunci API valid:

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

Keluaran kunci tidak valid:

{"detail":"Invalid API key"}

 

 

Keluaran kunci valid:

{"text":"This product is amazing!",
 "sentiment":"positive",
 "status":"success"}
Menerapkan AI ke Produksi dengan FastAPI

Ayo berlatih!

Menerapkan AI ke Produksi dengan FastAPI

Preparing Video For Download...