Libraries
Python SDK
The Python SDK provides an easy-to-use interface for integrating GeoIP lookups into your Python applications.
Installation
Install the SDK using pip:
pip install geoipapi
Quick Start
from geoipapi import GeoIP
# Initialize the client
with GeoIP() as client:
# Get current IP address
ip_response = client.geo_ip_endpoints.get_ip()
print(f"Your IP: {ip_response}")
# Get detailed geolocation data
geo_data = client.geo_ip_endpoints.get_ip_data()
print(f"Location: {geo_data.country.city}, {geo_data.country.name}")
Configuration
Configure the client with custom settings:
from geoipapi import GeoIP
from geoipapi.utils import RetryConfig, BackoffStrategy
retry_config = RetryConfig(
strategy="backoff",
backoff=BackoffStrategy(
initial_interval=1,
max_interval=50,
exponent=1.1,
max_elapsed_time=100
)
)
with GeoIP(
server_url="https://api.geoipapi.com",
retry_config=retry_config
) as client:
response = client.geo_ip_endpoints.get_ip()
Async Support
The SDK supports asynchronous operations:
import asyncio
from geoipapi import GeoIP
async def main():
async with GeoIP() as client:
# Get current IP address
ip_response = await client.geo_ip_endpoints.get_ip_async()
print(f"Your IP: {ip_response}")
# Get geolocation data
geo_data = await client.geo_ip_endpoints.get_ip_data_async()
print(f"Location: {geo_data.country.city}, {geo_data.country.name}")
asyncio.run(main())
Available Methods
get_ip()
Get your current public IP address:
ip_response = client.geo_ip_endpoints.get_ip()
print(f"Current IP: {ip_response}")
get_ip_data()
Get comprehensive geolocation data:
geo_data = client.geo_ip_endpoints.get_ip_data()
print(f"Country: {geo_data.country.name}")
print(f"City: {geo_data.country.city}")
print(f"Coordinates: {geo_data.location.latitude}, {geo_data.location.longitude}")
Response Model
from dataclasses import dataclass
from typing import Literal
@dataclass
class Country:
is_eu_member: bool
currency_code: str
continent: str
name: str
country_code: str
state: str
city: str
zip: str
timezone: str
@dataclass
class Location:
latitude: float
longitude: float
@dataclass
class ASN:
number: int
name: str
network: str
type: str
@dataclass
class GeoIPResponse:
ip: str
type: Literal['IPv4', 'IPv6']
country: Country
location: Location
asn: ASN
Error Handling
Handle API errors gracefully:
from geoipapi import GeoIP, errors
with GeoIP() as client:
try:
response = client.geo_ip_endpoints.get_ip_data()
print(response)
except errors.HTTPValidationError as e:
print(f"Validation error: {e.message}")
except errors.APIError as e:
print(f"API error: {e.message}")