IP Continent API
You need a simple, reliable way to map an IP address to its continent for analytics, routing, or compliance. By the end of this guide you will make a geolocation request to the ipXapi IP Continent API, parse the continentCode from the JSON response, and ship it in your app with production-ready patterns for caching, error handling, and testing.
What the IP Continent API solves
Many workflows require only a coarse geolocation: continent-level decisions for content localization, regulatory flows, or routing to the nearest edge. Pulling an entire geolocation payload and then normalizing it yourself takes time. The IP Continent API response includes a continentCode field you can extract directly and store, cache, or pass along to downstream services.
This guide focuses on exactly one endpoint and one key: getting continentCode from a single-IP lookup using the documented fixture. You will see a working cURL call, the official JSON response, and a minimal JavaScript client you can paste into a server-side handler.
Endpoint, authentication, and request format
The IP Continent API uses a single HTTP GET endpoint for IP lookups:
- Path: /api/ip
- Query parameter: ip
- Auth: Authorization: Bearer YOUR_API_KEY
Requests must include an Authorization header with a Bearer token. Responses are JSON when Accept: application/json is provided.
Official sample request (copy/paste):
curl "https://ipxapi.com/api/ip?ip=148.105.12.120" -H "Accept: application/json" -H "Authorization: Bearer YOUR_KEY"
Use this sample to verify connectivity, authentication header shape, content negotiation, and the response schema before you wire it into your code. Replace the token with YOUR_API_KEY in your application code. The fixture IP is stable for documentation, but do not treat it as your user’s IP.
Official JSON response and the field you need
Below is the official product-fixture JSON for the lookup. Live flags can change, but this is the exact structure you should build against. You will extract continentCode from it.
{
"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 will typically use in a continent-only integration:
- status: Validate that the lookup succeeded before reading other fields.
- query: Echo of the IP you asked about; log this for observability or cache keys.
- continentCode: The target field for this guide. Expect a two-letter continent code such as NA, EU, AS, AF, OC, SA, or AN.
Other fields (country, region, city, timezone, security) are present but not required when your logic only depends on continentCode.
Quick-start: JavaScript example to read continentCode
The snippet below calls the same endpoint and extracts continentCode. Use it in a server context (Node.js, serverless function, or backend framework) to avoid exposing your API key to browsers.
/**
* Minimal Node.js example: fetch continentCode for a single IP.
* Requirements: Node 18+ (built-in fetch) or install node-fetch.
*/
async function getContinentCode(ip) {
const url = `https://ipxapi.com/api/ip?ip=${encodeURIComponent(ip)}`;
const res = await fetch(url, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
},
// Consider short timeouts in production via AbortController
});
if (!res.ok) {
// Surface HTTP errors distinctly for retry/circuit-breaker logic
const text = await res.text().catch(() => '');
throw new Error(`ipXapi HTTP ${res.status}: ${text}`);
}
const data = await res.json();
// Validate the schema you depend on before using it
if (data && data.status === 'success' && typeof data.continentCode === 'string') {
return data.continentCode; // e.g., 'NA'
}
// If status is not success or continentCode missing, treat as a soft failure
throw new Error(`ipXapi lookup failed or incomplete for IP ${ip}`);
}
// Example usage with the documented fixture IP
getContinentCode('148.105.12.120')
.then(code => {
console.log('continentCode:', code);
})
.catch(err => {
console.error('Lookup error:', err);
});
Notes for production:
- Authorization header: Bearer YOUR_API_KEY. Keep tokens server-side only.
- Timeouts: Wrap fetch with AbortController so failing network calls don’t block your request threads.
- Retries: Use exponential backoff for transient 5xx statuses. Avoid retrying 4xx errors.
How to use continentCode in application logic
The continentCode is a compact, stable key for coarse routing and policy. Design your system to act on it without needing the rest of the payload.
- Edge routing: Choose a default CDN region by continentCode, then override with more granular signals if available.
- Content gating: Show continent-level consent flows (for example, different privacy notices by continent).
- Analytics grouping: Bucket events by continentCode to simplify dashboards that don’t need country-level detail.
- Pricing or feature flags: Toggle broad features per continent to keep logic short and fast.
Because continent is coarse, it tends to be more temporally stable than city-level data. That makes continentCode a good candidate for longer cache TTLs (see caching notes below).
Request patterns, caching, and idempotency
The /api/ip endpoint is a pure lookup: same inputs return the same result unless the provider’s knowledge base updates. You can safely treat it as idempotent per IP address and cache responses.
- Cache key: ip (data.query in the response is also available for logging and cache verification).
- TTL strategy: Practical TTLs often range from hours to days for continentCode because continent rarely changes for a given IP allocation. Start with 24 hours and adjust to your tolerance for drift.
- Stale-while-revalidate: Serve a cached continentCode immediately while asynchronously refreshing; this keeps latency low.
- Cold start protection: Prewarm cache for known traffic sources (e.g., payment providers or webhook IPs), if applicable.
If you perform bulk lookups, batch requests in your application layer (e.g., Promise.all in Node.js with a small concurrency limit) while respecting your account’s request constraints. The endpoint itself is per-IP; do not attempt to send multiple IPs in one request unless the official documentation adds such a feature.
Error handling and fallbacks
Design around two dimensions: HTTP transport errors and semantic response failures.
- HTTP errors: On non-2xx responses, capture the status code, response text, and the IP queried. Decide whether to retry based on status family (5xx vs 4xx).
- Semantic failures: If status is not success or continentCode is missing, treat the lookup as unsuccessful.
- Fallback continent: If policy allows, use a neutral fallback (for example, treat as unknown and route to a default region). Log these events to observe frequency.
- Partial data: Even when status is success, your logic should only depend on continentCode to keep behavior predictable.
Security, privacy, and client-side usage
Do not call /api/ip from a public browser with your API key. Proxy requests through your backend or a serverless function that injects the Authorization header. Log only what you need (IP and continentCode are usually sufficient) and apply your organization’s data retention policies.
The JSON includes a security object with flags that may vary for live IPs. If your application does not depend on those fields, avoid branching on them. This guide keeps its logic restricted to continentCode.
Latency, SLAs, and timezones
The response includes timezone, but continent-only decisions do not require it. If you do use timezone elsewhere in your stack, consider that it is an Olson database string, not a numeric offset, and can change with daylight saving rules. Avoid recomputing continentCode per request if a cache hit is available; this is the single largest latency optimization for geolocation lookups.
Testing and environments
For deterministic tests, use the documented fixture IP 148.105.12.120 with a recorded response. In local or CI tests, mock the network call to /api/ip and assert only on continentCode. Do not assume the fixture reflects your machine’s IP address; it is not a “what is my IP” service call.
If your organization manages requests via a control plane or gateway, coordinate the base domain and auth policy there. The MCP endpoint is available here: MCP.
Account setup and pricing
Sign up for access and a key, then add your key as a Bearer token in the Authorization header. A trial is available for 7 days or 50 requests, whichever comes first. The Basic plan is $29.99 per month. For details beyond what is covered here, review the official docs.
Links you will need once per project:
- Register to obtain YOUR_API_KEY.
- Documentation for endpoint reference and integration notes.
Operational checklist
- Authentication: Authorization: Bearer YOUR_API_KEY.
- Endpoint: GET https://ipxapi.com/api/ip with the ip query parameter.
- Response contract: Read continentCode when status is success.
- Caching: Cache per-IP results; 24h TTL is a practical starting point for continent-only logic.
- Observability: Log status, query, continentCode, and latency. Redact API keys in logs.
- Error paths: Separate transport errors (HTTP) from semantic failures (missing continentCode).
- Testing: Use the fixture IP in mocks; do not rely on client IP detection.
FAQ
What is the minimal set of fields I should persist?
Store the IP you queried (query) and continentCode. Keeping status in logs helps diagnose failures. Persisting only continentCode is sufficient for routing and feature flags.
Can I make requests from the browser?
Do not embed YOUR_API_KEY in client-side code. Proxy requests through your backend or a serverless function that adds the Authorization header.
How often should I refresh the continentCode?
A daily refresh is a practical default. Continent assignments typically change less frequently than city-level data, so longer TTLs are acceptable if your use case tolerates rare drift.
What should I do if status is not success?
Treat the lookup as failed: return a safe default, skip continent-based logic, and log the incident. Retry only on transient HTTP 5xx errors with backoff.
Is pagination or batching supported?
This endpoint resolves one IP per call via the ip query parameter. If you need to process many IPs, implement batching and concurrency in your application layer.
Get a key, call the single endpoint, and ship continent-aware routing in minutes. Start your trial and grab YOUR_API_KEY here: Register. Keep the endpoint reference handy while you integrate: Documentation.
