IP to Geolocation with Python
Tags: python, webdev, codenewbie, api
Published: 2022-09-04 12:00:49

## OR - My Own Headless SAAS - Part 2

[In my previous](https://dev.to/dacoder/my-own-headless-saas-part-1-where-i-begin-420c) post I described how I began developing my own SAAS and the different decisions I had to make.

Here I want to show you how I (and you can too!) develop an IP-to-geo service using Python.

### Background 

Before going in deep, we must realize that translating an IP address into a geolocation is a tricky business. IPs are commonly allocated by ranges (i.e. sets of hundreds or more IPs) to large organizations and associations, governments, ISPs, and large companies. 

Those organizations then allocate those IPs as they see fit, either internally, or for publicly accessible resources, and sometimes even to users (e.g. ISPs may allocate IP to an internet consumer, and one can purchase a fixed IP from cloud providers).  
However IP allocation tend to change with time, making it difficult to maintain an accurate mapping of IP to organization or IP to location. 

This is why there're several businesses out there that specialize in that exclusively - maintaining a constantly updated map of IPs, allocations and locations.
Among those firms are [Maxmind](https://www.maxmind.com/en/geoip2-databases), [IP2Location](https://www.ip2location.com/), [DP-IP](https://db-ip.com/), and more.

On this piece I'll use Maxmind's IP free database, and I'll show you how to read is using Python.
_Note that the GeoLite database is a free, limited and inaccurate version of Maxmind's full database, which requires a license._

### Code it!

If you're lazy, you can also checkout [my notebook](https://github.com/dacoderc/notebooks/blob/main/ip_to_geolocation.ipynb).

**Lets get started:**

1. [Register to MaxMind](https://dev.maxmind.com/geoip/geolite2-free-geolocation-data?lang=en)
1. Once you're in, go ahead to the "download database" section:
![Download database](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iggjhxjimf8pd8m6ku6e.png)
1. Next, scroll down and download the "GeoLite City" database. Make sure to download the GZIP and not the CSV file.
![Download GeoLite City GZIP](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c7kyke1esibil99s1hw1.png)
1. Extract and put the .mmdb file somewhere next to your code.

**Next we do some simple coding.**

To read this database we'll use Maxmind's own python library:

```
$ pip install geoip2
```

My geo.py file looks as follows, and I guess it's quite straightforward:

```
import geoip2.database

# Open the database file, the location of the database needs to match your setup
with geoip2.database.Reader('./files/GeoLite2-City.mmdb') as reader:
    
    # Query for a specific IP
    response = reader.city('90.190.169.0')
    print(f"Continent: {response.continent.names['en']}")
    print(f"Country: {response.country.names['en']}")
    print(f"City: {response.city.names['en']}")
    print(f"Coordinates: Lat {response.location.latitude} Long {response.location.longitude}")
    print(f"Timezone: {response.location.time_zone}")
```

In the above example I merely print out some data returned from Maxmind's database, but I can do much more, such as keeping it into my DB, use it for logging, user verification, cyber prevention, etc.

---

**Are you considering to add IP-to-location capabilities to your app?**
If so, you can definitely go ahead and purchase Maxmind's (or any other firm's) IP-to-geo database file, and implement it into your code.
The advantages for this approach is that you get a robust and independent app. 
The disadvantages for this approach is that you'll need to purchase a license regardless of your usage, and you'll forever need to make sure that the database file is being constantly updated into your codebase. 
This takes another (micro)service to develop, maintain and monitor.

Another wise alternative is to use an API service to query for IP-to-location.
If you're considering this approach, make sure to check out my own [tooltap.app](https://www.tooltap.app/) service. 

---

I'm still adding users as design partners with exclusive early-bird benefits. Contact me if you wish to enjoy this opportunity.