Skip to main content

FastAPI IP2Location Middleware

PyPI

A high-performance, asynchronous FastAPI middleware that automatically geolocates incoming requests using the IP2Location database or the IP2Location.io API. It seamlessly injects the geolocation data directly into the request.state.location object for easy access in your route handlers.

Features

  • Dual Mode Support: Use a local .BIN database for ultra-fast, zero-latency lookups, or use the IP2Location.io API if you don't want to host the database.
  • Async & Connection Pooling: Built with httpx for non-blocking API calls, utilizing connection pooling to ensure high throughput.
  • Proxy Aware: Automatically extracts the real client IP from headers like X-Forwarded-For or X-Real-IP when deployed behind load balancers or reverse proxies (like Nginx, Cloudflare, or AWS ALB).
  • Local Development Friendly: Includes a test_ip parameter to easily override 127.0.0.1 and test specific geographic locations locally.
  • Multilingual Support: Supports the language parameter (API mode) to return localized names for countries, regions, and cities.
  • Graceful Degradation: Never crashes your app. If a lookup fails, it safely injects an error message into the state object so your app can decide how to handle it.

Installation

Install the package via pip:

pip install fastapi-ip2proxy

Prerequisites

You need at least one of the following to use this middleware:

  • Local Database (.BIN): Download a free IP2Proxy Lite database (e.g., PX12) from IP2Location Lite.

  • API Key: Sign up for an API key at IP2Location.io.

Usage Examples

  1. Using the Local Database (Recommended for Production)
from fastapi import FastAPI, Request
from fastapi_ip2proxy import IP2ProxyMiddleware

app = FastAPI()

app.add_middleware(
    IP2ProxyMiddleware, 
    bin_path="IP2PROXY-LITE-PX12.BIN", # Path to your downloaded .BIN file
)

@app.get("/")
async def get_location(request: Request):
    return {"your_location": request.state.proxy}
  1. Using the IP2Location.io API
import os
from fastapi import FastAPI, Request
from fastapi_ip2proxy import IP2ProxyMiddleware

app = FastAPI()

app.add_middleware(
    IP2ProxyMiddleware, 
    api_key=os.getenv("IP2LOCATION_API_KEY")
)

@app.get("/")
async def get_location(request: Request):
    return {"your_location": request.state.proxy}

Advanced Configuration

You can fully customize the middleware to suit your environment:

app.add_middleware(
    IP2ProxyMiddleware,
    bin_path="IP2PROXY-LITE-PX12.BIN",
    api_key="OPTIONAL_FALLBACK_KEY",
    
    # Checks these headers first for the real IP. 
    # Defaults to ["X-Forwarded-For", "X-Real-IP"]
    ip_headers=["X-Forwarded-For", "X-Real-IP", "CF-Connecting-IP"], 
    
    # If the user connects from localhost (127.0.0.1), pretend they are 
    # connecting from this IP instead. Great for local testing!
    test_ip="8.8.8.8", 
    
    # Translate country/city names (Requires API mode and a supported plan)
    language="fr" 
)

Accessing the Data

The middleware standardizes the output regardless of whether you use the .BIN file or the API. The dictionary injected into request.state.proxy includes the following keys:

{
    "ip": "8.8.8.8",
    "country_short": "US",
    "country_long": "United States",
    "region": "California",
    "city": "Mountain View",
    "asn": "15169",
    "as": "Google LLC",
    "is_proxy": false,
    "error": null
}

(Note: Premium data fields like proxy data will also be populated if your specific .BIN file or API plan supports them).

License

This project is licensed under the MIT License.

Metadata

Release files for fastapi-ip2proxy 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fastapi-ip2proxy 1.0.0
File Size Uploaded Provenance Actions
fastapi_ip2proxy-1.0.0.tar.gz 7.9 kB Without provenance Details for fastapi_ip2proxy-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for fastapi-ip2proxy 1.0.0
File Interpreter ABI Platform Actions
fastapi_ip2proxy-1.0.0-py3-none-any.whl Python 3 none any Details for fastapi_ip2proxy-1.0.0-py3-none-any.whl

Total release size: 15.2 kB

Release files / fastapi_ip2proxy-1.0.0.tar.gz

Download URL fastapi_ip2proxy-1.0.0.tar.gz
Size 7.9 kB
Tags Source
SHA-256 checksum
How to use checksums
d6a0b48a060fe6eeaca53df94b1720d146c09183d4ea111e0747dba9b6cb1bc5
BLAKE2b-256 checksum
How to use checksums
80a50f67136ae81803ddcf715a7c4333cb8306d09a4eede443e0ca1363d8b784
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.10

Release files / fastapi_ip2proxy-1.0.0-py3-none-any.whl

Download URL fastapi_ip2proxy-1.0.0-py3-none-any.whl
Size 7.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
03c64efa1bc42963b621790e38bea981fa2a63f02066f6dd75352b51c25ef859
BLAKE2b-256 checksum
How to use checksums
faf6de6445c988cd8ab43c51d4c7f4c33a99a8526a5ed666b5013935ff3b30a8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.10

Security for fastapi-ip2proxy 1.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page