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
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
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.