IP Geolocation API: City, ASN, and VPN Flags
You need reliable IP geolocation to route traffic, customize content, or block fraud, and you want concrete fields like city, ASN, and VPN usage flags without guessing how to call the API or handle edge cases. By the end of this article you’ll know how to request ipXapi’s IP Geolocation endpoint, interpret the response (including the official sample), account for missing values, and ship a production-ready integration.
What you get from the IP Geolocation endpoint
ipXapi provides city-level geolocation, autonomous system information (ASN), and indicators related to VPN usage, along with network and hostname details, via a single GET endpoint that looks up any public IP. These fields are returned in one JSON object, so you can make a single request during sign-in, on the server at the edge, or inside a risk pipeline.
- City: helps with regional routing, regulatory or tax logic, and experience localization.
- ASN: maps the IP to a network operator (e.g., ISP or cloud provider) for traffic shaping, rate-limiting, or anomaly detection.
- VPN flags: detect privacy tooling or anonymity networks that can correlate with elevated fraud risk or account takeover attempts.
The same response typically includes additional fields such as hostname and network identifiers. We will use the official response for 8.8.8.8 to illustrate parsing hostname fields, and explain how to apply the identical approach for city, ASN, and VPN flags.
Endpoint, authentication, and request shape
ipXapi exposes a straightforward HTTP GET endpoint for lookups. You pass the IP address as a query parameter and send your token via the Authorization header:
- HTTP method: GET
- Endpoint: https://ipxapi.com/api/ip?ip=
- Auth: Authorization: Bearer YOUR_API_KEY
You can use any public IPv4 or IPv6 address. If you’re starting without a real user IP, the Google Public DNS address (8.8.8.8) is a clean test value.
Try the official request
Below is the official example request for 8.8.8.8. Copy it to your terminal, substitute YOUR_API_KEY in the Authorization header, and run it:
curl 'https://ipxapi.com/api/ip?ip=8.8.8.8' \
-H 'Accept: application/json' \
-H 'Authorization: Bearer YOUR_KEY'
Understanding the official response
The official example focuses on hostname-related fields for 8.8.8.8. It’s common for this IP to resolve to well-known DNS hostnames. Your production traffic will include different IPs and a wider set of fields (including city, ASN, and VPN flags) where available.
{
"ip": "8.8.8.8",
"hostname": "dns.google",
"isp": "Google LLC",
"is_listed": false
}
How to read it:
- Hostname fields: identify reverse DNS names or canonical hostnames associated with the IP (e.g., for 8.8.8.8 this often includes “dns.google”). These help you recognize well-known infrastructure, CDNs, or DNS resolvers.
This sample shows hostname-centric data. The same endpoint also returns the city, ASN, and VPN-related flags that this article targets. You don’t need a different path or parameter—use the same request format against any IP you care about. When those fields are available for a given IP, they will appear in the JSON.
How to extract city, ASN, and VPN flags in your code
The pattern is always the same:
- Send GET /api/ip with the IP you want.
- Parse the JSON into an object.
- Read the fields you need (city, ASN, VPN flags, and others such as hostname) if they exist.
- Handle missing values gracefully—don’t crash or block a user flow because one field is absent.
Here’s a minimal JavaScript example that calls the same endpoint, parses the JSON, and shows how you would safely access fields from the response. It prints the full payload, reads hostname-related fields (which are present in the official sample), and demonstrates the same guard pattern you’ll use for city, ASN, and VPN flags when they’re present in your responses.
async function lookupIp(ip) {
const url = `https://ipxapi.com/api/ip?ip=${encodeURIComponent(ip)}`;
const res = await fetch(url, {
headers: { Authorization: "Bearer YOUR_API_KEY" },
});
// Network-level errors and unexpected statuses
if (!res.ok) {
// Log or map to your error handling layer
throw new Error(`ipXapi request failed: ${res.status} ${res.statusText}`);
}
const data = await res.json();
// Inspect the whole payload (helps in dev to see available fields for your plan/account/region)
console.log("Full ipXapi payload:", data);
// Official sample highlights hostname fields; read them defensively:
const hostFields = {
hostname: data && data.hostname,
// If the response includes multiple hostname representations, extract as needed:
// e.g., data.ptr_record, data.reverse_dns, etc., depending on your account's response
};
console.log("Hostname-like fields (if present):", hostFields);
// Use the same null-safe pattern for city, ASN, and VPN-related flags:
// Example pattern (replace the property names with the ones present in your response):
// const city = data && data.city;
// const asn = data && data.asn;
// const isVpn = data && data.is_vpn;
return data;
}
// Example: use the same test IP as the official sample
lookupIp("8.8.8.8").catch(console.error);
Error handling, missing values, and fallbacks
Design for partial or missing data. Some IPs won’t map cleanly to a city, an ASN, or a VPN indicator. Your integration should:
- Check the HTTP status code. Retry transient 5xx errors with backoff; treat 4xx as non-retryable until you update inputs or credentials.
- Expect that some fields may be absent for certain IPs. Use null-safe access and defaults. For example, if a VPN flag is unavailable, continue with standard checks rather than blocking the request.
- Log the full JSON for unexpected shapes while you iterate. This helps you refine parsing without interrupting user flows.
Caching and performance
IP geolocation for a given address does not change frequently. To reduce latency and cost, cache results by IP address in a short- to medium-lived store (e.g., your CDN, a reverse proxy, or an application cache). You can:
- Cache lookups per IP, invalidating on your own schedule (for example, tied to session lifetimes or risk checkpoints).
- Normalize your input (e.g., trim spaces) before keying the cache.
- Warm caches for high-traffic IPs if your workload repeatedly hits the same addresses (like corporate NATs or popular DNS resolvers).
If you distribute traffic across regions or between server and edge, centralize your cache or propagate it to avoid duplicate lookups across tiers.
When exactly do you need city, ASN, and VPN flags?
- City: personalize pricing pages or delivery options; comply with regional content rules; select a nearest region for uploads.
- ASN: distinguish between eyeball ISPs and cloud data centers; adapt rate limits or 2FA flows for traffic from hosting providers.
- VPN flags: raise authentication requirements for high-risk sign-ins or payment attempts originating from anonymization tools.
Use these fields as signals, not absolute blockers. For example, a VPN flag might raise suspicion but shouldn’t automatically deny a legitimate, logged-in user; instead require an extra authentication factor.
Going live
1) Create your account
Sign up for the Basic plan at $29.99/mo with a 7-day trial or 50 requests to validate your use case and wire up your staging environment. You can start here: Register.
2) Make a real GET request
Use the same endpoint you tested, but with your real user IP from server-side code or an edge function. If you need a quick test user flow, you can also look up an IP directly from the dashboard flow here: Register.
Production notes:
- Send requests from your server or trusted edge runtime to protect your bearer token.
- Log the request ID or correlation ID used in your stack so you can trace lookups.
- Roll out gradually and watch your cache hit rate; you should see minimal repeated lookups for the same address.
City, ASN, and VPN flags versus the official sample
The official JSON shown above is focused on hostname fields for 8.8.8.8 (where the IP’s hostname includes dns.google). That is a different emphasis than this article’s target fields (city, ASN, and VPN flags), but all of them are delivered by the same endpoint. In your own traffic, when city, ASN, or VPN indicators are available, they appear in the same JSON object as the hostname fields shown in the sample. Your code should parse the response once and then read the subset of fields you need for each decision.
Operational and tooling details that save time
- Observability: dump raw JSON and your parsed subset to logs (redact any user identifiers) for a small percentage of requests in staging and early prod to confirm field availability.
- Idempotency: treat repeated lookups for the same IP as cache hits to keep latency predictable and costs low.
- Time handling: if the response includes any timestamps or date strings in your account’s payload, treat them consistently in your stack (store as-is or normalize in one place), and consult the Documentation for formatting details.
- Security: keep the Authorization: Bearer token in server-side configuration or a secrets manager. Do not embed it in client-side JavaScript.
Management endpoints and docs
Use the developer portal for configuration and to view usage data alongside your application’s CI/CD lifecycle. You can explore platform-level management and controls here: MCP. Review request/response formats, field availability, and integration guides in the official Documentation.
FAQ
Which endpoint returns city, ASN, and VPN flags?
Use the GET endpoint at https://ipxapi.com/api/ip?ip= with your IP address as the query parameter and send your token as Authorization: Bearer. Those fields, when available, are included in the same JSON response.
Why does the official example focus on hostname fields?
The sample uses 8.8.8.8, which commonly resolves to well-known DNS hostnames, so hostname data is highlighted. The same endpoint returns city, ASN, and VPN-related fields for other IPs where those signals are available.
How should I handle missing or null fields?
Use null-safe parsing and sensible defaults. If a field you expect isn’t present, continue your flow with fallbacks (e.g., show generic content, apply standard risk checks) and log the event for analysis.
Can I cache results?
Yes. Cache by IP address to reduce latency and request volume. Geolocation for the same IP usually changes infrequently, so caching is effective for most applications.
What’s the quickest way to try this in staging?
Start a trial of the Basic plan ($29.99/mo with a 7-day trial or 50 requests), run the official curl example for 8.8.8.8, and then switch to live user IPs from your server or edge runtime.
Ready to ship city-level geolocation, ASN, and VPN flags in your app? Start your 7-day trial (or use 50 requests to validate your flow) and get your bearer token here: Register. Then plug the bearer token into the official request above and integrate the parsed fields into your routing, personalization, or fraud checks.
