IP ZIP Code API
You need to programmatically turn an IP address into a ZIP code for geolocation-driven features (personalized content, shipping eligibility, compliance prompts). By the end of this guide, you will call ipXapi’s IP ZIP Code lookup, extract the zip field reliably, and ship a minimal production-ready integration.
What you will build
This guide implements a lookup that accepts an IPv4 address and returns geolocation metadata, including a ZIP code. You will:
- Authenticate using a Bearer token and call the single lookup endpoint.
- Parse the official response to read the zip field.
- Follow practices for caching and error handling so you can deploy with confidence.
Everything here stays focused on geolocation and the ZIP code key in the JSON response.
Endpoint and authentication
ipXapi exposes a single path for this lookup:
- HTTP method: GET
- Path: /api/ip
- Query parameter: ip (the IP address you want to geolocate)
- Headers:
- Accept: application/json
- Authorization: Bearer YOUR_API_KEY
All examples use the documented fixture IP 148.105.12.120 so you can copy/paste and verify your wiring without guessing. Replace YOUR_API_KEY with your key after you sign up.
If you are exploring the control plane or environment status, use the MCP endpoint here: MCP.
Plan and trial
Pricing: Basic is $29.99/mo. A trial is available for 7 days or 50 requests, whichever comes first. That’s enough to integrate the lookup into your dev or staging environment and validate ZIP extraction before going to production.
Quickstart: one request that returns a ZIP code
Run this curl command to perform a geolocation lookup and return the ZIP code in the zip field:
curl "https://ipxapi.com/api/ip?ip=148.105.12.120" -H "Accept: application/json" -H "Authorization: Bearer YOUR_KEY"
Official sample response (product fixture):
{
"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
}
}
Notes:
- The zip field contains the postal code you will use downstream.
- Live flags can change; treat this fixture as a stable example only, not as “your IP.”
- Keep your query parameter exactly as ip=148.105.12.120 when reproducing the example.
Parse only what you need: focus on zip
Most applications only need a few keys. Here, we’ll extract zip and also keep a couple of additional fields that can help with logging or debugging. Adjust to your needs, but avoid pulling more than you use.
Python example: fetch and extract zip
import json
import sys
import urllib.request
API_URL = "https://ipxapi.com/api/ip?ip=148.105.12.120"
REQ = urllib.request.Request(
API_URL,
headers={
"Accept": "application/json",
"Authorization": "Bearer YOUR_API_KEY",
},
)
try:
with urllib.request.urlopen(REQ, timeout=5) as resp:
body = resp.read().decode("utf-8")
data = json.loads(body)
except Exception as e:
print(f"Request failed: {e}", file=sys.stderr)
sys.exit(1)
# Basic validation: ensure success and key presence
if not isinstance(data, dict) or data.get("status") != "success":
print(f"Unexpected response or lookup failed: {data}", file=sys.stderr)
sys.exit(2)
zip_code = data.get("zip")
if not zip_code:
print("No ZIP code found in response.", file=sys.stderr)
sys.exit(3)
# Optional: a few helpful fields for logging/diagnostics
ip = data.get("query")
region = data.get("region")
city = data.get("city")
print(f"IP: {ip}")
print(f"ZIP: {zip_code}")
print(f"Region: {region}")
print(f"City: {city}")
What this does:
- Calls the same /api/ip endpoint used in curl and requests JSON.
- Checks status == "success" and then reads zip.
- Prints the ZIP code so you can connect it to your downstream logic (e.g., shipping rules, content routing).
Implementation details that save time
These notes help avoid surprises when integrating geolocation into production systems.
- Authentication header: Always send Authorization: Bearer YOUR_API_KEY. Do not append extra schemes or query parameters unless documented.
- Accept header: Set Accept: application/json to make intent explicit and ensure consistent parsing.
- Timeouts: Use a short network timeout (e.g., 2–5 seconds) and handle fallback behavior if a lookup is slow or fails.
- ZIP-only caching: Cache successful lookups keyed by IP for a reasonable TTL that aligns with your business needs. Geolocation usually doesn’t need sub-minute freshness. Even a 1–24 hour cache can cut latency and cost significantly.
- Idempotency: GET requests are safe to retry. If you implement retries, use small backoffs to avoid thundering herds during transient failures.
- Partial data: If zip is missing, degrade gracefully (e.g., hide ZIP-targeted features or fall back to a broader region gate).
- Live flags: Fields reflecting network state can change; don’t persist them indefinitely without a refresh strategy.
- Privacy controls: If a user opts out of geolocation-based features, bypass the lookup or discard results for that session.
Validating your integration
Use the documented fixture IP to confirm your request formatting, headers, and parsing. When your code returns a non-empty zip from that response, you can switch to dynamic inputs from your application layer.
- Use the curl command to confirm your key and network path are correct.
- Use your language client to ensure your HTTP stack, timeout, and JSON parsing are correct.
- Compare results from the same IP across your environments to confirm no proxy or middleware is stripping the Authorization header.
When you’re ready to explore operational endpoints or status, visit MCP.
Error handling and fallbacks
Build a simple policy that makes your product resilient:
- HTTP/network errors: Return a neutral experience and log the failure with the IP that triggered it.
- Non-success response: Check the status field in the JSON body. If not “success,” skip ZIP-dependent logic.
- Empty or malformed body: Treat as a soft failure; consider a short-lived negative cache to avoid repeat calls in a hot path.
For visibility, log the query, the status value, and whether zip was present. Avoid logging full responses in production if they are not needed.
Performance and cost control
Keep performance predictable and costs under control with a few simple steps:
- Cache by IP for reads that repeat (e.g., the same client over a session).
- Deduplicate concurrent lookups for the same IP within your service to prevent spikes.
- Leverage the trial (7 days or 50 requests) to measure typical traffic and set cache TTLs that reduce external calls without harming user experience.
- Start with the Basic plan ($29.99/mo) and instrument usage so you can right-size later.
Deployment checklist
- Configuration
- Store YOUR_API_KEY in your secrets manager.
- Set a default timeout (2–5 seconds) and retry policy (at most 1–2 retries).
- Ensure your proxies/load balancers forward the Authorization header unmodified.
- Functionality
- Call GET /api/ip with the ip query parameter.
- Verify status == "success" and read data.zip.
- Implement graceful fallback if zip is missing.
- Operations
- Cache results by IP with a sensible TTL.
- Add logging for request timing and error categories.
- Dashboards/alerts for error rates and timeouts.
FAQ
How do I authenticate?
Send Authorization: Bearer YOUR_API_KEY on every request, along with Accept: application/json.
Which endpoint do I use to get a ZIP code?
Use GET /api/ip with the ip query parameter. The ZIP code is returned in the zip field of the JSON response.
Can I test without using my users’ IPs?
Yes. Use the documented fixture IP 148.105.12.120 to verify your request formatting and JSON parsing. Do not treat the fixture as a live indicator for user geolocation.
What if the response does not include zip?
Handle it gracefully. Skip ZIP-dependent logic or fall back to a broader region gate. Log the condition for monitoring.
How should I control costs?
Cache results by IP, instrument your call volume, and use the trial (7 days or 50 requests) to fine-tune TTLs before moving to production. The Basic plan is $29.99/mo.
Ready to integrate the IP ZIP Code API? Create your key and start testing with the fixture IP today: Register. For parameters and field definitions, see the Documentation. If you need to explore control-plane or environment endpoints, visit MCP.
