Course contentsShow
← AI Engineering
Lesson 985 of 1,88624. Building AI APIsFree lesson

API Key Authentication Patterns

Implementing API key-based authentication for AI endpoints, including key generation, storage, and validation.

API Key Authentication Patterns

What you'll learn: How to secure your AI endpoints using API keys, from generation through validation.

Why API Keys for AI Endpoints?

Your LLM APIs are expensive to run — each request costs real money and compute. Without authentication, anyone could flood your endpoints, rack up costs, or abuse your service. API keys act like digital membership cards: only those with valid keys can enter.

Think of it like a hotel key card system. You generate unique cards (API keys) for each guest (client), store which cards are valid in your database, and check the card at the door (validate on each request) before granting access.

Core Components

Key Generation

Create cryptographically secure, random strings for each client:

import secrets

def generate_api_key() -> str:
    return f"sk_{secrets.token_urlsafe(32)}"

The sk_ prefix makes keys recognizable; the random portion ensures uniqueness and prevents guessing.

Storage

Store hashed versions of keys in your database (never plaintext):

import hashlib

def hash_api_key(key: str) -> str:
    return hashlib.sha256(key.encode()).hexdigest()

Validation in FastAPI

Use dependency injection to verify keys on protected endpoints:

from fastapi import Header, HTTPException

async def verify_api_key(x_api_key: str = Header()):
    hashed = hash_api_key(x_api_key)
    # Check hashed key exists in your database
    if not is_valid_key(hashed):
        raise HTTPException(status_code=401, detail="Invalid API key")
    return x_api_key

Show the key once during creation, then only compare hashes — this prevents leaked databases from exposing raw keys.

Key Takeaway: API key authentication protects your AI endpoints by generating unique secrets, storing them securely as hashes, and validating them on every request using FastAPI dependencies.