In This Guide
- The Problem: Your App Needs to Know Where Users Are
- What an IP Geolocation API Returns
- Choosing an API: What Actually Matters
- InfoSniper API Integration Tutorial
- Common Integration Patterns
- Performance Optimization
- Accuracy Considerations for API Users
- API Security Best Practices
- Scaling Your Integration
- Frequently Asked Questions
The Problem: Your App Needs to Know Where Users Are
You are building an e-commerce checkout flow and the fraud team wants location signals. Or you are implementing GDPR consent banners that should only appear for EU visitors. Maybe you are enriching analytics events with geographic data so the marketing team can stop guessing which regions drive conversions. Whatever the trigger, the requirement is the same: given an IP address, return structured location data your application can act on.
This is not a new problem, but it is one where the gap between a working prototype and a production-ready integration is wider than most developers expect. The API call itself is trivial — a GET request with two parameters. The complexity lives in everything around it: choosing the right provider, handling edge cases, caching effectively, managing API keys securely, and understanding the accuracy boundaries so your application does not make confident decisions on uncertain data.
This guide walks through the full integration path, from your first API call to a production deployment handling thousands of lookups per day. The code examples use the InfoSniper API, but the architectural patterns apply to any IP geolocation service.
What an IP Geolocation API Returns
Before writing any code, you need to understand the data structure you are working with. An IP geolocation API takes an IP address as input and returns a set of geographic and network metadata fields. Here is what the InfoSniper JSON API returns for a lookup on Google's public DNS server (8.8.8.8):
{
"result": {
"ipaddress": "8.8.8.8",
"hostname": "dns.google",
"provider": "Google LLC",
"country": "United States",
"countrycode": "US",
"countryflag": "https://www.infosniperpro.com/country_flags/us.gif",
"state": "CA",
"city": "Mountain View",
"areacode": "650",
"postalcode": "94043",
"dmacode": "+1",
"timezone": "America/Los_Angeles",
"gmtoffset": "-08:00",
"continent": "North America",
"latitude": "37.4056",
"longitude": "-122.0775",
"queries": 9999,
"accuracy": 0
}
}
Each field serves a distinct purpose in application logic. Here is a complete reference:
| Field | Type | Description | Use Case |
|---|---|---|---|
| ipaddress | string | The queried IP address | Request validation, logging |
| hostname | string | Reverse DNS hostname | VPN/proxy detection, network identification |
| provider | string | ISP or organization name | Fraud scoring, datacenter detection |
| country | string | Full country name | Display, compliance rules |
| countrycode | string | ISO 3166-1 alpha-2 code | Geo-fencing, content routing |
| state | string | State or region code | Regional compliance, tax calculation |
| city | string | City name | Localization, analytics |
| postalcode | string | ZIP or postal code | Shipping validation, local targeting |
| timezone | string | IANA timezone identifier | Scheduling, anomaly detection |
| gmtoffset | string | UTC offset | Timestamp normalization |
| latitude | float | Geographic latitude | Map display, proximity calculations |
| longitude | float | Geographic longitude | Map display, proximity calculations |
| continent | string | Continent name | CDN routing, broad geo-fencing |
| areacode | string | Telephone area code | Phone number validation |
| dmacode | string | International dialing code | Phone number formatting |
| queries | integer | Remaining API credits | Usage monitoring, alerting |
| accuracy | integer | Accuracy radius in miles | Confidence scoring |
provider field is often more valuable for fraud detection than the geographic fields. An IP geolocated to New York but operated by "DigitalOcean" or "NordVPN" tells you more about the request's nature than the city name alone.Choosing an API: What Actually Matters
There are dozens of IP geolocation APIs available, and most comparison articles rank them on features you will never use. Here are the factors that actually matter when you are building a production integration:
Data completeness
Some APIs return only country and city. Others include ISP, hostname, timezone, postal code, and network metadata. If you need the provider field for fraud scoring or the timezone for anomaly detection, verify the API returns those fields before committing. InfoSniper's API returns 17 fields per lookup, covering geographic, network, and telephony data — which covers the requirements for most common integration patterns.
Response format and simplicity
REST APIs with JSON responses are the standard. Some providers offer only JSON; the InfoSniper API supports both JSON and XML endpoints, which matters if you are integrating with legacy systems or enterprise SOAP services. Both endpoints return identical data — choose whichever format your stack handles more naturally.
Pricing model
Pricing varies wildly. Some providers charge per lookup (typically $0.001-$0.01 per query). Others offer monthly subscriptions with tiered limits. InfoSniper uses a prepaid credit model as well as monthly subscription plans — you buy credits and each lookup consumes one. This is predictable and avoids surprise bills from traffic spikes.
Rate limits and latency
For real-time integrations (fraud checks during checkout, content personalization on page load), API response time matters. Target under 200ms for synchronous lookups. For batch processing (log enrichment, analytics), throughput matters more than per-request latency. Ask providers about rate limits before you build — discovering a 10 requests/second cap after launch is a production problem.
IPv6 support
IPv6 adoption is growing. According to Google, IPv6 traffic reached approximately 45% of its global users by late 2024. If your application handles IPv6 addresses, confirm the API supports them — not all do.
InfoSniper API Integration Tutorial
This section walks through a complete integration with the InfoSniper API, from obtaining credentials to handling responses and errors.
Step 1: Get an API key
Visit the InfoSniper pricing page and purchase API credits. Your API key is delivered via email after purchase. The key is a string that authenticates all your API requests.
Step 2: Understand the endpoints
InfoSniper provides two endpoints that return identical data in different formats:
| Format | Endpoint | Best For |
|---|---|---|
| JSON | https://www.infosniper.net/json.php | Web apps, Node.js, Python, modern APIs |
| XML | https://www.infosniper.net/xml.php | Enterprise systems, SOAP services, .NET legacy apps |
Both endpoints accept the same parameters via GET or POST:
k— your API key (required)ip_address— the IPv4 or IPv6 address to look up (required)
Step 3: Make your first API call
The simplest possible call is a curl command:
curl "https://www.infosniper.net/json.php?k=YOUR_API_KEY&ip_address=8.8.8.8"
That returns the full JSON response shown earlier. Now let us build this into real application code.
Step 4: Code examples
import requests
API_KEY = "YOUR_API_KEY"
API_URL = "https://www.infosniper.net/json.php"
def lookup_ip(ip_address):
"""Look up geolocation data for an IP address."""
try:
response = requests.get(API_URL, params={
"k": API_KEY,
"ip_address": ip_address
}, timeout=10)
response.raise_for_status()
data = response.json()
if "result" not in data:
return None
result = data["result"]
return {
"ip": result.get("ipaddress"),
"country": result.get("country"),
"country_code": result.get("countrycode"),
"state": result.get("state"),
"city": result.get("city"),
"latitude": float(result.get("latitude", 0)),
"longitude": float(result.get("longitude", 0)),
"isp": result.get("provider"),
"timezone": result.get("timezone"),
"postal_code": result.get("postalcode"),
"remaining_queries": result.get("queries")
}
except requests.RequestException as e:
print(f"API request failed: {e}")
return None
# Usage
geo = lookup_ip("8.8.8.8")
if geo:
print(f"{geo['ip']} -> {geo['city']}, {geo['country']} ({geo['isp']})")
print(f"Queries remaining: {geo['remaining_queries']}")
const API_KEY = "YOUR_API_KEY";
const API_URL = "https://www.infosniper.net/json.php";
async function lookupIP(ipAddress) {
const params = new URLSearchParams({
k: API_KEY,
ip_address: ipAddress
});
try {
const response = await fetch(`${API_URL}?${params}`, {
signal: AbortSignal.timeout(10000)
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
if (!data.result) {
return null;
}
return {
ip: data.result.ipaddress,
country: data.result.country,
countryCode: data.result.countrycode,
state: data.result.state,
city: data.result.city,
latitude: parseFloat(data.result.latitude),
longitude: parseFloat(data.result.longitude),
isp: data.result.provider,
timezone: data.result.timezone,
postalCode: data.result.postalcode,
queriesRemaining: data.result.queries
};
} catch (error) {
console.error(`Geolocation lookup failed: ${error.message}`);
return null;
}
}
// Usage
const geo = await lookupIP("8.8.8.8");
if (geo) {
console.log(`${geo.ip} -> ${geo.city}, ${geo.country} (${geo.isp})`);
}
<?php
define('API_KEY', 'YOUR_API_KEY');
define('API_URL', 'https://www.infosniper.net/json.php');
function lookupIP(string $ipAddress): ?array {
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => API_URL . '?' . http_build_query([
'k' => API_KEY,
'ip_address' => $ipAddress
]),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => true,
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200 || $response === false) {
error_log("Geolocation API failed: HTTP $httpCode");
return null;
}
$data = json_decode($response, true);
if (!isset($data['result'])) {
return null;
}
return [
'ip' => $data['result']['ipaddress'],
'country' => $data['result']['country'],
'countryCode' => $data['result']['countrycode'],
'state' => $data['result']['state'],
'city' => $data['result']['city'],
'latitude' => (float)$data['result']['latitude'],
'longitude' => (float)$data['result']['longitude'],
'isp' => $data['result']['provider'],
'timezone' => $data['result']['timezone'],
'postalCode' => $data['result']['postalcode'],
'queries' => (int)$data['result']['queries'],
];
}
// Usage
$geo = lookupIP('8.8.8.8');
if ($geo) {
echo "{$geo['ip']} -> {$geo['city']}, {$geo['country']} ({$geo['isp']})\n";
echo "Queries remaining: {$geo['queries']}\n";
}
?>
# POST request to the XML endpoint curl -X POST "https://www.infosniper.net/xml.php" \ -d "k=YOUR_API_KEY" \ -d "ip_address=8.8.8.8" # Parse specific fields with xmllint curl -s "https://www.infosniper.net/xml.php?k=YOUR_API_KEY&ip_address=8.8.8.8" \ | xmllint --xpath "//city/text()" -
Step 5: Error handling
Production integrations need to handle failure gracefully. The API may return errors for several reasons:
- Invalid API key — the
kparameter is missing, malformed, or expired - Exhausted credits — check the
queriesfield in each response; when it reaches 0, subsequent requests will fail - Invalid IP format — the
ip_addressparameter is not a valid IPv4 or IPv6 address - Network errors — timeouts, DNS failures, or connectivity issues between your server and the API
queries field in every API response tells you how many lookups remain on your key. Set up an alert when this drops below a threshold (e.g., 500 remaining) so you can purchase additional credits before running out mid-production.
Common Integration Patterns
Raw geolocation data is a building block. Here is how developers use it in practice.
Fraud scoring
The most common integration pattern is adding IP geolocation as a signal in a fraud scoring pipeline. The logic is straightforward: compare the IP's geographic data against other transaction data.
def calculate_fraud_signals(geo_data, billing_country, billing_state):
"""Extract fraud signals from geolocation data."""
signals = {
"country_mismatch": geo_data["country_code"] != billing_country,
"state_mismatch": geo_data["state"] != billing_state,
"is_datacenter": is_datacenter_provider(geo_data["isp"]),
"is_vpn_likely": is_vpn_provider(geo_data["isp"]),
}
# Higher score = higher risk (0-100)
score = 0
if signals["country_mismatch"]:
score += 40
if signals["is_datacenter"]:
score += 30
if signals["is_vpn_likely"]:
score += 20
if signals["state_mismatch"]:
score += 10
signals["risk_score"] = min(score, 100)
return signals
def is_datacenter_provider(isp_name):
"""Check if ISP is a known hosting/datacenter provider."""
datacenter_keywords = [
"amazon", "aws", "digitalocean", "linode", "vultr",
"hetzner", "ovh", "google cloud", "microsoft azure"
]
isp_lower = isp_name.lower()
return any(kw in isp_lower for kw in datacenter_keywords)
This approach treats the ISP name as a stronger fraud signal than the city. A transaction from a VPN provider in the right country is more suspicious than a residential IP in a neighboring state — the customer might be traveling, but they probably are not routing through a datacenter.
Content localization
Serve different content based on visitor location: language, currency, regional promotions, or legal disclaimers. The countrycode field is the most reliable for this because country-level accuracy exceeds 97%.
Analytics enrichment
Append geolocation data to your analytics events to answer questions like "which cities drive the most signups?" or "where do our highest-value customers connect from?" The API adds geographic context that client-side analytics tools often miss due to ad blockers and consent restrictions.
Compliance geo-fencing
Financial services, gambling platforms, and content distributors use IP geolocation to enforce geographic restrictions. If your platform must block access from sanctioned countries or restrict services to licensed jurisdictions, the countrycode field provides the first layer of enforcement. For higher-confidence decisions, combine it with other signals — billing address, phone number country code, browser language.
Performance Optimization
The single most impactful optimization for any geolocation API integration is caching. IP-to-location mappings change infrequently — an IP that resolves to Chicago today will almost certainly resolve to Chicago tomorrow. Caching aggressively reduces API calls, lowers latency, and saves costs.
Caching strategy
Use a TTL-based cache (Redis, Memcached, or even an in-memory dictionary for smaller applications). A 24-48 hour TTL is the sweet spot for most use cases: short enough to pick up IP reassignments, long enough to eliminate redundant lookups.
import redis
import json
r = redis.Redis(host="localhost", port=6379, db=0)
CACHE_TTL = 86400 # 24 hours in seconds
def lookup_ip_cached(ip_address):
"""Look up IP with Redis caching."""
cache_key = f"geo:{ip_address}"
# Check cache first
cached = r.get(cache_key)
if cached:
return json.loads(cached)
# Cache miss — call API
result = lookup_ip(ip_address) # from earlier example
if result:
r.setex(cache_key, CACHE_TTL, json.dumps(result))
return result
Batch lookups vs. real-time
Not every use case requires real-time lookups. If you are enriching analytics events or processing log files, batch the IPs and process them asynchronously. This decouples your user-facing request latency from the geolocation API's response time.
For batch processing — say, enriching thousands of log entries — InfoSniper's Bulk IP Upload tool handles up to 100 IPs per submission through the web interface. For larger volumes, loop through the API programmatically with appropriate rate limiting.
Handling rate limits gracefully
If you hit rate limits, implement exponential backoff rather than hammering the API with retries. A simple pattern: wait 1 second, then 2, then 4, up to a maximum delay. Most rate limit issues resolve within a few seconds.
Accuracy Considerations for API Users
The accuracy of geolocation data varies by resolution level and region, and understanding these boundaries prevents you from building features that over-promise. For an in-depth analysis, see our IP geolocation accuracy breakdown.
| Resolution | Accuracy | Safe to Use For | Risky to Use For |
|---|---|---|---|
| Country | 95-99% | Geo-fencing, compliance, language defaults | N/A — reliable enough for most decisions |
| Region/State | 80-90% | Tax region, regional content, analytics | State-specific legal compliance (use with fallback) |
| City | 55-80% | Analytics, general localization | Delivery estimates, precise local targeting |
| Postal Code | 30-60% | Rough area estimation only | Anything requiring zip-code precision |
VPNs, proxies, and datacenter IPs
According to data from GlobalWebIndex, over 30% of internet users access the web through a VPN at least monthly. For API users, this means a significant portion of lookups will return the VPN server's location rather than the user's actual location.
The provider field is your primary detection tool. VPN services, hosting companies, and proxy networks have recognizable ISP names. You can also cross-reference IPs against the InfoSniper IP Reputation Checker for more detailed risk assessment.
Mobile IP accuracy
Mobile carriers frequently use carrier-grade NAT (CGNAT), which maps thousands of users to a shared pool of IP addresses. The geolocation API returns the location of the carrier's NAT gateway, which may be in a different city than the user. For applications targeting mobile traffic, treat city-level data as a rough estimate and lean on country and region instead.
API Security Best Practices
Your API key is a credential. Treat it like a password.
Never expose keys client-side
Do not embed your API key in JavaScript that runs in the browser. Anyone viewing source or monitoring network requests can steal it. All geolocation API calls should originate from your server, where the key stays hidden.
<!-- DO NOT DO THIS -->
<script>
// Anyone can see this key in the page source
fetch("https://www.infosniper.net/json.php?k=YOUR_KEY&ip_address=...")
</script>
// Node.js Express — your server acts as a proxy
app.get("/api/geolocate", async (req, res) => {
const ip = req.query.ip || req.ip;
// Server-side call — key never sent to browser
const geo = await lookupIP(ip); // uses server-stored API_KEY
res.json(geo);
});
Key management
- Environment variables — store the key in
process.env.INFOSNIPER_API_KEYor equivalent, not in source code - Secrets manager — for production deployments, use AWS Secrets Manager, HashiCorp Vault, or your platform's native secrets store
- Key rotation — if a key is compromised, purchase a new one and update your configuration immediately
- Separate keys — use different keys for development, staging, and production so a leaked dev key does not drain your production credits
HTTPS only
Always use HTTPS for API calls. Both InfoSniper endpoints support HTTPS, and there is no reason to transmit your API key over unencrypted HTTP. Most HTTP client libraries default to HTTPS, but verify your configuration — especially in legacy codebases.
Scaling Your Integration
The path from prototype to production involves several predictable scaling steps.
Prototype (0-100 lookups/day)
Direct API calls, no caching, minimal error handling. This is fine for development and testing. Use the code examples from earlier in this guide as-is.
Early production (100-5,000 lookups/day)
Add a caching layer (Redis or Memcached with 24-hour TTL). Implement error handling with retries. Monitor the queries field to track credit usage. Set up alerting when credits run low.
Growth (5,000-50,000 lookups/day)
At this scale, caching becomes critical — without it, you are burning through API credits unnecessarily. Consider a dedicated geolocation microservice that handles caching, rate limiting, and failover internally. Your application code calls the microservice, which handles the API complexity.
High volume (50,000+ lookups/day)
At very high volumes, consider supplementing real-time API lookups with a local geolocation database for the most common IP ranges, using the API for cache misses and less common IPs. Contact InfoSniper about subscription plans optimized for high-volume use.
| Scale | Architecture | Key Optimization |
|---|---|---|
| Prototype | Direct API calls | None needed — focus on correctness |
| Early Production | API + Redis cache | 24h cache TTL, credit monitoring |
| Growth | Geolocation microservice | Centralized caching, circuit breakers |
| High Volume | Local DB + API hybrid | Local lookups for common IPs, API for rest |
Start Building With the InfoSniper API
Get structured geolocation data for any IP address. JSON and XML endpoints, 17 data fields per lookup, IPv4 and IPv6 support.
View API Documentation Get API CreditsFrequently Asked Questions
/json.php and /xml.php. Choose whichever format your application stack handles most easily.
provider and hostname fields in the API response. VPN providers and hosting companies have recognizable names (e.g., "NordVPN", "DigitalOcean", "Amazon Technologies"). You can also cross-reference the IP against the InfoSniper IP Reputation Checker or maintain a list of known datacenter IP ranges. For critical applications, combine geolocation with other signals like browser timezone versus IP timezone mismatches.
Sources
- Google — "IPv6 Adoption Statistics" — google.com
- MaxMind — "GeoIP2 City Accuracy" — maxmind.com
- DB-IP — "IP Geolocation Accuracy Benchmarks" — db-ip.com
- GlobalWebIndex — "VPN Usage and Adoption Worldwide" — gwi.com
- RIPE NCC — "How IP Addresses Are Allocated and Managed" — ripe.net
- InfoSniper — "IP Geolocation API Documentation" — infosniper.net