NewConnect Claude, Cursor, ChatGPT, and other AI agents to API Ninjas via our MCP server

How to Get IP Geolocation in Python

IP Lookup APIUpdated May 23, 2026
To geolocate an IP address in Python, send a GET request to the API Ninjas IP Lookup endpoint with the address as a query parameter:
ip.py
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

Step 1: Get your API key

Sign up at api-ninjas.com/register.

Step 2: Make the API request

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

JSON
{
  "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

ip.py
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:

Python
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

Python
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')

Combine IP Lookup with the Geocoding API, Timezone API, or Weather API to build IP-aware features in your app.

Frequently asked questions

Does the API support IPv6?

Yes. Both IPv4 and IPv6 addresses are supported. Pass the address as the address query parameter.

How accurate is the geolocation data?

City-level accuracy is typically 80%+ for IPv4 addresses in well-mapped regions (North America, Europe). Country-level accuracy is 99%+ globally.

Can I look up my own IP?

Yes — first fetch your public IP from a service like ipify, then pass it to the IP Lookup endpoint.

Does the API return ISP and ASN information?

Yes. The response includes isp (Internet Service Provider name) along with city, region, country, coordinates, and timezone.

Is there a free tier?

Yes. Every API Ninjas account includes a free tier — no credit card required.