IPinfo - Comprehensive IP address data, IP geolocation API and database My IP ↗or
7 days ago by Abdullah 5 min read

Getting Started with IP Geolocation API in Python

How to Get Geolocation in Python?

Python is a versatile and widely used programming language known for its simplicity and powerful libraries. One of its many applications is IP geolocation, which involves converting IP addresses into geographic addresses (including latitude and longitude). This is especially useful for location-based services, mapping applications, and data analysis. 

IPinfo's Geolocation API in Python provides all the data benefits of IP geolocation, including the city, region, country, postal code, and timezone. In this article, we’ll explore using our API to perform IP geolocation with minimal effort.

Want to use a different language? Read our tutorial IP geolocation in C sharp.

Understanding IP Geolocation APIs

Geolocation APIs provide geolocation data, ISP and connection details, and time zone detection. Find the best IP geolocation API for your needs. 

Businesses are using IP geolocation data for:

  • Targeted advertising: Through IP geolocation, online businesses can provide location-aware advertisements to visitors.
  • Content localization based on region: Through IP geolocation, websites can create personalized solutions such as converting the site's content language to match the user's location, changing tax rates, calculating delivery costs in advance, etc.
  • Fraud detection: IP geolocation can also help with fraud detection, such as credit card fraud at checkout.
  • Regulatory compliance: IP geolocation can enforce digital rights management for streaming companies and digital asset companies.
  • Personalized recommendations based on proximity: Content and service recommendations can be made through IP geolocation. For example, most content recommendation systems in content sites rely on IP geolocation to match the visitor's country-specific trending and popular content.

Get Access to IPinfo’s IP Geolocation API

Discover location-based data instantly with IPinfo’s IP address geolocation API.

Try IPinfo for Free

Steps for Converting an IP Address Into Coordinates

IPinfo's IP geolocation service can convert an IP address to its approximate location. Although IP geolocation is not precise and may not be 100% accurate in providing geographic coordinates, it is usually pretty accurate for large data centers, office spaces, and buildings. We will walk you through the process of getting locations from IP addresses.

IPinfo Python Library

You can use either our API service directly or our official Python library in Python. In this tutorial, we are going to use the official Python library, which is super easy to use and comes with several features, such as caching and bulk enrichment.

Import the Python Library

The IPinfo Python library is available on PyPI and can be downloaded using pip, uv, conda or any package management system you prefer. We will use pip to install the library to our machine:

pip install ipinfo

Initialize The Handler or Instance

After you have installed the official IPinfo Python library, you are set to use it. You need to import and initialize the handler object that will receive your input with your IPinfo access token. You can get your IPinfo access token from this link after signing up.

import ipinfo

# Pass your IPinfo access token
access_token = '123456789abc'

# Initialize the handler using the IPinfo access token
handler = ipinfo.getHandler(access_token)

Get Geolocation Data From the IP Address

Now that you have the handler object initialized with your IPinfo access token, you can pass IP addresses to the handler object, which will return the location information for the IP address. We pass the IP address to the handler object's getDetails function.

For example, we can test with the IP address “35.65.56.98”

ip = '35.65.56.98'
data = handler.getDetails(ip)

This will return the details object assigned to the data variable.

From the data variable, we can now get all the available information (available to your IPinfo access) and individual information as needed.

Output

The details or the all method of the data object returns all the information in a dictionary form:

>>> print(data.details)

{
 'city': 'Ann Arbor',
 'continent': {'code': 'NA', 'name': 'North America'},
 'country': 'US',
 'country_currency': {'code': 'USD', 'symbol': '$'},
 'country_flag': {'emoji': '🇺🇸', 'unicode': 'U+1F1FA U+1F1F8'},
 'country_flag_url': 'https://cdn.ipinfo.io/static/images/countries-flags/US.svg',
 'country_name': 'United States',
 'ip': '35.65.56.98',
 'isEU': False,
 'latitude': '42.2328',
 'loc': '42.2328,-83.7015',
 'longitude': '-83.7015',
 'org': 'AS237 Merit Network Inc.',
 'postal': '48108',
 'region': 'Michigan',
 'timezone': 'America/Detroit'
 }

You can also get specific information such as city, country, loc (geographic coordinates), latitude, longitude, etc.

>>> print(data.city)
Ann Arbor

>>> print(data.country)
US

>>> print(data.loc)
42.2328,-83.7015

>>> print(data.latitude)
42.2328

>>> print(data.longitude)
-83.7015

Similarly, this API endpoint also supports IPv6 IP address inputs.

>>> ip = '2001:49f0:a005::'
>>> data = handler.getDetails(ip)
>>> pprint.pprint(data.details)

{
  'city': 'Denver',
  'continent': {'code': 'NA', 'name': 'North America'},
  'country': 'US',
  'country_currency': {'code': 'USD', 'symbol': '$'},
  'country_flag': {'emoji': '🇺🇸', 'unicode': 'U+1F1FA U+1F1F8'},
  'country_flag_url': 'https://cdn.ipinfo.io/static/images/countries-flags/US.svg',
  'country_name': 'United States',
  'ip': '2001:49f0:a005::',
  'isEU': False,
  'latitude': '39.7392',
  'loc': '39.7392,-104.9847',
  'longitude': '-104.9847',
  'org': 'AS174 Cogent Communications',
  'postal': '80203',
  'region': 'Colorado',
  'timezone': 'America/Denver'
}

Going beyond the standard IP lookup operation, the official Python library for IPinfo includes many more features, such as:

Steps to Retrieve an IP Address From Geographic Coordinates

IP geolocation is not precise enough to provide real-time, accurate reverse IP geolocation where you can enter in geographic coordinates and it will show which IP address is there – that is impossible. However, we can get a general idea of the IP ranges that are located within a certain radius of geographic coordinates.

Reversing the Coordinates to IP Address Ranges

For this operation, you will need access to our IP geolocation database, as this operation is not available as an API. You will also need to ingest the IP database in a database software that can support mathematical formulas or functions.

This can be done through our IP to geolocation data in Snowflake. The Snowflake marketplace has a native Haversine formula that can be used with our IP address to geolocation data available on the Snowflake Marketplace.

Random geographic coordinate input ⇒ 40.990, -100.713

SELECT
  HAVERSINE(40.990, -100.713, loc.lat, loc.lng) as distance,
  loc.start_ip,
  loc.end_ip,
  loc.city,
  loc.region,
  loc.country,
  loc.postal,
  loc.timezone
FROM public.ip_geolocation loc
ORDER BY distance
LIMIT 10;

Output

Here's how your results will appear:

Final Thoughts on Geolocation API Python

By using IPinfo's Geolocation API, Python library, and IP database, businesses can easily access location data from IP addresses to enhance user experiences, increase security, and optimize operations. Integrating IP geolocation into your applications can offer valuable insights. 

We deliver reliable and precise location data that sets the standard for IP data excellence. Our API requires little implementation time and is easy to set up. Support is available 24/7, and we have flexible pricing depending on your project’s needs. 

Try Our Industry Leading IP data API

Locate users, customise experiences, eliminate site risks, and much more.

Sign Up for Free

About the author

Abdullah

Abdullah

Abdullah leads the IPinfo internet data community and he also works on expanding IPinfo’s probe network of servers across the globe.