Guides
Last Updated Aug 03, 2023

How to Perform IP Geolocation Query using the Python Flask Framework

Shyam Purkayastha

Table of Contents:

Get your free
API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required
Get your free
IP Geolocation API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

IP geolocation refers to the information that determines the physical location and Internet connection characteristics of a web visitor.  For all the public IP addresses assigned to computers connected over the Internet, the geolocation data primarily contains latitude, longitude, and some more additional geographical information.

There are various techniques for finding the geolocation of a device connected to a network. In this post, we are going to see how to leverage the Abstract IP Geolocation API to access the location details on an IP address. Furthermore, we will show you how to build a demo Python server to serve up a webpage with geolocation details. This demo application leverages the popular Python Flask Framework to build an API, which is consumed by an HTML webpage to display the geolocation information.

Overview of Abstract IP Geolocation API

Abstract IP Geolocation API is a super fast and secure API to get the location of any IP address in the most non-intrusive way. Some of the key information elements contained within the IP geolocation data are the city, region, country names, and the approximate latitude and longitude point.

With this API you can build web applications to serve dynamic content to users based on their location. Some of the use cases that are achieved via IP geolocation information include:

  • Developing a multilingual application based on the visitor’s local language
  • Develop a multi-currency system based on the visitor’s country
  • Providing time zone-related information based on the visitor’s  location
  • Detecting fraudulent activities by comparing previous locations with the current location of the activity.

Accessing the IP Geolocation API

Open an account with Abstract and choose a subscription plan for the IP Geolocation API. You can choose the free plan for now, which gives you 20,000 API requests per month.

After successful signup, login to your dashboard and select the IP geolocation option.

Consuming the IP Geolocation API

Let's make a simple request using Postman to the IP Geolocation API endpoint. You can trigger the API with your private API key available in the Abstract dashboard.

The Abstract IP Geolocation API response contains the location details along with the currency, flag, timezone, and connection details. The API even detects if the user is using VPN.

You can limit the amount of response from the API by adding extra fields to the request.

Let’s send your first free
API
IP Geolocation API
call
See why the best developers build on Abstract
Get your free api

Using Abstract IP Geolocation API with Python Flask

Flask is one of the most popular web application frameworks written in Python. It is a microframework designed for an easy way to build web services. 

Let’s leverage the Flask framework to build the demo IP geolocation API. Internally it will make a call to the Abstract API to fetch the requisite geolocation details as required by a frontend HTML page. 

Before starting, make sure to set up a development environment with the following prerequisites:  

  • Python 3
  • Terminal CLI with administrator privileges

Step 1: Create Virtual Environment

Open the CLI with administrator privileges. Make a separate directory for your project using the mkdir command and change to that directory.

Within the directory, create the virtual environment for your project. Follow the python official documentation for creating and activating virtual environments. Before proceeding further, make sure to change the directory to the newly created virtual environment. This will be your project directory.

Step 2: Install Flask

Install Flask within the activated environment using pip:


pip install flask

Flask is installed automatically with all the dependencies.

You will need some other packages too, install them with


pip install ipaddress

pip install requests

Step 3: Test your Development Environment

To test the newly installed Flask framework, build a simple Flask application by creating an empty python file, hello.py in the project directory.

Edit the file using a text editor and add the following code to make an API that prints "Hello world!".


from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
    return 'Hello world!'

Save the file and close it. Open a terminal and set the FLASK_APP environment variable.

For Mac and Linux:

export FLASK_APP=hello.py

For Windows:

set FLASK_APP=hello.py

On the same terminal run the application with the command flask run.

Copy and paste the address "http://127.0.0.1:5000" into the browser and notice what you see.

If you see the “Hello World” message on the webpage then this means that your Flask installation is working fine. You can kill the flask app by pressing Ctrl+C (PC) or Cmd+C (Mac) on the terminal.

We are now ready to write the actual code that performs IP Geolocation Query.

Step 4: Create the demo application code

For the demo application, you need two components, the backend API written in Python using Flask, and the frontend HTML UI.

Backend Code for Flask API

For the backend, create another file in the project directory and name it ip.py. Copy and paste the code below into this file.


from flask import Flask, render_template, request,jsonify, make_response

import requests
import ipaddress
 
app = Flask(__name__)
 
app.config['DEBUG'] = True
 
 
@app.route('/')
def index():
    return 'Flask is Awesome!'
 
 
@app.route('/geolocation', methods=['GET'])
def get_geolocation():
        return render_template('index.html')


@app.route('/fetch-gelocation', methods=['POST'])
def post_geolocation():
    try:
        ipaddress.ip_address(request.form['ip_address'])
        req = requests.get('https://ipgeolocation.abstractapi.com/v1/?ip_address=' + request.form['ip_address'] + '&api_key=<YOUR_API_KEY>')
        return make_response(jsonify(req.json()))
    except ValueError:
        return make_response(jsonify({'error': 'Invalid IP Address'}))
    except Exception as e:
        return make_response(jsonify({'error': str(e)}))

        
 
if __name__ == "__main__":
    app.run(debug=True)

This code implements two APIs, GET /geolocation and POST /fetch-geolocation. The former loads the frontend HTML page on the browser, whereas the latter calls the Abstract IP Geolocation API and returns the parameters. This code leverages the popular requests library in Python for triggering the IP Geolocation API.

