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:

The easiest way to do Web Scraping

Get HTML from any page with a simple API call. We handle proxy rotation, browser identities, automatic retries, CAPTCHAs, JavaScript rendering, etc automatically for you


Try ProxiesAPI for free

curl "http://api.proxiesapi.com/?key=API_KEY&url=https://example.com"

<!doctype html>
<html>
<head>
    <title>Example Domain</title>
    <meta charset="utf-8" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
...

X

Don't leave just yet!

Enter your email below to claim your free API key: