Middleware and CORS
5 min read
Welcome back! Today, we're diving into the world of middleware and how it can make your FastAPI applications more robust and secure. Think of middleware as the friendly bouncers at a club, checking everyone who comes in and goes out.
1. Understanding the Middleware Pipeline ⛓️
Definition: A middleware is a function that processes every request before it reaches your specific endpoint and every response before it's sent back to the client. It's a way to add global functionalities to your application without repeating code in every single route.
The Problem: Imagine you want to log every single request that comes to your API. Without middleware, you would have to add logging code to every single path operation function. This is not only tedious but also prone to errors.
The Solution: Middleware to the rescue! By creating a single middleware, you can intercept all incoming requests and log their details.
How it Works
In FastAPI, middleware functions are executed in the order they are added for requests, and in reverse order for responses. The last middleware you add will be the first to process an incoming request and the last to handle an outgoing response.
Here's a simple example of a middleware that adds a custom header to every response:
import time
from fastapi import FastAPI, Request
app = FastAPI()
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
return responseIn this example, call_next is a function that passes the request to the next middleware or to the actual path operation. After the path operation generates a response, the middleware continues its execution.
2. Configuring CORS (Cross-Origin Resource Sharing) for Frontends 🌐
Definition: Cross-Origin Resource Sharing (CORS) is a security feature that browsers implement to control how web pages in one domain can request and interact with resources from a server in a different domain.
The Problem: If your frontend (e.g., a React app running on http://localhost:3000) tries to make a request to your FastAPI backend (running on http://localhost:8000), the browser will block the request by default. This is because they are on different "origins". An origin is the combination of the protocol (http, https), domain, and port.
The Solution: FastAPI provides a CORSMiddleware to handle this. You can specify which origins, methods, and headers are allowed.
Setting up CORSMiddleware
To allow your frontend to communicate with your backend, you need to add and configure the CORSMiddleware.
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
origins = [
"http://localhost:3000",
"http://localhost:8080",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
def read_root():
return {"Hello": "World"}Here's a breakdown of the parameters:
allow_origins: A list of origins that are allowed to make cross-origin requests.allow_credentials: Indicates that cookies should be supported for cross-origin requests. Defaults toFalse.allow_methods: A list of HTTP methods that are allowed.["*"]allows all standard methods.allow_headers: A list of HTTP request headers that are supported.["*"]allows all headers.
3. Creating Custom HTTP Middleware for Logging or Timing 📝⏱️
While FastAPI provides some built-in middleware, you'll often want to create your own to handle specific tasks like logging or timing requests.
Logging Middleware
A logging middleware can be incredibly useful for debugging and monitoring your application's activity.
Here's a simple logging middleware that logs basic request information:
import logging
from fastapi import FastAPI, Request
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = FastAPI()
@app.middleware("http")
async def log_requests(request: Request, call_next):
logger.info(f"Incoming request: {request.method} {request.url}")
response = await call_next(request)
logger.info(f"Outgoing response: {response.status_code}")
return responseThis middleware will log the HTTP method and URL of every incoming request, and the status code of every outgoing response.
Timing Middleware
A timing middleware can help you identify slow endpoints and performance bottlenecks. You can create a simple one yourself or use existing libraries.
Here's an example of a custom timing middleware:
import time
from fastapi import FastAPI, Request
app = FastAPI()
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
start_time = time.perf_counter()
response = await call_next(request)
process_time = time.perf_counter() - start_time
response.headers["X-Process-Time"] = str(process_time)
return responseThis is the same example from the beginning, and as you can see, it's a very practical way to measure the processing time of each request.
4. Implementing Basic Rate Limiting 🚦
Definition: Rate limiting is a technique to control the amount of incoming traffic to your API. It helps prevent abuse, denial-of-service attacks, and ensures fair usage for all clients.
The Problem: Without rate limiting, a single user or a malicious actor could flood your API with requests, overwhelming your server and making it unavailable for legitimate users.
The Solution: Implementing a rate-limiting middleware can protect your API by blocking requests from a client that exceeds a certain number of requests in a given time frame.
While you can build a simple in-memory rate limiter, for production applications, it's recommended to use a more robust solution with a centralized store like Redis, especially in a distributed environment. There are also excellent third-party libraries like slowapi that simplify this process.
Here is a conceptual example using a simple in-memory store:
import time
from fastapi import FastAPI, Request, status
from fastapi.responses import JSONResponse
app = FastAPI()
# In-memory storage for request counts (not for production)
request_counts = {}
RATE_LIMIT_DURATION = 60 # seconds
RATE_LIMIT_REQUESTS = 10
@app.middleware("http")
async def rate_limit_middleware(request: Request, call_next):
client_ip = request.client.host
current_time = int(time.time())
if client_ip not in request_counts:
request_counts[client_ip] = []
# Remove timestamps older than the rate limit duration
request_counts[client_ip] = [
timestamp for timestamp in request_counts[client_ip]
if timestamp > current_time - RATE_LIMIT_DURATION
]
if len(request_counts[client_ip]) >= RATE_LIMIT_REQUESTS:
return JSONResponse(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
content={"detail": "Too Many Requests"},
)
request_counts[client_ip].append(current_time)
response = await call_next(request)
return response
@app.get("/")
async def root():
return {"message": "Hello World"}Funny exaggeration: Imagine your API is a popular new ice cream shop. Without a rate limit (a one-ice-cream-per-person-per-hour rule), one very enthusiastic customer could order all the ice cream, leaving none for anyone else!
Extra Reading & References 📚
- FastAPI Middleware Documentation: https://fastapi.tiangolo.com/tutorial/middleware/
- FastAPI CORS Documentation: https://fastapi.tiangolo.com/tutorial/cors/
- Starlette Middleware: https://www.starlette.io/middleware/
Challenge
Challenge: Implement a Multi-Layer Middleware Pipeline in FastAPI
Your task is to build a FastAPI application and secure it by implementing a three-layer middleware pipeline. You must configure CORS, add a custom timing header, and implement a simple in-memory rate limiter.
Requirements:
CORS Middleware: Configure the built-in
CORSMiddleware. The API must only accept cross-origin requests from"http://localhost:3000". It should only permitGETandPOSTmethods and must allow a custom request header namedX-Client-ID.Custom Timing Middleware: Create a custom HTTP middleware that calculates the processing time of each request. This middleware must add an
X-Process-Timeheader to every outgoing response. The header's value should be the total processing time in seconds, formatted as a string.Custom Rate-Limiting Middleware: Create a second custom HTTP middleware to function as a simple rate limiter. This middleware should track requests based on the client's IP address (
request.client.host). If any single client makes more than 5 requests within a 10-second window, the server must reject the request by raising anHTTPExceptionwith a429 Too Many Requestsstatus code. The providedrequest_countsdictionary should be used for this purpose.
Expected result
Your final code should be a single Python script containing a complete FastAPI application.
The solution must meet the following criteria:
- An instance of
FastAPIis created. app.add_middleware()is called forCORSMiddlewarewith the following parameters correctly set:allow_origins=["http://localhost:3000"]allow_methods=["GET", "POST"]allow_headers=["X-Client-ID"]
- A custom middleware function is defined and added to the app. This function must:
- Accept
request: Requestandcall_nextas arguments. - Record the start time before
await call_next(request). - Await the response from
call_next. - Calculate the elapsed time.
- Add the calculated time as a string to the
response.headersdictionary with the key"X-Process-Time". - Return the
response.
- Accept
- A second custom middleware function for rate limiting is defined and added to the app. This function must:
- Get the client's IP from
request.client.host. - Use the global
request_countsdictionary and the current time (time.time()) to manage request timestamps. - Remove timestamps from the client's list that are older than
RATE_LIMIT_DURATION. - If the number of remaining timestamps is greater than or equal to
RATE_LIMIT_REQUESTS, it must raise anHTTPExceptionwithstatus_code=429. - If the request is allowed, it must append the current timestamp to the client's list and then proceed by calling and returning
await call_next(request).
- Get the client's IP from
- The provided
/statusendpoint should remain unchanged.