Table Of Contents

This Page

MaxMind GeoIP2 Python API

Beta Note

This is a beta release. The API may change before the first production release, which will be numbered 2.0.0.

You may find information on the GeoIP2 beta release process on our website.

Description

This package provides an API for the GeoIP2 web services and the GeoLite2 databases. The commercial GeoIP2 databases have not yet been released as a downloadable product.

Installation

To install the geoip2 module, type:

$ pip install geoip2[DB]

If you do not need the database reader, you may omit [DB].

If you are not able to use pip, you may also use easy_install from the source directory:

$ easy_install .

Usage

To use this API, you first create either a web service object with your MaxMind user_id and license_key or a database reader object with the path to your database file. After doing this, you may call the method corresponding to request type (e.g., city or country), passing it the IP address you wantto look up.

If the request succeeds, the method call will return a model class for the end point 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.

Web Service Example

>>> import geoip2.webservice
>>>
>>> # This creates a Client object that can be reused across requests.
>>> # Replace "42" with your user ID and "license_key" with your license
>>> # key.
>>> client = geoip2.webservice.Client(42, 'license_key')
>>>
>>> # Replace "omni" with the method corresponding to the web service
>>> # that you are using, e.g., "country", "city_isp_org", "city".
>>> response = client.omni('128.101.101.101')
>>>
>>> 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

Database Example

>>> import geoip2.database
>>>
>>> # This creates a Reader object. You should use the same object
>>> # across multiple requests as creation of it is expensive.
>>> reader = geoip2.database.Reader('/path/to/GeoLite2-City.mmdb')
>>>
>>> # Replace "city" with the method corresponding to the database
>>> # that you are using, e.g., "country".
>>> response = reader.city('128.101.101.101')
>>>
>>> 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

Web Service Client Exceptions

For details on the possible errors returned by the web service itself, see http://dev.maxmind.com/geoip/geoip2/web-services 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 Reader Exceptions

If the database file does not exist or is not readable, a ValueError will be thrown. If the file is invalid or there is a bug in the reader, a maxminddb.InvalidDatabaseError will be thrown with a description of the problem. If an IP address is not in the database, a AddressNotFoundError exception will be thrown.

What data is returned?

While many of the models contain the same basic records, the attributes which can be populated vary between web service end points 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

This code requires Python 2.6+ or 3.3+. Older versions are not supported.

The Requests HTTP library is also required. See <http://python-requests.org> 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(filename, languages=None)

Creates a new 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 and city methods. We also provide city_isp_org and omni methods to ease compatibility with the web service client, although we may offer the ability to specify additional databases to replicate these web services in the future (e.g., the ISP/Org database).

The basic API for this class is the same for every database. First, you create a reader object, specifying a file name. 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, a maxminddb.InvalidDatabaseError will be thrown.

city(ip_address)

Get the City record object for the IP address

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
city_isp_org(ip_address)

Get the CityISPOrg record object for the IP address

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.CityISPOrg object
close()

Closes the GeoIP2 database

country(ip_address)

Get the Country record object for the IP address

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
omni(ip_address)

Get the Omni record object for the IP address

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.Omni object

WebServices Client API

This class provides a client API for all the GeoIP2 web service’s end points. The end points are Country, City, City/ISP/Org, and Omni. Each end point returns a different set of data about an IP address, with Country returning the least data and Omni the most.

Each web service end point 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 web service does not return a particular piece of data for an IP address, the associated attribute is not populated.

The web 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 GeoIP2 web service are always made with SSL.

class geoip2.webservice.Client(user_id, license_key, host='geoip.maxmind.com', languages=None)

Creates a new client object.

It accepts the following required arguments:

Parameters:
  • user_id – Your MaxMind User ID.
  • license_key – Your MaxMind license key.

Go to https://www.maxmind.com/en/my_license_key to see your MaxMind User 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”. In most cases, you should not need to set this explicitly.
  • languages

    This is list of language 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 languages is significant. When a record class has multiple names (country, city, etc.), its name property will return the name in the first language that has one.

    Note that the only language which is always present in the GeoIP2 data is “en”. If you do not include this language, the name property may end up returning None even when the record has an English name.

    Currently, the valid language 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.
city(ip_address='me')

This method calls the GeoIP2 Precision City endpoint.

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
city_isp_org(ip_address='me')

This method calls the GeoIP2 Precision City/ISP/Org endpoint.

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.CityISPOrg object
country(ip_address='me')

This method calls the GeoIP2 Country endpoint.

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
omni(ip_address='me')

This method calls the GeoIP2 Precision Omni endpoint.

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.Omni object

Models

These classes provide models for the data returned by the GeoIP2 end points.

The only difference between the City, City/ISP/Org, and Omni model classes is which fields in each record may be populated. See http://dev.maxmind.com/geoip/geoip2/web-services for more details.

class geoip2.models.City(raw_response, languages=None)

Model class for the GeoIP2 Precision City end point

city

City object for the requested IP address.