Before saving the file, make sure to replace the placeholder <YOUR_API_KEY> with the API key assigned to your account by Abstract.

Frontend code for HTML

To add the frontend UI, first create a sub-directory under the project directory and name it “templates”.

Inside the “templates” subdirectory, create a file and name it index.html. Copy the code below inside this file.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
        integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
        <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
        integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
        crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
        integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
        crossorigin="anonymous"></script>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css"
            integrity="sha512-5A8nwdMOWrSz20fDsjczgUidUBR8liPYU+WymTZP1lmY9G6Oc7HlZv156XqnsgNUzTyMefFTcsFH/tnJE/+xBg=="
            crossorigin="anonymous" referrerpolicy="no-referrer" />
    <title>IP Geolocation API</title>
</head>
<body>
    <div class="container">
        <div class="row mt-4">
            <div class="col-md-12">
                <h1>IP Geolocation API</h1>
                <div id="error"></div>
                <form id="geo">
                    <div class="form-group">
                        <label for="ip_address">IP Address</label>
                        <input type="text" class="form-control" id="ip_address" name="ip_address" placeholder="Enter IP Address">
                    </div>
                    <button type="submit" class="btn btn-primary">Submit</button>
                </form>
            </div>
        </div>

        <div class="row mt-4">
            <div class="table-responsive">
                <table class="table table-bordered">
                    <thead>
                        <th>Flag</th>
                        <th>IP Address</th>
                        <th>Country Name</th>
                        <th>City</th>
                        <th>Country Currency</th>
                        <th>Continent</th>
                        <th>Timezone</th>
                    </thead>
                    <tbody>

                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script>
        $(".btn-primary").on("click", function(e) {
            e.preventDefault();
            var ip_address = $("#ip_address").val();
            $.ajax({
                url: "{{url_for('post_geolocation')}}",
                method: "POST",
                data: {
                    ip_address: ip_address
                },
                beforeSend:function(){
                    // show loader button
                    $("#geo").find(".btn-primary").html("<i class='fa fa-spinner fa-spin'></i>");
                },
                success: function(data){
                    $(".table-bordered tbody").html("");
                    var html = "";
                    html += "<tr>";
                    html += "<td><img width='100' height='100' src='"+data.flag.png+"'></td>";
                    html += "<td>"+data.ip_address+"</td>";
                    html += "<td>"+data.country+"</td>";
                    html += "<td>"+data.city+"</td>";
                    html += "<td>"+data.currency.currency_name+"</td>";
                    html += "<td>"+data.continent+"</td>";
                    html += "<td>"+data.timezone.name+"</td>";
                    html += "</tr>";
                    $(".table-bordered tbody").append(html);

                    // hide loader button
                    $("#geo").find(".btn-primary").html("Submit");
                },
                error: function(err){
                    console.log(err);
                    $("#error").html(err.error);
                    // hide loader button
                    $("#geo").find(".btn-primary").html("Submit");
                }
            })
        })
    </script>
</body>
</html>

This is a simple Bootstrap and JQuery-based webpage, which presents a form to the user to key in the IP address. Upon submitting the form, it triggers the POST /fetch-geolocation API to return and display the geolocation data in a table.

Step 5: Run the Demo Application

Now let's run the demo code. You need to open another terminal and update the environment to take into account the source file ip.py for the demo app.

For Mac and Linux:

export FLASK_APP=ip.py

For Windows:

set FLASK_APP=ip.py

Now run the command flask run to launch this demo application.

You can access the frontend web page via http://127.0.0.1:5000/gelocation

Enter a valid IP address and click on the “Submit: button. You should see the location details of this IP address in a few seconds.

Conclusion

As you just witnessed, it is easy to integrate Abstract IP Geolocation API with Python Flask. You can add more details in the frontend to show an exhaustive list of information for each IP address based on the API response.

We encourage you to modify the demo application to build more awesome apps by leveraging the Abstract API suite.

FAQs

What is IP Geolocation

IP geolocation is the process of determining the physical location and Internet connection characteristics of a web visitor based on their IP address. It contains the latitude and longitude information of the IP address, and geopolitical information such as city, state, and country names. Using the Abstract IP Geolocation API, you can even get a connection and timezone-related information about the IP addresses’ location. 

What information can be extracted from the IP Geolocation query?

The basic information returned by IP geolocation includes location, latitude and longitude, country flag, currency, and timezone. Additionally, using the Abstract IP Geolocation API, you can also fetch the type of Internet connection such as dial-up, cellular, or corporate network, along with ISP name and autonomous system number. This API also returns meta information related to location, such as timezone, and country flag.  

How Do You Perform IP Geolocation Query Using Python?

You can perform an IP Geolocation query in Python Flask by using the Python requests library to trigger the Abstract IP Geolocation API. This API returns the latitude, and longitude coordinates of the IP address, along with other information such as city, state, and country names, ISP-related information, and timezone information.

5/5 stars (10 votes)

Shyam Purkayastha
Shyam Purkayastha is a proficient web developer and PHP maestro, renowned for his expertise in API creation and integration. His deep knowledge of PHP scripting and backend development enables him to build scalable server-side applications. Shyam is particularly passionate about RESTful API design, significantly enhancing web service functionality and data interoperability.
Get your free
IP Geolocation API
API
key now
Abstract's IP Geolocation API comes with libraries, code snippets, guides, and more.
get started for free

Related Articles

Get your free
API
IP Geolocation API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required