Geolocate IP Addresses with Python and IPinfo

Feb 3, 2024 ยท 2 min read

When building location-aware applications in Python, it's often useful to map IP addresses to countries. The IPinfo API provides a simple way to geolocate IP addresses without needing to compile or maintain your own IP geolocation database.

In this tutorial, we'll use the IPinfo API and the Python requests library to lookup the country for an IP address.

Getting an IPinfo API Access Token

To use the IPinfo API, you'll need to sign up for a free access token. This will allow up to 50,000 requests per month. Higher usage limits are available for paid plans.

Once you have your token, save it to an environment variable or configuration file to load into your Python code.

Making Requests with the IPinfo API

Here is how to use Python requests to call the IPinfo API and lookup the country for the IP address 8.8.8.8:

import requests

IPINFO_TOKEN = "123456789abc" 

ip_address = '8.8.8.8'
url = f'https://ipinfo.io/{ip_address}/country'

headers = {'Authorization': f'Bearer {IPINFO_TOKEN}'}

response = requests.get(url, headers=headers)
print(response.text)
# "US" 

We make a GET request to the /country endpoint for that IP address, passing our access token in the Authorization header.

The API returns the two-letter country code for that IP address. Simple!

Handling Errors

Be sure to check the response status and handle any errors. The API will return helpful messages if there are issues with authorization or invalid requests.

By leveraging IPinfo's API in Python, you can easily add IP geolocation and customization based on the user's country to your Python applications.

Browse by tags:

Browse by language:

Tired of getting blocked while scraping the web?

ProxiesAPI handles headless browsers and rotates proxies for you.
Get access to 1,000 free API credits, no credit card required!