Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

How to Create an Interceptor or Middleware to Obtain X-REAL-IP and X-Forwarded-For in Calls with FAST-API

Tiempo de lectura: 2 minutos

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:

  1. Python and FastAPI installed on your system.
  2. 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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
pip install fastapi
pip install fastapi
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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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
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
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
from fastapi import FastAPI
app = FastAPI()
app.add_middleware(real_ip_interceptor)
from fastapi import FastAPI app = FastAPI() app.add_middleware(real_ip_interceptor)
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
@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}
@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}
@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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
uvicorn your_app_name:app --reload
uvicorn your_app_name:app --reload
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.

0

Leave a Comment