Best IP Geolocation API to detect client location

Best IP Geolocation API to detect client location

The progression of geolocation technology has made it possible for us to locate things via the internet. Whether it is locating your lost pet with its GPS embedded collar or finding your favorite restaurant, geolocation has graduated to become an imperative technology for everyday living. Besides, the technology has evolved and is now used on a bigger scale by enterprises to identify and target consumers based on location.

However, before we delve deep into the core aspects of this technology, let’s break it down.

What is IP Geolocation?

Geolocation is the identification or designation of the geographic location of an item, such as a mobile phone, radar source, or internet-connected computer. In that sense, IP Geolocation can be defined as the technique used to map a particular IP address to a geographic location from where the device is connecting to the internet. Through this technology, individuals or organizations can identify or estimate the real-world location of a device that you are using to connect to the internet. This technique provides your device’s location details such as the country, state city, latitude/longitude, zip code, and even the street if fine-tuned further.

Here we are going to use IP-API

IP Geolocation API Fast, accurate, reliable

https://ip-api.com/

class Helper:
   @staticmethod 
   def get_client_ip(request): 
     x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if 
     x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = 
     request.META.get('REMOTE_ADDR') 
     return ip
   def get_location(request): 
     # ip_address = Helper.get_ip(clientAddress) ip_address = 
     Helper.get_client_ip(request)  
     print('ip_address' , ip_address) 
     response = requests.get(f'https://ipapi.co/{ip_address}/json/').json() 
     # response = requests.get(f'http://ipinfo.io/json') 
     # print('response' , response.data) 
     # location_data = {} 
     location_data = { 
         "ip": ip_address, 
         "city": response.get("city"), 
         "region": response.get("region"), 
         "country": response.get("country_name") 
      }
     # print('location_data' , location_data) 
     
     return location_data

Leave a Reply