Skip to content
IP IPBot
Get Started

Code Examples

Ready-to-use code snippets for integrating IPBot into your application.

Terminal window
# Lookup a specific IP
curl -s https://api.ipbot.com/8.8.8.8 | jq
# Auto-detect your IP
curl -s https://api.ipbot.com/ | jq
# Lookup via query parameter
curl -s "https://api.ipbot.com/api?ip=8.8.8.8" | jq
Terminal window
# With API key for 200 req/min (free tier) or 600 req/min (pro tier)
curl -s -H "X-API-Key: ipb_free_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" \
https://api.ipbot.com/8.8.8.8 | jq
# Check rate limit headers
curl -sI -H "X-API-Key: ipb_free_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" \
https://api.ipbot.com/8.8.8.8 | grep -i x-ratelimit
Terminal window
# Get country code only
curl -s https://api.ipbot.com/8.8.8.8 | jq -r '.location.country_code'
# Get risk score
curl -s https://api.ipbot.com/8.8.8.8 | jq -r '.security.risk_score'
# Check if IP is a datacenter
curl -s https://api.ipbot.com/8.8.8.8 | jq -r '.security.is_datacenter'
# Get all threat lists
curl -s https://api.ipbot.com/8.8.8.8 | jq -r '.security.threat_lists[]'
# Get ASN info
curl -s https://api.ipbot.com/8.8.8.8 | jq -r '.network.asn, .network.org'
Terminal window
# Lookup ASN details
curl -s https://api.ipbot.com/asn/15169 | jq
curl -s https://api.ipbot.com/asn/AS15169 | jq

// Lookup a specific IP
const response = await fetch("https://api.ipbot.com/8.8.8.8");
const data = await response.json();
console.log(data);
// Auto-detect caller IP
const myIP = await fetch("https://api.ipbot.com/").then((r) => r.json());
console.log("My IP:", myIP.ip);
const API_KEY = "ipb_free_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
async function lookupIP(ip) {
const response = await fetch(`https://api.ipbot.com/${ip}`, {
headers: {
"X-API-Key": API_KEY,
},
});
// Check rate limit headers
const remaining = response.headers.get("X-RateLimit-Remaining");
const limit = response.headers.get("X-RateLimit-Limit");
console.log(`Rate limit: ${remaining}/${limit}`);
if (!response.ok) {
const error = await response.json();
throw new Error(`${error.code}: ${error.error}`);
}
return response.json();
}
const data = await lookupIP("8.8.8.8");
console.log(data.location.country);
async function lookupIPWithRetry(ip, maxRetries = 3) {
const API_KEY = process.env.IPBOT_API_KEY;
for (let attempt = 0; attempt < maxRetries; attempt++) {
const response = await fetch(`https://api.ipbot.com/${ip}`, {
headers: API_KEY ? { "X-API-Key": API_KEY } : {},
});
if (response.status === 429) {
// Rate limited - wait and retry
const retryAfter = response.headers.get("X-RateLimit-Reset");
const waitMs = retryAfter
? (parseInt(retryAfter) - Date.now() / 1000) * 1000
: Math.pow(2, attempt) * 1000;
console.log(`Rate limited, waiting ${waitMs}ms...`);
await new Promise((r) => setTimeout(r, Math.max(waitMs, 1000)));
continue;
}
const data = await response.json();
if (data.error) {
throw new Error(`${data.code}: ${data.error}`);
}
return data;
}
throw new Error("Max retries exceeded");
}
const cache = new Map();
const CACHE_TTL = 24 * 60 * 60 * 1000; // 24 hours
async function lookupIPCached(ip) {
const cached = cache.get(ip);
if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
return cached.data;
}
const data = await fetch(`https://api.ipbot.com/${ip}`).then((r) => r.json());
cache.set(ip, { data, timestamp: Date.now() });
return data;
}
import axios from "axios";
const ipbot = axios.create({
baseURL: "https://api.ipbot.com",
headers: {
"X-API-Key": process.env.IPBOT_API_KEY,
},
});
// Lookup IP
const { data } = await ipbot.get("/8.8.8.8");
console.log(data);
// Auto-detect IP
const myData = await ipbot.get("/");
console.log("My IP:", myData.data.ip);
// Check if IP is risky
function isRiskyIP(data) {
return (
data.security.risk_score >= 50 ||
data.security.is_proxy ||
data.security.threat_lists.length > 0
);
}

