Official Python library for IPInfo IP address geolocation and data lookups
—
Synchronous API clients for IP geolocation lookups using the requests library. Provides both Core API and Lite API access with comprehensive configuration options, caching, and batch processing capabilities.
Factory functions that create and return configured handler instances with simplified initialization.
def getHandler(access_token=None, **kwargs):
"""
Create and return Handler object for Core API access.
Parameters:
- access_token (str, optional): IPinfo API access token
- **kwargs: Additional configuration options
Returns:
Handler: Configured Handler instance
"""
def getHandlerLite(access_token=None, **kwargs):
"""
Create and return HandlerLite object for Lite API access.
Parameters:
- access_token (str, optional): IPinfo API access token
- **kwargs: Additional configuration options
Returns:
HandlerLite: Configured HandlerLite instance
"""Primary synchronous client for the IPinfo Core API, supporting single IP lookups, batch operations, and map generation with comprehensive caching and configuration options.
class Handler:
def __init__(self, access_token=None, **kwargs):
"""
Initialize Handler with configuration options.
Parameters:
- access_token (str, optional): IPinfo API access token
- countries (dict, optional): Custom country code to name mappings
- eu_countries (list, optional): Custom list of EU country codes
- countries_flags (dict, optional): Custom country flag mappings
- countries_currencies (dict, optional): Custom country currency mappings
- continent (dict, optional): Custom continent mappings
- request_options (dict, optional): HTTP request configuration
- cache_options (dict, optional): Cache configuration (maxsize, ttl)
- cache (CacheInterface, optional): Custom cache implementation
- headers (dict, optional): Custom HTTP headers
"""
def getDetails(self, ip_address=None, timeout=None):
"""
Get details for specified IP address or current IP.
Parameters:
- ip_address (str|IPv4Address|IPv6Address, optional): IP address to lookup
- timeout (int, optional): Request timeout override
Returns:
Details: IP address details object
Raises:
RequestQuotaExceededError: When API quota exceeded
APIError: When API returns error response
"""
def getBatchDetails(self, ip_addresses, batch_size=None, timeout_per_batch=5, timeout_total=None, raise_on_fail=True):
"""
Get details for multiple IP addresses in batch requests.
Parameters:
- ip_addresses (list): List of IP addresses to lookup
- batch_size (int, optional): Batch size (default: 1000, max: 1000)
- timeout_per_batch (int, optional): Timeout per batch request (default: 5)
- timeout_total (int, optional): Total operation timeout
- raise_on_fail (bool, optional): Whether to raise on errors (default: True)
Returns:
dict: Mapping of IP addresses to Details objects or error info
Raises:
RequestQuotaExceededError: When API quota exceeded
TimeoutExceededError: When timeout limits exceeded
"""
def getMap(self, ips):
"""
Get URL to map visualization for list of IPs.
Parameters:
- ips (list): List of IP addresses (max 500,000)
Returns:
str: URL to map visualization
Raises:
requests.HTTPError: When request fails
"""
def getBatchDetailsIter(self, ip_addresses, batch_size=None, raise_on_fail=True):
"""
Iterator version of batch details lookup.
Parameters:
- ip_addresses (list): List of IP addresses to lookup
- batch_size (int, optional): Batch size (default: 1000)
- raise_on_fail (bool, optional): Whether to raise on errors (default: True)
Yields:
Details: IP address details for each batch
Raises:
RequestQuotaExceededError: When API quota exceeded
"""Synchronous client for the IPinfo Lite API, providing simplified IP geolocation data with reduced response fields and faster processing.
class HandlerLite:
def __init__(self, access_token=None, **kwargs):
"""
Initialize HandlerLite with configuration options.
Parameters: Same as Handler class
"""
def getDetails(self, ip_address=None, timeout=None):
"""
Get details for specified IP address using Lite API.
Parameters:
- ip_address (str|IPv4Address|IPv6Address, optional): IP address to lookup
- timeout (int, optional): Request timeout override
Returns:
Details: IP address details object with Lite API fields
Raises:
RequestQuotaExceededError: When API quota exceeded
APIError: When API returns error response
"""import ipinfo
# Create handler
handler = ipinfo.getHandler('your_access_token')
# Single IP lookup
details = handler.getDetails('8.8.8.8')
print(f"Location: {details.city}, {details.region}, {details.country}")
print(f"ISP: {details.org}")
print(f"Coordinates: {details.latitude}, {details.longitude}")import ipinfo
handler = ipinfo.getHandler('your_access_token')
# Batch lookup
ips = ['8.8.8.8', '1.1.1.1', '208.67.222.222']
results = handler.getBatchDetails(ips)
for ip, details in results.items():
if isinstance(details, dict):
print(f"{ip}: {details.get('city', 'Unknown')}")
else:
print(f"{ip}: {details.city}")import ipinfo
# Custom cache and timeout settings
handler = ipinfo.getHandler(
'your_access_token',
cache_options={'maxsize': 1000, 'ttl': 3600}, # 1 hour TTL
request_options={'timeout': 5},
headers={'User-Agent': 'MyApp/1.0'}
)
details = handler.getDetails('8.8.8.8', timeout=10)import ipinfo
# Use Lite API for faster, simpler responses
handler_lite = ipinfo.getHandlerLite('your_access_token')
details = handler_lite.getDetails('8.8.8.8')
print(f"Country: {details.country}") # Country name
print(f"Country Code: {details.country_code}") # Country codeimport ipinfo
from ipinfo.exceptions import RequestQuotaExceededError, TimeoutExceededError
from ipinfo.error import APIError
handler = ipinfo.getHandler('your_access_token')
try:
details = handler.getDetails('8.8.8.8')
print(details.city)
except RequestQuotaExceededError:
print("Monthly quota exceeded")
except APIError as e:
print(f"API error {e.error_code}: {e.error_json}")
except Exception as e:
print(f"Unexpected error: {e}")# Handler configuration options
HandlerOptions = {
'countries': dict, # Country code to name mappings
'eu_countries': list, # List of EU country codes
'countries_flags': dict, # Country flag emoji/unicode info
'countries_currencies': dict, # Country currency info
'continent': dict, # Continent mappings
'request_options': dict, # HTTP request options
'cache_options': dict, # Cache configuration
'cache': CacheInterface, # Custom cache implementation
'headers': dict # Custom HTTP headers
}
# Batch operation result
BatchResult = dict # IP address -> Details object or error info
# Cache configuration
CacheOptions = {
'maxsize': int, # Maximum cache entries (default: 4096)
'ttl': int # Time to live in seconds (default: 86400)
}
# Request configuration
RequestOptions = {
'timeout': int, # Request timeout in seconds (default: 2)
'proxies': dict, # Proxy configuration
'verify': bool, # SSL verification
'cert': str, # Client certificate
'stream': bool # Stream response
}Install with Tessl CLI
npx tessl i tessl/pypi-ipinfo