IP Coordinates API
You need to geolocate an IP address and reliably extract its latitude and longitude so you can power features like location-aware content, analytics, mapping, and risk controls. By the end of this guide, you’ll be able to call the ipXapi IP Coordinates API, authenticate correctly, parse the official response, and productionize your integration with caching, retries, and guardrails.
What the IP Coordinates API provides
The IP Coordinates API returns geolocation data for a given IP address. For integration work focused on maps or distance calculations, the key fields are the numeric latitude and longitude. The same response also includes country, region, city, timezone, and network descriptors you can use for display or policy decisions.
This guide focuses on extracting lat and lon from a single endpoint and ensuring your application handles common operational concerns for geolocation: caching, variability across networks, and timezones.
Access, pricing, and where to start
You can create an account and obtain an API key here: Register. A free trial is available for 7 days or 50 requests, and the Basic plan is $29.99/mo. Consult the product pages for full details before moving to production.
For reference materials and up-to-date parameter notes, see the Documentation. If you manage multiple environments or need an administrative plane, visit MCP.
Endpoint and authentication
The geolocation lookup lives at the following path:
- Path: /api/ip
- HTTP: GET
- Query: ip (the IP address to look up)
- Auth: Authorization: Bearer YOUR_API_KEY
Include the Authorization header and request JSON. Below is the official cURL you can copy and run after substituting your key:
curl "https://ipxapi.com/api/ip?ip=148.105.12.120" -H "Accept: application/json" -H "Authorization: Bearer YOUR_KEY"
Here is the official product-fixture JSON for that IP. Use this for development, testing, and field mapping. Live values can differ in production, but the structure and keys (including lat and lon) remain consistent.
{
"status": "success",
"country": "United States",
"countryCode": "US",
"region": "US-CA",
"regionName": "California",
"city": "Mountain View",
"zip": "94043",
"lat": 37.40599,
"lon": -122.0786,
"timezone": "America/Los_Angeles",
"isp": "MailChimp",
"org": "MailChimp",
"as": "AS14782 MailChimp",
"query": "148.105.12.120",
"inEU": false,
"continentCode": "NA",
"security": {
"is_proxy": false,
"is_vpn": false,
"is_cloud_provider": true
}
}
Fields you’ll typically use for geolocation workflows:
- lat: latitude as a floating-point number
- lon: longitude as a floating-point number
- timezone: a canonical IANA string (e.g., America/Los_Angeles) for localizing times
- country, regionName, city: textual geolocation descriptors for UI display or rules
Minimal Python example to extract coordinates
The snippet below calls the same endpoint, reads lat and lon, and includes simple handling for non-success responses. Replace YOUR_API_KEY with your actual token when testing.
import json
import sys
import time
from urllib.parse import urlencode
import urllib.request
API_BASE = "https://ipxapi.com/api/ip"
def lookup_ip(ip_addr, api_key, timeout=5.0):
url = f"{API_BASE}?{urlencode({'ip': ip_addr})}"
req = urllib.request.Request(url, headers={
"Accept": "application/json",
"Authorization": "Bearer YOUR_API_KEY"
})
with urllib.request.urlopen(req, timeout=timeout) as resp:
data = resp.read().decode("utf-8")
return json.loads(data)
def main():
ip = "148.105.12.120" # documented fixture IP for development
try:
payload = lookup_ip(ip, "YOUR_API_KEY")
except Exception as e:
print(f"Request failed: {e}", file=sys.stderr)
sys.exit(2)
status = payload.get("status")
if status != "success":
print(f"Lookup not successful. Raw payload: {payload}", file=sys.stderr)
sys.exit(1)
lat = payload.get("lat")
lon = payload.get("lon")
tz = payload.get("timezone")
if lat is None or lon is None:
print(f"Coordinates missing. Raw payload: {payload}", file=sys.stderr)
sys.exit(1)
print(f"IP {payload.get('query')} => lat={lat}, lon={lon}, tz={tz}")
if __name__ == "__main__":
main()
Notes:
- The Authorization header uses the Bearer scheme. Substitute YOUR_API_KEY with your real key.
- The fixture IP 148.105.12.120 is provided for development consistency. Do not treat it as the user’s or server’s own IP.
Computing distances with the returned coordinates
If your use case involves distance-based logic, you can apply the haversine formula to the lat and lon values. The inputs should be decimal degrees; convert to radians within your code before applying trigonometric functions. For UI elements (e.g., map pins), lat and lon can be fed directly into most mapping libraries or server-side renderers.
Units: The latitude and longitude are unitless angles in decimal degrees. Distances computed from them depend on your chosen earth radius constant; many implementations use kilometers (R ≈ 6371.0088 km) or miles (R ≈ 3958.7613 mi). Choose one unit system and keep it consistent across your application.
Timezone handling
The timezone field is an IANA identifier you can pass to standard libraries for local time calculations, scheduling, or analytics bucketing. Treat it as advisory for the IP’s approximate location; if you are logging events, always store UTC timestamps and convert at the presentation layer using the provided timezone string.
Caching to control latency and cost
Responses for the same IP typically do not change minute-to-minute. To reduce network overhead and request volume, cache lookups per IP in your application or edge for a short TTL (for example, several hours). Choose a TTL that matches your freshness requirements: shorter for dynamic access control, longer for analytics batch jobs.
Use a simple key like ipx:geo:{ip} in your cache store and invalidate on demand when you detect major network changes (e.g., user has switched networks or is on a mobile carrier with changing egress points). Avoid caching sensitive user associations beyond your stated retention policy.
Error handling and resilience
Plan for intermittent network errors and implement bounded retries with small backoff. For critical paths where you still need to proceed without a successful lookup, fall back to a safe default (e.g., skip personalization) instead of blocking the user flow.
Validation: Ensure you check payload.get("status") and verify that lat and lon are present before acting on the result. Log the response body for troubleshooting when status is not successful, and consider surfacing the query IP and a correlation ID from your logs to aid incident response.
Dealing with proxies, VPNs, and clouds
The security object includes booleans (e.g., is_proxy, is_vpn, is_cloud_provider) that can inform your policies. Treat these flags as signals, not absolute truth, and layer them with other checks in your system. Because live flags can change, avoid persisting them indefinitely; re-resolve as needed.
Development and testing workflow
Start by integrating the fixture IP 148.105.12.120 to validate your parsing and mapping. Build unit tests that assert the presence and type of lat and lon rather than exact numeric values (prod data can differ). For end-to-end tests, inject known IPs via configuration so your CI can run without hitting rate or trial limits unnecessarily.
When moving to staging and production, monitor latency and error rates. Depending on your architecture, a short client-side timeout (3–5 seconds) is a reasonable starting point; pair it with retries on idempotent GETs. Log the round-trip time of each call to help you tune caching and concurrency.
Operational tips that save time
- Normalization: Always store coordinates as floats in decimal degrees. Avoid string formatting or rounding until display time.
- Ordering: The pair is lat, lon (not lon, lat). Many libraries accept both orders; be explicit to prevent subtle bugs.
- Coordinate bounds: Validate that -90 ≤ lat ≤ 90 and -180 ≤ lon ≤ 180 when accepting inputs or before writing to your DB.
- Idempotency: The GET /api/ip call is safe to repeat on transient errors under your retry policy.
- Rate planning: Use your cache hit ratio to plan how many direct API calls you’ll make vs. your trial and plan thresholds.
Security and privacy considerations
Store API keys outside your repository (e.g., secrets manager or environment variables) and inject them into your application at runtime. Restrict who can read logs that may contain user IPs. If you present location-based features, provide transparency in your privacy notice and allow users to opt out where required.
Environment management with MCP
If you operate multiple projects or regions, use MCP as the management control plane for environment separation and administrative tasks. Keep keys scoped to the minimal set of services that need them, and rotate them on a regular cadence.
Putting it together
With a single GET to /api/ip, you can geolocate an IP address and extract lat and lon for mapping, analytics, and policy. Combine a short-lived cache, defensive parsing, and retries to keep your integration robust. When in doubt about a field or the latest behavior, consult the Documentation.
FAQ
Q: Which endpoint should I use to get coordinates?
A: Use GET /api/ip with the ip query parameter. Authenticate with Authorization: Bearer YOUR_API_KEY.
Q: Which fields contain the coordinates?
A: lat and lon. They are floating-point decimal degrees suitable for mapping and distance calculations.
Q: Can I treat the documented fixture IP as a user’s live IP?
A: No. The documented fixture IP 148.105.12.120 is for development and testing only. Live data varies by user and network.
Q: How should I handle timezones returned by the API?
A: Use the timezone field as an IANA identifier for localizing display times. Keep event storage in UTC and convert at render time.
Q: What are the trial and plan details I should know before production?
A: The trial is 7 days or 50 requests. The Basic plan is $29.99/mo. Review the product pages for any updates before launching.
Ready to add geolocation to your app? Create your key and try the IP Coordinates API now: Register.