import requests
# Lookup a specific IP
response = requests.get('https://api.ipbot.com/8.8.8.8')
data = response.json()
print(data)
# Auto-detect your IP
my_ip = requests.get('https://api.ipbot.com/').json()
print(f"My IP: {my_ip['ip']}")
import os
import requests
API_KEY = os.environ.get('IPBOT_API_KEY')
HEADERS = {'X-API-Key': API_KEY} if API_KEY else {}
def lookup_ip(ip: str) -> dict:
response = requests.get(
f'https://api.ipbot.com/{ip}',
headers=HEADERS
)
# Check rate limit headers
remaining = response.headers.get('X-RateLimit-Remaining')
limit = response.headers.get('X-RateLimit-Limit')
print(f'Rate limit: {remaining}/{limit}')
response.raise_for_status()
return response.json()
data = lookup_ip('8.8.8.8')
print(f"Country: {data['location']['country']}")
print(f"Risk Score: {data['security']['risk_score']}")
import time
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
def create_session(api_key: str = None) -> requests.Session:
"""Create a session with retry logic."""
session = requests.Session()
retries = Retry(
total=3,
backoff_factor=1,
status_forcelist=[429, 500, 502, 503, 504],
allowed_methods=['GET']
)
adapter = HTTPAdapter(max_retries=retries)
session.mount('https://', adapter)
if api_key:
session.headers['X-API-Key'] = api_key
return session
# Usage
session = create_session(api_key='ipb_free_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
data = session.get('https://api.ipbot.com/8.8.8.8').json()
print(data)
from functools import lru_cache
import requests
@lru_cache(maxsize=1000)
def lookup_ip_cached(ip: str) -> dict:
"""Lookup IP with in-memory caching."""
response = requests.get(f'https://api.ipbot.com/{ip}')
response.raise_for_status()
return response.json()
# First call - fetches from API
data1 = lookup_ip_cached('8.8.8.8')
# Second call - returns cached result
data2 = lookup_ip_cached('8.8.8.8')
import aiohttp
import asyncio
async def lookup_ip_async(ip: str, api_key: str = None) -> dict:
headers = {'X-API-Key': api_key} if api_key else {}
async with aiohttp.ClientSession() as session:
async with session.get(
f'https://api.ipbot.com/{ip}',
headers=headers
) as response:
return await response.json()
# Batch lookup multiple IPs concurrently
async def batch_lookup(ips: list[str], api_key: str = None) -> list[dict]:
tasks = [lookup_ip_async(ip, api_key) for ip in ips]
return await asyncio.gather(*tasks)
# Usage
async def main():
ips = ['8.8.8.8', '1.1.1.1', '9.9.9.9']
results = await batch_lookup(ips)
for ip, data in zip(ips, results):
print(f"{ip}: {data['location']['country']}")
asyncio.run(main())
def assess_risk(data: dict) -> dict:
"""Analyze IP risk based on IPBot response."""
security = data.get('security', {})
return {
'ip': data.get('ip'),
'risk_score': security.get('risk_score', 0),
'is_risky': security.get('risk_score', 0) >= 50,
'is_datacenter': security.get('is_datacenter', False),
'is_proxy': security.get('is_proxy', False),
'on_threat_list': len(security.get('threat_lists', [])) > 0,
'threat_lists': security.get('threat_lists', []),
'reasons': security.get('risk_reasons', []),
'recommendation': 'block' if security.get('risk_score', 0) >= 70 else
'challenge' if security.get('risk_score', 0) >= 40 else
'allow'
}
# Usage
data = requests.get('https://api.ipbot.com/8.8.8.8').json()
risk = assess_risk(data)
print(f"Recommendation: {risk['recommendation']}")

package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
)
type IPBotResponse struct {
IP string `json:"ip"`
Location struct {
Country string `json:"country"`
CountryCode string `json:"country_code"`
City string `json:"city"`
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
} `json:"location"`
Network struct {
ASN string `json:"asn"`
Org string `json:"org"`
} `json:"network"`
Security struct {
RiskScore int `json:"risk_score"`
IsDatacenter bool `json:"is_datacenter"`
IsProxy bool `json:"is_proxy"`
ThreatLists []string `json:"threat_lists"`
} `json:"security"`
}
func LookupIP(ip string) (*IPBotResponse, error) {
resp, err := http.Get("https://api.ipbot.com/" + ip)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var data IPBotResponse
if err := json.Unmarshal(body, &data); err != nil {
return nil, err
}
return &data, nil
}
func main() {
data, err := LookupIP("8.8.8.8")
if err != nil {
panic(err)
}
fmt.Printf("IP: %s, Country: %s, Risk: %d\n",
data.IP, data.Location.Country, data.Security.RiskScore)
}
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
)
type IPBotClient struct {
APIKey string
Client *http.Client
}
func NewClient(apiKey string) *IPBotClient {
return &IPBotClient{
APIKey: apiKey,
Client: &http.Client{},
}
}
func (c *IPBotClient) Lookup(ip string) (*IPBotResponse, error) {
req, err := http.NewRequest("GET", "https://api.ipbot.com/"+ip, nil)
if err != nil {
return nil, err
}
if c.APIKey != "" {
req.Header.Set("X-API-Key", c.APIKey)
}
resp, err := c.Client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// Log rate limit headers
fmt.Printf("Rate Limit: %s/%s\n",
resp.Header.Get("X-RateLimit-Remaining"),
resp.Header.Get("X-RateLimit-Limit"))
var data IPBotResponse
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
return nil, err
}
return &data, nil
}
func main() {
client := NewClient(os.Getenv("IPBOT_API_KEY"))
data, err := client.Lookup("8.8.8.8")
if err != nil {
panic(err)
}
fmt.Printf("Country: %s\n", data.Location.Country)
}

