How-To Guides

Mastering IP Geolocation in Python with Requests for Developers

IP Address Details Team November 9, 2026 19 min read
Mastering IP Geolocation in Python with Requests for Developers
Learn to implement robust IP geolocation in Python using the requests library. This guide covers API integration, bulk lookups, rate limiting, and accuracy considerations.

In today's interconnected digital landscape, understanding the geographical origin of your users' IP addresses is crucial for a myriad of applications. From content localization and fraud detection to personalized user experiences and security analytics, IP geolocation in Python with requests provides a powerful and accessible method for developers to integrate this capability into their systems. This guide will walk you through the process of leveraging the IP Address Details API with Python's popular requests library, offering practical code examples, best practices for handling rate limits, and an honest look at the capabilities and limitations of IP geolocation data.

Web and backend developers frequently encounter scenarios where identifying the country, city, or even the ISP of a client's IP address can significantly enhance application functionality and security posture. Whether you're building a global service that needs to serve region-specific content, a security system to flag suspicious login attempts from unusual locations, or an analytics dashboard to visualize user distribution, mastering IP geolocation with Python is an invaluable skill. We'll delve into the technical specifics, ensuring you have the tools and knowledge to implement reliable and efficient IP geolocation solutions in your production environments.

Understanding IP Geolocation: Fundamentals and Use Cases

IP geolocation is the process of mapping an IP address to a real-world geographical location. This mapping is achieved by analyzing databases that correlate IP address ranges with geographical coordinates, often maintained by Internet Registries (RIRs) and commercial providers. While not as precise as GPS, IP geolocation can typically identify a user's country with high accuracy and their city with reasonable accuracy.

How IP Geolocation Works

At its core, IP geolocation relies on publicly available information about how IP addresses are allocated and routed. The Internet Assigned Numbers Authority (IANA) delegates large blocks of IP addresses to Regional Internet Registries (RIRs) like ARIN, RIPE NCC, APNIC, LACNIC, and AFRINIC. These RIRs then assign smaller blocks to Internet Service Providers (ISPs) and other organizations. By tracking these assignments and observing network routing data, geolocation databases are built and continually updated to provide location estimates. For a deeper understanding of IP addressing, refer to RFC 791, the Internet Protocol specification.

Common Applications for Developers

  • Content Localization: Delivering language-specific content, currency, or regional product catalogs.
  • Fraud Detection: Identifying suspicious transactions originating from high-risk countries or locations inconsistent with user profiles.
  • Security Analytics: Detecting anomalous login attempts, DDoS attack origins, or unauthorized access patterns.
  • Audience Segmentation: Understanding user distribution for marketing and business intelligence.
  • Compliance: Ensuring adherence to regional regulations (e.g., GDPR, CCPA) by controlling data access or content availability based on location.
  • Load Balancing/CDN Optimization: Directing users to the nearest server or content delivery network edge node.

Getting Started with the IP Address Details API

The IP Address Details API provides a straightforward way to obtain comprehensive geolocation data. Our API offers a simple RESTful interface, returning data in JSON format, making it easy to parse with Python.

API Endpoint and Authentication

The base URL for our API is https://www.ipaddressdetails.com/api/v1/ip/{ip}, where {ip} is the IP address you wish to query. While many requests can be made without an API key, for higher rate limits and guaranteed service, we recommend obtaining a free API key. This key should be sent in an X-API-Key HTTP header.

You can sign up for your free API key and manage your account at https://www.ipaddressdetails.com/developers. Our free tier allows for 1,000 requests per day, which is ample for testing and many small-scale applications. For higher volumes, please refer to our pricing comparison page at https://www.ipaddressdetails.com/pages/api-comparison.html.

API Response Fields

Upon a successful request, the API returns a JSON object containing various fields. Here's a table describing the key fields you'll receive:

FieldTypeDescription
ipstringThe queried IP address.
versionintegerIP protocol version (4 or 6).
citystringThe city associated with the IP address.
regionstringThe region/state associated with the IP address.
countrystringThe country associated with the IP address.
country_codestringTwo-letter ISO country code.
continentstringThe continent associated with the IP address.
latitudefloatGeographical latitude.
longitudefloatGeographical longitude.
timezonestringTimezone in IANA format (e.g., 'America/New_York').
postalstringPostal code (where available).
asnstringAutonomous System Number.
orgstringOrganization name (ISP/company).
hostnamestringReverse DNS hostname (if available).
is_privatebooleanTrue if the IP is a private address (e.g., 192.168.x.x).
is_eubooleanTrue if the IP is located within the European Union.

