Middleware is a powerful concept in web development that allows you to add extra functionality to your application's request/response cycle. In FastAPI, middleware acts as a layer between the incoming request and your application's route handlers, enabling you to perform operations before the request reaches your main logic or after the response is generated.
Let's dive into how middleware works in FastAPI and explore some practical examples.
In FastAPI, you can create middleware using the @app.middleware("http")
decorator. Here's a simple example:
from fastapi import FastAPI, Request app = FastAPI() @app.middleware("http") async def my_middleware(request: Request, call_next): # Pre-processing logic response = await call_next(request) # Post-processing logic return response
In this structure:
request
and call_next
.call_next
.call_next
is a function that calls the next middleware or the route handler.Let's look at some real-world scenarios where middleware can be incredibly useful:
@app.middleware("http") async def add_custom_header(request: Request, call_next): response = await call_next(request) response.headers["X-Custom-Header"] = "FastAPI Rocks!" return response
This middleware adds a custom header to every response.
import time @app.middleware("http") async def log_requests(request: Request, call_next): start_time = time.time() response = await call_next(request) process_time = time.time() - start_time print(f"Path: {request.url.path}, Time: {process_time:.2f}s") return response
This middleware logs the path and processing time for each request.
from fastapi import HTTPException @app.middleware("http") async def catch_exceptions(request: Request, call_next): try: return await call_next(request) except Exception as e: return JSONResponse(status_code=500, content={"detail": "Internal Server Error"})
This middleware catches any unhandled exceptions and returns a generic 500 error response.
Cross-Origin Resource Sharing (CORS) is a crucial security mechanism that controls how web browsers interact with resources from different origins. When building APIs with FastAPI, properly handling CORS is essential for allowing or restricting access to your API from different domains.
FastAPI makes it easy to implement CORS using the CORSMiddleware
. Here's how you can add basic CORS support to your application:
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI() app.add_middleware( CORSMiddleware, allow_origins=["http://localhost:3000"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], )
In this example:
allow_origins
specifies which origins are allowed to make requests to your API.allow_credentials
enables sending cookies in CORS requests.allow_methods
and allow_headers
are set to allow all methods and headers.For more granular control, you can adjust the CORS settings:
app.add_middleware( CORSMiddleware, allow_origins=["http://localhost:3000"], allow_methods=["GET", "POST"], allow_headers=["Authorization", "Content-Type"], )
This configuration only allows GET and POST requests and specific headers.
app.add_middleware( CORSMiddleware, allow_origin_regex="https://.*\.example\.com$", allow_credentials=True, allow_methods=["*"], allow_headers=["*"], )
This setup allows any subdomain of example.com using HTTPS.
app.add_middleware( CORSMiddleware, allow_origins=["http://localhost:3000"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], max_age=600, )
The max_age
parameter sets how long browsers should cache the preflight response.
Keep middleware lightweight: Avoid heavy computations in middleware to prevent performance issues.
Order matters: The order in which you add middleware affects the execution order. Place critical middleware like authentication early in the chain.
Be specific with CORS: Only allow necessary origins, methods, and headers to enhance security.
Test thoroughly: Ensure your CORS configuration works as expected across different browsers and scenarios.
Use environment variables: Store CORS settings in environment variables for easy configuration across different environments.
By mastering middleware and CORS handling in FastAPI, you'll be well-equipped to build robust, secure, and efficient APIs. These concepts are fundamental to creating web applications that can safely interact with various clients and services across different domains.
15/11/2024 | Python
25/09/2024 | Python
15/11/2024 | Python
06/10/2024 | Python
22/11/2024 | Python
17/11/2024 | Python
14/11/2024 | Python
25/09/2024 | Python
08/12/2024 | Python
26/10/2024 | Python
26/10/2024 | Python