Type :geoip2.records.City
continent

Continent object for the requested IP address.

Type :geoip2.records.Continent
country

Country object for the requested IP address. This record represents the country where MaxMind believes the IP is located.

Type :geoip2.records.Country
location

Location object for the requested IP address.

maxmind

Information related to your MaxMind account.

Type :geoip2.records.MaxMind
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 :geoip2.records.Country
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 or embassy.

Type :geoip2.records.RepresentedCountry
subdivisions

Object (tuple) representing the subdivisions of the country to which the location of the requested IP address belongs.

Type :geoip2.records.Subdivisions
traits

Object with the traits of the requested IP address.

Type :geoip2.records.Traits
class geoip2.models.CityISPOrg(raw_response, languages=None)

Model class for the GeoIP2 Precision City/ISP/Org end point

city

City object for the requested IP address.

Type :geoip2.records.City
continent

Continent object for the requested IP address.

Type :geoip2.records.Continent
country

Country object for the requested IP address. This record represents the country where MaxMind believes the IP is located.

Type :geoip2.records.Country
location

Location object for the requested IP address.

maxmind

Information related to your MaxMind account.

Type :geoip2.records.MaxMind
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 :geoip2.records.Country
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 or embassy.

Type :geoip2.records.RepresentedCountry
subdivisions

Object (tuple) representing the subdivisions of the country to which the location of the requested IP address belongs.

Type :geoip2.records.Subdivisions
traits

Object with the traits of the requested IP address.

Type :geoip2.records.Traits
class geoip2.models.Country(raw_response, languages=None)

Model class for the GeoIP2 Country end point

This class provides the following methods, each of which returns a record object.

continent

Continent object for the requested IP address.

Type :geoip2.records.Continent
country

Country object for the requested IP address. This record represents the country where MaxMind believes the IP is located.

Type :geoip2.records.Country
maxmind

Information related to your MaxMind account.

Type :geoip2.records.MaxMind
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 :geoip2.records.Country
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 or embassy.

Type :geoip2.records.RepresentedCountry
traits

Object with the traits of the requested IP address.

Type :geoip2.records.Traits
class geoip2.models.Omni(raw_response, languages=None)

Model class for the GeoIP2 Precision Omni end point

city

City object for the requested IP address.

Type :geoip2.records.City
continent

Continent object for the requested IP address.

Type :geoip2.records.Continent
country

Country object for the requested IP address. This record represents the country where MaxMind believes the IP is located.

Type :geoip2.records.Country
location

Location object for the requested IP address.

maxmind

Information related to your MaxMind account.

Type :geoip2.records.MaxMind
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 :geoip2.records.Country
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 or embassy.

Type :geoip2.records.RepresentedCountry
subdivisions

Object (tuple) representing the subdivisions of the country to which the location of the requested IP address belongs.

Type :geoip2.records.Subdivisions
traits

Object with the traits of the requested IP address.

Type :geoip2.records.Traits

Records

class geoip2.records.City(languages=None, **kwargs)

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 all the end points except the Country end point.

Attributes:

confidence

A value from 0-100 indicating MaxMind’s confidence that the city is correct. This attribute is only available from the Omni end point.

Type :int
geoname_id

The GeoName ID for the city. This attribute is returned by all end points.

Type :int
name

The name of the city based on the languages list passed to the constructor. This attribute is returned by all end points.

Type :unicode
names

A dictionary where the keys are language codes and the values are names. This attribute is returned by all end points.

Type :dict
class geoip2.records.Continent(languages=None, **kwargs)

Contains data for the continent record associated with an IP address

This class contains the continent-level data associated with an IP address.

This record is returned by all the end points.

Attributes:

code

A two character continent code like “NA” (North America) or “OC” (Oceania). This attribute is returned by all end points.

Type :unicode
geoname_id

The GeoName ID for the continent. This attribute is returned by all end points.

Type :int
name

Returns the name of the continent based on the languages list passed to the constructor. This attribute is returned by all end points.

Type :unicode
names

A dictionary where the keys are language codes and the values are names. This attribute is returned by all end points.

Type :dict
class geoip2.records.Country(languages=None, **kwargs)

Contains data for the country record associated with an IP address

This class contains the country-level data associated with an IP address.

This record is returned by all the end points.

Attributes:

confidence

A value from 0-100 indicating MaxMind’s confidence that the country is correct. This attribute is only available from the Omni end point.

Type :int
geoname_id

The GeoName ID for the country. This attribute is returned by all end points.

Type :int
iso_code

The two-character ISO 3166-1 alpha code for the country. This attribute is returned by all end points.

Type :unicode
name

The name of the country based on the languages list passed to the constructor. This attribute is returned by all end points.

Type :unicode
names

A dictionary where the keys are language codes and the values are names. This attribute is returned by all end points.

Type :dict
class geoip2.records.Location(**kwargs)

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 all the end points except the Country end point.

Attributes:

accuracy_radius