Performing IP Geolocation in Python with Requests

The requests library is the de facto standard for making HTTP requests in Python. Its simplicity and power make it ideal for interacting with RESTful APIs like ours.

Installation

First, ensure you have the requests library installed:

pip install requests

Basic API Request (Python)

Here's a simple example to perform IP geolocation in Python with requests for a public IP address:

import requestsimport jsondef get_ip_geolocation(ip_address):    api_url = f"https://www.ipaddressdetails.com/api/v1/ip/{ip_address}"    try:        resp        response.raise_for_status()  # Raises HTTPError for bad responses (4xx or 5xx)        data = response.json()        return data    except requests.exceptions.HTTPError as http_err:        print(f"HTTP error occurred: {http_err}")    except requests.exceptions.ConnectionError as conn_err:        print(f"Connection error occurred: {conn_err}")    except requests.exceptions.Timeout as timeout_err:        print(f"Timeout error occurred: {timeout_err}")    except requests.exceptions.RequestException as req_err:        print(f"An unexpected error occurred: {req_err}")    except json.JSONDecodeError:        print("Failed to decode JSON response.")    return None# Example usageip_to_lookup = "8.8.8.8"  # Google's Public DNSip_info = get_ip_geolocation(ip_to_lookup)if ip_info:    print(f"Geolocation for {ip_to_lookup}:")    print(f"  Country: {ip_info.get('country')}")    print(f"  City: {ip_info.get('city')}")    print(f"  Organization: {ip_info.get('org')}")    print(f"  Latitude: {ip_info.get('latitude')}")    print(f"  Longitude: {ip_info.get('longitude')}")else:    print(f"Could not retrieve geolocation for {ip_to_lookup}")

Including Your API Key for Production Use

For higher rate limits and reliable service, always include your API key. Replace 'YOUR_API_KEY' with your actual key from our developer portal.

import requestsimport js  # Replace with your actual API keydef get_ip_geolocation_with_key(ip_address, api_key):    api_url = f"https://www.ipaddressdetails.com/api/v1/ip/{ip_address}"    headers = {        "X-API-Key": api_key    }    try:        resp headers=headers)        response.raise_for_status()        data = response.json()        return data    except requests.exceptions.HTTPError as http_err:        print(f"HTTP error occurred: {http_err} - Status Code: {response.status_code}")        if response.status_code == 401:            print("Authentication failed. Check your API key.")        elif response.status_code == 429:            print("Rate limit exceeded. Try again later.")    except requests.exceptions.RequestException as req_err:        print(f"An error occurred: {req_err}")    except json.JSONDecodeError:        print("Failed to decode JSON response.")    return None# Example usage with API keyip_to_lookup_key = "203.0.113.45" # An example public IPip_info_key = get_ip_geolocation_with_key(ip_to_lookup_key, API_KEY)if ip_info_key:    print(f"\nGeolocation for {ip_to_lookup_key} (with API key):")    print(f"  Country: {ip_info_key.get('country')}")    print(f"  City: {ip_info_key.get('city')}")    print(f"  Continent: {ip_info_key.get('continent')}")else:    print(f"Could not retrieve geolocation for {ip_to_lookup_key} with API key.")

Alternative Request Examples (Curl, JavaScript Fetch)

For developers working with other tools, here are equivalent examples:

Curl Example

curl -H "X-API-Key: YOUR_API_KEY" https://www.ipaddressdetails.com/api/v1/ip/1.1.1.1

JavaScript Fetch Example

fetch('https://www.ipaddressdetails.com/api/v1/ip/1.1.1.1', {  headers: {    'X-API-Key': 'YOUR_API_KEY'  }})  .then(resp> {    if (!response.ok) {      throw new Error(`HTTP error! status: ${response.status}`);    }    return response.json();  })  .then(data => console.log(data))  .catch(error => console.error('Error:', error));

Advanced IP Geolocation with Python Requests

Beyond basic lookups, developers often need to handle bulk requests, manage rate limits, and consider caching strategies for optimal performance in production.

Bulk IP Lookup Script

