MaxMind GeoIP2 API for IP geolocation using web services and databases
npx @tessl/cli install tessl/pypi-geoip2@5.1.00
# GeoIP2
1
2
MaxMind 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.
3
4
## Package Information
5
6
- **Package Name**: geoip2
7
- **Language**: Python
8
- **Installation**: `pip install geoip2`
9
- **Version**: 5.1.0
10
- **License**: Apache-2.0
11
12
## Core Imports
13
14
```python
15
import geoip2.webservice
16
import geoip2.database
17
```
18
19
Common imports for web services:
20
21
```python
22
from geoip2.webservice import Client, AsyncClient
23
```
24
25
Common imports for database access:
26
27
```python
28
from geoip2.database import Reader
29
```
30
31
Error handling imports:
32
33
```python
34
from geoip2.errors import AddressNotFoundError, AuthenticationError
35
```
36
37
## Basic Usage
38
39
### Web Service Usage
40
41
```python
42
import geoip2.webservice
43
44
# Synchronous client
45
with geoip2.webservice.Client(account_id, 'license_key') as client:
46
response = client.city('203.0.113.0')
47
48
print(response.country.name) # 'United States'
49
print(response.country.iso_code) # 'US'
50
print(response.city.name) # 'Minneapolis'
51
print(response.postal.code) # '55455'
52
print(response.location.latitude) # 44.9733
53
print(response.location.longitude) # -93.2323
54
55
# Asynchronous client
56
import asyncio
57
58
async def main():
59
async with geoip2.webservice.AsyncClient(account_id, 'license_key') as client:
60
response = await client.city('203.0.113.0')
61
print(response.country.name)
62
63
asyncio.run(main())
64
```
65
66
### Database Usage
67
68
```python
69
import geoip2.database
70
71
# City database
72
with geoip2.database.Reader('/path/to/GeoLite2-City.mmdb') as reader:
73
response = reader.city('203.0.113.0')
74
75
print(response.country.name) # 'United States'
76
print(response.city.name) # 'Minneapolis'
77
print(response.location.latitude) # 44.9733
78
79
# ASN database
80
with geoip2.database.Reader('/path/to/GeoLite2-ASN.mmdb') as reader:
81
response = reader.asn('203.0.113.0')
82
print(response.autonomous_system_number) # 1221
83
print(response.autonomous_system_organization) # 'Telstra Pty Ltd'
84
```
85
86
## Architecture
87
88
The GeoIP2 package is structured around three main components:
89
90
- **Web Service Clients**: Synchronous and asynchronous clients for querying MaxMind's web services
91
- **Database Reader**: Local database access for MMDB format files
92
- **Model Classes**: Structured response objects containing geographic and network information organized as nested records
93
94
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.
95
96
## Capabilities
97
98
### Web Service Client
99
100
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.
101
102
```python { .api }
103
class Client:
104
def __init__(self, account_id: int, license_key: str, host: str = "geoip.maxmind.com",
105
locales: Optional[Sequence[str]] = None, timeout: float = 60,
106
proxy: Optional[str] = None): ...
107
108
def city(self, ip_address: IPAddress = "me") -> City: ...
109
def country(self, ip_address: IPAddress = "me") -> Country: ...
110
def insights(self, ip_address: IPAddress = "me") -> Insights: ...
111
112
class AsyncClient:
113
def __init__(self, account_id: int, license_key: str, host: str = "geoip.maxmind.com",
114
locales: Optional[Sequence[str]] = None, timeout: float = 60,
115
proxy: Optional[str] = None): ...
116
117
async def city(self, ip_address: IPAddress = "me") -> City: ...
118
async def country(self, ip_address: IPAddress = "me") -> Country: ...
119
async def insights(self, ip_address: IPAddress = "me") -> Insights: ...
120
```
121
122
[Web Service Client](./web-service.md)
123
124
### Database Reader
125
126
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.
127
128
```python { .api }
129
class Reader:
130
def __init__(self, fileish: Union[AnyStr, int, os.PathLike, IO],
131
locales: Optional[Sequence[str]] = None, mode: int = MODE_AUTO): ...
132
133
def city(self, ip_address: IPAddress) -> City: ...
134
def country(self, ip_address: IPAddress) -> Country: ...
135
def asn(self, ip_address: IPAddress) -> ASN: ...
136
def isp(self, ip_address: IPAddress) -> ISP: ...
137
def anonymous_ip(self, ip_address: IPAddress) -> AnonymousIP: ...
138
def anonymous_plus(self, ip_address: IPAddress) -> AnonymousPlus: ...
139
def connection_type(self, ip_address: IPAddress) -> ConnectionType: ...
140
def domain(self, ip_address: IPAddress) -> Domain: ...
141
def enterprise(self, ip_address: IPAddress) -> Enterprise: ...
142
```
143
144
[Database Reader](./database-reader.md)
145
146
### Response Models
147
148
Structured data models representing geographic and network information returned by web services and database lookups. Models contain nested record classes for hierarchical geographic data.
149
150
```python { .api }
151
class City:
152
continent: geoip2.records.Continent
153
country: geoip2.records.Country
154
city: geoip2.records.City
155
location: geoip2.records.Location
156
postal: geoip2.records.Postal
157
subdivisions: geoip2.records.Subdivisions
158
traits: geoip2.records.Traits
159
160
class Country:
161
continent: geoip2.records.Continent
162
country: geoip2.records.Country
163
traits: geoip2.records.Traits
164
165
class ASN:
166
autonomous_system_number: Optional[int]
167
autonomous_system_organization: Optional[str]
168
ip_address: Union[IPv4Address, IPv6Address]
169
network: Optional[Union[ipaddress.IPv4Network, ipaddress.IPv6Network]]
170
171
class AnonymousPlus:
172
# Inherits all AnonymousIP fields plus:
173
anonymizer_confidence: Optional[int]
174
network_last_seen: Optional[datetime.date]
175
provider_name: Optional[str]
176
```
177
178
[Response Models](./models.md)
179
180
### Error Handling
181
182
Comprehensive exception hierarchy for handling various error conditions including address not found, authentication failures, rate limiting, and network errors.
183
184
```python { .api }
185
class AddressNotFoundError(GeoIP2Error):
186
ip_address: Optional[str]
187
network: Optional[Union[ipaddress.IPv4Network, ipaddress.IPv6Network]]
188
189
class AuthenticationError(GeoIP2Error): ...
190
class HTTPError(GeoIP2Error):
191
http_status: Optional[int]
192
uri: Optional[str]
193
decoded_content: Optional[str]
194
195
class OutOfQueriesError(GeoIP2Error): ...
196
class PermissionRequiredError(GeoIP2Error): ...
197
```
198
199
[Error Handling](./errors.md)
200
201
## Types
202
203
```python { .api }
204
import datetime
205
from ipaddress import IPv4Address, IPv6Address
206
import ipaddress
207
from typing import Union, Optional
208
209
IPAddress = Union[str, IPv6Address, IPv4Address]
210
```