API Key Authentication

Deploying AI into Production with FastAPI

Matt Eckerle

Software and Data Engineering Leader

Why secure APIs?

 

 

  • Stop unauthorized users
  • Secure API endpoints with API key authentication

A secure vault

Deploying AI into Production with FastAPI

How API keys work

 

  • Like a digital password for our API
  • Sent in request headers
  • Verified before accessing endpoints

Flow diagram explaining how API keys work

Deploying AI into Production with FastAPI

Understanding APIKeyHeader

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

name="X-API-Key",
auto_error=True
)
Deploying AI into Production with FastAPI

Authenticating an 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 adds header scheme
  • HTTPException for exceptions
  • Defines API key header and secret key
  • Validates API keys with test_api_key
  • Raises 403 if the key doesn't match API_SECRET_KEY
Deploying AI into Production with FastAPI

Authenticating an app

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" }
Deploying AI into Production with FastAPI

Testing the endpoint

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

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

Invalid key output:

{"detail":"Invalid API key"}

 

 

Valid key output:

{"text":"This product is amazing!",
 "sentiment":"positive",
 "status":"success"}
Deploying AI into Production with FastAPI

Let's practice!

Deploying AI into Production with FastAPI

Preparing Video For Download...