Performance: API key authentication
API key authentication affects server response time and initial request processing speed, impacting how fast the server can validate and respond to client requests.
Jump into concepts and practice - no test required
from fastapi import FastAPI, Header, HTTPException app = FastAPI() API_KEYS = {"key1", "key2", "key3"} # Use a set for O(1) lookup @app.get("/items/") async def read_items(x_api_key: str = Header(...)): if x_api_key not in API_KEYS: raise HTTPException(status_code=401, detail="Invalid API Key") return {"items": [1, 2, 3]}
from fastapi import FastAPI, Header, HTTPException app = FastAPI() API_KEYS = ["key1", "key2", "key3"] @app.get("/items/") async def read_items(x_api_key: str = Header(...)): if x_api_key not in API_KEYS: raise HTTPException(status_code=401, detail="Invalid API Key") return {"items": [1, 2, 3]}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| API key checked with list lookup | N/A | N/A | N/A | [X] Bad |
| API key checked with set lookup | N/A | N/A | N/A | [OK] Good |
| API key fetched from DB on every request | N/A | N/A | N/A | [X] Bad |
| API key cached in memory at startup | N/A | N/A | N/A | [OK] Good |
APIKeyHeader to extract API keys from headers.APIKeyHeader from fastapi.security, which is correct.from fastapi import FastAPI, Security, HTTPException
from fastapi.security import APIKeyHeader
app = FastAPI()
api_key_header = APIKeyHeader(name='X-API-Key')
@app.get('/secure')
async def secure_endpoint(api_key: str = Security(api_key_header)):
if api_key != 'secret123':
raise HTTPException(status_code=403, detail='Invalid API Key')
return {'message': 'Access granted'}from fastapi import FastAPI, Security, HTTPException
from fastapi.security import APIKeyHeader
app = FastAPI()
api_key_header = APIKeyHeader(name='X-API-Key')
@app.get('/data')
async def get_data(api_key: str = api_key_header):
if api_key != 'topsecret':
raise HTTPException(status_code=401, detail='Unauthorized')
return {'data': 'Here is your data'}api_key: str = api_key_header instead of Security(api_key_header).