Python
The trackified package on PyPI, with sync and async clients. Python 3.9+.
The trackified package is typed and has one dependency, httpx. It has a sync client, Trackified, and an async one, AsyncTrackified, with the same methods. Source: trackified/trackified-python.
Install
- pip
- uv
- poetry
pip install trackifieduv add trackifiedpoetry add trackifiedUntil it reaches PyPI
If pip install trackified can't find the package yet, install the release straight from GitHub:
pip install https://github.com/trackified/trackified-python/releases/download/v0.2.0/trackified-0.2.0-py3-none-any.whlConfigure
from trackified import Trackified
client = Trackified() # reads TRACKIFIED_API_KEY and TRACKIFIED_BASE_URLPass options to override the defaults:
client = Trackified(
"test_...", # api_key
base_url="https://api.trackified.net",
timeout=30.0, # seconds
max_retries=2,
)The base URL works with or without /v1 at the end. Use the client as a context manager, or call client.close(), to release its connections.
Check that the API is up. No key is needed for this call:
print(client.health()["status"]) # "ok"; a 503 raises APIErrorResponses are plain dicts, typed as TypedDicts (Tracking, TrackingEvent, Webhook, Usage and so on).
Trackings
Create
tracking = client.trackings.create(
"1Z999AA10123456784",
carrier="ups", # optional: our id or a name like "UPS Ground"; detected when left out
custom_id="order_1042", # optional: your own reference
customer_email="ada@example.com", # optional
)carrier takes our carrier id, a carrier or service name ("USPS Priority Mail"), or another provider's slug ("dhl_express"). The tracking stores our id. Leave carrier out and we detect it from the number. If we can't tell, the call raises ValidationError with code set to carrier_not_detected.
Get
tracking = client.trackings.get("trk_...")
print(tracking["status"], tracking["estimated_delivery"])
for event in tracking["events"]: # newest first
print(event["occurred_at"], event["status"], event["description"], event["location"])List and auto-paginate
# One page
page = client.trackings.list(status="in_transit", limit=50)
print(len(page["data"]), "of", page["pagination"]["total"])
# Every matching tracking, fetching pages as needed
for t in client.trackings.list_auto_paging(status="delivered"):
print(t["tracking_number"], t["delivered_at"])Filters: status, carrier, custom_id, tracking_number, plus limit and offset.
Update, stop and retrack
# Change the carrier, custom_id or customer_email. Arguments you leave out stay as they are.
client.trackings.update("trk_...", carrier="usps")
# Ask for the carrier to be checked again within a minute.
result = client.trackings.retrack("trk_...")
print(result["queued"])
# Stop tracking. The tracking is no longer checked or returned.
client.trackings.delete("trk_...")Bulk create
result = client.trackings.create_bulk([
{"tracking_number": "1Z999AA10123456784", "custom_id": "order_1042"},
{"tracking_number": "9434650110837017316201", "carrier": "usps", "custom_id": "order_1043"},
])
for row in result["data"]:
print(row["tracking"]["id"] if row["ok"] else row["error"])Each row succeeds or fails on its own. Your plan sets the most rows per request. See Rate limits and plans.
Carriers
detection = client.carriers.detect("1Z999AA10123456784")
best = detection["candidates"][0] # best first
print(best["carrier"], best["confidence"])
# Map a free-text name or another provider's slug to our id. None if we don't serve it.
match = client.carriers.resolve("FedEx SmartPost")
if match:
print(match["carrier"], match["confidence"], match["matched"])
catalog = client.carriers.catalog(q="dhl") # the full carrier catalogWebhooks
Create an endpoint
webhook = client.webhooks.create(
"https://example.com/webhooks/trackified",
event_types=["tracking.status_changed", "tracking.delivered"],
)
# Store webhook["secret"] now. It's only returned here.Update, pause and rotate
# Change the URL or events, or pause it. The secret stays the same.
client.webhooks.update(webhook["id"], event_types=["tracking.status_changed"])
client.webhooks.update(webhook["id"], enabled=False)
# New secret, shown once. The old one keeps verifying for 24 hours by default.
rotated = client.webhooks.rotate_secret(webhook["id"], expires_in_hours=24)
print(rotated["secret"], rotated["previous_secret_expires_at"])During the window, pass both secrets when you verify (below).
Verify in Flask
request.get_data() gives the raw body bytes.
import os
import trackified
from flask import Flask, request
app = Flask(__name__)
@app.post("/webhooks/trackified")
def trackified_webhook():
try:
event = trackified.construct_event(
request.get_data(),
request.headers.get("x-tracking-signature", ""),
os.environ["TRACKIFIED_WEBHOOK_SECRET"],
)
except trackified.SignatureVerificationError:
return "", 400
tracking = trackified.tracking_of(event) # the tracking, for any event type
print(event["type"], tracking["tracking_number"])
return "", 200Verify in FastAPI
await request.body() gives the raw body bytes. Don't declare the body as a Pydantic model on this route: FastAPI would parse it first.
import os
import trackified
from fastapi import FastAPI, Request, Response
app = FastAPI()
@app.post("/webhooks/trackified")
async def trackified_webhook(request: Request) -> Response:
try:
event = trackified.construct_event(
await request.body(),
request.headers.get("x-tracking-signature", ""),
os.environ["TRACKIFIED_WEBHOOK_SECRET"],
)
except trackified.SignatureVerificationError:
return Response(status_code=400)
if event["type"] == "tracking.delivered":
print("delivered:", event["data"]["tracking_number"])
return Response(status_code=200)Events and their data
event["data"] is the tracking for every type except tracking.status_changed, which carries {"tracking", "previous_status", "current_status"}. trackified.tracking_of(event) returns the tracking for any type.
Failed carrier checks
A tracking.exception sent because we couldn't reach the carrier carries {"tracking_id", "error"}, not a tracking, so tracking_of doesn't return a full tracking for it. Check for "tracking_id" before you use the result. See Webhook events.
Why verification failed
construct_event raises SignatureVerificationError with a reason: missing, malformed, timestamp or mismatch. verify_detailed returns it without raising; verify returns a bool:
result = trackified.verify_detailed(raw_body, header, secret)
if not result.valid:
print("webhook rejected:", result.reason)All three take one secret or a list of secrets (any may match), and tolerance= in seconds (default 300). Pass both secrets while a rotation is in progress:
event = trackified.construct_event(
raw_body,
header,
[os.environ["TRACKIFIED_WEBHOOK_SECRET"], os.environ["TRACKIFIED_WEBHOOK_SECRET_OLD"]],
)They're also available as client.webhooks.verify, verify_detailed, construct_event and tracking_of. WebhookVerificationError, the 0.1 name, still works: it's the same class as SignatureVerificationError.
Async
import asyncio
from trackified import AsyncTrackified
async def main() -> None:
async with AsyncTrackified() as client:
tracking = await client.trackings.create("1Z999AA10123456784", custom_id="order_1042")
async for t in client.trackings.list_auto_paging(status="in_transit"):
print(t["id"], t["status"])
asyncio.run(main())Errors
from trackified import (
ConnectionError,
NotFoundError,
QuotaExceededError,
RateLimitError,
TrackifiedError,
ValidationError,
)
try:
client.trackings.create("ABC123", idempotency_key="order_1042")
except ValidationError as e:
if e.code == "carrier_not_detected":
... # ask the user for the carrier
except QuotaExceededError:
... # 402: this month's trackings are used up
except ConnectionError as e:
if e.code == "timeout":
... # the outcome is unknown: retry later with the same idempotency key
except NotFoundError:
... # 404
except RateLimitError as e:
print("retry in", e.retry_after, "s")
except TrackifiedError as e:
print(e.status, e.code, e.message, e.request_id)The classes are AuthenticationError (401), PermissionError (403), NotFoundError (404), ValidationError (400, 422), QuotaExceededError (402), ConflictError (409, including idempotency_in_progress), RateLimitError (429), APIError (5xx), ConnectionError (no response; code is "timeout" or "connection") and SignatureVerificationError. Import them from trackified: two of the names shadow Python built-ins.
A timeout means the outcome is unknown: the request may have reached us. The library's own retries reuse the idempotency key, so a create is never doubled. If you retry yourself later, pass the same idempotency_key.
Options
Argument | Default | |
|---|---|---|
|
| The first positional argument. |
|
| |
|
| Seconds. |
|
| Retries for network errors, 408, 429 and 5xx. |
| a new | Pass your own |
| none | Called before each attempt. |
| none | Called after each attempt. |
Request hooks
from trackified import RequestInfo, ResponseInfo, Trackified
def on_request(info: RequestInfo) -> None:
print("->", info["method"], info["url"], "attempt", info["attempt"], info["idempotency_key"])
def on_response(info: ResponseInfo) -> None:
outcome = info["status"] if info["status"] is not None else info["error"]
print("<-", info["method"], info["url"], outcome, info["request_id"], f"{info['duration_ms']:.0f}ms")
client = Trackified(on_request=on_request, on_response=on_response)Each hook runs once per attempt, so a retried request calls them more than once. attempt is 1 for the first try. status is None when no response arrived; error is the typed error when the status is 400 or more or the connection failed. idempotent_replayed says whether a create was a replay. A hook that raises is ignored.
trackings.create and trackings.create_bulk take idempotency_key= to replace the generated key. See Pagination, retries and idempotency.