<?php
function lookupIP(string $ip, ?string $apiKey = null): array {
$url = "https://api.ipbot.com/{$ip}";
$opts = [
'http' => [
'method' => 'GET',
'header' => $apiKey ? "X-API-Key: {$apiKey}\r\n" : '',
]
];
$context = stream_context_create($opts);
$response = file_get_contents($url, false, $context);
return json_decode($response, true);
}
// Usage
$data = lookupIP('8.8.8.8');
echo "Country: " . $data['location']['country'] . "\n";
echo "Risk Score: " . $data['security']['risk_score'] . "\n";
// With API key
$data = lookupIP('8.8.8.8', 'ipb_free_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
<?php
function lookupIPWithCurl(string $ip, ?string $apiKey = null): array {
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => "https://api.ipbot.com/{$ip}",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $apiKey ? ["X-API-Key: {$apiKey}"] : [],
CURLOPT_HEADER => true,
]);
$response = curl_exec($ch);
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headers = substr($response, 0, $headerSize);
$body = substr($response, $headerSize);
curl_close($ch);
// Parse rate limit headers
preg_match('/X-RateLimit-Remaining: (\d+)/', $headers, $remaining);
preg_match('/X-RateLimit-Limit: (\d+)/', $headers, $limit);
if ($remaining && $limit) {
echo "Rate limit: {$remaining[1]}/{$limit[1]}\n";
}
return json_decode($body, true);
}
$data = lookupIPWithCurl('8.8.8.8', getenv('IPBOT_API_KEY'));
print_r($data);

require 'net/http'
require 'json'
def lookup_ip(ip, api_key: nil)
uri = URI("https://api.ipbot.com/#{ip}")
request = Net::HTTP::Get.new(uri)
request['X-API-Key'] = api_key if api_key
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
http.request(request)
end
# Log rate limit info
remaining = response['X-RateLimit-Remaining']
limit = response['X-RateLimit-Limit']
puts "Rate limit: #{remaining}/#{limit}" if remaining
JSON.parse(response.body)
end
# Usage
data = lookup_ip('8.8.8.8')
puts "Country: #{data['location']['country']}"
puts "Risk Score: #{data['security']['risk_score']}"
# With API key
data = lookup_ip('8.8.8.8', api_key: ENV['IPBOT_API_KEY'])