How to geolocate an IP address in Python

Last Updated Jan 26, 2021
Emma Jagger

Engineer, maker, Google alumna, CMU grad

Geolocating an IP address is a convenient way to identify a user's real-world location. This information can be used in a variety of ways to improve user experience, provide custom marketing, and restrict content by region. You can get a lot of data just from an IP address, like the user's currency, timezone, whether they're using a proxy or VPN, and general location. With this information, you can improve user experience by tailoring your platform to the user. For example, you can display prices in the local currency, show dates and times in the appropriate regional format, and provide the location of the closest physical story.

This blog post covers how to geolocate a user's IP address using Python.

Geolocate an IP address using an IP address database

One way to geolocate an IP address is to use an online geolocation database. One popular option, Geolocation DB, is free-to-use without an API key. This database includes a massive number of IP addresses obtained from Internet service providers. By querying the service, you can get an approximate location for a specified IP address.

For example, we can query Geolocation DB to geolocate the IP address 147.229.2.90 as follows:


import requests
import json

# IP address to test
ip_address = '147.229.2.90'

# URL to send the request to
request_url = 'https://geolocation-db.com/jsonp/' + ip_address
# Send request and decode the result
response = requests.get(request_url)
result = response.content.decode()
# Clean the returned string so it just contains the dictionary data for the IP address
result = result.split("(")[1].strip(")")
# Convert this data into a dictionary
result  = json.loads(result)
print(result)

For the provided IP address, this call returns the data:


{
    'country_code': 'AU',
    'country_name': 'Australia',
    'city': 'Broome',
    'postal': '6725',
    'latitude': -17.9554,
    'longitude': 122.2392,
    'IPv4': '139.130.4.5',
    'state': 'Western Australia'
}

Drawbacks to this approach

Because Geolocation DB is a free-to-use database, it does not provide much transparency toward the accuracy of its data. There also is not a method to easily confirm the validity of the IP locations. As a result, the use of this database introduces an unknown level of inaccuracy to geolocation data.

Additionally, this approach provides minimal information about the IP address and returns data exclusively referring to the estimated location. For example, accessing information like timezone and currency from this data would require querying secondary databases. This database also does not provide any information about whether the user is using a VPN to access the information. Since some people use VPNs to hide their real IP addresses and location, identifying the use of a VPN can be used to eliminate inaccurate location data.

Geolocate an IP address using Abstract's geolocation API

Abstract API offers a free geolocation API that provides detailed information about user IP addresses. It provides information about the user's location including city, state/region, country, and more, as well as information about their timezone, currency, and regional flag. The availability of this information makes it easy to customize your platform without querying external sources. Additionally, this API detects whether the user is connecting to the network via a VPN, making it easier to identify altered location data.


import json
import requests

# Your API key, available from your account page
YOUR_GEOLOCATION_KEY = 'your_key'

# IP address to test
ip_address = '147.229.2.90'

request_url = 'https://ipgeolocation.abstractapi.com/v1/?api_key=' + YOUR_GEOLOCATION_KEY + '&ip_address=' + ip_address
result = json.loads(response.content)
print(result)

For the provided IP address, this call returns the following data:


{
    'ip_address': '139.130.4.5',
    'city': 'Sydney',
    'city_geoname_id': 2147714,
    'region': 'New South Wales',
    'region_iso_code': 'NSW',
    'region_geoname_id': 2155400,
    'postal_code': '1001',
    'country': 'Australia',
    'country_code': 'AU',
    'country_geoname_id': 2077456,
    'country_is_eu': False,
    'continent': 'Oceania',
    'continent_code': 'OC',
    'continent_geoname_id': 6255151,
    'longitude': 151.209,
    'latitude': -33.8688,
    'security': {
        'is_vpn': False
    },
    'timezone': {
        'name': 'Australia/Sydney',
        'abbreviation': 'AEDT',
        'gmt_offset': 11,
        'current_time': '12:17:29',
        'is_dst': True
    },
    'flag': {
        'emoji': '🇦🇺',
        'unicode': 'U+1F1E6 U+1F1FA',
        'png': 'https://static.abstractapi.com/country-flags/AU_flag.png',
        'svg': 'https://static.abstractapi.com/country-flags/AU_flag.svg'
    },
    'currency': {
        'currency_name': 'Australian Dollars',
        'currency_code': 'AUD'
    },
    'connection': {
        'autonomous_system_number': 1221,
        'autonomous_system_organization': 'Telstra Corporation',
        'connection_type': 'Corporate',
        'isp_name': 'Telstra Internet',
        'organization_name': None
    }
}
Abstract makes IP geolocation in Python quick and easy.
Get started