Guides
Last updated
August 3, 2023

How to Perform IP Geolocation Query using the Python Flask Framework

Shyam Purkayastha

Table of Contents:

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
IP Geolocation
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=')
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.








integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">



integrity="sha512-5A8nwdMOWrSz20fDsjczgUidUBR8liPYU+WymTZP1lmY9G6Oc7HlZv156XqnsgNUzTyMefFTcsFH/tnJE/+xBg=="
crossorigin="anonymous" referrerpolicy="no-referrer" />
IP Geolocation API





IP Geolocation API




























Flag IP Address Country Name City Country Currency Continent Timezone








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.

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
key now
See why the best developers build on Abstract
get started for free

Related Articles

Get your free
IP Geolocation
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