Code Examples
Ready-to-use code snippets for integrating IPBot into your application.
Basic Lookup (Anonymous)
Section titled “Basic Lookup (Anonymous)”# Lookup a specific IPcurl -s https://api.ipbot.com/8.8.8.8 | jq
# Auto-detect your IPcurl -s https://api.ipbot.com/ | jq
# Lookup via query parametercurl -s "https://api.ipbot.com/api?ip=8.8.8.8" | jqWith API Key (Higher Limits)
Section titled “With API Key (Higher Limits)”# 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 headerscurl -sI -H "X-API-Key: ipb_free_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" \ https://api.ipbot.com/8.8.8.8 | grep -i x-ratelimitExtract Specific Fields
Section titled “Extract Specific Fields”# Get country code onlycurl -s https://api.ipbot.com/8.8.8.8 | jq -r '.location.country_code'
# Get risk scorecurl -s https://api.ipbot.com/8.8.8.8 | jq -r '.security.risk_score'
# Check if IP is a datacentercurl -s https://api.ipbot.com/8.8.8.8 | jq -r '.security.is_datacenter'
# Get all threat listscurl -s https://api.ipbot.com/8.8.8.8 | jq -r '.security.threat_lists[]'
# Get ASN infocurl -s https://api.ipbot.com/8.8.8.8 | jq -r '.network.asn, .network.org'ASN Lookup
Section titled “ASN Lookup”# Lookup ASN detailscurl -s https://api.ipbot.com/asn/15169 | jqcurl -s https://api.ipbot.com/asn/AS15169 | jqJavaScript / TypeScript
Section titled “JavaScript / TypeScript”Basic Fetch (Anonymous)
Section titled “Basic Fetch (Anonymous)”// Lookup a specific IPconst response = await fetch("https://api.ipbot.com/8.8.8.8");const data = await response.json();console.log(data);
// Auto-detect caller IPconst myIP = await fetch("https://api.ipbot.com/").then((r) => r.json());console.log("My IP:", myIP.ip);With API Key
Section titled “With API Key”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);With Error Handling and Retry
Section titled “With Error Handling and Retry”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");}Simple Cache Wrapper
Section titled “Simple Cache Wrapper”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;}Node.js with Axios
Section titled “Node.js with Axios”import axios from "axios";
const ipbot = axios.create({ baseURL: "https://api.ipbot.com", headers: { "X-API-Key": process.env.IPBOT_API_KEY, },});
// Lookup IPconst { data } = await ipbot.get("/8.8.8.8");console.log(data);
// Auto-detect IPconst myData = await ipbot.get("/");console.log("My IP:", myData.data.ip);
// Check if IP is riskyfunction isRiskyIP(data) { return ( data.security.risk_score >= 50 || data.security.is_proxy || data.security.threat_lists.length > 0 );}Python
Section titled “Python”Basic Request (Anonymous)
Section titled “Basic Request (Anonymous)”import requests
# Lookup a specific IPresponse = requests.get('https://api.ipbot.com/8.8.8.8')data = response.json()print(data)
# Auto-detect your IPmy_ip = requests.get('https://api.ipbot.com/').json()print(f"My IP: {my_ip['ip']}")With API Key
Section titled “With API Key”import osimport 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']}")With Retry Logic
Section titled “With Retry Logic”import timeimport requestsfrom requests.adapters import HTTPAdapterfrom 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
# Usagesession = create_session(api_key='ipb_free_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')data = session.get('https://api.ipbot.com/8.8.8.8').json()print(data)Simple Caching with functools
Section titled “Simple Caching with functools”from functools import lru_cacheimport 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 APIdata1 = lookup_ip_cached('8.8.8.8')
# Second call - returns cached resultdata2 = lookup_ip_cached('8.8.8.8')Async with aiohttp
Section titled “Async with aiohttp”import aiohttpimport 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 concurrentlyasync 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)
# Usageasync 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())Risk Assessment Helper
Section titled “Risk Assessment Helper”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' }
# Usagedata = requests.get('https://api.ipbot.com/8.8.8.8').json()risk = assess_risk(data)print(f"Recommendation: {risk['recommendation']}")Basic Request
Section titled “Basic Request”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)}With API Key and Rate Limit Headers
Section titled “With API Key and Rate Limit Headers”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)}Basic Request
Section titled “Basic Request”<?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');With cURL
Section titled “With cURL”<?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
# Usagedata = lookup_ip('8.8.8.8')puts "Country: #{data['location']['country']}"puts "Risk Score: #{data['security']['risk_score']}"
# With API keydata = lookup_ip('8.8.8.8', api_key: ENV['IPBOT_API_KEY'])Next Steps
Section titled “Next Steps”- API Reference - Complete endpoint documentation
- Response Schema - Field-by-field response details
- Rate Limits - Caching strategies and best practices
- Integration Guides - Framework-specific tutorials