Learn / Frameworks / FastAPI / API Security Hardening

FastAPI · Lesson 13 of 15

API Security Hardening

Rate limits, HTTPS, CORS discipline and never leaking stack traces.

  • Advanced
  • 15 min read
  • 3 objectives

Before this lessonLesson 12: SQLAlchemy Relationships and Pagination

What you will learn

  • Rate-limit a route
  • Hide details in 500s
  • Lock CORS origins

Your Progress

0 of 15 lessons 0%

  • Lessons0 / 15
  • Completed0
  • Est. time left~ 4 hours

Create a free account to keep your progress on every device.

An open API on the internet will be scanned within minutes. Rate-limit brute force, do not leak internals, and keep CORS tight.

Rate limiting

# pip install slowapi
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded

limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)

@app.post("/token")
@limiter.limit("5/minute")
def login(...):
    ...

Error responses

from fastapi.responses import JSONResponse

@app.exception_handler(Exception)
async def unhandled(request, exc):
    # log the traceback with the request id, never send it to the client
    return JSONResponse({"detail": "Internal Server Error"}, status_code=500)

A short checklist

  • HTTPS only; HSTS at the load balancer.
  • CORS allow-list of exact origins, not * with credentials.
  • Validate file types and sizes; store uploads outside the web root.
  • Least-privilege database role; secrets from the environment.
  • Dependency updates; pin versions in production.
Up next · Lesson 14Custom OpenAPI and DocsTags, examples, description markdown and hiding routes from /docs.