IP Usage Type API in Python: CDN JSON
You need to programmatically detect whether an IP address is coming from a Content Delivery Network (CDN) or another usage category, and you want to do it from Python. By the end of this guide you’ll be able to query ipXapi’s endpoint, read the usage_type value (e.g., “Content Delivery Network”), and ship robust code that handles edge cases and production concerns.
What “usage_type” tells you and when it matters
usage_type is a classification of how an IP is typically used (for example, a CDN). This is crucial for routing, fraud checks, analytics, and personalization. If you need to decide whether to block, challenge, bypass, or treat traffic differently based on the source network role, usage_type is the field you reach for.
On ipXapi, the usage_type is available from the GET /api/abuse-check?ip= endpoint. When you query a specific IP, the response includes the official usage_type string. For example, querying 8.8.8.8 returns “Content Delivery Network.”
Plan, trial, and request volume
You can start with a 7-day trial or 50 requests. If you need a paid plan, the Basic plan is $29.99/mo.
How to go live
- Register for ipXapi here: Register — includes a 7-day trial.
- Copy your Bearer token (API key) from your account.
- Make a GET request to /api/abuse-check?ip= with the Authorization header.
- Store the returned usage_type with the relevant entity (request log, user/account, or IP table) for reuse.
Make the request (curl)
The following official request calls the abuse-check endpoint and will return a JSON payload containing usage_type for the provided IP address.
curl 'https://ipxapi.com/api/abuse-check?ip=8.8.8.8' -H 'Authorization: Bearer YOUR_KEY'
Understand the response (CDN JSON)
Here is the official response body showing the selected usage_type field. The example IP 8.8.8.8 resolves to Content Delivery Network.
{"ip": "8.8.8.8", "hostname": "dns.google", "usage_type": "Content Delivery Network", "isp": "Google LLC"}
Fields you will actually use:
- usage_type: A human-readable string declaring the IP’s typical usage, for example “Content Delivery Network.” This is the primary value your application will branch on.
Data specifics:
- Type: usage_type is a string.
- Localization: usage_type is provided as text; do not assume alternate languages.
- Dates/timezones: This response does not include dates or timestamps.
- Units/currency: Not applicable for this endpoint.
Python example: request and parse usage_type
You can use Python to call the same endpoint and read usage_type. Set your base URL (from the service you are using to access ipXapi) and your Bearer key. If you prefer to start quickly, you can also begin via the link under “Read usage_type in Python”: Register.
import os
import sys
import json
import time
from typing import Optional, Tuple
import requests
# Configuration
# Set IPXAPI_BASE_URL to the host that serves ipXapi (e.g., via your MCP or gateway).
BASE_URL = os.environ.get("IPXAPI_BASE_URL", "").rstrip("/")
API_KEY = os.environ.get("IPXAPI_BEARER", "YOUR_API_KEY").strip()
def fetch_usage_type(ip: str, timeout: float = 5.0) -> Tuple[Optional[str], Optional[dict]]:
"""
Returns (usage_type, raw_json). If the request fails or usage_type is missing, usage_type is None.
"""
if not BASE_URL:
raise RuntimeError("BASE_URL not set. Set IPXAPI_BASE_URL to your ipXapi host.")
url = f"{BASE_URL}/api/abuse-check"
headers = {
"Authorization": f"Bearer {API_KEY}",
"Accept": "application/json",
}
params = {"ip": ip}
try:
resp = requests.get(url, headers=headers, params=params, timeout=timeout)
except requests.RequestException as e:
# Network or DNS error; retry/backoff as needed
print(f"Request error: {e}", file=sys.stderr)
return None, None
# Basic HTTP error handling
if resp.status_code != 200:
# Consider inspecting resp.text or JSON for error info
print(f"Non-200 response: {resp.status_code} - {resp.text}", file=sys.stderr)
return None, None
try:
data = resp.json()
except json.JSONDecodeError:
print("Invalid JSON in response", file=sys.stderr)
return None, None
# Handle a potential explicit failure flag if present.
# Some APIs include success=false on errors. If absent, just proceed.
if isinstance(data, dict) and data.get("success") is False:
# Log diagnostic info for triage
print(f"API reported failure: {data}", file=sys.stderr)
return None, data
usage_type = None
if isinstance(data, dict):
usage_type = data.get("usage_type")
return usage_type, data
if __name__ == "__main__":
ip = sys.argv[1] if len(sys.argv) > 1 else "8.8.8.8"
usage_type, raw = fetch_usage_type(ip)
if usage_type:
print(f"IP {ip} usage_type: {usage_type}")
else:
print(f"usage_type unavailable for IP {ip}. See stderr for details.")
Error handling, missing values, and retries
Production code should anticipate that the API or network may temporarily fail. Treat non-200 HTTP codes as transient or permanent errors and decide whether to retry with backoff. If the JSON body includes a boolean success flag and it is false, treat it as an application-level error. When usage_type is missing or null, default to a conservative behavior (for example, require additional verification, or bypass special routing) and log the incident for later review.
Practical details that save time
- Authentication: Use a Bearer token in the Authorization header.
- Idempotency: Re-checking the same IP returns the same classification until the dataset updates; you can cache by IP.
- Caching: Cache usage_type by IP for a period that matches your risk tolerance. Because the field is a string label without timestamps, use your own TTL. A few hours to a day is a common starting point; adjust based on how often you observe changes.
- Pagination: Not applicable to this single-IP check endpoint.
- Timezones and dates: Not applicable; the response shown is purely categorical.
- Localization: usage_type is a plain string. Avoid downstream logic that depends on localized variants.
- CDN-specific logic: If your flow needs to know “Is this IP from a CDN?”, compare usage_type to “Content Delivery Network”. Avoid partial matches that could misclassify future categories.
Testing: working with the CDN case
The example IP 8.8.8.8 in the official sample resolves to usage_type “Content Delivery Network,” which is exactly what you need to verify a CDN classification path. Use this during development to ensure your code path for CDNs (e.g., bypass origin rate limits or tag analytics) operates correctly.
Security and deployment tips
- Keep your Bearer key out of source control. Use environment variables or a secrets manager.
- Set reasonable timeouts (connect and read) for all HTTP calls to avoid thread starvation under network issues.
- Log the raw JSON body when classification is missing (redacted for sensitive fields) to speed up troubleshooting.
- Protect against overuse by centralizing calls and caching results for shared services.
Where to find host, SDKs, and full parameter details
Endpoint shape (path and query) for usage_type is: GET /api/abuse-check?ip=. For host information, SDKs, and broader API details, see the Documentation and the MCP entry point used in your environment.
Production checklist
- Register and obtain a Bearer token: Register.
- Implement the GET /api/abuse-check?ip= call in your backend.
- Parse usage_type and persist alongside your IP/user/session models.
- Add caching by IP to reduce latency and cost.
- Handle non-200 responses, empty bodies, and missing usage_type.
- Write unit tests for CDN and non-CDN branches.
FAQ
Does the API return only usage_type?
This guide focuses on usage_type. Use the official sample and the docs to see the complete response for your plan and environment.
How do I authenticate?
Send your API key as a Bearer token in the Authorization header.
What if usage_type is missing?
Treat it as unknown and take a safe default. Log and retry later. Cache known-good results to avoid repeated lookups.
How often should I refresh the classification?
There is no timestamp in the response shown here. Choose a TTL that fits your risk tolerance and update when you re-encounter the IP or on a scheduled sweep.
How do I detect specifically if an IP is a CDN?
Compare usage_type to the string “Content Delivery Network.” Keep comparisons exact and case-sensitive per your data handling policy.
Ready to identify CDN traffic from Python? Start your 7-day trial and get a Bearer key here: Register. If you need endpoint details beyond this article, visit the Documentation or your MCP environment, then implement GET /api/abuse-check?ip= and persist usage_type in your service.