Processing a list of IP addresses efficiently is a common requirement. Here's how to create a simple script to perform a bulk IP lookup, reading IPs from a file and saving results to a CSV.

import requestsimport csvimport timeAPI_KEY = "YOUR_API_KEY"  # Replace with your actual API keydef bulk_ip_geolocation(ip_list, api_key, output_filename="geolocation_results.csv"):    results = []    headers = {        "X-API-Key": api_key    }    # Define CSV headers based on API response fields    csv_headers = [        'ip', 'version', 'city', 'region', 'country', 'country_code',        'continent', 'latitude', 'longitude', 'timezone', 'postal',        'asn', 'org', 'hostname', 'is_private', 'is_eu'    ]    with open(output_filename, 'w', newline='', encoding='utf-8') as outfile:        writer = csv.DictWriter(outfile, fieldnames=csv_headers)        writer.writeheader()        for i, ip_address in enumerate(ip_list):            ip_address = ip_address.strip()            if not ip_address:                continue            print(f"Processing IP: {ip_address} ({i+1}/{len(ip_list)})")            api_url = f"https://www.ipaddressdetails.com/api/v1/ip/{ip_address}"            try:                resp headers=headers, timeout=5)                response.raise_for_status()                data = response.json()                # Filter to only include fields defined in csv_headers                filtered_data = {key: data.get(key, '') for key in csv_headers}                writer.writerow(filtered_data)                print(f"  Success: {ip_address}")            except requests.exceptions.HTTPError as http_err:                print(f"  HTTP error for {ip_address}: {http_err} - Status: {response.status_code}")                if response.status_code == 429:                    print("    Rate limit hit. Pausing for 60 seconds...")                    time.sleep(60) # Pause for a minute on rate limit                elif response.status_code == 401:                    print("    Authentication failed. Check API key.")                    break # Stop processing if API key is invalid            except requests.exceptions.RequestException as req_err:                print(f"  Request error for {ip_address}: {req_err}")            except json.JSONDecodeError:                print(f"  JSON decode error for {ip_address}. Response: {response.text[:100]}...")            time.sleep(0.1) # Be a good API citizen and add a small delay# Create a dummy IP list file for demonstrationwith open("ips.txt", "w") as f:    f.write("8.8.8.8\n")    f.write("1.1.1.1\n")    f.write("192.168.1.1\n") # Private IP    f.write("203.0.113.1\n")    f.write("66.249.66.1\n")    f.write("invalid-ip\n") # Example of bad input# Read IPs from a file with open("ips.txt", "r") as f:    ips_to_process = f.readlines()# Run the bulk lookupbulk_ip_geolocation(ips_to_process, API_KEY)print(f"\nBulk geolocation complete. Results saved to geolocation_results.csv")

Handling Rate Limits

Rate limits are a common mechanism for API providers to ensure fair usage and system stability. Exceeding them typically results in a 429 Too Many Requests HTTP status code. Our API also provides X-RateLimit-* headers to help you manage your usage effectively. For more on HTTP status codes, refer to MDN Web Docs on 429.

Implementing Exponential Backoff

A robust way to handle rate limits is with exponential backoff. This strategy involves retrying a failed request after an increasing delay.

import requestsimport timeAPI_KEY = "YOUR_API_KEY"MAX_RETRIES = 5INITIAL_DELAY = 1 # secondsdef get_ip_geolocation_with_retry(ip_address, api_key):    api_url = f"https://www.ipaddressdetails.com/api/v1/ip/{ip_address}"    headers = {        "X-API-Key": api_key    }    delay = INITIAL_DELAY    for attempt in range(MAX_RETRIES):        try:            resp headers=headers, timeout=10)            # Check for RateLimit headers            if 'X-RateLimit-Remaining' in response.headers and 'X-RateLimit-Reset' in response.headers:                remaining = int(response.headers['X-RateLimit-Remaining'])                reset_time = int(response.headers['X-RateLimit-Reset'])                print(f"  Rate Limit: {remaining} requests remaining, resets in {reset_time} seconds.")            response.raise_for_status()            return response.json()        except requests.exceptions.HTTPError as http_err:            if response.status_code == 429:                print(f"Attempt {attempt + 1}/{MAX_RETRIES}: Rate limit hit for {ip_address}. Retrying in {delay} seconds...")                time.sleep(delay)                delay *= 2  # Exponential increase                if attempt == MAX_RETRIES - 1:                    print(f"Max retries reached for {ip_address}. Giving up.")                    return None            else:                print(f"HTTP error occurred: {http_err} for {ip_address}")                return None        except requests.exceptions.RequestException as req_err:            print(f"An error occurred: {req_err} for {ip_address}")            return None    return None# Example usageip_to_test = "198.51.100.1" # Another example public IPfor _ in range(10): # Simulate multiple requests, potentially hitting rate limit    info = get_ip_geolocation_with_retry(ip_to_test, API_KEY)    if info:        print(f"  Country: {info.get('country')}, City: {info.get('city')}")    else:        print(f"  Failed to get info for {ip_to_test}")    time.sleep(0.5) # Small delay between requests

