Security best practices in FastAPI

Difficulty: Advanced

Question

What security best practices should you follow when building a FastAPI application?

Answer

  1. HTTPS everywhere - Terminate SSL at the reverse proxy. Use --forwarded-allow-ips to trust proxy headers.
  1. Security headers - Add via middleware: X-Content-Type-Options: nosniff, X-Frame-Options: DENY, Strict-Transport-Security, Content-Security-Policy.
  1. CORS - Whitelist specific origins, never use allow_origins=['*'] with allow_credentials=True.
  1. Input validation - Pydantic models handle this, but sanitize HTML output and use parameterized DB queries.
  1. Secrets management - Use pydantic-settings with env vars. Never commit secrets to code.
  1. Rate limiting - Prevent brute force and DDoS with SlowAPI or API gateway.
  1. SQL injection - Use ORM (SQLAlchemy) or parameterized queries. Never interpolate user input into SQL strings.
  1. Dependency updates - Regularly update dependencies. Use pip-audit or safety to check for CVEs.

Code examples

Security headers middleware

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware

app = FastAPI()

# Restrict allowed hosts
app.add_middleware(TrustedHostMiddleware, allowed_hosts=["example.com", "*.example.com"])

# Strict CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://app.example.com"],
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE"],
    allow_headers=["Authorization", "Content-Type"],
)

# Custom security headers
@app.middleware("http")
async def add_security_headers(request: Request, call_next):
    response = await call_next(request)
    response.headers["X-Content-Type-Options"] = "nosniff"
    response.headers["X-Frame-Options"] = "DENY"
    response.headers["X-XSS-Protection"] = "1; mode=block"
    response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
    return response

Key points

  • TrustedHostMiddleware prevents Host header attacks
  • Use `secrets.token_urlsafe()` for generating tokens, not `random`
  • Enable Pydantic's strict mode to prevent type coercion attacks

Common follow-up questions

  • How do you prevent CSRF attacks in a FastAPI + SPA architecture?
  • What is the difference between CORS and CSRF protection?

Interview tips

  • Security is a broad topic - focus on the OWASP Top 10 and how FastAPI addresses each one

Concepts covered

security headers, HTTPS, CSRF, input sanitization, secrets

More FastAPI Interview questions