MaxMind GeoIP2 Python API¶
Description¶
This package provides an API for the GeoIP2 and GeoLite2 web services and databases.
Installation¶
To install the geoip2
module, type:
$ pip install geoip2
If you are not able to use pip, you may also use easy_install from the source directory:
$ easy_install .
Database Reader Extension¶
If you wish to use the C extension for the database reader, you must first install the libmaxminddb C API. Please see the instructions distributed with it.
IP Geolocation Usage¶
IP geolocation is inherently imprecise. Locations are often near the center of the population. Any location provided by a GeoIP2 database or web service should not be used to identify a particular address or household.
Web Service Usage¶
To use this API, you first construct either a geoip2.webservice.Client
or
geoip2.webservice.AsyncClient
, passing your MaxMind account_id
and
license_key
to the constructor. To use the GeoLite2 web service instead of
the GeoIP2 web service, set the optional host
keyword argument to
geolite.info
. To use the Sandbox GeoIP2 web service instead of the
production GeoIP2 web service, set the optional host
keyword argument to
sandbox.maxmind.com
.
After doing this, you may call the method corresponding to request type
(e.g., city
or country
), passing it the IP address you want to look up.
If the request succeeds, the method call will return a model class for the endpoint you called. This model in turn contains multiple record classes, each of which represents part of the data returned by the web service.
If the request fails, the client class throws an exception.
Sync Web Service Example¶
>>> import geoip2.webservice
>>>
>>> # This creates a Client object that can be reused across requests.
>>> # Replace "42" with your account ID and "license_key" with your license
>>> # key. Set the "host" keyword argument to "geolite.info" to use the
>>> # GeoLite2 web service instead of the GeoIP2 web service. Set the
>>> # "host" keyword argument to "sandbox.maxmind.com" to use the Sandbox
>>> # GeoIP2 web service instead of the production GeoIP2 web service.
>>> with geoip2.webservice.Client(42, 'license_key') as client:
>>>
>>> # Replace "city" with the method corresponding to the web service
>>> # that you are using, i.e., "country", "city", or "insights". Please
>>> # note that Insights is not supported by the GeoLite2 web service.
>>> response = client.city('203.0.113.0')
>>>
>>> response.country.iso_code
'US'
>>> response.country.name
'United States'
>>> response.country.names['zh-CN']
u'美国'
>>>
>>> response.subdivisions.most_specific.name
'Minnesota'
>>> response.subdivisions.most_specific.iso_code
'MN'
>>>
>>> response.city.name
'Minneapolis'
>>>
>>> response.postal.code
'55455'
>>>
>>> response.location.latitude
44.9733
>>> response.location.longitude
-93.2323
>>>
>>> response.traits.network
IPv4Network('203.0.113.0/32')
Async Web Service Example¶
>>> import asyncio
>>>
>>> import geoip2.webservice
>>>
>>> async def main():
>>> # This creates an AsyncClient object that can be reused across
>>> # requests on the running event loop. If you are using multiple event
>>> # loops, you must ensure the object is not used on another loop.
>>> #
>>> # Replace "42" with your account ID and "license_key" with your license
>>> # key. Set the "host" keyword argument to "geolite.info" to use the
>>> # GeoLite2 web service instead of the GeoIP2 web service. Set the
>>> # "host" keyword argument to "sandbox.maxmind.com" to use the Sandbox
>>> # GeoIP2 web service instead of the production GeoIP2 web service.
>>> async with geoip2.webservice.AsyncClient(42, 'license_key') as client:
>>>
>>> # Replace "city" with the method corresponding to the web service
>>> # that you are using, i.e., "country", "city", or "insights". Please
>>> # note that Insights is not supported by the GeoLite2 web service.
>>> response = await client.city('203.0.113.0')
>>>
>>> response.country.iso_code
'US'
>>> response.country.name
'United States'
>>> response.country.names['zh-CN']
u'美国'
>>>
>>> response.subdivisions.most_specific.name
'Minnesota'
>>> response.subdivisions.most_specific.iso_code
'MN'
>>>
>>> response.city.name
'Minneapolis'
>>>
>>> response.postal.code
'55455'
>>>
>>> response.location.latitude
44.9733
>>> response.location.longitude
-93.2323
>>>
>>> response.traits.network
IPv4Network('203.0.113.0/32')
>>>
>>> asyncio.run(main())
Web Service Client Exceptions¶
For details on the possible errors returned by the web service itself, see https://dev.maxmind.com/geoip/docs/web-services?lang=en for the GeoIP2 web service docs.
If the web service returns an explicit error document, this is thrown as a
AddressNotFoundError
, AuthenticationError
, InvalidRequestError
, or
OutOfQueriesError
as appropriate. These all subclass GeoIP2Error
.
If some other sort of error occurs, this is thrown as an HTTPError
. This
is thrown when some sort of unanticipated error occurs, such as the web
service returning a 500 or an invalid error document. If the web service
returns any status code besides 200, 4xx, or 5xx, this also becomes an
HTTPError
.
Finally, if the web service returns a 200 but the body is invalid, the client
throws a GeoIP2Error
.
Database Usage¶
To use the database API, you first construct a geoip2.database.Reader
using
the path to the file as the first argument. After doing this, you may call the
method corresponding to database type (e.g., city
or country
), passing it
the IP address you want to look up.
If the lookup succeeds, the method call will return a model class for the database method you called. This model in turn contains multiple record classes, each of which represents part of the data for the record.
If the request fails, the reader class throws an exception.
Database Example¶
City Database¶
>>> import geoip2.database
>>>
>>> # This creates a Reader object. You should use the same object
>>> # across multiple requests as creation of it is expensive.
>>> with geoip2.database.Reader('/path/to/GeoLite2-City.mmdb') as reader:
>>>
>>> # Replace "city" with the method corresponding to the database
>>> # that you are using, e.g., "country".
>>> response = reader.city('203.0.113.0')
>>>
>>> response.country.iso_code
'US'
>>> response.country.name
'United States'
>>> response.country.names['zh-CN']
u'美国'
>>>
>>> response.subdivisions.most_specific.name
'Minnesota'
>>> response.subdivisions.most_specific.iso_code
'MN'
>>>
>>> response.city.name
'Minneapolis'
>>>
>>> response.postal.code
'55455'
>>>
>>> response.location.latitude
44.9733
>>> response.location.longitude
-93.2323
>>>
>>> response.traits.network
IPv4Network('203.0.113.0/24')
Anonymous IP Database¶
>>> import geoip2.database
>>>
>>> # This creates a Reader object. You should use the same object
>>> # across multiple requests as creation of it is expensive.
>>> with geoip2.database.Reader('/path/to/GeoIP2-Anonymous-IP.mmdb') as reader:
>>>
>>> response = reader.anonymous_ip('203.0.113.0')
>>>
>>> response.is_anonymous
True
>>> response.is_anonymous_vpn
False
>>> response.is_hosting_provider
False
>>> response.is_public_proxy
False
>>> response.is_residential_proxy
False
>>> response.is_tor_exit_node
True
>>> response.ip_address
'203.0.113.0'
>>> response.network
IPv4Network('203.0.113.0/24')
ASN Database¶
>>> import geoip2.database
>>>
>>> # This creates a Reader object. You should use the same object
>>> # across multiple requests as creation of it is expensive.
>>> with geoip2.database.Reader('/path/to/GeoLite2-ASN.mmdb') as reader:
>>> response = reader.asn('203.0.113.0')
>>> response.autonomous_system_number
1221
>>> response.autonomous_system_organization
'Telstra Pty Ltd'
>>> response.ip_address
'203.0.113.0'
>>> response.network
IPv4Network('203.0.113.0/24')
Connection-Type Database¶
>>> import geoip2.database
>>>
>>> # This creates a Reader object. You should use the same object
>>> # across multiple requests as creation of it is expensive.
>>> with geoip2.database.Reader('/path/to/GeoIP2-Connection-Type.mmdb') as reader:
>>> response = reader.connection_type('203.0.113.0')
>>> response.connection_type
'Corporate'
>>> response.ip_address
'203.0.113.0'
>>> response.network
IPv4Network('203.0.113.0/24')
Domain Database¶
>>> import geoip2.database
>>>
>>> # This creates a Reader object. You should use the same object
>>> # across multiple requests as creation of it is expensive.
>>> with geoip2.database.Reader('/path/to/GeoIP2-Domain.mmdb') as reader:
>>> response = reader.domain('203.0.113.0')
>>> response.domain
'umn.edu'
>>> response.ip_address
'203.0.113.0'
Enterprise Database¶
>>> import geoip2.database
>>>
>>> # This creates a Reader object. You should use the same object
>>> # across multiple requests as creation of it is expensive.
>>> with geoip2.database.Reader('/path/to/GeoIP2-Enterprise.mmdb') as reader:
>>>
>>> # Use the .enterprise method to do a lookup in the Enterprise database
>>> response = reader.enterprise('203.0.113.0')
>>>
>>> response.country.confidence
99
>>> response.country.iso_code
'US'
>>> response.country.name
'United States'
>>> response.country.names['zh-CN']
u'美国'
>>>
>>> response.subdivisions.most_specific.name
'Minnesota'
>>> response.subdivisions.most_specific.iso_code
'MN'
>>> response.subdivisions.most_specific.confidence
77
>>>
>>> response.city.name
'Minneapolis'
>>> response.country.confidence
11
>>>
>>> response.postal.code
'55455'
>>>
>>> response.location.accuracy_radius
50
>>> response.location.latitude
44.9733
>>> response.location.longitude
-93.2323
>>>
>>> response.traits.network
IPv4Network('203.0.113.0/24')
ISP Database¶
>>> import geoip2.database
>>>
>>> # This creates a Reader object. You should use the same object
>>> # across multiple requests as creation of it is expensive.
>>> with geoip2.database.Reader('/path/to/GeoIP2-ISP.mmdb') as reader:
>>> response = reader.isp('203.0.113.0')
>>> response.autonomous_system_number
1221
>>> response.autonomous_system_organization
'Telstra Pty Ltd'
>>> response.isp
'Telstra Internet'
>>> response.organization
'Telstra Internet'
>>> response.ip_address
'203.0.113.0'
>>> response.network
IPv4Network('203.0.113.0/24')
Database Reader Exceptions¶
If the database file does not exist or is not readable, the constructor will
raise a FileNotFoundError
or a PermissionError
. If the IP address passed
to a method is invalid, a ValueError
will be raised. If the file is invalid
or there is a bug in the reader, a maxminddb.InvalidDatabaseError
will be
raised with a description of the problem. If an IP address is not in the
database, a AddressNotFoundError
will be raised.
AddressNotFoundError
references the largest subnet where no address would be
found. This can be used to efficiently enumerate entire subnets:
import geoip2.database
import geoip2.errors
import ipaddress
# This creates a Reader object. You should use the same object
# across multiple requests as creation of it is expensive.
with geoip2.database.Reader('/path/to/GeoLite2-ASN.mmdb') as reader:
network = ipaddress.ip_network("192.128.0.0/15")
ip_address = network[0]
while ip_address in network:
try:
response = reader.asn(ip_address)
response_network = response.network
except geoip2.errors.AddressNotFoundError as e:
response = None
response_network = e.network
print(f"{response_network}: {response!r}")
ip_address = response_network[-1] + 1 # move to next subnet
Values to use for Database or Dictionary Keys¶
We strongly discourage you from using a value from any ``names`` property as a key in a database or dictionaries.
These names may change between releases. Instead we recommend using one of the following:
geoip2.records.City
-city.geoname_id
geoip2.records.Continent
-continent.code
orcontinent.geoname_id
geoip2.records.Country
andgeoip2.records.RepresentedCountry
-country.iso_code
orcountry.geoname_id
geoip2.records.subdivision
-subdivision.iso_code
orsubdivision.geoname_id
What data is returned?¶
While many of the models contain the same basic records, the attributes which can be populated vary between web service endpoints or databases. In addition, while a model may offer a particular piece of data, MaxMind does not always have every piece of data for any given IP address.
Because of these factors, it is possible for any request to return a record where some or all of the attributes are unpopulated.
The only piece of data which is always returned is the ip_address
attribute in the geoip2.records.Traits
record.
Integration with GeoNames¶
GeoNames offers web services and downloadable
databases with data on geographical features around the world, including
populated places. They offer both free and paid premium data. Each feature is
uniquely identified by a geoname_id
, which is an integer.
Many of the records returned by the GeoIP web services and databases include a
geoname_id
field. This is the ID of a geographical feature (city, region,
country, etc.) in the GeoNames database.
Some of the data that MaxMind provides is also sourced from GeoNames. We source things like place names, ISO codes, and other similar data from the GeoNames premium data set.
Reporting Data Problems¶
If the problem you find is that an IP address is incorrectly mapped, please submit your correction to MaxMind.
If you find some other sort of mistake, like an incorrect spelling, please check the GeoNames site first. Once you’ve searched for a place and found it on the GeoNames map view, there are a number of links you can use to correct data (“move”, “edit”, “alternate names”, etc.). Once the correction is part of the GeoNames data set, it will be automatically incorporated into future MaxMind releases.
If you are a paying MaxMind customer and you’re not sure where to submit a correction, please contact MaxMind support for help.
Requirements¶
Python 3.8 or greater is required. Older versions are not supported.
The Requests HTTP library is also required. See <https://pypi.org/project/requests/> for details.
Versioning¶
The GeoIP2 Python API uses Semantic Versioning.
Support¶
Please report all issues with this code using the GitHub issue tracker
If you are having an issue with a MaxMind service that is not specific to the client API, please contact MaxMind support for assistance.
Modules¶
GeoIP2 Database Reader¶
- class geoip2.database.Reader(fileish: AnyStr | int | PathLike | IO, locales: List[str] | None = None, mode: int = 0)¶
GeoIP2 database Reader object.
Instances of this class provide a reader for the GeoIP2 database format. IP addresses can be looked up using the
country
andcity
methods.The basic API for this class is the same for every database. First, you create a reader object, specifying a file name or file descriptor. You then call the method corresponding to the specific database, passing it the IP address you want to look up.
If the request succeeds, the method call will return a model class for the method you called. This model in turn contains multiple record classes, each of which represents part of the data returned by the database. If the database does not contain the requested information, the attributes on the record class will have a
None
value.If the address is not in the database, an
geoip2.errors.AddressNotFoundError
exception will be thrown. If the database is corrupt or invalid, amaxminddb.InvalidDatabaseError
will be thrown.- anonymous_ip(ip_address: str | IPv6Address | IPv4Address) AnonymousIP ¶
Get the AnonymousIP object for the IP address.
- Parameters:
ip_address – IPv4 or IPv6 address as a string.
- Returns:
geoip2.models.AnonymousIP
object
- asn(ip_address: str | IPv6Address | IPv4Address) ASN ¶
Get the ASN object for the IP address.
- Parameters:
ip_address – IPv4 or IPv6 address as a string.
- Returns:
geoip2.models.ASN
object
- city(ip_address: str | IPv6Address | IPv4Address) City ¶
Get the City object for the IP address.
- Parameters:
ip_address – IPv4 or IPv6 address as a string.
- Returns:
geoip2.models.City
object
- connection_type(ip_address: str | IPv6Address | IPv4Address) ConnectionType ¶
Get the ConnectionType object for the IP address.
- Parameters:
ip_address – IPv4 or IPv6 address as a string.
- Returns:
geoip2.models.ConnectionType
object
- country(ip_address: str | IPv6Address | IPv4Address) Country ¶
Get the Country object for the IP address.
- Parameters:
ip_address – IPv4 or IPv6 address as a string.
- Returns:
geoip2.models.Country
object
- domain(ip_address: str | IPv6Address | IPv4Address) Domain ¶
Get the Domain object for the IP address.
- Parameters:
ip_address – IPv4 or IPv6 address as a string.
- Returns:
geoip2.models.Domain
object
- enterprise(ip_address: str | IPv6Address | IPv4Address) Enterprise ¶
Get the Enterprise object for the IP address.
- Parameters:
ip_address – IPv4 or IPv6 address as a string.
- Returns:
geoip2.models.Enterprise
object
- isp(ip_address: str | IPv6Address | IPv4Address) ISP ¶
Get the ISP object for the IP address.
- Parameters:
ip_address – IPv4 or IPv6 address as a string.
- Returns:
geoip2.models.ISP
object
- metadata() Metadata ¶
The metadata for the open database.
- Returns:
maxminddb.reader.Metadata
object
WebServices Client API¶
This class provides a client API for all the GeoIP2 web services. The web services are Country, City Plus, and Insights. Each service returns a different set of data about an IP address, with Country returning the least data and Insights the most.
Each service is represented by a different model class, and these model classes in turn contain multiple record classes. The record classes have attributes which contain data about the IP address.
If the service does not return a particular piece of data for an IP address, the associated attribute is not populated.
The service may not return any information for an entire record, in which case all of the attributes for that record class will be empty.
SSL¶
Requests to the web service are always made with SSL.
- class geoip2.webservice.AsyncClient(account_id: int, license_key: str, host: str = 'geoip.maxmind.com', locales: List[str] | None = None, timeout: float = 60, proxy: str | None = None)¶
An async GeoIP2 client.
It accepts the following required arguments:
- Parameters:
account_id – Your MaxMind account ID.
license_key – Your MaxMind license key.
Go to https://www.maxmind.com/en/my_license_key to see your MaxMind account ID and license key.
The following keyword arguments are also accepted:
- Parameters:
host – The hostname to make a request against. This defaults to “geoip.maxmind.com”. To use the GeoLite2 web service instead of the GeoIP2 web service, set this to “geolite.info”. To use the Sandbox GeoIP2 web service instead of the production GeoIP2 web service, set this to “sandbox.maxmind.com”. The sandbox allows you to experiment with the API without affecting your production data.
locales –
This is list of locale codes. This argument will be passed on to record classes to use when their name properties are called. The default value is [‘en’].
The order of the locales is significant. When a record class has multiple names (country, city, etc.), its name property will return the name in the first locale that has one.
Note that the only locale which is always present in the GeoIP2 data is “en”. If you do not include this locale, the name property may end up returning None even when the record has an English name.
Currently, the valid locale codes are:
de – German
en – English names may still include accented characters if that is the accepted spelling in English. In other words, English does not mean ASCII.
es – Spanish
fr – French
ja – Japanese
pt-BR – Brazilian Portuguese
ru – Russian
zh-CN – Simplified Chinese.
timeout – The timeout in seconds to use when waiting on the request. This sets both the connect timeout and the read timeout. The default is 60.
proxy – The URL of an HTTP proxy to use. It may optionally include a basic auth username and password, e.g.,
http://username:password@host:port
.
- async city(ip_address: str | IPv6Address | IPv4Address = 'me') City ¶
Call City Plus endpoint with the specified IP.
- Parameters:
ip_address – IPv4 or IPv6 address as a string. If no address is provided, the address that the web service is called from will be used.
- Returns:
geoip2.models.City
object
- async close()¶
Close underlying session
This will close the session and any associated connections.
- async country(ip_address: str | IPv6Address | IPv4Address = 'me') Country ¶
Call the GeoIP2 Country endpoint with the specified IP.
- Parameters:
ip_address – IPv4 or IPv6 address as a string. If no address is provided, the address that the web service is called from will be used.
- Returns:
geoip2.models.Country
object
- async insights(ip_address: str | IPv6Address | IPv4Address = 'me') Insights ¶
Call the Insights endpoint with the specified IP.
Insights is only supported by the GeoIP2 web service. The GeoLite2 web service does not support it.
- Parameters:
ip_address – IPv4 or IPv6 address as a string. If no address is provided, the address that the web service is called from will be used.
- Returns:
geoip2.models.Insights
object
- class geoip2.webservice.Client(account_id: int, license_key: str, host: str = 'geoip.maxmind.com', locales: List[str] | None = None, timeout: float = 60, proxy: str | None = None)¶
A synchronous GeoIP2 client.
It accepts the following required arguments:
- Parameters:
account_id – Your MaxMind account ID.
license_key – Your MaxMind license key.
Go to https://www.maxmind.com/en/my_license_key to see your MaxMind account ID and license key.
The following keyword arguments are also accepted:
- Parameters:
host – The hostname to make a request against. This defaults to “geoip.maxmind.com”. To use the GeoLite2 web service instead of the GeoIP2 web service, set this to “geolite.info”. To use the Sandbox GeoIP2 web service instead of the production GeoIP2 web service, set this to “sandbox.maxmind.com”. The sandbox allows you to experiment with the API without affecting your production data.
locales –
This is list of locale codes. This argument will be passed on to record classes to use when their name properties are called. The default value is [‘en’].
The order of the locales is significant. When a record class has multiple names (country, city, etc.), its name property will return the name in the first locale that has one.
Note that the only locale which is always present in the GeoIP2 data is “en”. If you do not include this locale, the name property may end up returning None even when the record has an English name.
Currently, the valid locale codes are:
de – German
en – English names may still include accented characters if that is the accepted spelling in English. In other words, English does not mean ASCII.
es – Spanish
fr – French
ja – Japanese
pt-BR – Brazilian Portuguese
ru – Russian
zh-CN – Simplified Chinese.
timeout – The timeout in seconds to use when waiting on the request. This sets both the connect timeout and the read timeout. The default is 60.
proxy – The URL of an HTTP proxy to use. It may optionally include a basic auth username and password, e.g.,
http://username:password@host:port
.
- city(ip_address: str | IPv6Address | IPv4Address = 'me') City ¶
Call City Plus endpoint with the specified IP.
- Parameters:
ip_address – IPv4 or IPv6 address as a string. If no address is provided, the address that the web service is called from will be used.
- Returns:
geoip2.models.City
object
- close()¶
Close underlying session
This will close the session and any associated connections.
- country(ip_address: str | IPv6Address | IPv4Address = 'me') Country ¶
Call the GeoIP2 Country endpoint with the specified IP.
- Parameters:
ip_address – IPv4 or IPv6 address as a string. If no address is provided, the address that the web service is called from will be used.
- Returns:
geoip2.models.Country
object
- insights(ip_address: str | IPv6Address | IPv4Address = 'me') Insights ¶
Call the Insights endpoint with the specified IP.
Insights is only supported by the GeoIP2 web service. The GeoLite2 web service does not support it.
- Parameters:
ip_address – IPv4 or IPv6 address as a string. If no address is provided, the address that the web service is called from will be used.
- Returns:
geoip2.models.Insights
object
Models¶
These classes provide models for the data returned by the GeoIP2 web service and databases.
The only difference between the City and Insights model classes is which fields in each record may be populated. See https://dev.maxmind.com/geoip/docs/web-services?lang=en for more details.
- class geoip2.models.ASN(raw: Dict[str, str | int])¶
Model class for the GeoLite2 ASN.
This class provides the following attribute:
- autonomous_system_organization¶
The organization associated with the registered autonomous system number for the IP address.
- Type:
- network¶
The network associated with the record. In particular, this is the largest network where all of the fields besides ip_address have the same value.
- class geoip2.models.AnonymousIP(raw: Dict[str, bool])¶
Model class for the GeoIP2 Anonymous IP.
This class provides the following attribute:
- is_anonymous_vpn¶
This is true if the IP address is registered to an anonymous VPN provider.
If a VPN provider does not register subnets under names associated with them, we will likely only flag their IP ranges using the
is_hosting_provider
attribute.- Type:
- is_hosting_provider¶
This is true if the IP address belongs to a hosting or VPN provider (see description of
is_anonymous_vpn
attribute).- Type:
- is_residential_proxy¶
This is true if the IP address is on a suspected anonymizing network and belongs to a residential ISP.
- Type:
- network¶
The network associated with the record. In particular, this is the largest network where all of the fields besides ip_address have the same value.
- class geoip2.models.City(raw_response: Dict[str, Any], locales: List[str] | None = None)¶
Model for the City Plus web service and the City database.
- city¶
City object for the requested IP address.
- Type:
- continent¶
Continent object for the requested IP address.
- Type:
- country¶
Country object for the requested IP address. This record represents the country where MaxMind believes the IP is located.
- Type:
- location¶
Location object for the requested IP address.
- Type:
- maxmind¶
Information related to your MaxMind account.
- Type:
- postal¶
Postal object for the requested IP address.
- Type:
- registered_country¶
The registered country object for the requested IP address. This record represents the country where the ISP has registered a given IP block in and may differ from the user’s country.
- Type:
- represented_country¶
Object for the country represented by the users of the IP address when that country is different than the country in
country
. For instance, the country represented by an overseas military base.
- subdivisions¶
Object (tuple) representing the subdivisions of the country to which the location of the requested IP address belongs.
- traits¶
Object with the traits of the requested IP address.
- Type:
- class geoip2.models.ConnectionType(raw: Dict[str, str | int])¶
Model class for the GeoIP2 Connection-Type.
This class provides the following attribute:
- connection_type¶
The connection type may take the following values:
Dialup
Cable/DSL
Corporate
Cellular
Satellite
Additional values may be added in the future.
- Type:
- network¶
The network associated with the record. In particular, this is the largest network where all of the fields besides ip_address have the same value.
- class geoip2.models.Country(raw_response: Dict[str, Any], locales: List[str] | None = None)¶
Model for the Country web service and Country database.
This class provides the following attributes:
- continent¶
Continent object for the requested IP address.
- Type:
- country¶
Country object for the requested IP address. This record represents the country where MaxMind believes the IP is located.
- Type:
- maxmind¶
Information related to your MaxMind account.
- Type:
- registered_country¶
The registered country object for the requested IP address. This record represents the country where the ISP has registered a given IP block in and may differ from the user’s country.
- Type:
- represented_country¶
Object for the country represented by the users of the IP address when that country is different than the country in
country
. For instance, the country represented by an overseas military base.
- traits¶
Object with the traits of the requested IP address.
- Type:
- class geoip2.models.Domain(raw: Dict[str, str | int])¶
Model class for the GeoIP2 Domain.
This class provides the following attribute:
- network¶
The network associated with the record. In particular, this is the largest network where all of the fields besides ip_address have the same value.
- class geoip2.models.Enterprise(raw_response: Dict[str, Any], locales: List[str] | None = None)¶
Model for the GeoIP2 Enterprise database.
- city¶
City object for the requested IP address.
- Type:
- continent¶
Continent object for the requested IP address.
- Type:
- country¶
Country object for the requested IP address. This record represents the country where MaxMind believes the IP is located.
- Type:
- location¶
Location object for the requested IP address.
- maxmind¶
Information related to your MaxMind account.
- Type:
- registered_country¶
The registered country object for the requested IP address. This record represents the country where the ISP has registered a given IP block in and may differ from the user’s country.
- Type:
- represented_country¶
Object for the country represented by the users of the IP address when that country is different than the country in
country
. For instance, the country represented by an overseas military base.
- subdivisions¶
Object (tuple) representing the subdivisions of the country to which the location of the requested IP address belongs.
- traits¶
Object with the traits of the requested IP address.
- Type:
- class geoip2.models.ISP(raw: Dict[str, str | int])¶
Model class for the GeoIP2 ISP.
This class provides the following attribute:
- autonomous_system_organization¶
The organization associated with the registered autonomous system number for the IP address.
- Type:
- network¶
The network associated with the record. In particular, this is the largest network where all of the fields besides ip_address have the same value.
- class geoip2.models.Insights(raw_response: Dict[str, Any], locales: List[str] | None = None)¶
Model for the GeoIP2 Insights web service.
- city¶
City object for the requested IP address.
- Type:
- continent¶
Continent object for the requested IP address.
- Type:
- country¶
Country object for the requested IP address. This record represents the country where MaxMind believes the IP is located.
- Type:
- location¶
Location object for the requested IP address.
- maxmind¶
Information related to your MaxMind account.
- Type:
- registered_country¶
The registered country object for the requested IP address. This record represents the country where the ISP has registered a given IP block in and may differ from the user’s country.
- Type:
- represented_country¶
Object for the country represented by the users of the IP address when that country is different than the country in
country
. For instance, the country represented by an overseas military base.
- subdivisions¶
Object (tuple) representing the subdivisions of the country to which the location of the requested IP address belongs.
- traits¶
Object with the traits of the requested IP address.
- Type:
- class geoip2.models.SimpleModel(raw: Dict[str, bool | str | int])¶
Provides basic methods for non-location models
- property network: IPv4Network | IPv6Network | None¶
The network for the record
Records¶
- class geoip2.records.City(locales: List[str] | None = None, confidence: int | None = None, geoname_id: int | None = None, names: Dict[str, str] | None = None, **_)¶
Contains data for the city record associated with an IP address.
This class contains the city-level data associated with an IP address.
This record is returned by
city
,enterprise
, andinsights
.Attributes:
- confidence¶
A value from 0-100 indicating MaxMind’s confidence that the city is correct. This attribute is only available from the Insights end point and the Enterprise database.
- Type:
- class geoip2.records.Continent(locales: List[str] | None = None, code: str | None = None, geoname_id: int | None = None, names: Dict[str, str] | None = None, **_)¶
Contains data for the continent record associated with an IP address.
This class contains the continent-level data associated with an IP address.
Attributes:
- name¶
Returns the name of the continent based on the locales list passed to the constructor.
- Type:
- class geoip2.records.Country(locales: List[str] | None = None, confidence: int | None = None, geoname_id: int | None = None, is_in_european_union: bool = False, iso_code: str | None = None, names: Dict[str, str] | None = None, **_)¶
Contains data for the country record associated with an IP address.
This class contains the country-level data associated with an IP address.
Attributes:
- confidence¶
A value from 0-100 indicating MaxMind’s confidence that the country is correct. This attribute is only available from the Insights end point and the Enterprise database.
- Type:
- is_in_european_union¶
This is true if the country is a member state of the European Union.
- Type:
- iso_code¶
The two-character ISO 3166-1 alpha code for the country.
- Type:
- class geoip2.records.Location(average_income: int | None = None, accuracy_radius: int | None = None, latitude: float | None = None, longitude: float | None = None, metro_code: int | None = None, population_density: int | None = None, time_zone: str | None = None, **_)¶
Contains data for the location record associated with an IP address.
This class contains the location data associated with an IP address.
This record is returned by
city
,enterprise
, andinsights
.Attributes:
- average_income¶
The average income in US dollars associated with the requested IP address. This attribute is only available from the Insights end point.
- Type:
- accuracy_radius¶
The approximate accuracy radius in kilometers around the latitude and longitude for the IP address. This is the radius where we have a 67% confidence that the device using the IP address resides within the circle centered at the latitude and longitude with the provided radius.
- Type:
- latitude¶
The approximate latitude of the location associated with the IP address. This value is not precise and should not be used to identify a particular address or household.
- Type:
- longitude¶
The approximate longitude of the location associated with the IP address. This value is not precise and should not be used to identify a particular address or household.
- Type:
- metro_code¶
The metro code of the location if the location is in the US. MaxMind returns the same metro codes as the Google AdWords API.
- Type:
- population_density¶
The estimated population per square kilometer associated with the IP address. This attribute is only available from the Insights end point.
- Type:
- time_zone¶
The time zone associated with location, as specified by the IANA Time Zone Database, e.g., “America/New_York”.
- Type:
- class geoip2.records.MaxMind(queries_remaining: int | None = None, **_)¶
Contains data related to your MaxMind account.
Attributes:
- class geoip2.records.PlaceRecord(locales: List[str] | None = None, names: Dict[str, str] | None = None)¶
All records with
names
subclassPlaceRecord
.
- class geoip2.records.Postal(code: str | None = None, confidence: int | None = None, **_)¶
Contains data for the postal record associated with an IP address.
This class contains the postal data associated with an IP address.
This attribute is returned by
city
,enterprise
, andinsights
.Attributes:
- code¶
The postal code of the location. Postal codes are not available for all countries. In some countries, this will only contain part of the postal code.
- Type:
- class geoip2.records.Record¶
All records are subclasses of the abstract class
Record
.
- class geoip2.records.RepresentedCountry(locales: List[str] | None = None, confidence: int | None = None, geoname_id: int | None = None, is_in_european_union: bool = False, iso_code: str | None = None, names: Dict[str, str] | None = None, type: str | None = None, **_)¶
Contains data for the represented country associated with an IP address.
This class contains the country-level data associated with an IP address for the IP’s represented country. The represented country is the country represented by something like a military base.
Attributes:
- confidence¶
A value from 0-100 indicating MaxMind’s confidence that the country is correct. This attribute is only available from the Insights end point and the Enterprise database.
- Type:
- is_in_european_union¶
This is true if the country is a member state of the European Union.
- Type:
- iso_code¶
The two-character ISO 3166-1 alpha code for the country.
- Type:
- class geoip2.records.Subdivision(locales: List[str] | None = None, confidence: int | None = None, geoname_id: int | None = None, iso_code: str | None = None, names: Dict[str, str] | None = None, **_)¶
Contains data for the subdivisions associated with an IP address.
This class contains the subdivision data associated with an IP address.
This attribute is returned by
city
,enterprise
, andinsights
.Attributes:
- confidence¶
This is a value from 0-100 indicating MaxMind’s confidence that the subdivision is correct. This attribute is only available from the Insights end point and the Enterprise database.
- Type:
- iso_code¶
This is a string up to three characters long contain the subdivision portion of the ISO 3166-2 code.
- Type:
- class geoip2.records.Subdivisions(locales: List[str] | None, *subdivisions)¶
A tuple-like collection of subdivisions associated with an IP address.
This class contains the subdivisions of the country associated with the IP address from largest to smallest.
For instance, the response for Oxford in the United Kingdom would have England as the first element and Oxfordshire as the second element.
This attribute is returned by
city
,enterprise
, andinsights
.- property most_specific: Subdivision¶
The most specific (smallest) subdivision available.
If there are no
Subdivision
objects for the response, this returns an emptySubdivision
.- Type:
- class geoip2.records.Traits(autonomous_system_number: int | None = None, autonomous_system_organization: str | None = None, connection_type: str | None = None, domain: str | None = None, is_anonymous: bool = False, is_anonymous_proxy: bool = False, is_anonymous_vpn: bool = False, is_hosting_provider: bool = False, is_legitimate_proxy: bool = False, is_public_proxy: bool = False, is_residential_proxy: bool = False, is_satellite_provider: bool = False, is_tor_exit_node: bool = False, isp: str | None = None, ip_address: str | None = None, network: str | None = None, organization: str | None = None, prefix_len: int | None = None, static_ip_score: float | None = None, user_count: int | None = None, user_type: str | None = None, mobile_country_code: str | None = None, mobile_network_code: str | None = None, is_anycast: bool = False, **_)¶
Contains data for the traits record associated with an IP address.
This class contains the traits data associated with an IP address.
This class has the following attributes:
- autonomous_system_number¶
The autonomous system number associated with the IP address. This attribute is only available from the City Plus and Insights web services and the Enterprise database.
- Type:
- autonomous_system_organization¶
The organization associated with the registered autonomous system number for the IP address. This attribute is only available from the City Plus and Insights web service end points and the Enterprise database.
- Type:
- connection_type¶
The connection type may take the following values:
Dialup
Cable/DSL
Corporate
Cellular
Satellite
Additional values may be added in the future.
This attribute is only available from the City Plus and Insights web service end points and the Enterprise database.
- Type:
- domain¶
The second level domain associated with the IP address. This will be something like “example.com” or “example.co.uk”, not “foo.example.com”. This attribute is only available from the City Plus and Insights web service end points and the Enterprise database.
- Type:
- ip_address¶
The IP address that the data in the model is for. If you performed a “me” lookup against the web service, this will be the externally routable IP address for the system the code is running on. If the system is behind a NAT, this may differ from the IP address locally assigned to it.
- Type:
- is_anonymous¶
This is true if the IP address belongs to any sort of anonymous network. This attribute is only available from Insights.
- Type:
- is_anonymous_proxy¶
This is true if the IP is an anonymous proxy.
- Type:
Deprecated since version 2.2.0: Use our our GeoIP2 Anonymous IP database instead.
- is_anonymous_vpn¶
This is true if the IP address is registered to an anonymous VPN provider.
If a VPN provider does not register subnets under names associated with them, we will likely only flag their IP ranges using the
is_hosting_provider
attribute.This attribute is only available from Insights.
- Type:
- is_anycast¶
This returns true if the IP address belongs to an anycast network. This is available for the GeoIP2 Country, City Plus, and Insights web services and the GeoIP2 Country, City, and Enterprise databases.
- Type:
- is_hosting_provider¶
This is true if the IP address belongs to a hosting or VPN provider (see description of
is_anonymous_vpn
attribute). This attribute is only available from Insights.- Type:
- is_legitimate_proxy¶
This attribute is true if MaxMind believes this IP address to be a legitimate proxy, such as an internal VPN used by a corporation. This attribute is only available in the Enterprise database.
- Type:
- is_public_proxy¶
This is true if the IP address belongs to a public proxy. This attribute is only available from Insights.
- Type:
- is_residential_proxy¶
This is true if the IP address is on a suspected anonymizing network and belongs to a residential ISP. This attribute is only available from Insights.
- Type:
- is_satellite_provider¶
This is true if the IP address is from a satellite provider that provides service to multiple countries.
- Type:
Deprecated since version 2.2.0: Due to the increased coverage by mobile carriers, very few satellite providers now serve multiple countries. As a result, the output does not provide sufficiently relevant data for us to maintain it.
- is_tor_exit_node¶
This is true if the IP address is a Tor exit node. This attribute is only available from Insights.
- Type:
- isp¶
The name of the ISP associated with the IP address. This attribute is only available from the City Plus and Insights web services and the Enterprise database.
- Type:
- network¶
The network associated with the record. In particular, this is the largest network where all of the fields besides ip_address have the same value.
- organization¶
The name of the organization associated with the IP address. This attribute is only available from the City Plus and Insights web services and the Enterprise database.
- Type:
- static_ip_score¶
An indicator of how static or dynamic an IP address is. The value ranges from 0 to 99.99 with higher values meaning a greater static association. For example, many IP addresses with a user_type of cellular have a lifetime under one. Static Cable/DSL IPs typically have a lifetime above thirty.
This indicator can be useful for deciding whether an IP address represents the same user over time. This attribute is only available from Insights.
- Type:
- user_count¶
The estimated number of users sharing the IP/network during the past 24 hours. For IPv4, the count is for the individual IP. For IPv6, the count is for the /64 network. This attribute is only available from Insights.
- Type:
- user_type¶
The user type associated with the IP address. This can be one of the following values:
business
cafe
cellular
college
consumer_privacy_network
content_delivery_network
dialup
government
hosting
library
military
residential
router
school
search_engine_spider
traveler
This attribute is only available from the Insights end point and the Enterprise database.
- Type:
- property network: IPv4Network | IPv6Network | None¶
The network for the record
Errors¶
- exception geoip2.errors.AddressNotFoundError(message: str, ip_address: str | None = None, prefix_len: int | None = None)¶
The address you were looking up was not found.
- ip_address¶
The IP address used in the lookup. This is only available for database lookups.
- Type:
- network¶
The network associated with the error. In particular, this is the largest network where no address would be found. This is only available for database lookups.
- property network: IPv4Network | IPv6Network | None¶
The network for the error
- exception geoip2.errors.AuthenticationError¶
There was a problem authenticating the request.
- exception geoip2.errors.GeoIP2Error¶
There was a generic error in GeoIP2.
This class represents a generic error. It extends
RuntimeError
and does not add any additional attributes.
- exception geoip2.errors.HTTPError(message: str, http_status: int | None = None, uri: str | None = None, decoded_content: str | None = None)¶
There was an error when making your HTTP request.
This class represents an HTTP transport error. It extends
GeoIP2Error
and adds attributes of its own.- Variables:
http_status – The HTTP status code returned
uri – The URI queried
decoded_content – The decoded response content
- exception geoip2.errors.InvalidRequestError¶
The request was invalid.
- exception geoip2.errors.OutOfQueriesError¶
Your account is out of funds for the service queried.
- exception geoip2.errors.PermissionRequiredError¶
Your account does not have permission to access this service.
Indices and tables¶
- copyright:
2013-2024 by MaxMind, Inc.
- license:
Apache License, Version 2.0