Caching IP Geolocation Data

For frequently accessed IP addresses, caching results can significantly reduce API calls and improve performance. Python's functools.lru_cache is an excellent option for simple in-memory caching.

import requestsimport jsonfrom functools import lru_cacheAPI_KEY = "YOUR_API_KEY"CACHE_SIZE = 1024  # Cache up to 1024 unique IP results@lru_cache(maxsize=CACHE_SIZE)def get_ip_geolocation_cached(ip_address, api_key):    # Note: lru_cache caches based on ALL arguments.    # If API_KEY changes, it's a new cache entry.    # For simplicity, we pass it here, but in a real app,    # you might pass a fixed API_KEY to the cached function or use a class.    api_url = f"https://www.ipaddressdetails.com/api/v1/ip/{ip_address}"    headers = {        "X-API-Key": api_key    }    try:        resp headers=headers, timeout=5)        response.raise_for_status()        return response.json()    except requests.exceptions.RequestException as req_err:        print(f"Error fetching {ip_address}: {req_err}")        return None    except json.JSONDecodeError:        print(f"JSON decode error for {ip_address}")        return None# Example usageip_addresses = ["8.8.8.8", "1.1.1.1", "8.8.8.8", "4.4.4.4", "1.1.1.1"]print("\n--- Testing Caching ---")for ip in ip_addresses:    print(f"Looking up {ip}...")    info = get_ip_geolocation_cached(ip, API_KEY)    if info:        print(f"  Result: {info.get('country')}, {info.get('city')}")    else:        print(f"  Failed to get info for {ip}")print(f"Cache Info: {get_ip_geolocation_cached.cache_info()}")

IP Geolocation Accuracy and Limitations

While incredibly useful, it's vital for developers to understand the inherent limitations and accuracy caveats of IP geolocation:

  • Country Level: Generally, country-level accuracy is very high, often around 98-99%. This is because country-level IP block assignments are relatively stable and well-documented by RIRs like IANA.
  • City Level: City-level accuracy is lower, typically ranging from 70-80%. This is due to several factors:
    • ISP Infrastructure: Many ISPs route traffic through central hubs, meaning the IP address might reflect the location of the ISP's data center, not the end-user's precise location.
    • Dynamic IP Addresses: Consumer internet connections often use dynamic IPs, which can change frequently and be assigned from large pools spanning broad geographical areas.
    • Mobile IP Addresses: Mobile networks often use complex routing, making precise geolocation challenging.
  • Anycast Networks: Services like CDNs and public DNS providers (e.g., Google DNS 8.8.8.8) use anycast routing, where the same IP address is advertised from multiple geographical locations. A query to an anycast IP will return the location of the *nearest* server responding, not a single fixed point.
  • VPNs, Proxies, and Tor: Users employing Virtual Private Networks (VPNs), proxy servers, or the Tor network will have their apparent IP address masked. Geolocation will reflect the location of the VPN server or exit node, not the user's actual physical location.
  • Carrier-Grade NAT (CGNAT): ISPs using CGNAT share a single public IP address among many customers. This makes it impossible to pinpoint individual users within that shared public IP, often only providing a coarse location for the entire CGNAT block.
  • Private IP Addresses: IP addresses within reserved private ranges (e.g., 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, as defined in RFC 1918) are not routable on the public internet. Our API will identify these as is_private: true and will not return geolocation data for them.

It's crucial to use IP geolocation as a strong indicator rather than absolute proof of location, especially for sensitive applications. Always combine it with other data points when higher confidence is required.

Comparing IP Geolocation Providers

