Python helpers

track_shipment

Get live carrier tracking for a parcel, so the bot can tell a customer where it is right now.

track_shipment(tracking_number: str, carrier: str = None, fallback=None) -> dict

Looks up live carrier tracking for a tracking number. Use it when the store only knows that a parcel was handed to the carrier, but the bot should answer "where is my parcel?" or "has it arrived?". A Shopify fulfillment with a tracking number is a typical case. It also tracks parcels the store did not ship, such as a customer's return parcel.

Supported carriers:

  • DHL (Germany: DHL Paket, Deutsche Post).
  • USPS. Since April 2026, USPS only shares tracking of labels created by a business (through Shippo, Pirate Ship, a returns app and similar) with the account that created them. For such numbers track_shipment raises a ValueError saying automatic tracking is not supported for this label. Labels bought at a Post Office counter stay trackable.

Numbers from other carriers raise a ValueError (a UPS 1Z... number gets an error that names UPS). Pass fallback to keep your action running and share the store's own tracking link instead.

Results are cached for an hour per tracking number. An uncached DHL lookup can take 15-30 seconds and a USPS lookup a few seconds, so call it only when you need the status, not on every message. Each organization can run up to 10 uncached lookups a minute and 100 an hour; beyond that the lookup fails (or returns fallback).


Parameters

NameTypeDescription
tracking_numberstrThe carrier tracking number. Spaces are ignored.
carrierstr or NoneThe carrier name as the store records it, e.g. "USPS", "DHL" or "Deutsche Post DHL". When omitted, it is detected from the number (USPS: 20-22 digits starting 91-95, or XX123456789US).
fallbackanyValue to return if the lookup fails, e.g. {}. If omitted or None, errors are raised (including unsupported carriers, labels USPS will not share and invalid numbers).

Returns

{
    "carrier": "dhl" | "usps",
    "trackingNumber": str,
    "found": bool,              # False if the carrier has no events for this number
    "status": "delivered" | "in_progress" | "not_found",
    "detailedStatus": "pre_transit" | "in_transit" | "out_for_delivery"
        | "available_for_pickup" | "delivered" | "exception" | "unknown",
    "delivered": bool,
    "deliveredAt": str | None,  # ISO timestamp of the delivery event
    "latestEvent": {
        "timestamp": str | None,
        "description": str,     # e.g. "Delivered, Left with Individual"
        "location": str | None, # e.g. "NORTH HILLS, CA 91343"
        "city": str | None,     # city, state, postalCode, country: USPS only
        "state": str | None,
        "postalCode": str | None,
        "country": str | None,
    } | None,
    "events": [...],            # same shape as latestEvent, oldest first, at most the 50 most recent
    "trackingUrl": str,         # public carrier tracking page
}

status is the same for every carrier: in_progress means the carrier has events but no delivery yet, including parcels where only the label data has been received. detailedStatus gives the carrier's finer stage where it reports one; exception covers alerts, failed delivery attempts and returns to sender. DHL only reports delivered, in_transit or unknown.

A USPS parcel returned to its sender also ends as delivered. When the destination matters (for example a return to your warehouse), check the delivery event's postalCode.


Examples

Add carrier status to a Shopify tracking action

def execute_action(context):
    fulfillment = get_fulfillment(context)  # your own order lookup
    # fallback={} returns an empty dict instead of raising, for example when
    # the carrier is not supported or the carrier site is unreachable.
    tracking = track_shipment(
        fulfillment["trackingNumber"],
        carrier=fulfillment["carrier"],
        fallback={},
    )

    if not tracking.get("found"):
        return {"trackingUrl": fulfillment["trackingUrl"], "carrierStatus": None}

    return {
        "delivered": tracking["delivered"],
        "deliveredAt": tracking["deliveredAt"],
        "latestEvent": tracking["latestEvent"],
        "events": tracking["events"][-5:],
        "trackingUrl": tracking["trackingUrl"],
    }

Check that a return parcel reached the warehouse

WAREHOUSE_ZIP = "91343"

def execute_action(context):
    try:
        tracking = track_shipment(context["args"]["returnTrackingNumber"])
    except ValueError as error:
        # Unsupported carrier, a label USPS will not share, or an invalid number.
        return {"status": "manual-check", "reason": str(error)}

    latest = tracking["latestEvent"] or {}
    if tracking["delivered"] and latest.get("postalCode") == WAREHOUSE_ZIP:
        return {"status": "received", "deliveredAt": tracking["deliveredAt"]}

    return {"status": tracking["detailedStatus"], "trackingUrl": tracking["trackingUrl"]}

On this page