How to Get Location Information of an IP Address Using Python

A tutorial on how to fetch location information of an IP address using Requests and Python.

Get your tools ready

  1. ipify: This API will help us know the IP address from where the request is coming.
  2. ipapi: This API will help us fetch location information for a particular IP address.
$ pip install requests

Get Location Information

import requestsdef get_ip():
    response = requests.get('https://api64.ipify.org?format=json').json()
    return response["ip"]def get_location():
    ip_address = get_ip()
    response = requests.get(f'https://ipapi.co/{ip_address}/json/').json()
    location_data = {
        "ip": ip_address,
        "city": response.get("city"),
        "region": response.get("region"),
        "country": response.get("country_name")
    }
    return location_dataprint(get_location())

get_ip() function

{
  "ip": "117.214.109.137"
}

get_location() function

{
  "ip": "117.214.109.137",
  "version": "IPv4",
  "city": "Gaya",
  "region": "Bihar",
  "region_code": "BR",
  "country": "IN",
  "country_name": "India",
  "country_code": "IN",
  "country_code_iso3": "IND",
  "country_capital": "New Delhi",
  "country_tld": ".in",
  "continent_code": "AS",
  "in_eu": false,
  "postal": "823002",
  "latitude": 24.7935,
  "longitude": 85.012,
  "timezone": "Asia/Kolkata",
  "utc_offset": "+0530",
  "country_calling_code": "+91",
  "currency": "INR",
  "currency_name": "Rupee",
  "languages": "en-IN,hi,bn,te,mr,ta,ur,gu,kn,ml,or,pa,as,bh,sat,ks,ne,sd,kok,doi,mni,sit,sa,fr,lus,inc",
  "country_area": 3287590,
  "country_population": 1352617328,
  "asn": "AS9829",
  "org": "National Internet Backbone"
}
{
  "ip": "117.214.109.137", 
  "city": "Gaya", 
  "region": "Bihar", 
  "country": "India"
}

Conclusion

Exit mobile version