While we believe IP Address Details offers a competitive and reliable service, it's good practice to be aware of the broader market. Different providers may have varying data sources, update frequencies, accuracy levels, pricing models, and feature sets (e.g., threat intelligence, device detection). We encourage you to review our detailed comparison of IP geolocation providers at https://www.ipaddressdetails.com/pages/api-comparison.html to make an informed decision based on your specific needs.

Integrating the IP Address Details Widget

For front-end applications or websites where you need to display IP information directly to users without complex backend integration, our embeddable widget can be a convenient solution. You can find more details and customization options at https://www.ipaddressdetails.com/widget. This can complement your backend IP geolocation in Python with requests implementation by providing a client-side visual component.

FAQ

How accurate is IP geolocation?

Country-level geolocation is highly accurate, typically 98-99%. City-level accuracy is lower, around 70-80%, as it depends on ISP infrastructure, dynamic IP assignments, and other factors. It should be treated as an indicator, not absolute proof of location.

Can I get geolocation for private IP addresses?

No. Private IP addresses (e.g., 192.168.x.x, 10.x.x.x) are not routable on the public internet. Our API will identify them as private ("is_private": true) but cannot provide geographical data for them. Geolocation is only possible for public IP addresses.

What happens if I exceed the API rate limit?

If you exceed your allocated rate limit (e.g., 1,000 requests/day for the free tier), the API will return a 429 Too Many Requests HTTP status code. We recommend implementing retry logic with exponential backoff and monitoring X-RateLimit-* headers to manage your usage effectively.

How does IP Address Details get its geolocation data?

We aggregate and process data from multiple authoritative sources, including Regional Internet Registries (RIRs) for IP block assignments, network routing data, and other proprietary databases. Our system continuously updates these records to maintain high accuracy.

Is an API key required for all requests?

While basic requests might work without an API key, we highly recommend obtaining and using an API key for all production and development environments. An API key grants you higher rate limits, improved reliability, and access to all API features, ensuring a smoother experience.

Can I use this for real-time fraud detection?

Yes, IP geolocation is a valuable component of real-time fraud detection systems. By quickly identifying the geographical origin of a transaction or login attempt, you can flag suspicious activities, especially when combined with other user behavior data. However, remember its limitations and use it as part of a multi-layered security strategy.

Conclusion

Implementing robust IP geolocation in Python with requests is an essential capability for modern web and backend development. The IP Address Details API, coupled with Python's powerful requests library, provides a flexible and reliable foundation for integrating location intelligence into your applications. We've covered everything from basic API calls and handling authentication with API keys to advanced topics like bulk lookups, rate limit management, and the critical understanding of geolocation accuracy and its limitations.

By following the best practices outlined in this guide, including proper error handling, intelligent rate limit management, and strategic caching, you can build resilient systems that leverage IP geolocation effectively. Whether you're enhancing user experience, bolstering security, or driving data-driven insights, the ability to accurately determine an IP address's geographical context is a powerful asset in your development toolkit. Start integrating the IP Address Details API today to unlock the full potential of location-aware applications.

Author: IP Address Details Security Team

๐Ÿ›ก๏ธ Protect Your Privacy Today

Get a VPN and browse securely with up to 82% off.

Compare Top VPNs
Share:
๐Ÿ”’

Our Top Recommended VPNs

Tested & Verified

We independently test every VPN. These are the best options for privacy, speed, and unblocking content โ€” especially in restricted regions like UAE and Saudi Arabia.

Surfshark Editor's Choice
Unlimited devices ยท Works in UAE/Saudi Arabia ยท CleanWeb ad blocker
$2.49/mo $12.95/mo 82% OFF
โ˜…โ˜…โ˜…โ˜…โ˜…
Get Surfshark โ†’
NordVPN Most Popular
5500+ servers ยท Double VPN ยท Threat Protection ยท 24/7 support
$3.29/mo $11.99/mo 74% OFF
โ˜…โ˜…โ˜…โ˜…โ˜…
Get NordVPN โ†’
ExpressVPN Fastest Speeds
Lightway protocol ยท Works everywhere ยท 30-day money-back
$6.67/mo $12.95/mo 49% OFF
โ˜…โ˜…โ˜…โ˜…โ˜…
Get ExpressVPN โ†’

* Affiliate disclosure: We may earn a commission if you purchase through our links, at no extra cost to you. We only recommend VPNs we trust.