The geoip2 Python package provides an API for both MaxMind's GeoIP2 and GeoLite2 web services and local databases. It allows developers to perform IP geolocation lookups, retrieving information such as country, city, and ASN details. The library is actively maintained, with version 5.2.0 being the latest stable release, and follows semantic versioning with a regular release cadence.
Install & Compatibility
Where this runs
tested against v5.2.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.930 runs
installs and imports cleanly · install 0.0s · import 0.164s · 30.5MB
glibcpy 3.10–3.930 runs
installs and imports cleanly · install 4.5s · import 0.143s · 33MB
30MB installed
● package 30MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
Reader
✓ from geoip2.database import Reader
Client
✓ from geoip2.webservice import Client
AsyncClient
✓ from geoip2.webservice import AsyncClient
AddressNotFoundError
✓ from geoip2.errors import AddressNotFoundError
✗ try: ... except AddressNotFoundError: ... (without import)
Exceptions must be explicitly imported to be caught by name.
This example demonstrates how to perform a geolocation lookup using a local GeoLite2 City database. It also includes an optional section for using the GeoIP2 Web Service, which requires a MaxMind account ID and license key. Remember to download a MaxMind database (e.g., GeoLite2-City.mmdb) and specify its path for the local database example. Reader and Client objects should be initialized once and reused for performance.
import os
import geoip2.database
from geoip2.errors import AddressNotFoundError
# --- Using a local GeoLite2 City database ---
# 1. Download GeoLite2 City database from MaxMind (requires account):
# https://dev.maxmind.com/geoip/geolite2-free-geolocation-data
# 2. Extract the .mmdb file (e.g., GeoLite2-City.mmdb) and place it in a known directory.
database_path = os.environ.get('GEOLITE2_CITY_DB_PATH', './GeoLite2-City.mmdb')
if not os.path.exists(database_path):
print(f"Error: GeoLite2 City database not found at {database_path}.")
print("Please download it from MaxMind and update GEOLITE2_CITY_DB_PATH environment variable or file path.")
else:
try:
# Reader objects are expensive to create and should be reused across lookups.
with geoip2.database.Reader(database_path) as reader:
ip_address = '8.8.8.8'
try:
response = reader.city(ip_address)
print(f"IP: {ip_address}")
print(f" Country: {response.country.name} ({response.country.iso_code})")
print(f" City: {response.city.name}")
print(f" Location: Latitude {response.location.latitude}, Longitude {response.location.longitude}")
except AddressNotFoundError:
print(f"IP address {ip_address} not found in the database.")
except Exception as e:
print(f"An error occurred during lookup for {ip_address}: {e}")
# --- Using the GeoIP2 Web Service (requires MaxMind Account ID and License Key) ---
# MAXMIND_ACCOUNT_ID and MAXMIND_LICENSE_KEY should be set as environment variables
account_id = os.environ.get('MAXMIND_ACCOUNT_ID')
license_key = os.environ.get('MAXMIND_LICENSE_KEY')
if account_id and license_key:
print("\n--- Web Service Lookup ---")
try:
# Client objects are also expensive and should be reused.
with geoip2.webservice.Client(account_id, license_key) as client:
ip_address_ws = '1.1.1.1'
try:
response_ws = client.city(ip_address_ws)
print(f"IP: {ip_address_ws}")
print(f" Country: {response_ws.country.name} ({response_ws.country.iso_code})")
print(f" City: {response_ws.city.name}")
print(f" Location: Latitude {response_ws.location.latitude}, Longitude {response_ws.location.longitude}")
except AddressNotFoundError:
print(f"IP address {ip_address_ws} not found via web service.")
except Exception as e:
print(f"An error occurred during web service lookup for {ip_address_ws}: {e}")
except Exception as e:
print(f"Error initializing web service client: {e}")
else:
print("\nSkipping web service example: MAXMIND_ACCOUNT_ID and MAXMIND_LICENSE_KEY environment variables not set.")
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'geoip2' OR ImportError: No module named geoip2.database
The 'geoip2' package is not installed in the Python environment being used, or there is a local script named 'geoip2.py' that is shadowing the actual library.
fixInstall the package using `pip install geoip2`. If the issue persists, rename any local script named `geoip2.py` or `geoip2.pyc` to avoid a name collision.
FileNotFoundError: [Errno 2] No such file or directory: '/path/to/GeoLite2-City.mmdb'
The specified GeoIP2 database file (e.g., GeoLite2-City.mmdb) does not exist at the provided path, or the application lacks the necessary read permissions for the file or its directory.
fixEnsure the database file exists at the exact path provided to `geoip2.database.Reader()`. Verify the file name and extension are correct. Download the latest GeoLite2 or GeoIP2 database from MaxMind and place it in the expected directory, then check file permissions.
maxminddb.errors.InvalidDatabaseError: The MaxMind DB file's search tree is corrupt OR Error opening database file (...). Is this a valid MaxMind DB file?
The provided .mmdb database file is corrupted, not a valid MaxMind DB format, or its format is incompatible with the installed 'geoip2' or 'maxminddb' library version.
fixRedownload a fresh, uncorrupted copy of the GeoIP2 database from MaxMind. Ensure your 'geoip2' and 'maxminddb' Python packages are updated to their latest stable versions to guarantee compatibility with the database format.
geoip2.errors.AddressNotFoundError: The address X.X.X.X is not in the database.
The IP address queried is not present in the loaded GeoIP2 database. This commonly occurs for private, reserved, or certain unallocated IP addresses for which MaxMind does not provide public geolocation data.
fixImplement error handling (a `try-except` block) for `geoip2.errors.AddressNotFoundError` to gracefully manage cases where an IP address lookup yields no results. Consider if the IP is intentionally not in the database (e.g., a local network IP).
AttributeError: 'City' object has no attribute 'name' (or similar for other attributes like country.iso_code returning None)
While the IP lookup was successful, the specific attribute requested (e.g., city name, country ISO code) does not have data available in the loaded GeoIP2 database for that particular IP address.
fixAlways check if the attribute's value is not `None` before attempting to access sub-attributes or perform operations on it. This indicates that MaxMind does not have that specific piece of information for the given IP address in the database version you are using.
Audit
Dependencies
maxminddbrequiredRequired for reading local MaxMind DB files (often installed as a dependency of geoip2).
requestsoptionalUsed by the synchronous web service client.
aiohttpoptionalUsed by the asynchronous web service client.