0
# Web Service Client
1
2
Synchronous and asynchronous clients for accessing MaxMind's GeoIP2 and GeoLite2 web services. The clients provide access to Country, City Plus, and Insights endpoints with comprehensive authentication, error handling, and proxy support.
3
4
```python
5
from collections.abc import Sequence
6
from typing import Optional
7
8
from geoip2.models import City, Country, Insights
9
from geoip2.types import IPAddress
10
```
11
12
## Capabilities
13
14
### Synchronous Client
15
16
The synchronous Client class provides blocking HTTP requests to MaxMind's web services using the requests library.
17
18
```python { .api }
19
class Client:
20
def __init__(self, account_id: int, license_key: str, host: str = "geoip.maxmind.com",
21
locales: Optional[Sequence[str]] = None, timeout: float = 60,
22
proxy: Optional[str] = None):
23
"""
24
Create a synchronous GeoIP2 client.
25
26
Parameters:
27
- account_id: MaxMind account ID
28
- license_key: MaxMind license key
29
- host: Hostname for requests (default: "geoip.maxmind.com")
30
Use "geolite.info" for GeoLite2 web service
31
Use "sandbox.maxmind.com" for Sandbox GeoIP2 web service
32
- locales: List of locale codes for name properties (default: ['en'])
33
Valid codes: 'de', 'en', 'es', 'fr', 'ja', 'pt-BR', 'ru', 'zh-CN'
34
- timeout: Request timeout in seconds (default: 60)
35
- proxy: HTTP proxy URL with optional basic auth
36
"""
37
38
def city(self, ip_address: IPAddress = "me") -> City:
39
"""
40
Call City Plus endpoint with the specified IP.
41
42
Parameters:
43
- ip_address: IPv4 or IPv6 address as string, or "me" for caller's IP
44
45
Returns:
46
City model object containing geographic data
47
48
Raises:
49
- AddressNotFoundError: IP address not found in database
50
- AuthenticationError: Invalid credentials
51
- OutOfQueriesError: Account out of queries
52
- HTTPError: HTTP transport error
53
"""
54
55
def country(self, ip_address: IPAddress = "me") -> Country:
56
"""
57
Call GeoIP2 Country endpoint with the specified IP.
58
59
Parameters:
60
- ip_address: IPv4 or IPv6 address as string, or "me" for caller's IP
61
62
Returns:
63
Country model object containing country-level geographic data
64
65
Raises:
66
- AddressNotFoundError: IP address not found in database
67
- AuthenticationError: Invalid credentials
68
- OutOfQueriesError: Account out of queries
69
- HTTPError: HTTP transport error
70
"""
71
72
def insights(self, ip_address: IPAddress = "me") -> Insights:
73
"""
74
Call Insights endpoint with the specified IP.
75
76
Note: Insights is only supported by GeoIP2 web service, not GeoLite2.
77
78
Parameters:
79
- ip_address: IPv4 or IPv6 address as string, or "me" for caller's IP
80
81
Returns:
82
Insights model object containing comprehensive data including user behavior analytics
83
84
Raises:
85
- AddressNotFoundError: IP address not found in database
86
- AuthenticationError: Invalid credentials
87
- OutOfQueriesError: Account out of queries
88
- PermissionRequiredError: Account lacks Insights permission
89
- HTTPError: HTTP transport error
90
"""
91
92
def close(self):
93
"""Close underlying HTTP session and connections."""
94
95
def __enter__(self) -> "Client": ...
96
def __exit__(self, exc_type, exc_value, traceback): ...
97
```
98
99
### Asynchronous Client
100
101
The AsyncClient class provides non-blocking HTTP requests using aiohttp for integration with asyncio applications.
102
103
```python { .api }
104
class AsyncClient:
105
def __init__(self, account_id: int, license_key: str, host: str = "geoip.maxmind.com",
106
locales: Optional[Sequence[str]] = None, timeout: float = 60,
107
proxy: Optional[str] = None):
108
"""
109
Create an asynchronous GeoIP2 client.
110
111
Parameters are identical to synchronous Client.
112
Note: Client objects should not be shared across different event loops.
113
"""
114
115
async def city(self, ip_address: IPAddress = "me") -> City:
116
"""
117
Async version of city endpoint call.
118
119
Parameters and returns are identical to synchronous version.
120
"""
121
122
async def country(self, ip_address: IPAddress = "me") -> Country:
123
"""
124
Async version of country endpoint call.
125
126
Parameters and returns are identical to synchronous version.
127
"""
128
129
async def insights(self, ip_address: IPAddress = "me") -> Insights:
130
"""
131
Async version of insights endpoint call.
132
133
Parameters and returns are identical to synchronous version.
134
"""
135
136
async def close(self):
137
"""Close underlying aiohttp session and connections."""
138
139
async def __aenter__(self) -> "AsyncClient": ...
140
async def __aexit__(self, exc_type, exc_value, traceback): ...
141
```
142
143
## Usage Examples
144
145
### Basic Synchronous Usage
146
147
```python
148
import geoip2.webservice
149
150
# Create client with credentials
151
with geoip2.webservice.Client(42, 'your_license_key') as client:
152
# Query an IP address
153
response = client.city('203.0.113.0')
154
155
# Access geographic data
156
print(f"Country: {response.country.name}")
157
print(f"City: {response.city.name}")
158
print(f"Coordinates: {response.location.latitude}, {response.location.longitude}")
159
```
160
161
### Basic Asynchronous Usage
162
163
```python
164
import asyncio
165
import geoip2.webservice
166
167
async def lookup_ip(ip_address):
168
async with geoip2.webservice.AsyncClient(42, 'your_license_key') as client:
169
response = await client.city(ip_address)
170
return response.country.name
171
172
# Run async function
173
country = asyncio.run(lookup_ip('203.0.113.0'))
174
```
175
176
### Using Different Services
177
178
```python
179
with geoip2.webservice.Client(42, 'license_key') as client:
180
# Country-level data only (faster, less detailed)
181
country_response = client.country('203.0.113.0')
182
183
# City-level data (includes country data plus city, subdivision, postal)
184
city_response = client.city('203.0.113.0')
185
186
# Insights data (includes city data plus user behavior analytics)
187
insights_response = client.insights('203.0.113.0')
188
```
189
190
### Using GeoLite2 Web Service
191
192
```python
193
# Use GeoLite2 instead of GeoIP2
194
with geoip2.webservice.Client(42, 'license_key', host='geolite.info') as client:
195
response = client.city('203.0.113.0')
196
# Note: Insights is not available on GeoLite2
197
```
198
199
### Custom Configuration
200
201
```python
202
# Custom locales, timeout, and proxy
203
with geoip2.webservice.Client(
204
account_id=42,
205
license_key='license_key',
206
locales=['es', 'en'], # Spanish first, English fallback
207
timeout=30, # 30 second timeout
208
proxy='http://proxy.example.com:8080'
209
) as client:
210
response = client.city('203.0.113.0')
211
print(response.country.name) # Name in Spanish if available
212
```
213
214
### Error Handling
215
216
```python
217
import geoip2.webservice
218
from geoip2.errors import AddressNotFoundError, AuthenticationError, OutOfQueriesError
219
220
try:
221
with geoip2.webservice.Client(42, 'license_key') as client:
222
response = client.city('127.0.0.1') # Private IP
223
except AddressNotFoundError:
224
print("IP address not found in database")
225
except AuthenticationError:
226
print("Invalid account ID or license key")
227
except OutOfQueriesError:
228
print("Account is out of queries")
229
```
230
231
## Types
232
233
```python { .api }
234
IPAddress = Union[str, IPv6Address, IPv4Address]
235
```