MaxMind GeoIP2 API for IP geolocation using web services and databases
npx @tessl/cli install tessl/pypi-geoip2@5.1.0MaxMind GeoIP2 API for IP geolocation using web services and databases. This package provides comprehensive Python access to MaxMind's GeoIP2 and GeoLite2 services, enabling developers to perform IP geolocation queries to determine geographic information such as country, city, subdivision, postal code, ISP, ASN, and connection type for any given IP address.
pip install geoip2import geoip2.webservice
import geoip2.databaseCommon imports for web services:
from geoip2.webservice import Client, AsyncClientCommon imports for database access:
from geoip2.database import ReaderError handling imports:
from geoip2.errors import AddressNotFoundError, AuthenticationErrorimport geoip2.webservice
# Synchronous client
with geoip2.webservice.Client(account_id, 'license_key') as client:
response = client.city('203.0.113.0')
print(response.country.name) # 'United States'
print(response.country.iso_code) # 'US'
print(response.city.name) # 'Minneapolis'
print(response.postal.code) # '55455'
print(response.location.latitude) # 44.9733
print(response.location.longitude) # -93.2323
# Asynchronous client
import asyncio
async def main():
async with geoip2.webservice.AsyncClient(account_id, 'license_key') as client:
response = await client.city('203.0.113.0')
print(response.country.name)
asyncio.run(main())import geoip2.database
# City database
with geoip2.database.Reader('/path/to/GeoLite2-City.mmdb') as reader:
response = reader.city('203.0.113.0')
print(response.country.name) # 'United States'
print(response.city.name) # 'Minneapolis'
print(response.location.latitude) # 44.9733
# ASN database
with geoip2.database.Reader('/path/to/GeoLite2-ASN.mmdb') as reader:
response = reader.asn('203.0.113.0')
print(response.autonomous_system_number) # 1221
print(response.autonomous_system_organization) # 'Telstra Pty Ltd'The GeoIP2 package is structured around three main components:
The package provides both online (web service) and offline (database) access methods, with consistent API interfaces and response models across both approaches. All geographic data is organized hierarchically from continent to city level, with additional network and ISP information available depending on the service or database used.
Synchronous and asynchronous clients for accessing MaxMind's GeoIP2 and GeoLite2 web services. Provides country, city, and insights endpoints with comprehensive error handling and authentication.
class Client:
def __init__(self, account_id: int, license_key: str, host: str = "geoip.maxmind.com",
locales: Optional[Sequence[str]] = None, timeout: float = 60,
proxy: Optional[str] = None): ...
def city(self, ip_address: IPAddress = "me") -> City: ...
def country(self, ip_address: IPAddress = "me") -> Country: ...
def insights(self, ip_address: IPAddress = "me") -> Insights: ...
class AsyncClient:
def __init__(self, account_id: int, license_key: str, host: str = "geoip.maxmind.com",
locales: Optional[Sequence[str]] = None, timeout: float = 60,
proxy: Optional[str] = None): ...
async def city(self, ip_address: IPAddress = "me") -> City: ...
async def country(self, ip_address: IPAddress = "me") -> Country: ...
async def insights(self, ip_address: IPAddress = "me") -> Insights: ...Local database reader for MaxMind's MMDB format files. Supports all database types including City, Country, ASN, ISP, Domain, Connection-Type, Anonymous IP, and Enterprise databases.
class Reader:
def __init__(self, fileish: Union[AnyStr, int, os.PathLike, IO],
locales: Optional[Sequence[str]] = None, mode: int = MODE_AUTO): ...
def city(self, ip_address: IPAddress) -> City: ...
def country(self, ip_address: IPAddress) -> Country: ...
def asn(self, ip_address: IPAddress) -> ASN: ...
def isp(self, ip_address: IPAddress) -> ISP: ...
def anonymous_ip(self, ip_address: IPAddress) -> AnonymousIP: ...
def anonymous_plus(self, ip_address: IPAddress) -> AnonymousPlus: ...
def connection_type(self, ip_address: IPAddress) -> ConnectionType: ...
def domain(self, ip_address: IPAddress) -> Domain: ...
def enterprise(self, ip_address: IPAddress) -> Enterprise: ...Structured data models representing geographic and network information returned by web services and database lookups. Models contain nested record classes for hierarchical geographic data.
class City:
continent: geoip2.records.Continent
country: geoip2.records.Country
city: geoip2.records.City
location: geoip2.records.Location
postal: geoip2.records.Postal
subdivisions: geoip2.records.Subdivisions
traits: geoip2.records.Traits
class Country:
continent: geoip2.records.Continent
country: geoip2.records.Country
traits: geoip2.records.Traits
class ASN:
autonomous_system_number: Optional[int]
autonomous_system_organization: Optional[str]
ip_address: Union[IPv4Address, IPv6Address]
network: Optional[Union[ipaddress.IPv4Network, ipaddress.IPv6Network]]
class AnonymousPlus:
# Inherits all AnonymousIP fields plus:
anonymizer_confidence: Optional[int]
network_last_seen: Optional[datetime.date]
provider_name: Optional[str]Comprehensive exception hierarchy for handling various error conditions including address not found, authentication failures, rate limiting, and network errors.
class AddressNotFoundError(GeoIP2Error):
ip_address: Optional[str]
network: Optional[Union[ipaddress.IPv4Network, ipaddress.IPv6Network]]
class AuthenticationError(GeoIP2Error): ...
class HTTPError(GeoIP2Error):
http_status: Optional[int]
uri: Optional[str]
decoded_content: Optional[str]
class OutOfQueriesError(GeoIP2Error): ...
class PermissionRequiredError(GeoIP2Error): ...import datetime
from ipaddress import IPv4Address, IPv6Address
import ipaddress
from typing import Union, Optional
IPAddress = Union[str, IPv6Address, IPv4Address]