shipzil

Reference

Public Gateway, model, service and transport interfaces.

This page covers the caller-facing API. The generated Python reference is produced from source docstrings and also includes adapter-author interfaces.

import shipzil as z
from shipzil.providers import Adapter, Capabilities, Quote

Public dataclasses are frozen. Rate and Label use keyword-only constructors.

Gateway

z.Gateway(
    sources=None,
    *,
    fallback=None,
    max_spend=None,
    max_spend_currency=None,
    dry_run=False,
    max_workers=None,
    **credentials,
)
ParameterMeaning
sourcesMapping[str, Adapter]; caller-defined source name to configured adapter
**credentialsshort form: provider name to credential; mutually exclusive with sources
fallbacksequential source order; None calls all eligible sources concurrently
max_spendrefuse to buy above this amount
max_spend_currencycurrency max_spend is expressed in; a rate in another currency is refused, not converted
dry_runreturn a synthetic label instead of calling a purchase endpoint
max_workersworker count per source or parcel executor, not a global request cap

Credential examples:

z.Gateway(shippo="shippo_test_...", easyship="sand_...")
z.Gateway(shipstation_v1=("key", "secret"))

Methods

gateway.get_rates(
    shipment,
    *,
    sources=None,
    providers=None,
    carriers=None,
    services=None,
) -> GatewayQuote

gateway.buy(shipment, rate) -> Label
gateway.void(label) -> bool

sources= matches configured source names; providers= matches adapter types. All filters intersect, and an unknown source or provider raises ConfigurationError.

buy() requires a rate returned by this Gateway and uses rate.source. void() uses label.source.

GatewayQuote

quote.rates       # tuple[Rate, ...]
quote.sources     # tuple[SourceResult, ...]
quote.excluded    # tuple[Exclusion, ...]
quote.errors      # tuple[ShipzilError, ...]
quote.messages    # tuple[str, ...]
quote.services    # ServiceMap
quote.cheapest    # Rate | None
quote.fastest     # Rate | None
quote.explain()   # str

bool, len, iteration and integer indexing operate on rates.

cheapest returns None unless every rate has the same non-null currency. fastest ignores rates with no delivery_days.

SourceResult

FieldTypeMeaning
sourcestrconfigured account name
providerstradapter name
ratestuple[Rate, ...]rates contributed after filtering
excludedtuple[Exclusion, ...]exclusions from this source
messagestuple[str, ...]provider warnings
viastrprovider operation used for rating
errorShipzilError | Nonesource failure
okbooltrue when no source error was raised

Request models

Address

Required: street1, city, postal_code.

Optional: country="US", state, street2, street3, name, company, phone, email, address_class.

address_class is UNKNOWN, RESIDENTIAL, COMMERCIAL, PO_BOX or MILITARY. Providers that accept only a residential boolean receive no value when the class is unknown.

Item

FieldMeaning
descriptionitem description
quantityinteger, at least 1
weightper-unit Weight
dimensionsper-unit Dimensions; currently used by Easyship
valueper-unit Decimal customs value
currencycustoms currency, default USD
skuprovider SKU lookup key
hs_codecaller-supplied HS/Schedule B code; shipzil does not validate it
categoryprovider category; currently used by Easyship
origin_countrycaller-supplied ISO alpha-2 origin

Every cross-border item needs weight and value. Easyship requires at least one item on domestic requests and requires an explicit value plus category or HS code.

Parcel

Required: a weight or items from which weight can be derived.

FieldMeaning
weightpackage weight
dimensionspackage dimensions
itemstuple[Item, ...]
packagingprovider packaging token; provider metadata is not currently enforced
dangerous_goodsDangerousGoods | None
insured_valuenumeric amount; currently sent by Shippo and ShipStation v2 as USD
referenceretained locally; current adapters do not transmit it

Shipment

FieldMeaning
from_addressorigin Address
to_addressdestination Address
parcelsnon-empty tuple[Parcel, ...]
duties_paid_byUNSPECIFIED, SENDER or RECIPIENT
ship_datetransmitted by ShipStation v2 only
eei_exemptiontransmitted by Shippo only
referenceretained locally; current adapters do not transmit it

Response models

Rate

FieldMeaning
carrier, serviceprovider display text
provideradapter name
sourceconfigured account name, added by Gateway
service_codeprovider purchase token when separate from display text
service_keyprovider-scoped ServiceKey; may be None if unaddressable
amount, currencyprovider quote; currency is None on ShipStation v1
base_amount, surchargesprovider components when available
delivery_days, guaranteedoptional service estimates
strategyNATIVE or FANOUT
parcel_countnumber of parcels represented
rawprovider response fragment

Label

FieldMeaning
tracking_numberfirst available tracking number
tracking_legstracking legs returned by providers that expose them
label_urlprovider-hosted label URL, or empty string
label_database64 label content, currently ShipStation v1
carrier, service, amount, currencypurchase result
provider, sourceadapter and configured account
shipment_idprovider shipment/transaction id
is_testTrue, False or None when undetectable
rawprovider response

Exclusion

FieldMeaning
codeExclusionCode
messageprovider or local explanation
carrier, serviceaffected identity when known
sourceprovider for provider output; shipzil for local validation/filtering

See Errors and exclusions for all codes.

ServiceKey

key.provider
key.carrier
key.service
key.packaging
key.slug
key.unqualified

slug renders {provider}-{carrier}-{service}[-packaging]. unqualified removes the provider and is a grouping key only. It does not imply that services are interchangeable.

ServiceMap.resolve() intersects provider, carrier and exact service filters over services observed in returned rates.

Units

z.Weight.of(16, "oz")
z.Dimensions.of(10, 8, 4, "in")

Supported weight units: mg, g, kg, oz, lb.

Supported dimension units: mm, cm, m, in, ft.

Values use Decimal internally. ValueError is raised for unsupported units or non-positive dimensions/weights.

Dangerous goods

DangerousGoods stores declarations supplied by the caller. shipzil does not determine whether a shipment is legally compliant.

has_core_regulated_fields checks only for UN number, hazard class and packing group. It is not a compliance result.

If an adapter cannot transmit populated dangerous-goods fields, the quote includes HAZMAT_DETAIL_UNSUPPORTED.

Transport

class Transport(Protocol):
    def send(self, request: HttpRequest) -> HttpResponse: ...

The transport returns HttpResponse for every HTTP status. It raises OSError for DNS, connection, reset and timeout failures so shipzil can apply retry and error mapping. send() can be called concurrently and should be thread-safe.

The default UrllibTransport is stateless and does not pool connections.

Adapter constructors

ShippoAdapter(api_token, *, timeout=90, transport=None)

EasyshipAdapter(
    api_key,
    *,
    sandbox=None,
    label_timeout=60,
    poll_interval=2,
    default_category=None,
    timeout=60,
    transport=None,
)

ShipStationV1Adapter(
    api_key,
    api_secret,
    *,
    carriers=None,
    test_labels=True,
    confirmation="none",
    timeout=60,
    transport=None,
)

ShipStationV2Adapter(
    api_key,
    *,
    carrier_ids=None,
    timeout=60,
    transport=None,
)

See Providers before relying on a provider-specific operation.

On this page