Hello, today I bring you a tutorial on how to create an interceptor or middleware in FastAPI to obtain the
X-REAL-IP and X-Forwarded-For headers in API calls:
Introduction
In FastAPI, interceptors (middlewares) are a powerful tool that allows you to customize the handling of HTTP requests before or after they reach the route handlers. In this tutorial, you will learn how to create an interceptor that extracts the X-REAL-IP
and X-Forwarded-For
headers from incoming HTTP calls in your FastAPI application.
Prerequisites:
- Python and FastAPI installed on your system.
- Basic knowledge of FastAPI and Python.
Step 1: Set Up Your Environment
Make sure you have a Python environment set up with FastAPI installed. You can install FastAPI using pip:
pip install fastapi
Step 2: Create an Interceptor
Create a function that will act as your interceptor. This function takes two arguments: request
and call_next
. The call_next
function represents the next action that will be executed after the interceptor performs its task.
from fastapi import Request async def real_ip_interceptor(request: Request, call_next): # Extract the X-REAL-IP header if present real_ip = request.headers.get('x-real-ip') # Extract the X-FORWARD header if present forward_header = request.headers.get('x-forwarded-for') # Assign the values to variables if present if real_ip: request.client.host = real_ip if forward_header: request.headers['x-forwarded-for'] = forward_header # Continue with the next step in the request handling chain response = await call_next(request) return response
In this example, we are extracting the X-REAL-IP
and X-FORWARD
headers if they are present in the request and assigning them to the real_ip
and x-forwarded-for
variables. Then, we update the request.client.host
property with the value of X-REAL-IP
if it exists and add the x-forwarded-for
header with the value of x-forwarded-for
if it exists.
Step 3: Implement the Interceptor
Add your interceptor to the FastAPI application using the add_middleware
method:
from fastapi import FastAPI app = FastAPI() app.add_middleware(real_ip_interceptor)
Step 4: Create a Sample Route
Add a sample route to test the interceptor:
@app.get("/") async def read_root(request: Request): # Access the X-REAL-IP and X-FORWARD headers if they have been assigned correctly real_ip = request.client.host forward_header = request.headers.get('Forwarded') return {"X-REAL-IP": real_ip, "X-FORWARD": forward_header}
Step 5: Run Your Application
Run your FastAPI application:
uvicorn your_app_name:app --reload
Step 6: Test Your Interceptor
Make a request to your FastAPI application and verify that the X-REAL-IP
and X-FORWARD
headers are correctly extracted and displayed in the response.
Conclusion:
You have learned how to create an interceptor in FastAPI to obtain the X-REAL-IP
and X-FORWARDED-FOR
headers from incoming HTTP calls. Interceptors allow you to customize the handling of HTTP requests and perform additional tasks before or after a request is handled by your application. You can adapt this approach to work with other headers or perform other customization tasks according to your specific needs.