Back to Python
2025-12-125 min read

API Geolocation (Python Programming)

Learn API Geolocation (Python Programming) step by step with clear examples and exercises.

Why This Matters

today, understanding how to use APIs is crucial for developers. One such API that has gained significant importance is the Geolocation API, which allows us to find the geographical location of a device or IP address. This knowledge can be applied in various scenarios, like building web applications that provide location-based services, tracking user locations for safety purposes, and even in developing smart city solutions.

In this lesson, we will learn how to use the Geolocation API with Python to fetch location data from an IP address. We'll cover the core concept, work through a detailed example, explore common mistakes, provide practice questions, and answer frequently asked questions.

Prerequisites

To follow along with this lesson, you should have a basic understanding of:

  1. Python programming language
  2. How to install Python packages using pip
  3. Working with REST APIs (REpresentational State Transfer)
  4. Understanding file handling in Python
  5. Familiarity with the concept of IP addresses and their structure
  6. Basic knowledge of object-oriented programming concepts in Python
  7. Understanding how to handle exceptions in Python

If you're new to these concepts, consider checking out our Python tutorials and API tutorials for beginners.

Core Concept

The Geolocation API we will be using is the free MaxMind GeoIP2 API. To use this API, you need to sign up for a free account at MaxMind and obtain your API key.

Once you have your API key, install the required Python package using pip:

pip install geoip2

Now let's dive into the code to fetch location data from an IP address.

Fetching Location Data with Geolocation API (Python)

First, import the necessary libraries and initialize the GeoIP2 manager:

from geoip2.database import EditorDBReader
import geoip2.records as records

reader = EditorDBReader("/path/to/GeoLite2-City.mmdb")

Replace /path/to/GeoLite2-City.mmdb with the path to your downloaded GeoLite2-City.mmdb file.

Next, we will create a class called LocationFetcher that encapsulates the logic for fetching location data from an IP address:

class LocationFetcher:
def __init__(self):
self.reader = EditorDBReader("/path/to/GeoLite2-City.mmdb")

def get_location(self, ip):
response = self.reader.query(ip)
record = response.location

return {
'country': record.country.name,
'region': record.subdivision.name,
'city': record.city.name,
'postal_code': record.postal.code,
'latitude': record.location.latitude,
'longitude': record.location.longitude
}

Now, let's test our class with an example IP address:

fetcher = LocationFetcher() # Instantiate the LocationFetcher class
ip = "8.8.8.8" # Google's public DNS server IP address
location_data = fetcher.get_location(ip)
print(location_data)

When you run this code, it will output the location data for the provided IP address:

{'country': 'United States', 'region': 'Virginia', 'city': 'Ashburn', 'postal_code': '20146', 'latitude': 39.0758, 'longitude': -77.4853}

Worked Example

In this example, we will fetch the location data for multiple IP addresses and store it in a CSV file:

import csv

List of IP addresses to fetch location data for

ips = ["8.8.8.8", "192.168.0.1", "10.0.0.1"]

fetcher = LocationFetcher() # Instantiate the LocationFetcher class

with open('location_data.csv', 'w', newline='') as csvfile:

fieldnames = ['IP Address', 'Country', 'Region', 'City', 'Postal Code', 'Latitude', 'Longitude']

writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

writer.writeheader()

for ip in ips:

location_data = fetcher.get_location(ip)

writer.writerow(location_data)


After running this script, you'll find a CSV file named `location_data.csv` in your current directory containing the fetched location data for the provided IP addresses.

Common Mistakes

1. Incorrectly downloading or using the GeoLite2-City.mmdb file

Make sure to download the GeoLite2-City.mmdb file from MaxMind's website and use the correct path in your code. Also, ensure that you have the appropriate permissions to read the file.

2. Using an outdated or incorrect version of the GeoLite2-City.mmdb file

MaxMind periodically updates their database. Make sure to download the latest version from MaxMind's website and update your code accordingly.

3. Not handling exceptions properly

The Geolocation API might not always return data for a given IP address. It is essential to handle exceptions when working with APIs to ensure your application can handle such cases gracefully. In our example, we could add exception handling to print an error message if the IP address cannot be found in the database.

4. Not properly initializing the GeoIP2 manager

Ensure that you initialize the LocationFetcher class with the correct path to your GeoLite2-City.mmdb file before using it to fetch location data.

Practice Questions

  1. Modify the get_location method in the LocationFetcher class to accept an optional parameter called format. If set to 'json', return the location data as a JSON object instead of a dictionary.
  2. Write a Python script that fetches the location data for multiple IP addresses and stores it in a CSV file, but this time allow the user to input the list of IP addresses from the command line.
  3. Implement a simple web application using Flask or Django that accepts an IP address as input and displays the corresponding location data. Also, handle exceptions gracefully if the provided IP address cannot be found in the database.
  4. Extend the LocationFetcher class to fetch additional data such as timezone or currency for a given IP address.
  5. Write a Python script that fetches the location data for multiple IP addresses and stores it in a SQLite database instead of a CSV file.

FAQ

Q: Can I use this API for commercial purposes?

A: Yes, but you must upgrade to a paid plan if your monthly requests exceed 50 million. For more details, visit MaxMind's pricing page.

Q: How often is the GeoLite2-City database updated?

A: MaxMind updates their database daily. You can download the latest version from their website.

Q: What happens if an IP address cannot be found in the GeoLite2-City database?

A: If an IP address is not found, the function will return an empty dictionary. It's essential to handle such cases gracefully in your application. In our example, we could add exception handling to print an error message if the IP address cannot be found in the database.

API Geolocation (Python Programming) | Python | XQA Learn