Package Tracking API Tutorial in Python: USPS, UPS & FedEx
Track USPS, UPS and FedEx packages from Python with one REST API — requests examples for lookups, carrier detection, webhooks and signature checks. Copy-paste ready.
WhereParcel Team
This tutorial walks through tracking packages from Python with the WhereParcel API — from a single USPS lookup to a webhook receiver that keeps your database up to date. Everything uses requests and plain functions you can drop into a Django, Flask or FastAPI project.
By the end you’ll have:
- a small client with authentication and rate-limit handling,
- functions to look up a package, detect its carrier and register many packages for push updates,
- a Flask webhook receiver that verifies the signature on every request,
- a catch-up job for when your server was down.
TL;DR — The Quick Answer
- Send
POST https://api.whereparcel.com/v2/trackwithAuthorization: Bearer API_KEY:SECRET_KEYand a list oftrackingItems. Each result has astatus(successorerror) and, on success, a normalizeddeliveryStatus. - One
/v2/trackcall takes up to five tracking numbers, but USPS, UPS, FedEx and DHL are limited to one per request combined. For batches, register them for push updates instead — up to 100 per call. - Verify webhooks by computing HMAC-SHA256 of the raw request body with your endpoint secret and comparing it to the
X-WhereParcel-Signatureheader.
Prerequisites
- Python 3.9 or newer and
requests. - A WhereParcel API key and secret key from the console. Plans start at $49/month; see pricing.
pip install requests
export WHEREPARCEL_API_KEY="your_api_key"
export WHEREPARCEL_SECRET_KEY="your_secret_key"
Keep the keys in environment variables or your secret manager — never in source control.
Step 1 — A Small Client
Every endpoint takes and returns JSON, and every response has a top-level success flag. This helper sends a request, raises a clear exception when success is false, and waits and retries when you hit the per-minute rate limit:
import os
import time
import requests
API_BASE = "https://api.whereparcel.com"
RETRYABLE = {"RATE_LIMIT_EXCEEDED", "MINUTE_QUOTA_EXCEEDED"}
session = requests.Session()
session.headers.update({
"Authorization": f"Bearer {os.environ['WHEREPARCEL_API_KEY']}:{os.environ['WHEREPARCEL_SECRET_KEY']}",
"Content-Type": "application/json",
})
class WhereParcelError(Exception):
def __init__(self, status, code, message):
super().__init__(f"{status} {code}: {message}")
self.status = status
self.code = code
def call(method, path, payload=None, retries=3):
"""Send one request. Retries on per-minute rate limits, raises on any other error."""
for attempt in range(retries + 1):
resp = session.request(method, API_BASE + path, json=payload, timeout=90)
body = resp.json()
if resp.ok and body.get("success"):
return body
error = body.get("error") or {}
if resp.status_code == 429 and error.get("code") in RETRYABLE and attempt < retries:
time.sleep(error.get("retryAfter") or 2 ** attempt)
continue
raise WhereParcelError(resp.status_code, error.get("code"), error.get("message"))
Two choices worth explaining:
- The timeout is generous. Lookups for USPS, UPS, FedEx and DHL can take noticeably longer than other carriers. Don’t set a 5-second timeout and treat slow answers as failures.
- Only short rate limits are retried.
MONTHLY_QUOTA_EXCEEDEDalso returns 429, but waiting a few seconds won’t fix it — the helper raises it so you can alert on it.
Step 2 — Look Up One Package
def track(carrier, tracking_number):
body = call("POST", "/v2/track", {
"trackingItems": [{"carrier": carrier, "trackingNumber": tracking_number}],
})
item = body["data"][0]
if item["status"] != "success":
error = item.get("error") or {}
raise WhereParcelError(200, error.get("code"), error.get("message"))
return item["data"]
result = track("us.usps", "9400111899562537866361")
print(result["deliveryStatus"])
for event in result["events"]:
print(event["timestamp"], event["status"], event.get("location"), "-", event["description"])
The response looks like this:
{
"success": true,
"data": [
{
"carrier": "us.usps",
"trackingNumber": "9400111899562537866361",
"status": "success",
"data": {
"deliveryStatus": "delivered",
"events": [
{
"timestamp": "2026-10-01T18:31:00.000Z",
"status": "delivered",
"location": "DECATUR, GA 30030",
"description": "Delivered, Front Door/Porch",
"rawStatus": "Delivered, Front Door/Porch",
"rawDescription": "Delivered, Front Door/Porch"
}
],
"lastUpdated": "2026-10-02T14:05:12.000Z"
},
"billable": true,
"cached": false
}
],
"summary": { "total": 1, "success": 1, "failed": 0, "usageIncremented": 1 }
}
data is a list — one entry per tracking number — and each entry succeeds or fails on its own, which is why track() checks the item’s status rather than only the top-level success. Timestamps are UTC. Cached answers come back with billable: false.
Step 3 — Turn Statuses Into Messages
Whatever the carrier, deliveryStatus is one of nine values. Map them once and your UI never needs to know about carriers:
STATUS_TEXT = {
"pending": "Label created — waiting for the carrier to pick it up",
"in_transit": "On its way",
"out_for_delivery": "Out for delivery today",
"delivered": "Delivered",
"failed": "Delivery attempt failed",
"returned": "Returned to sender",
"cancelled": "Shipment cancelled",
"lost": "Reported lost by the carrier",
"unknown": "Status not available yet",
}
print(STATUS_TEXT[result["deliveryStatus"]])
Each event also keeps the carrier’s own wording in rawStatus and rawDescription — handy for support staff who want the exact scan text.
Step 4 — Detect the Carrier
Customers paste tracking numbers without saying which carrier they’re with. POST /v2/detect matches the number’s format and returns candidates, most specific first. It’s pattern matching only, so it’s free and doesn’t count toward usage:
def detect_carrier(tracking_number):
body = call("POST", "/v2/detect", {"trackingNumber": tracking_number})
candidates = body["data"]["candidates"]
if not candidates:
return None
return max(candidates, key=lambda c: c["specificityScore"])["code"]
carrier = detect_carrier("1Z999AA10123456784") # "us.ups"
result = track(carrier, "1Z999AA10123456784")
Formats overlap — a long run of digits can match several carriers — so treat detection as a strong guess. If the lookup comes back with TRACKING_NOT_FOUND, try the next candidate or ask the customer to pick a carrier. You can test the same logic in the browser with the tracking number validator.
Step 5 — Track Many Packages With Webhooks
Two limits shape how you track in bulk:
/v2/tracktakes up to five tracking numbers per call.us.usps,us.ups,us.fedexandintl.dhlcount as one combined slot per/v2/trackrequest, because their lookups take longer. Sending two of them in one call returnsINVALID_REQUEST.
For anything more than a handful, register the packages for push updates. One registration takes up to 100 tracking numbers; each package counts once, and we re-check it about every 12 hours for up to 10 days, posting the result to your endpoint after every check.
First, create an endpoint — once, not per package:
endpoint = call("POST", "/v2/webhook-endpoints", {
"name": "Production",
"url": "https://example.com/webhooks/whereparcel",
})["data"]
print(endpoint["endpointId"]) # wep_... — use it when registering
print(endpoint["secret"]) # whsec_... — store it; you need it to verify signatures
Then register packages in chunks of 100:
def register(parcels, endpoint_id):
"""parcels: list of (carrier, tracking_number, order_id) tuples."""
request_ids = []
for start in range(0, len(parcels), 100):
chunk = parcels[start:start + 100]
body = call("POST", "/v2/webhooks/register", {
"webhookEndpointId": endpoint_id,
"recurring": True,
"trackingItems": [
{"carrier": c, "trackingNumber": n, "clientId": order_id}
for c, n, order_id in chunk
],
})
request_ids.append(body["data"]["requestId"])
return request_ids
request_ids = register([
("us.usps", "9400111899562537866361", "order-1001"),
("us.ups", "1Z999AA10123456784", "order-1002"),
("us.fedex", "794644790132", "order-1003"),
], endpoint["endpointId"])
Save each requestId — it’s how you look up a registration later.
Step 6 — Receive Webhooks in Flask
Every webhook is a POST with a JSON body and three headers: X-WhereParcel-Signature, X-WhereParcel-Event and X-WhereParcel-Timestamp. The signature is an HMAC-SHA256 hex digest of the raw request body, keyed with your endpoint secret.
import hashlib
import hmac
import os
from flask import Flask, abort, request
app = Flask(__name__)
WEBHOOK_SECRET = os.environ["WHEREPARCEL_WEBHOOK_SECRET"].encode()
def valid_signature(raw_body: bytes, signature: str) -> bool:
expected = hmac.new(WEBHOOK_SECRET, raw_body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, signature or "")
@app.post("/webhooks/whereparcel")
def whereparcel_webhook():
raw = request.get_data() # the exact bytes that were signed
if not valid_signature(raw, request.headers.get("X-WhereParcel-Signature")):
abort(401)
payload = request.get_json()
for item in payload["data"]["trackingItems"]:
if item["status"] == "failed":
continue # this check didn't reach the carrier; the next one will try again
save_status(
item["carrier"]["code"],
item["trackingNumber"],
item["currentStatus"],
item["trackingData"],
)
return "", 204
Details that trip people up:
- Verify against the raw bytes. Don’t parse the JSON and re-serialize it before hashing — key order and spacing change and the signature won’t match.
carrieris an object here (code,name,country), not a string as in/v2/trackresponses. And a lookup that didn’t succeed is marked"failed"in webhooks, where/v2/trackuses"error".- Answer within 10 seconds. If
save_statusis slow, put the payload on a queue and return204straight away. - Each delivery is attempted once. Make your handler idempotent — saving the same status twice should be harmless — and use the catch-up job below after any downtime.
The first post for a registration arrives with event: "tracking.registered"; later checks arrive as tracking.updated. Our webhook best practices post covers more on endpoint design.
Step 7 — Catch Up After Downtime
Webhooks aren’t resent, so if your server was down, ask for the change history of each registration and replay anything newer than the last update you saved:
def catch_up(request_id, since_iso):
"""Replay status changes recorded after `since_iso` (an ISO 8601 UTC timestamp)."""
changes = call("GET", f"/v2/webhooks/subscriptions/{request_id}/changes?limit=100")["data"]["changes"]
for change in reversed(changes): # the API returns newest first
if change["timestamp"] <= since_iso:
continue
detail = call("GET", f"/v2/webhooks/subscriptions/{request_id}/changes/{change['changeId']}")["data"]
for item in detail["changedItems"]:
save_status(item["carrier"], item["trackingNumber"], item["currentStatus"], item["trackingData"])
Run it from a scheduled job after deploys or outages. Reading the change history is free.
Step 8 — Errors You’ll Actually See
| Where | Code | What it means | What to do |
|---|---|---|---|
Item in /v2/track | TRACKING_NOT_FOUND | The carrier has no record of this number yet | Common for new labels — try again later, or try the next detected carrier |
/v2/track (400) | INVALID_REQUEST | More than one USPS/UPS/FedEx/DHL number in one request | Send them one per request, or register them for push |
/v2/track (400) | REQUEST_VALIDATION_FAILED | A carrier code or tracking number is invalid | Check invalidItems in the response |
| Any (429) | RATE_LIMIT_EXCEEDED | Burst limit — more than 10 requests in 3 seconds | Wait retryAfter seconds — the client above does this |
| Any (429) | MINUTE_QUOTA_EXCEEDED | Your plan’s per-minute limit | Wait retryAfter seconds (until the minute resets) — the client above does this |
| Any (429) | MONTHLY_QUOTA_EXCEEDED | You’ve used this month’s requests | Alert someone; upgrade the plan or wait for the next month |
Responses from the billable endpoints (/v2/track and /v2/webhooks/register) carry X-RateLimit-Remaining-Minute (and -Day / -Month) headers if you want to slow down before you hit the limit. Plan limits are listed in Rate Limits.
Production Checklist
- Keys and the webhook secret come from environment variables or a secret manager.
/v2/trackis used for on-demand answers; everything you follow over days is registered for push.- No more than one USPS/UPS/FedEx/DHL number per
/v2/trackcall. - The webhook handler verifies the signature on the raw body, returns within 10 seconds and is idempotent.
- A catch-up job replays change history after downtime.
- You alert on
MONTHLY_QUOTA_EXCEEDED.
FAQ
Is there an official Python SDK?
Not today — the API is a handful of JSON endpoints, so requests (or httpx) is all you need. There’s an official Node.js SDK, published on npm as whereparcel.
How do I track several USPS packages at once in Python?
Register them with POST /v2/webhooks/register — up to 100 per call — and receive the results on your webhook endpoint. On /v2/track, USPS, UPS, FedEx and DHL share one slot per request.
Do I need a USPS, UPS or FedEx developer account?
No. You call one API with one key; WhereParcel handles the carriers.
How often are webhooks sent?
After every check: the first arrives shortly after you register, and later ones about every 12 hours, for up to 10 days per registration.
Can I try it without writing code?
Yes — run a lookup in the API Playground. When you’re ready for the full reference, see the Tracking API docs, Webhooks and Webhook Endpoints. For the bigger picture, read Shipment Tracking API: How It Works & How to Choose.
Can't find your carrier? We add new carriers on request — just let us know.
Request a carrier →Got a question? Just ask. Drop by our Discord — the developer behind WhereParcel reads every message and replies personally. No bots, no tickets, just a real conversation.
Join Discord → Join Slack →