20. API Security Best Practices
Security is not an afterthought — it must be built into your API from the start. This module covers essential security practices including input validation, rate limiting, CORS configuration, SQL injection prevention, and security headers. To test these examples, save to main.py and run uvicorn main:app --reload.
Input Validation and Sanitization
Never trust user input. Validate everything using Pydantic, and sanitize data to prevent injection attacks.
from pydantic import BaseModel, Field, validator import re class UserInput(BaseModel): email: str = Field(..., regex=r'^[^@\s]+@[^@\s]+\.[^@\s]+$') username: str = Field(..., min_length=3, max_length=20, regex=r'^[a-zA-Z0-9_]+$') age: int = Field(..., ge=0, le=150) @validator('username') def username_no_sql(cls, v): dangerous = ['--', ';', 'DROP', 'SELECT', 'INSERT', "'", '"'] for d in dangerous: if d in v.upper(): raise ValueError(f'Username contains invalid characters') return v @app.post("/users") async def create_user(user: UserInput): return {"user": user.model_dump()}
Rate Limiting (Prevent DDoS)
Rate limiting prevents brute-force attacks and DDoS by limiting requests per IP.
from slowapi import Limiter, _rate_limit_exceeded_handler from slowapi.util import get_remote_address from slowapi.errors import RateLimitExceeded from fastapi import FastAPI, Request limiter = Limiter(key_func=get_remote_address) app = FastAPI() app.state.limiter = limiter app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler) @app.get("/api/public") @limiter.limit("10/minute") async def public_endpoint(request: Request): return {"message": "You can only call this 10 times per minute"} @app.post("/api/login") @limiter.limit("5/minute") async def login(request: Request): return {"message": "Login attempt"}
Security Headers
Add security headers to protect against common attacks.
from fastapi import FastAPI, Request from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware from fastapi.middleware.trustedhost import TrustedHostMiddleware app = FastAPI() app.add_middleware(TrustedHostMiddleware, allowed_hosts=["api.myapp.com", "localhost"]) @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" response.headers["Content-Security-Policy"] = "default-src 'self'" response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin" return response @app.get("/") def root(): return {"message": "Hello"}
CORS Configuration
Configure CORS properly to allow only trusted origins.
from fastapi.middleware.cors import CORSMiddleware origins = ["https://myapp.com", "https://api.myapp.com"] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["GET", "POST", "PUT", "DELETE"], allow_headers=["Authorization", "Content-Type"], expose_headers=["X-Request-ID"], max_age=86400, )
*] in production! This allows any website to access your API. Always specify exact origins.SQL Injection Prevention
Use ORM parameters instead of raw SQL concatenation.
# DANGEROUS: Raw SQL concatenation user_input = request.query_params["name"] query = f"SELECT * FROM users WHERE name = '{user_input}'" # SAFE: SQLAlchemy parameters from sqlalchemy import text query = text("SELECT * FROM users WHERE name = :name") result = db.execute(query, {"name": user_input}) # SAFEST: Using ORM user = db.query(User).filter(User.name == user_input).first()
Environment Variables for Secrets
Never hardcode secrets. Use environment variables and never commit .env files.
from pydantic_settings import BaseSettings class Settings(BaseSettings): SECRET_KEY: str DATABASE_PASSWORD: str API_KEY: str REDIS_PASSWORD: str class Config: env_file = ".env" env_file_encoding = "utf-8" settings = Settings() # .gitignore MUST include: # .env # .env.production # *.pem
Knowledge Check
Ready to test your understanding of 20. API Security Best Practices?