
FastAPI is a modern, high-performance web framework designed for building APIs with Python, prioritized for its speed, ease of learning, and production-ready capabilities. A core component of its extensible architecture is the middleware system, which functions as a plugin layer that executes logic before a request reaches a specific path operation and after a response is generated. By utilizing a straightforward app.add_middleware() declaration, developers can seamlessly integrate global functionalities, such as the fastapi-ip2location SDK to automatically intercept incoming requests and retrieve vital information like visitor geolocation data or postal codes before the request is processed by the application logic. This mechanism ensures that cross-cutting concerns are handled consistently and efficiently across the entire platform, facilitating a more streamlined development workflow.
By identifying the visitor’s IP address and performing a lookup through the IP2Location.io API or a local BIN database, the IP2Location FastAPI middleware enriches incoming requests with geolocation data. This information is injected into HTTP request headers, making it readily available for Python, PHP, Node.js, or other backend services to process.
Prerequisites #
Before we get started with this guide, make sure that Python and pip, the Python package manager, have been installed. You will also need to install the following packages:
- FastAPI
- IP2Location FastAPI middleware SDK
We will cover the installation of both packages below.
Installation #
Step 1: Install FastAPI #
To install FastAPI, just run the following command:
pip install "fastapi[standard]"
You can verify the installation by running this command: pip list | grep 'fastapi'
You should see FastAPI listed:

Step 2: Install IP2Location FastAPI middleware SDK #
To install the IP2Location FastAPI middleware SDK, run the following command:
pip install fastapi-ip2location
Then verify the installation by running this command:
You should see the IP2Location FastAPI middleware SDK listed:

Usage #
To use the IP2Location FastAPI middleware SDK in your FastAPI project, it is simple.
First, create a new folder called fastapi-geo using the following command:
mkdir fastapi-geo && cd fastapi-geo
After that, in the folder create a new file named main.py and paste the following content:
import os
from dotenv import load_dotenv
from fastapi import FastAPI, Request, HTTPException, Depends
from fastapi_ip2location import IP2LocationMiddleware
# Load the variables from the .env file into the system environment
load_dotenv()
app = FastAPI(title="Advanced IP Geolocation API")
# Setup the middleware
app.add_middleware(
IP2LocationMiddleware,
api_key=os.getenv("IP2LOCATION_API_KEY", "YOUR_API_KEY_HERE"),
)
# This is the "FastAPI way" to access request state cleanly across multiple routes
def get_user_location(request: Request) -> dict:
location = getattr(request.state, "location", None)
if not location:
raise HTTPException(status_code=500, detail="Geolocation middleware failed to inject data.")
if location.get("error"):
print(f"Warning: Location error - {location['error']}")
# You could choose to raise a 400 error here, but usually,
# it is better to let the app degrade gracefully.
return location
@app.get("/api/location")
async def debug_location(location: dict = Depends(get_user_location)):
"""Returns the exact dictionary injected by the middleware to verify all fields."""
return {
"status": "success",
"data": location
}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000, proxy_headers=True)
Then, create a .env file, and paste the following content:
IP2LOCATION_API_KEY=YOUR_IP2LOCATION_IO_API_KEY
Replace the value of the IP2LOCATION_API_KEY with your actual IP2Location.io API key. If you donβt have an API key yet, you can sign up for a free IP2Location.io API key.
After that, run the following command to start the local server:
fastapi dev
You should see output similar to this:

Now you can open another terminal and send a request to the server:
curl -i http://127.0.0.1:8000/api/location
Because this request comes from localhost, the detected IP may be 127.0.0.1, which usually does not return useful geolocation data.

To test more effectively, send a simulated client IP using X-Forwarded-For:
curl -i http://127.0.0.1:8000/api/location -H "X-Forwarded-For: 8.8.8.8"
You should see output similar to this:

If you prefer using the BIN database for location lookup instead of API, itβs very easy to do it. First, download the IP2Location BIN database to the fastapi-geo folder in your server. Then, replace the code inside the main.py with this:
import os
from dotenv import load_dotenv
from fastapi import FastAPI, Request, HTTPException, Depends
from fastapi_ip2location import IP2LocationMiddleware
# Load the variables from the .env file into the system environment
load_dotenv()
app = FastAPI(title="Advanced IP Geolocation API")
# Setup the middleware
app.add_middleware(
IP2LocationMiddleware,
bin_path="IP2LOCATION-LITE-DB11.BIN", # Path to your downloaded .BIN file
)
# This is the "FastAPI way" to access request state cleanly across multiple routes
def get_user_location(request: Request) -> dict:
location = getattr(request.state, "location", None)
if not location:
raise HTTPException(status_code=500, detail="Geolocation middleware failed to inject data.")
if location.get("error"):
print(f"Warning: Location error - {location['error']}")
# You could choose to raise a 400 error here, but usually,
# it is better to let the app degrade gracefully.
return location
@app.get("/api/location")
async def debug_location(location: dict = Depends(get_user_location)):
"""Returns the exact dictionary injected by the middleware to verify all fields."""
return {
"status": "success",
"data": location
}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000, proxy_headers=True)
Replace the βIP2LOCATION-LITE-DB11.BINβ with the actual filename of the BIN database.
Finally, run fastapi dev again if you terminated the server, and send the same request again:
curl -i http://127.0.0.1:8000/api/location -H "X-Forwarded-For: 8.8.8.8"
You should get the same results as the API.
Conclusion #
By integrating the IP2Location FastAPI middleware, you have successfully set up a robust system to automatically enrich your application with geolocation data. Whether leveraging the flexibility of the IP2Location.io API or the high-performance capabilities of the local BIN database, this solution streamlines the process of identifying visitor locations. With this foundation, you can now easily implement location-based features, personalize user experiences, and enhance your security protocols across your FastAPI applications.
