import requests
API_KEY = 'YOUR_API_KEY'
response = requests.get(
'https://api.api-ninjas.com/v1/iplookup',
params={'address': '24.48.0.1'},
headers={'X-Api-Key': API_KEY},
)
print(response.json())Prerequisites
- Python 3.7+ installed
- The
requestslibrary (pip install requests) - A free API Ninjas API key
Step 1: Get your API key
Sign up at api-ninjas.com/register.
Step 2: Make the API request
import requests
API_KEY = 'YOUR_API_KEY'
response = requests.get(
'https://api.api-ninjas.com/v1/iplookup',
params={'address': '24.48.0.1'},
headers={'X-Api-Key': API_KEY},
)
print(response.json())Step 3: Use the response
{
"address": "24.48.0.1",
"is_valid": true,
"country": "Canada",
"country_code": "CA",
"region": "Quebec",
"city": "Montreal",
"zip": "H1S",
"lat": 45.5808,
"lon": -73.5825,
"timezone": "America/Toronto",
"isp": "Le Groupe Videotron Ltee"
}Complete example
import os
import requests
API_KEY = os.environ['API_NINJAS_KEY']
URL = 'https://api.api-ninjas.com/v1/iplookup'
def lookup_ip(ip: str) -> dict:
response = requests.get(
URL,
params={'address': ip},
headers={'X-Api-Key': API_KEY},
timeout=10,
)
response.raise_for_status()
return response.json()
if __name__ == '__main__':
info = lookup_ip('24.48.0.1')
print(f"Country: {info['country']}")
print(f"Region: {info['region']}")
print(f"City: {info['city']}")
print(f"Lat/Lon: {info['lat']}, {info['lon']}")
print(f"Timezone: {info['timezone']}")
print(f"ISP: {info['isp']}")Looking up IPs from a log file
To geolocate visitors from a web-server access log:
import re
LOG_LINE = re.compile(r'^(\S+)\s')
ips = set()
with open('access.log') as f:
for line in f:
match = LOG_LINE.match(line)
if match:
ips.add(match.group(1))
for ip in ips:
info = lookup_ip(ip)
print(f"{ip:15} {info['country']:20} {info['city']}")For large logs, deduplicate IPs first (as shown) and consider caching results in a local SQLite database to avoid repeat lookups.
Error handling
from requests.exceptions import HTTPError
try:
info = lookup_ip('not-an-ip')
except HTTPError as e:
if e.response.status_code == 400:
print('Invalid IP address format')
elif e.response.status_code == 401:
print('Invalid or missing API key')
elif e.response.status_code == 429:
print('Rate limit exceeded')Related APIs
Combine IP Lookup with the Geocoding API, Timezone API, or Weather API to build IP-aware features in your app.