X-Credits-Charged is a response header that IPGeolocation.io adds to every successful API response, holding the exact number of credits that the request used. It's the billing source of truth: log it on every call and you have the credits per request, a bill you can total, check, and alert on.
That matters the day your credits run faster than you planned. The dashboard tells you how many you used; it doesn't tell you which part of your app used them, or that a refactor quietly made one lookup cost more. Below, you'll build that in Python and Node.js: one JSON log line per call, tagged with the feature that made it, a daily total per feature, and a check that flags any call whose cost changed. For what each call costs in the first place, see what each IPGeolocation.io call costs.
TL;DR
X-Credits-Charged comes only with successful (HTTP 200) IPGeolocation.io responses; error responses carry no header and aren't billed, and a timeout leaves the charge unknown. Read it on your server, because browser code can't see it on a cross-origin call, and write it to a log with the feature that made the call.
- A bulk request reports one total for the whole batch, plus
X-Successful-Recordwhen some entries were invalid. - The official SDKs parse it for you:
responsein Python,.metadata .credits_charged responsein JavaScript..metadata .creditsCharged - No response header reports your remaining balance; the dashboard does.
What X-Credits-Charged tells you, and when it's absent
The header's value is a whole number: the credits deducted for that one request, and only successful (HTTP 200) responses carry it. These are the results of our test calls on November 4, 2026, and they match the per-module credit table in the credits documentation:
| Request | Status | X-Credits-Charged |
|---|---|---|
/v3/ipgeo, default lookup |
200 |
1 |
/ |
200 |
3 |
/ |
200 |
2 |
/v3/security (IP Security API) |
200 |
2 |
/v3/abuse (IP Abuse Contact API) |
200 |
1 |
/ (private IP) |
423 |
absent, not billed |
/v3/ipgeo with an invalid key |
401 |
absent, not billed |
/v3/getip (free utility endpoint) |
200 |
0 |
The credits documentation adds 429 (credits used up) and server errors to the unbilled list. So a missing header on an error response is normal. A timeout is different: no response came back, so you can't tell whether the API finished the request and charged it. Log it as unknown, not as zero, as the wrappers in Steps 2 and 3 do. A missing header on a 200 shouldn't happen, and Step 5 flags it.
Over HTTP/2, the header arrives in lowercase, x-credits-charged. HTTP field names are case-insensitive by definition, and both clients in this tutorial (Python's requests and the Headers object behind fetch) match them that way.
Before you start
- You have an IPGeolocation.io API key in the
IPGEO_API_KEYenvironment variable. If you don't have one yet, get an API key and make your first request. - For the Python steps: Python 3.10 or later with
requestsinstalled (pip install requests). - For the Node.js step: Node.js 18 or later, which ships
fetch. curlfor Step 1.
Step 1: See the header in a raw response
curl -i prints the response headers above the body, which is the quickest way to see the header before writing any code:
curl -i "https://api.ipgeolocation.io/v3/ipgeo?apiKey=$IPGEO_API_KEY&ip=8.8.8.8&fields=location.country_name"
The header block includes the charge (trimmed):
HTTP/2 200
content-type: application/json
x-credits-charged: 1
{"ip":"8.8.8.8","location":{"country_name":"United States"}}
If you see HTTP/2 401 and no x-credits-charged line, the key is missing or wrong: check that IPGEO_API_KEY is set in this shell. Nothing was charged.
Step 2: Log credit usage per call in Python
This wrapper sends a request, reads the header, and writes one JSON object per line to credits.jsonl. Every call passes a feature name, such as signup_check or login_geo, which is what turns a credit total into an answer about where the credits went. Save it as credit_log.py:
"""Call the IPGeolocation.io API and log the credits each request used."""
import json
import logging
import os
import re
import time
import uuid
from datetime import datetime, timezone
import requests
API_BASE = "https://api.ipgeolocation.io"
API_KEY = os.environ.get("IPGEO_API_KEY")
# One JSON object per line. In production, swap the FileHandler for
# logging.StreamHandler(sys.stdout) and let your log pipeline rotate and keep the lines.
credit_log = logging.getLogger("ipgeo.credits")
credit_log.setLevel(logging.INFO)
credit_log.propagate = False
if not credit_log.handlers: # a reloaded module must not add a second handler
_handler = logging.FileHandler(os.environ.get("CREDITS_LOG", "credits.jsonl"))
_handler.setFormatter(logging.Formatter("%(message)s"))
credit_log.addHandler(_handler)
def _int_header(response, name):
"""Return a numeric response header as an int, or None if it's absent or not plain digits."""
value = response.headers.get(name) # requests matches header names case-insensitively
if value is None or not re.fullmatch(r"\d+", value):
return None # int() would also accept "+3", " 3 ", and "3_0"; treat those as unknown
return int(value)
def call_ipgeo(feature, path, params=None, body=None):
"""Call one endpoint, write one log line, and return the parsed JSON (or None on failure).
feature: the part of your app that made the call, such as "signup_check".
path: the endpoint, such as "/v3/ipgeo" or "/v3/ipgeo-bulk".
params: query parameters other than apiKey, such as {"ip": "8.8.8.8", "include": "security"}.
body: a JSON body for POST endpoints (bulk lookups); None sends a GET.
"""
if not API_KEY:
raise RuntimeError("Set IPGEO_API_KEY before calling the API.")
params = dict(params or {})
record = {
"ts": datetime.now(timezone.utc).isoformat(timespec="seconds"),
"request_id": str(uuid.uuid4()), # our own ID: the API doesn't return one
"feature": feature,
"endpoint": path,
"include": params.get("include"),
"fields": params.get("fields"),
"sent": len(body["ips"]) if body and "ips" in body else 1,
}
started = time.monotonic()
try:
response = requests.request(
"POST" if body is not None else "GET",
API_BASE + path,
params={**params, "apiKey": API_KEY},
json=body,
timeout=10,
)
except requests.RequestException as exc:
# Log the error type only: the exception text includes the URL, and the URL holds your key.
record.update(status=None, credits=None, error=type(exc).__name__)
credit_log.info(json.dumps(record))
return None
record.update(
status=response.status_code,
# Only HTTP 200 responses carry X-Credits-Charged; anything else wasn't billed.
credits=_int_header(response, "X-Credits-Charged") if response.status_code == 200 else 0,
successful_records=_int_header(response, "X-Successful-Record"),
duration_ms=round((time.monotonic() - started) * 1000),
)
credit_log.info(json.dumps(record))
if response.status_code != 200:
return None
try:
return response.json()
except ValueError:
return None # billed but unreadable; the credits are already logged
if __name__ == "__main__":
data = call_ipgeo("login_geo", "/v3/ipgeo", {"ip": "8.8.8.8"})
country = ((data or {}).get("location") or {}).get("country_name")
print(country or "lookup failed; see credits.jsonl")
The log never holds the request URL, because the API takes the key as the apiKey query parameter, and an exception message that includes the URL would write your key to disk. The request_id is generated on your side: the API doesn't return a request ID, so this is the value you'll quote when you trace one call. An API error response is logged with credits set to 0, which keeps failed calls visible in your totals without inflating them. A network error is logged with credits: null: the charge is unknown, not zero. The line also records include and fields, the two parameters that decide what a lookup costs.
In production, send the lines to stdout (the swap in the comment), let your logging pipeline handle rotation, retention, and lines from several workers, and run Steps 4 and 5 on the lines it collects. For a single process, at least set CREDITS_LOG to an absolute path; the scripts in Steps 4 and 5 read the same variable. And because the key travels in the query string, check that HTTP client debug logs, APM and tracing tools, proxies, and error trackers redact the apiKey parameter too.
Run it, then look at the log:
python3 credit_log.py
cat credits.jsonl
The script prints United States, and the log holds one line like this (IDs, timestamps, and durations differ on every run):
{"ts": "2026-11-04T14:38:56+00:00", "request_id": "9f1c2b7e-4d1a-4c55-9a3e-2f0b6c1d8e47", "feature": "login_geo", "endpoint": "/v3/ipgeo", "include": null, "fields": null, "sent": 1, "status": 200, "credits": 1, "successful_records": null, "duration_ms": 214}
In your app, import call_ipgeo and pass the feature at each call site:
from credit_log import call_ipgeo
# include=security needs a paid plan key
risk = call_ipgeo("signup_check", "/v3/ipgeo", {"ip": visitor_ip, "include": "security"})
A failed lookup shows up as its own line, such as "status": 423, "credits": 0 for a private address.
If you use the official SDK instead, it reads the header for you. In the official IPGeolocation.io Python SDK, every call returns metadata alongside data:
import os
from ipgeolocation import (
ApiException,
IpGeolocationClient,
IpGeolocationClientConfig,
LookupIpGeolocationRequest,
SerializationException,
TransportException,
)
config = IpGeolocationClientConfig(api_key=os.environ["IPGEO_API_KEY"])
try:
with IpGeolocationClient(config) as client:
response = client.lookup_ip_geolocation(LookupIpGeolocationRequest(ip="8.8.8.8"))
print(response.metadata.status_code, response.metadata.credits_charged) # 200 1
except ApiException as exc:
# The API answered with an error status (401, 423, 429, 5xx): not billed.
print("lookup failed:", exc.status_code, "credits: 0")
except (TransportException, SerializationException) as exc:
# A timeout, a dropped connection, or an unreadable response: the charge is unknown.
print("lookup failed:", type(exc).__name__, "credits: unknown")
credits_charged is an int parsed from X-Credits-Charged, and successful_records holds X-Successful-Record. Write them into the same log line format and the next steps work unchanged. The SDK raises an exception instead of returning a failed call, and the exception class tells you which kind of failure it was. An ApiException (such as LockedException for a private IP) means the API answered with an error status, so log credits as 0. A TransportException, which includes timeouts, or a SerializationException for an unreadable response means the charge is unknown, so log credits as null. A ValidationException is different: it's raised before anything is sent, so it isn't an API call and doesn't belong in your credit totals.
Step 3: The same in Node.js
Node.js 18 and later have fetch built in, and res.headers.get() ignores case. The module writes the same JSON line format as the Python version, so the scripts in Steps 4 and 5 read lines from either. Save it as creditLog.mjs:
// Call the IPGeolocation.io API and log the credits each request used (Node.js 18+).
import { appendFile } from "node:fs/promises";
import { randomUUID } from "node:crypto";
import { pathToFileURL } from "node:url";
const API_BASE = "https://api.ipgeolocation.io";
const API_KEY = process.env.IPGEO_API_KEY;
const LOG_PATH = process.env.CREDITS_LOG ?? "credits.jsonl";
function intHeader(res, name) {
const value = res.headers.get(name); // Headers.get() ignores case
return value !== null && /^\d+$/.test(value) ? Number(value) : null;
}
async function writeLine(record) {
try {
await appendFile(LOG_PATH, JSON.stringify(record) + "\n");
} catch (err) {
// A full disk shouldn't break the lookup, but the record mustn't vanish either:
// send it to stderr so your central logs (and alerts) still see it.
console.error("credit log write failed:", err.code ?? err.message, JSON.stringify(record));
}
}
export async function callIpgeo(feature, path, params = {}, body = null) {
if (!API_KEY) throw new Error("Set IPGEO_API_KEY before calling the API.");
const url = new URL(path, API_BASE);
for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
url.searchParams.set("apiKey", API_KEY);
const record = {
ts: new Date().toISOString().slice(0, 19) + "+00:00",
request_id: randomUUID(), // our own ID: the API doesn't return one
feature,
endpoint: path,
include: params.include ?? null,
fields: params.fields ?? null,
sent: body?.ips ? body.ips.length : 1,
};
const started = performance.now();
let res;
try {
res = await fetch(url, {
method: body ? "POST" : "GET",
headers: body ? { "Content-Type": "application/json" } : {},
body: body ? JSON.stringify(body) : undefined,
signal: AbortSignal.timeout(10_000),
});
} catch (err) {
// Log the error name only: some fetch errors include the URL, and the URL holds your key.
await writeLine({ ...record, status: null, credits: null, error: err.name });
return null;
}
await writeLine({
...record,
status: res.status,
// Only HTTP 200 responses carry X-Credits-Charged; anything else wasn't billed.
credits: res.status === 200 ? intHeader(res, "x-credits-charged") : 0,
successful_records: intHeader(res, "x-successful-record"),
duration_ms: Math.round(performance.now() - started),
});
if (res.status !== 200) {
await res.body?.cancel(); // free the connection; the status is already logged
return null;
}
try {
return await res.json();
} catch {
return null; // billed but unreadable; the credits are already logged
}
}
// Run directly: node creditLog.mjs
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
const data = await callIpgeo("login_geo", "/v3/ipgeo", { ip: "8.8.8.8" });
console.log(data?.location?.country_name ?? "lookup failed; see credits.jsonl");
}
node creditLog.mjs prints United States and appends a line in the same shape as Step 2's; from your app, import { callIpgeo } from ". A timeout is logged with "error": "TimeoutError" and credits: null. If the log write itself fails, the record goes to stderr in full. That only helps if stderr is collected and alerted on, and Step 4's totals won't include those lines, so count them in by hand. In production, with several workers or services, write these records to stdout instead and collect them through your central logging pipeline, rather than having every process append to the same local file.
With the JavaScript SDK, the value is on response, as documented in the JavaScript SDK's response metadata, and its error classes sort the same way:
import { ApiError, IpGeolocationClient, SerializationError, TransportError } from "ip-geolocation-api-javascript-sdk";
const client = new IpGeolocationClient({ apiKey: process.env.IPGEO_API_KEY });
try {
const response = await client.lookupIpGeolocation({ ip: "8.8.8.8" });
console.log(response.metadata.statusCode, response.metadata.creditsCharged); // 200 1
} catch (err) {
if (err instanceof ApiError) {
// The API answered with an error status (401, 423, 429, 5xx): not billed.
console.error("lookup failed:", err.statusCode, "credits: 0");
} else if (err instanceof TransportError || err instanceof SerializationError) {
// A timeout, a dropped connection, or an unreadable response: the charge is unknown.
console.error("lookup failed:", err.name, "credits: unknown");
} else {
throw err;
}
} finally {
await client.close();
}
Timeouts and retries: log every attempt
Neither wrapper retries, and neither official SDK does either, so each log line is one request. If you add retries, call the wrapper once per attempt, so every attempt gets its own line and request_id. Don't assume a retry replaces the attempt before it: a request that timed out may have been processed and charged even though your client never saw the response, so a retry after a timeout can cost credits twice. Retry timeouts and 5xx errors only. A 401 or 423 fails the same way every time. A 429 means a credit, billing, or subscription limit is blocking the request: the plan's credits are used up with overage off, the overage cap is reached, or the subscription isn't active. The response message says which, and retrying right away won't help.
Step 4: Total credits by feature and day
This script reads credits.jsonl and prints calls, billed calls, credits, and calls whose charge is unknown, per UTC day and feature. It needs no extra installs. Save it as rollup.py:
"""Total the credits in credits.jsonl by day and feature."""
import json
import os
import sys
from collections import defaultdict
path = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("CREDITS_LOG", "credits.jsonl")
totals = defaultdict(lambda: {"calls": 0, "billed": 0, "credits": 0, "unknown": 0})
try:
with open(path, encoding="utf-8") as log:
for line_no, line in enumerate(log, 1):
try:
rec = json.loads(line)
day, feature = rec["ts"][:10], rec["feature"] # ts is UTC, so [:10] is the UTC day
except (json.JSONDecodeError, KeyError, TypeError):
print(f"skipping line {line_no}: not a credit record", file=sys.stderr)
continue
row = totals[(day, feature)]
row["calls"] += 1
status, credits = rec.get("status"), rec.get("credits")
if status == 200:
row["billed"] += 1
if status is None or (status == 200 and credits is None):
row["unknown"] += 1 # no response, or a 200 without the header: charge not known
elif status == 200:
row["credits"] += credits
except FileNotFoundError:
sys.exit(f"No log at {path}. Run credit_log.py first.")
print(f"{'day':<12}{'feature':<16}{'calls':>6}{'billed':>8}{'credits':>9}{'unknown':>9}")
for (day, feature), row in sorted(totals.items()):
print(f"{day:<12}{feature:<16}{row['calls']:>6}{row['billed']:>8}{row['credits']:>9}{row['unknown']:>9}")
After a mixed run, python3 rollup.py prints something like:
day feature calls billed credits unknown
2026-11-04 fraud_score 2 2 5 0
2026-11-04 log_enrichment 1 1 2 0
2026-11-04 login_geo 3 1 1 1
2026-11-04 signup_check 1 1 3 0
signup_check spent 3 credits on one call because it asks for security data. login_geo was billed for one of three calls: the private IP (423) cost nothing, and the timeout lands in unknown, so that day's total may be low. fraud_score spent 5 credits on two calls, which is the clue Step 5 exists to catch.
Step 5: Alert when a call's cost changes or a feature passes its budget
Totals tell you where the credits went, but not that a call's cost changed. A fraud check that only needs IP security data can call / for 2 credits. If someone drops fields in a refactor, the same call returns the full lookup plus security data and costs 3. Nothing errors, and the bill grows by half for that feature.
The fix is to write down what each feature should cost and compare every logged call against it. If one part of your app makes calls that cost different amounts, give each kind its own feature name, such as signup_check and signup_geo, so each has one expected cost. Save this as check_credits.py; the budgets are examples, and a week of rollup.py totals plus some headroom is a good place to start yours:
"""Check every call logged since the last run: flag unknown charges, cost changes,
and features over their daily budget. Exits 1 on any alert."""
import json
import os
import sys
from collections import defaultdict
# Credits per looked-up IP or domain for each feature, from the credits documentation.
EXPECTED = {
"signup_check": 3, # /v3/ipgeo with include=security
"login_geo": 1, # /v3/ipgeo, default response
"fraud_score": 2, # /v3/ipgeo with include=security&fields=security
"log_enrichment": 1, # /v3/ipgeo-bulk, default response, per valid entry
}
DAILY_BUDGET = {"signup_check": 3000, "login_geo": 5000, "fraud_score": 2000, "log_enrichment": 20000}
path = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("CREDITS_LOG", "credits.jsonl")
state_path = path + ".checked" # how far into the log the last run got
try:
with open(state_path, encoding="utf-8") as f:
state = json.load(f)
except FileNotFoundError:
state = {"inode": None, "offset": 0} # first run: check the whole log
spent = defaultdict(int) # (day, feature) -> known credits
unknown = defaultdict(int) # (day, feature) -> calls with an unknown charge
unknown_max = defaultdict(int) # (day, feature) -> most those calls could have cost
new_days = set() # days that got new lines since the last run
alerts = []
pos = 0
try:
log = open(path, "rb") # bytes, so the saved offset is exact
except FileNotFoundError:
sys.exit(f"No log at {path}. Run credit_log.py first.")
with log:
# Take the inode from the open file, so a rotation right now can't pair
# this file's offset with another file's inode.
st = os.fstat(log.fileno())
if st.st_ino != state["inode"] or st.st_size < state["offset"]:
state = {"inode": st.st_ino, "offset": 0} # a new or rotated log: start from its top
for raw in log:
if not raw.endswith(b"\n"):
break # a line still being written; the next run picks it up
is_new = pos >= state["offset"]
pos += len(raw)
try:
rec = json.loads(raw)
day, rid, feature = rec["ts"][:10], rec["request_id"], rec["feature"]
except (ValueError, KeyError, TypeError):
continue # not a credit record
status, credits = rec.get("status"), rec.get("credits")
if status is None or (status == 200 and credits is None):
unknown[(day, feature)] += 1
unknown_max[(day, feature)] += EXPECTED.get(feature, 0) * rec.get("sent", 1)
elif status == 200:
spent[(day, feature)] += credits
if not is_new:
continue # checked on an earlier run
new_days.add(day)
if status is None:
alerts.append(f"{rid}: {feature} got no response ({rec.get('error')}); charge unknown")
continue
if status != 200:
continue # an API error response: no header, not billed
if credits is None:
alerts.append(f"{rid}: {feature} 200 response without X-Credits-Charged; charge unknown")
continue
per_entry = EXPECTED.get(feature)
if per_entry is None:
alerts.append(f"{rid}: no expected cost set for feature {feature!r}")
continue
# Bulk: X-Successful-Record is sent only when some entries were invalid;
# otherwise every entry sent was valid.
valid = rec.get("successful_records")
entries = valid if valid is not None else rec.get("sent", 1)
if credits != per_entry * entries:
alerts.append(
f"{rid}: {feature} charged {credits}, expected {per_entry * entries}"
f" (include={rec.get('include')}, fields={rec.get('fields')})"
)
for day, feature in sorted(set(spent) | set(unknown)):
budget = DAILY_BUDGET.get(feature)
if day not in new_days or budget is None:
continue
known, at_most = spent[(day, feature)], spent[(day, feature)] + unknown_max[(day, feature)]
if known > budget:
alerts.append(f"{feature}: {known} credits on {day}, budget {budget}")
elif at_most > budget: # unknown charges could tip it over: say so instead of reporting OK
alerts.append(
f"{feature}: may be over budget on {day}: {known} known"
f" + up to {at_most - known} in {unknown[(day, feature)]} unknown calls, budget {budget}"
)
for alert in alerts:
print("ALERT", alert)
if not alerts:
print("OK: every new call cost what it should, and every feature is within budget")
# Save progress only after the log was read, so a crash rechecks instead of skipping.
tmp = state_path + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump({"inode": st.st_ino, "offset": pos}, f)
os.replace(tmp, state_path)
sys.exit(1 if alerts else 0)
On the same log, python3 check_credits finds the call that lost its fields parameter, with the logged parameters that show why, and flags the timeout as an unknown charge:
ALERT 63b1d305-2704-468f-8d63-248afcc80f7a: fraud_score charged 3, expected 2 (include=security, fields=None)
ALERT 4d582eda-aeb7-42ff-ac05-71c51d8cf7f2: login_geo got no response (ReadTimeout); charge unknown
It exits with status 1, so you can run it from cron every hour and pass its output to whatever sends your alerts. flock keeps two runs from overlapping and checking the same lines twice:
0 * * * * flock -n /tmp/ipgeo-credit-check.lock sh -c 'cd /srv/app && out=$(python3 check_credits.py) || echo "$out" | your-alert-command'
It saves its position in the log (a byte offset) to credits after each full read, so every run checks exactly the lines written since the last one, even a slow call whose line was written late, and a missed run is caught up on the next.
The first run checks the whole log, so expect alerts for old history. The checkpoint assumes your log rotation renames the file and starts a new one; with copytruncate, run the check just before rotation or use the offsets your log collector keeps. A feature over budget alerts on each run that adds lines for that day, and when unknown charges could push a feature over its budget, the check says it may be over instead of reporting OK. The same pass flags a 200 with no header (worth a support ticket) and a feature with no expected cost, which usually means a new call site the check doesn't know about.
We'd keep the expected-cost check even if you never set a budget. Budgets catch volume; this catches the change that makes every call more expensive, on the first run after it ships rather than at the end of the billing period.
Bulk lookups report one total
A request to /v3/ipgeo-bulk takes up to 50,000 IP addresses or domain names and returns one X-Credits-Charged value for the whole batch: the credits per lookup times the number of valid entries. Private, bogon, and malformed IPs, and domains that don't resolve, don't count. When at least one entry is invalid, the response also carries X-Successful-Record with the number of entries that returned data, not the number you sent; when every entry is valid, that header is absent.
That's why the log line stores sent and successful_records next to credits, and why Step 5 multiplies the expected cost by the number of valid entries. Log the request once, as the wrapper does; logging it once per entry would count the same credits many times over:
# Bulk lookups need a paid plan key.
results = call_ipgeo("log_enrichment", "/v3/ipgeo-bulk",
body={"ips": ["8.8.8.8", "165.227.0.0", "10.0.0.1"]})
With the default response, that request charges 2 credits: two valid IPs at 1 credit each, with X-Successful-Record: 2 because 10.0.0.1 is a private address. The bulk lookup documentation has the full request and response format.
Why browser code can't read the header
If you call the API from the browser with Request Origin authentication, which accepts calls from your site's domain instead of an API key, you'll get the data but not the header. Browsers let scripts read only a short list of safe response headers on a cross-origin request unless the server names others in Access-Control-Expose-Headers, and the API's responses don't list X-Credits-Charged. In our test on November 4, 2026, a billed call from browser JavaScript returned 200, and res returned null; the JavaScript SDK's creditsCharged is undefined there for the same reason.
So log on the server. If your frontend needs IP data, have it call your own endpoint, and let that endpoint call IPGeolocation.io through the Step 2 or Step 3 wrapper. That's also the setup the guide to securing and monitoring your API key recommends, because the key never reaches the browser.
Check your log against the dashboard
The IPGeolocation.io dashboard shows your credit usage for the whole account: credits used, credits remaining, and usage history. Once a day, compare a finished day on the dashboard with the same day's total from rollup.py, for the same account or key, and make sure both count the same day: the rollup uses UTC. If every request made with that key goes through your wrapper and the day has no unknown charges, the two should match. A gap tells you something:
- The dashboard is higher: some calls aren't going through your wrapper. That might be another service on the same key, a script someone runs by hand, or a key that leaked. Give each service its own key (see extra API keys and request origins) and the gap points to one of them. The API logs you can request for each key from the dashboard list the IP address each call came from.
- Your log is higher: check whether test runs on another key are writing to the same log file.
- The dashboard is higher by about your
unknowncount: those timed-out calls were charged, which is how you settle unknown charges after the fact.
One call, the data you asked for, and its cost
IPGeolocation.io returns geolocation, security data (VPN, proxy, and Tor detection with a threat score), ASN, company, abuse contact data, time zone, and user agent data from one call to the IP Geolocation API, and every successful response states its own cost. The data and the bill arrive together, on the call that incurred it, which is what makes this log possible.
The same header comes back from the dedicated APIs, such as the IP Security API, and from bulk requests of up to 50,000 addresses, so one wrapper covers every endpoint you call. At volumes where per-call billing stops making sense, such as enriching years of logs, a downloadable database fits better; the guide on when a database beats per-call billing walks through that choice.
To see which data and features each plan includes, compare plans on the pricing page.
Frequently Asked Questions
Read the X-Credits-Charged header on the response. IPGeolocation.io sends it on every successful (HTTP 200) response with the exact credits deducted, such as 1 for a default lookup or 3 with security data. Use curl -i to see it, or read metadata in the Python SDK and metadata in the JavaScript SDK.
Usually because the request failed. IPGeolocation.io sends X-Credits-Charged only with HTTP 200 responses; a 401, 423, 429 (a credit, overage, or subscription limit), or server error carries no header and costs nothing. The other common cause is browser code: on a cross-origin call, the browser hides the header from scripts.
No. IPGeolocation.io's responses don't list X-Credits-Charged in Access-Control-Expose-Headers, so on a cross-origin call from browser JavaScript, headers returns null even though the request was billed. Read and log the header on your server, and have the browser call your server.
As one total for the whole request: the credits per lookup times the number of valid IP addresses or domains. IPGeolocation.io doesn't charge for private, bogon, or malformed IPs or unresolvable domains, and when a request contains any, the response adds X-Successful-Record with the number of entries that returned data.
No. IPGeolocation.io responses carry X-Credits-Charged for the call itself, but no header for the remaining balance. The dashboard shows credits used, credits remaining, and usage history for the account.







