• Stars
    star
    1,107
  • Rank 41,944 (Top 0.9 %)
  • Language
    Python
  • License
    Apache License 2.0
  • Created over 11 years ago
  • Updated about 1 month ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Python code for GeoIP2 webservice client and database reader

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.

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.
>>> 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.
>>>     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 or continent.geoname_id
  • geoip2.records.Country and geoip2.records.RepresentedCountry - country.iso_code or country.geoname_id
  • geoip2.records.subdivision - subdivision.iso_code or subdivision.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.7 or greater is required. 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.

More Repositories

1

GeoIP2-php

PHP API for GeoIP2 webservice client and database reader
PHP
2,325
star
2

libmaxminddb

C library for the MaxMind DB file format
C
913
star
3

GeoIP2-java

Java API for GeoIP2 webservice client and database reader
Java
781
star
4

geoipupdate

GeoIP update client code
Go
723
star
5

MaxMind-DB-Reader-php

PHP Reader for the MaxMind DB Database Format
PHP
639
star
6

geoip-api-php

DEPRECATED GeoIP Legacy PHP API
PHP
523
star
7

geoip-api-c

DEPRECATED GeoIP Legacy C API
C
371
star
8

GeoIP2-dotnet

MaxMind GeoIP2 .NET API
C#
348
star
9

web-service-common-php

Shared code for the MaxMind Web Service PHP client APIs
PHP
288
star
10

MaxMind-DB

Spec and test data for the MaxMind DB file format
Go
277
star
11

geoipupdate-legacy

GeoIP update client code
C
258
star
12

geoip-api-python

DEPRECATED GeoIP Legacy Python API
C
232
star
13

GeoIP2-node

Node.js API for GeoIP2 webservice client and database reader
TypeScript
223
star
14

geoip2-csv-converter

GeoIP2 CSV Format Converter
Go
202
star
15

MaxMind-DB-Reader-python

Python MaxMind DB reader extension
Python
178
star
16

geoip-api-java

DEPRECATED GeoIP Legacy Java API
Java
176
star
17

mmdbinspect

look up records for one or more IPs/networks in one or more .mmdb databases
Go
130
star
18

mod_maxminddb

MaxMind DB Apache Module
C
126
star
19

MaxMind-DB-Reader-java

Java reader for the MaxMind DB format
Java
114
star
20

mmdbwriter

Go library for writing MaxMind DB (mmdb) files
Go
114
star
21

MaxMind-DB-Reader-dotnet

.NET Reader for the MaxMind DB Database Format
C#
102
star
22

MaxMind-DB-Writer-perl

Create MaxMind DB database files
Perl
75
star
23

GeoIP2-ruby

Ruby API for GeoIP2 webservice client and database reader
Ruby
59
star
24

geoip-api-mod_geoip2

DEPRECATED GeoIP Legacy module for Apache 2
C
50
star
25

minfraud-api-php

PHP API for minFraud Score, Insights, and Factors
PHP
49
star
26

geoip-api-csharp2

DEPRECATED GeoIP Legacy C# API
C#
47
star
27

MaxMind-DB-Reader-ruby

Ruby reader for the MaxMind DB Database Format
Ruby
46
star
28

getting-started-with-mmdb

A quick guide to writing and reading from your own MMDB databases.
Perl
37
star
29

minfraud-api-python

Python API for minFraud Score, Insights, and Factors
Python
27
star
30

mmdb-from-go-blogpost

Enriching MMDB files with your own data using Go.
Go
23
star
31

ccfd-api-php

Deprecated minFraud Legacy PHP API
PHP
23
star
32

minfraud-api-dotnet

.NET API for MaxMind minFraud Score, Insights, and Factors
C#
20
star
33

minfraud-api-java

Java API for minFraud Score, Insights, and Factors
Java
19
star
34

GeoIP2-perl

Perl API for MaxMind's GeoIP2 web services and databases
Perl
18
star
35

mm-geofeed-verifier

Verify the format of a geofeed file, and make some comparisons to data in an MMDB file.
Go
16
star
36

minfraud-api-ruby

Ruby API for minFraud Score, Insights, and Factors
Ruby
14
star
37

minfraud-api-node

Node.js API for MaxMind minFraud Score, Insights, and Factors
TypeScript
14
star
38

mm-network-analyzer

A program to aid in diagnosing networking issues
Go
13
star
39

dev-hire-homework

A homework exercise for engineering applicants
Perl
13
star
40

MaxMind-DB-Reader-perl

Read MaxMind DB files and look up IP addresses
Perl
12
star
41

mmdbverify

Verifier for the MaxMind DB format
Go
10
star
42

geoip-api-perl

DEPRECATED GeoIP Legacy Perl API
Perl
10
star
43

Stepford

A vaguely Rake/Make/Cake-like thing for Perl - create steps and let a runner run them
Perl
9
star
44

ccfd-api-java

Deprecated minFraud Legacy Java API
Java
7
star
45

Locale-Country-Multilingual

mapping ISO codes to localized country names
Perl
6
star
46

Database-Migrator

Mirror of Database-Migrator on urth.org
Perl
5
star
47

Net-Works

Sane APIs for IP addresses and networks
Perl
5
star
48

MaxMind-DB-Reader-XS

Fast XS implementation of MaxMind DB reader
Perl
5
star
49

dev-site

Static site generator for https://dev.maxmind.com.
HTML
4
star
50

xgb2code

A converter for xgboost model dumps to code.
Go
4
star
51

ccfd-api-asp

minFraud ASP API
ASP
3
star
52

webservice-paypal-paymentsadvanced

A simple wrapper around the PayPal Payments Advanced web service
Perl
3
star
53

gatling-gen

C++
2
star
54

geoip-api-mscom

DEPRECATED GeoIP Legacy MS COM API
C
2
star
55

App-CISetup

Command line tools to generate and update Travis and AppVeyor configs for Perl libraries
Perl
2
star
56

api-specs

TypeScript
2
star
57

MaxMind-DB-Common-perl

Code shared by the MaxMind DB reader and writer modules
Perl
2
star
58

WebService-PivotalTracker

Perl library for the Pivotal Tracker REST API
Perl
2
star
59

minfraud-api-perl

Perl API for minFraud Score, Insights, and Factors
Perl
2
star
60

TAP-Formatter-TeamCity

Emit test results as TeamCity build messages
Perl
2
star
61

geolite2-ws-blogpost

Integrating MaxMind's Free and Paid IP Geolocation Web Services (in PHP)
PHP
2
star
62

fuzzing-workshop

Code for Summit Fuzzing Workshop
Go
1
star
63

Dist-Zilla-PluginBundle-MAXMIND

Perl
1
star
64

blog-site

Static site generator for https://blog.maxmind.com.
SCSS
1
star
65

TeamCity-Message

Generate TeamCity build messages
Perl
1
star
66

xgbshap

Calculates feature contributions for XGBoost models
Go
1
star