CORS, HTTPS, Rate Limitingยถ
๐ฏ What Youโll Learnยถ
- Why CORS matters in modern web APIs and how to configure it in FastAPI
- Why HTTPS is essential and how to enable it in production
- How rate limiting protects your API from abuse and denial-of-service attacks
๐ Step 1: Cross-Origin Resource Sharing (CORS)ยถ
๐ง What is CORS?ยถ
CORS (Cross-Origin Resource Sharing) is a browser security feature. By default, browsers block requests from one domain (e.g. frontend.com) to another (e.g. api.com).
CORS defines rules that tell the browser:
โItโs safe to allow requests from this origin.โ
Without proper CORS configuration:
- Your frontend app may fail to call your API
- You risk exposing your API to unwanted domains if configured too loosely
๐ง How to Configure CORS in FastAPIยถ
FastAPI provides a middleware for CORS:
๐ main.py
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
origins = [
"http://localhost:3000", # e.g. frontend dev server
"https://myfrontend.com", # Production frontend
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins, # Which domains can access
allow_credentials=True, # Allow cookies/headers
allow_methods=["*"], # Which HTTP methods
allow_headers=["*"], # Which headers
)
๐ Best Practiceยถ
- Restrict
allow_originsto trusted domains (not["*"]in production) - Only allow necessary methods and headers
๐ Step 2: HTTPS Everywhereยถ
๐ง Why HTTPS?ยถ
HTTPS encrypts traffic between client and server. Without HTTPS:
- Passwords, tokens, and data can be intercepted (man-in-the-middle attacks)
- Browsers will mark your site as insecure
๐ง How to Enable HTTPSยถ
FastAPI itself doesnโt handle HTTPS โ you typically use a reverse proxy like NGINX or Traefik.
Example NGINX config snippet:
server {
listen 443 ssl;
server_name api.myapp.com;
ssl_certificate /etc/letsencrypt/live/api.myapp.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/api.myapp.com/privkey.pem;
location / {
proxy_pass http://127.0.0.1:8000;
}
}
๐ Best Practiceยถ
- Use Letโs Encrypt for free SSL certificates
- Redirect all HTTP traffic to HTTPS
- Always deploy FastAPI behind a secure proxy (not directly exposed)
Refer to FastAPI official guide for more details on how this works and how to implement it: About HTTPS - FastAPI
โก Step 3: Rate Limitingยถ
๐ง Why Rate Limiting?ยถ
Rate limiting prevents:
- Abuse (e.g. spamming login attempts)
- Denial-of-service attacks
- Excessive resource consumption
It ensures fair usage by limiting requests per user/IP.
๐ง How to Implement Rate Limiting in FastAPIยถ
FastAPI doesnโt include rate limiting out of the box, but you can use libraries like SlowAPI:
pip install slowapi
๐ main.py
from fastapi import FastAPI
from slowapi import Limiter
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded
from slowapi.middleware import SlowAPIMiddleware
limiter = Limiter(key_func=get_remote_address)
app = FastAPI()
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, limiter._rate_limit_exceeded_handler)
app.add_middleware(SlowAPIMiddleware)
@app.get("/login")
@limiter.limit("5/minute")
def login():
return {"message": "Login attempt"}
๐ Best Practiceยถ
- Apply stricter limits on sensitive endpoints (e.g.
/login) - Use more generous limits for public endpoints (e.g.
/docs) - Monitor logs for abuse patterns
๐ง Recapยถ
You now know how to secure your API with:
- CORS โ Control which domains can call your API
- HTTPS โ Encrypt all traffic to prevent interception
- Rate Limiting โ Protect against abuse and denial-of-service
Together, these practices harden your API against common threats.
๐งช Practice Challengeยถ
- Configure CORS to allow only your frontend domain.
- Set up HTTPS with Letโs Encrypt on a test server.
- Add rate limiting to your
/auth/loginendpoint (e.g. 5 requests per minute per IP).