{"id":1098,"library":"geoip2","title":"MaxMind GeoIP2 Python API","description":"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.","status":"active","version":"5.2.0","language":"python","source_language":"en","source_url":"https://github.com/maxmind/GeoIP2-python","tags":["geolocation","geoip","maxmind","ip-lookup","database","web-service"],"install":[{"cmd":"pip install geoip2","lang":"bash","label":"Install with pip"}],"dependencies":[{"reason":"Required for reading local MaxMind DB files (often installed as a dependency of geoip2).","package":"maxminddb","optional":false},{"reason":"Used by the synchronous web service client.","package":"requests","optional":true},{"reason":"Used by the asynchronous web service client.","package":"aiohttp","optional":true}],"imports":[{"symbol":"Reader","correct":"from geoip2.database import Reader"},{"symbol":"Client","correct":"from geoip2.webservice import Client"},{"symbol":"AsyncClient","correct":"from geoip2.webservice import AsyncClient"},{"note":"Exceptions must be explicitly imported to be caught by name.","wrong":"try: ... except AddressNotFoundError: ... (without import)","symbol":"AddressNotFoundError","correct":"from geoip2.errors import AddressNotFoundError"}],"quickstart":{"code":"import os\nimport geoip2.database\nfrom geoip2.errors import AddressNotFoundError\n\n# --- Using a local GeoLite2 City database ---\n# 1. Download GeoLite2 City database from MaxMind (requires account):\n#    https://dev.maxmind.com/geoip/geolite2-free-geolocation-data\n# 2. Extract the .mmdb file (e.g., GeoLite2-City.mmdb) and place it in a known directory.\n\ndatabase_path = os.environ.get('GEOLITE2_CITY_DB_PATH', './GeoLite2-City.mmdb')\n\nif not os.path.exists(database_path):\n    print(f\"Error: GeoLite2 City database not found at {database_path}.\")\n    print(\"Please download it from MaxMind and update GEOLITE2_CITY_DB_PATH environment variable or file path.\")\nelse:\n    try:\n        # Reader objects are expensive to create and should be reused across lookups.\n        with geoip2.database.Reader(database_path) as reader:\n            ip_address = '8.8.8.8'\n            try:\n                response = reader.city(ip_address)\n                print(f\"IP: {ip_address}\")\n                print(f\"  Country: {response.country.name} ({response.country.iso_code})\")\n                print(f\"  City: {response.city.name}\")\n                print(f\"  Location: Latitude {response.location.latitude}, Longitude {response.location.longitude}\")\n            except AddressNotFoundError:\n                print(f\"IP address {ip_address} not found in the database.\")\n            except Exception as e:\n                print(f\"An error occurred during lookup for {ip_address}: {e}\")\n\n\n# --- Using the GeoIP2 Web Service (requires MaxMind Account ID and License Key) ---\n# MAXMIND_ACCOUNT_ID and MAXMIND_LICENSE_KEY should be set as environment variables\naccount_id = os.environ.get('MAXMIND_ACCOUNT_ID')\nlicense_key = os.environ.get('MAXMIND_LICENSE_KEY')\n\nif account_id and license_key:\n    print(\"\\n--- Web Service Lookup ---\")\n    try:\n        # Client objects are also expensive and should be reused.\n        with geoip2.webservice.Client(account_id, license_key) as client:\n            ip_address_ws = '1.1.1.1'\n            try:\n                response_ws = client.city(ip_address_ws)\n                print(f\"IP: {ip_address_ws}\")\n                print(f\"  Country: {response_ws.country.name} ({response_ws.country.iso_code})\")\n                print(f\"  City: {response_ws.city.name}\")\n                print(f\"  Location: Latitude {response_ws.location.latitude}, Longitude {response_ws.location.longitude}\")\n            except AddressNotFoundError:\n                print(f\"IP address {ip_address_ws} not found via web service.\")\n            except Exception as e:\n                print(f\"An error occurred during web service lookup for {ip_address_ws}: {e}\")\n    except Exception as e:\n        print(f\"Error initializing web service client: {e}\")\nelse:\n    print(\"\\nSkipping web service example: MAXMIND_ACCOUNT_ID and MAXMIND_LICENSE_KEY environment variables not set.\")","lang":"python","description":"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."},"warnings":[{"fix":"Upgrade Python to 3.10+ or pin `geoip2` to an earlier major version (e.g., `geoip2<5`) if using older Python.","message":"Version 5.0.0 and above require Python 3.10 or greater. Earlier Python versions should use an older `geoip2` release (e.g., v4.x.x for Python 3.9).","severity":"breaking","affected_versions":">=5.0.0"},{"fix":"Update code to use `.to_dict()` for dictionary representation and expect `ipaddress` objects for `ip_address` attributes.","message":"The `raw` attribute on model classes has been replaced by a `to_dict()` method. Also, `ip_address` properties on models now consistently return `ipaddress.IPv4Address` or `ipaddress.IPv6Address` objects.","severity":"breaking","affected_versions":">=4.5.0"},{"fix":"Avoid using `metro_code` or consider alternative geographic identifiers if possible.","message":"The `metro_code` on `geoip2.record.Location` is deprecated, as the code values are no longer maintained by MaxMind.","severity":"deprecated","affected_versions":">=4.5.0"},{"fix":"If using the Insights web service, refactor to use the `anonymizer` object for VPN and proxy information.","message":"Several boolean properties (e.g., `is_anonymous`, `is_anonymous_vpn`) on `geoip2.records.Traits` have been deprecated in favor of a new `anonymizer` object within the `Insights` model.","severity":"deprecated","affected_versions":">=4.5.0"},{"fix":"Always wrap IP lookup calls in a `try...except geoip2.errors.AddressNotFoundError:` block to gracefully handle unknown IP addresses.","message":"Failure to handle `geoip2.errors.AddressNotFoundError` when an IP address is not found in the database or by the web service can lead to unhandled exceptions.","severity":"gotcha","affected_versions":"All"},{"fix":"Create `Reader` or `Client` objects once and reuse them for multiple lookups. Use `with` statements to ensure proper resource management (e.g., database file closure).","message":"The `geoip2.database.Reader` and `geoip2.webservice.Client` objects are expensive to create. Instantiating them repeatedly in a loop will severely impact performance.","severity":"gotcha","affected_versions":"All"},{"fix":"Rely on stable identifiers like `geoname_id`, `iso_code`, or other unique codes (e.g., `response.country.iso_code`, `response.city.geoname_id`).","message":"Using values from `names` properties (e.g., `response.country.name`) as keys in databases or dictionaries is discouraged, as these names may change between MaxMind releases. Instead, use stable identifiers.","severity":"gotcha","affected_versions":"All"}],"env_vars":null,"search_vec":"'5.2.0':48 'activ':44 'allow':25 'api':4,11 'asn':39 'cadenc':62 'citi':37 'countri':36 'databas':23,69 'detail':40 'develop':26 'follow':55 'geoip':64 'geoip2':2,6,16 'geolite2':18 'geoloc':30,63 'inform':33 'ip':29,67 'ip-lookup':66 'latest':51 'librari':42 'local':22 'lookup':31,68 'maintain':45 'maxmind':1,14,65 'packag':8 'perform':28 'provid':9 'python':3,7 'regular':60 'releas':53,61 'retriev':32 'semant':56 'servic':20,72 'stabl':52 'version':47,57 'web':19,71 'web-servic':70","created_at":"2026-04-05T13:05:37.210833+00:00","updated_at":"2026-04-16T15:14:50.423685+00:00","problems":[{"fix":"Install 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.","cause":"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.","error":"ModuleNotFoundError: No module named 'geoip2' OR ImportError: No module named geoip2.database"},{"fix":"Ensure 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.","cause":"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.","error":"FileNotFoundError: [Errno 2] No such file or directory: '/path/to/GeoLite2-City.mmdb'"},{"fix":"Redownload 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.","cause":"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.","error":"maxminddb.errors.InvalidDatabaseError: The MaxMind DB file's search tree is corrupt OR Error opening database file (...). Is this a valid MaxMind DB file?"},{"fix":"Implement 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).","cause":"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.","error":"geoip2.errors.AddressNotFoundError: The address X.X.X.X is not in the database."},{"fix":"Always 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.","cause":"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.","error":"AttributeError: 'City' object has no attribute 'name' (or similar for other attributes like country.iso_code returning None)"}],"ecosystem":"pypi","meta_description":null,"install_score":100,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":"5.2.0","cli_name":"","cli_version":null,"type":"library","homepage":"https://www.maxmind.com/","github":"https://github.com/maxmind/GeoIP2-python","docs":"https://geoip2.readthedocs.org/","changelog":null,"pypi":"https://pypi.org/project/geoip2/","npm":null,"openapi_spec":null,"status_page":null,"smithery":null,"categories":["http-networking","data"],"base_url":null,"auth_type":null,"provenance":{"verified_status":"passing","verified_at":"2026-06-28","last_verified":"2026-06-28","next_check":"2026-07-28","install_tag":"verified"}}