Skip to main content

A FastAPI middleware SDK for the IP2Location Python library.

Project description

FastAPI IP2Location Middleware

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-ip2location

Prerequisites

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

  • Local Database (.BIN): Download a free IP2Location Lite database (e.g., DB11) 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_ip2location import IP2LocationMiddleware

app = FastAPI()

app.add_middleware(
    IP2LocationMiddleware, 
    bin_path="IP2LOCATION-LITE-DB11.BIN", # Path to your downloaded .BIN file
    # use_memory=True # Only use this if you have plenty of memory.
)

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

app = FastAPI()

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

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

Advanced Configuration

You can fully customize the middleware to suit your environment:

app.add_middleware(
    IP2LocationMiddleware,
    bin_path="IP2LOCATION-LITE-DB11.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.location includes the following keys:

{
    "ip": "8.8.8.8",
    "country_short": "US",
    "country_long": "United States",
    "region": "California",
    "city": "Mountain View",
    "latitude": 37.40599,
    "longitude": -122.078514,
    "zipcode": "94043",
    "timezone": "-07:00",
    "error": null
}

(Note: Premium data fields like isp, domain, netspeed, weather, and 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.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastapi_ip2location-1.0.0.tar.gz (8.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastapi_ip2location-1.0.0-py3-none-any.whl (7.4 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_ip2location-1.0.0.tar.gz.

File metadata

  • Download URL: fastapi_ip2location-1.0.0.tar.gz
  • Upload date:
  • Size: 8.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.12

File hashes

Hashes for fastapi_ip2location-1.0.0.tar.gz
Algorithm Hash digest
SHA256 d3a51589b83b0b5e10992de4284d39d9ccf01baecbb017cefadeebaf422343ea
MD5 abd0aba24db8a5e54553f0b7776f5ddd
BLAKE2b-256 56b55ec48973336535fff76a804d75cd095a6a389b534a78110c8fb35afa22ea

See more details on using hashes here.

File details

Details for the file fastapi_ip2location-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_ip2location-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 118db3ef73307fe6bc9defb5164d978d47b4ea01ada8f0e60c3f026921bdc3a0
MD5 3809641e59dbf78c9026cf0527a9355c
BLAKE2b-256 f2012c5112d17e8c4e475d4c12e1f9df6d447d9bcbb180ab9cc6a985e69afb6c

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page