The radius in kilometers around the specified location where the IP address is likely to be. This attribute is only available from the Omni end point.

Type :int
latitude

The latitude of the location as a floating point number. This attribute is returned by all end points except the Country end point.

Type :float
longitude

The longitude of the location as a floating point number. This attribute is returned by all end points except the Country end point.

Type :float
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. This attribute is returned by all end points except the Country end point.

Type :int
time_zone

The time zone associated with location, as specified by the IANA Time Zone Database, e.g., “America/New_York”. This attribute is returned by all end points except the Country end point.

Type :unicode
class geoip2.records.MaxMind(**kwargs)

Contains data related to your MaxMind account

This record is returned by all the end points.

Attributes:

queries_remaining

The number of remaining queries you have for the end point you are calling.

Type :int
class geoip2.records.PlaceRecord(languages=None, **kwargs)

All records with names subclass PlaceRecord

name

Dict with language codes as keys and localized name as value

class geoip2.records.Postal(**kwargs)

Contains data for the postal record associated with an IP address

This class contains the postal data associated with an IP address.

This record is returned by all the end points except the Country end point.

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. This attribute is returned by all end points except the Country end point.

Type :unicode
confidence

A value from 0-100 indicating MaxMind’s confidence that the postal code is correct. This attribute is only available from the Omni end point.

Type :int
class geoip2.records.Record(**kwargs)

All records are subclasses of the abstract class Record

class geoip2.records.RepresentedCountry(languages=None, **kwargs)

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 or embassy.

This record is returned by all the end points.

Attributes:

confidence

A value from 0-100 indicating MaxMind’s confidence that the country is correct. This attribute is only available from the Omni end point.

Type :int
geoname_id

The GeoName ID for the country. This attribute is returned by all end points.

Type :int
iso_code

The two-character ISO 3166-1 alpha code for the country. This attribute is returned by all end points.

Type :unicode
name

The name of the country based on the languages list passed to the constructor. This attribute is returned by all end points.

Type :unicode
names

A dictionary where the keys are language codes and the values are names. This attribute is returned by all end points.

Type :dict
type

A string indicating the type of entity that is representing the country. Currently we only return military but this could expand to include other types such as embassy in the future. Returned by all endpoints.

Type :unicode
class geoip2.records.Subdivision(languages=None, **kwargs)

Contains data for the subdivisions associated with an IP address

This class contains the subdivision data associated with an IP address.

This record is returned by all the end points except the Country end point.

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 Omni end point.

Type :int
geoname_id

This is a GeoName ID for the subdivision. This attribute is returned by all end points except Country.

Type :int
iso_code

This is a string up to three characters long contain the subdivision portion of the ISO 3166-2 code. This attribute is returned by all end points except Country.

Type :unicode
name

The name of the subdivision based on the languages list passed to the constructor. This attribute is returned by all end points.

Type :unicode
names

A dictionary where the keys are language codes and the values are names. This attribute is returned by all end points except Country.

Type :dict
class geoip2.records.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 collection is returned by all the end points except the Country end point.

most_specific

The most specific (smallest) subdivision available.

If there are no Subdivision objects for the response, this returns an empty Subdivision.

Type :Subdivision
class geoip2.records.Traits(**kwargs)

Contains data for the traits record associated with an IP address

This class contains the traits data associated with an IP address.

This record is returned by all the end points.

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/ISP/Org and Omni end points.

Type :int
autonomous_system_organization

The organization associated with the registered autonomous system number for the IP address. This attribute is only available from the City/ISP/Org and Omni end points.

Type :unicode
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/ISP/Org and Omni end points.

Type :unicode
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. This attribute is returned by all end points.

Type :unicode
is_anonymous_proxy

This is true if the IP is an anonymous proxy. See http://dev.maxmind.com/faq/geoip#anonproxy for further details. This attribute is returned by all end points.

Type :bool
is_satellite_provider

This is true if the IP address is from a satellite provider that provides service to multiple countries. This attribute is returned by all end points.

Type :bool
isp

The name of the ISP associated with the IP address. This attribute is only available from the City/ISP/Org and Omni end points.

Type :unicode
organization

The name of the organization associated with the IP address. This attribute is only available from the City/ISP/Org and Omni end points.

Type :unicode
user_type

The user type associated with the IP address. This can be one of the following values:

  • business
  • cafe
  • cellular
  • college
  • content_delivery_network
  • dialup
  • government
  • hosting
  • library
  • military
  • residential
  • router
  • school
  • search_engine_spider
  • traveler

This attribute is only available from the Omni end point.

Type :unicode

Errors

exception geoip2.errors.AddressNotFoundError

The address you were looking up was not found.

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, http_status=None, uri=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
exception geoip2.errors.InvalidRequestError

The request was invalid.

exception geoip2.errors.OutOfQueriesError

Your account is out of funds for the service queried.

Indices and tables

copyright:
  1. 2013 by MaxMind, Inc.
license:

GNU Lesser General Public License v2 or later (LGPLv2+)