RUNLOCALAIv38
->Will it run?Best GPUCompareTroubleshootStartLearnPulseModelsHardwareToolsBench
Run check
RUNLOCALAI

Independently operated catalog for local-AI hardware and software. Hand-written verdicts. Source-cited claims. Reproducible commands when we have them.

OP·Eruo Fredoline
DIR
  • Models
  • Hardware
  • Tools
  • Benchmarks
TOOLS
  • Will it run?
  • Compare hardware
  • Cost vs cloud
  • Choose my GPU
  • Prompting kits
  • Quick answers
REF
  • All buyer guides
  • Learn local AI
  • Methodology
  • Glossary
  • Errors KB
  • Trust
EDITOR
  • About
  • Author
  • How we make money
  • Editorial policy
  • Contact
LEGAL
  • Privacy
  • Terms
  • Sitemap
MAIL · MONTHLY DIGEST
Get monthly local AI changes
Monthly recap. No spam.
DISCLOSURE

Some links on this site are affiliate links (Amazon Associates and other first-class retailers). When you buy through them, we earn a small commission at no extra cost to you. Affiliate links do not influence our verdicts — there are cards we rate highly that we don't have affiliate relationships with, and cards that sell well that we refuse to recommend. Read more →

© 2026 runlocalai.coIndependently operated
RUNLOCALAI · v38
  1. >
  2. Home
  3. /Learn
  4. /Courses
  5. /Local AI APIs and Integration
  6. /Ch. 6
Local AI APIs and Integration

06. API Key Authentication

Chapter 6 of 18 · 20 min
KEY INSIGHT

Authentication protects your API from unauthorized access. For local deployments, a simple API key header check prevents accidental exposure and blocks non-local clients from consuming resources meant for internal use. ### Header-Based Authentication The standard pattern checks for a specific header and validates its value against a stored secret. FastAPI provides a dependency system that makes this clean and reusable. ```python from fastapi import Header, HTTPException async def verify_api_key(x_api_key: str = Header(default=None)): if not x_api_key: raise HTTPException( status_code=401, detail="Missing API key. Provide X-API-Key header." ) if x_api_key != os.environ.get("API_KEY"): raise HTTPException( status_code=403, detail="Invalid API key." ) return True ``` The `Header()` parameter extracts the header value and validates its presence. Returning an error with a `detail` message helps clients diagnose authentication failures. ### Applying Authentication to Routes ```python @app.post("/v1/chat/completions") async def completions(request: CompletionRequest, _: bool = Depends(verify_api_key)): return await generate(request) ``` The `Depends()` function injects the authentication check before the endpoint logic executes. If authentication fails, the endpoint never runs. ### API Key Generation Generate keys using a cryptographically secure random function. Store the hash, not the plain key, to limit damage if your database is compromised. ```python import secrets def generate_api_key() -> tuple[str, str]: raw_key = secrets.token_urlsafe(32) hashed_key = hashlib.sha256(raw_key.encode()).hexdigest() return raw_key, hashed_key ``` When a client provides a key, hash it and compare against the stored hash. ### Security Considerations Never log API keys. Never return the key in responses. Use HTTPS in production even for local deployment to prevent key interception by local network observers. Rotate keys regularly and provide an endpoint for key revocation.

Local verification checkpoint

Run the smallest example from this chapter in a local workspace and record the package version, runtime, data path, and observed output. If the result depends on model size, vector count, CPU/GPU backend, or available memory, note that constraint beside the exercise so the lesson remains reproducible.

EXERCISE

Implement authentication middleware that validates the X-API-Key header and returns 401 for missing keys and 403 for invalid keys. Write a test that verifies the endpoint returns 401 without a header and succeeds with a valid header.

← Chapter 5
Streaming with SSE
Chapter 7 →
Rate Limiting