estimate.py
Runnable TariffTrust integration example: a product, then a whole declaration, saved.
Show the code · 85 lines
"""Runnable TariffTrust integration example: a product, then a whole declaration, saved.
TARIFFTRUST_URL=https://api.tarifftrust.com TARIFFTRUST_API_KEY=tarifftrust_... python estimate.py
Uses only ``httpx``. Keep the API key on your server, never in a browser or a mobile app.
"""
import os
import sys
import uuid
import httpx
def client(url=None, key=None):
return httpx.Client(
base_url=(url or os.environ["TARIFFTRUST_URL"]).rstrip("/") + "/v1",
headers={"Authorization": f"Bearer {key or os.environ['TARIFFTRUST_API_KEY']}"},
timeout=30,
)
def money(amount):
"""An amount as the API gives it: a decimal string in USD, or null when unknown, never zero."""
return "unknown" if amount is None else f"${amount}"
def describe(result):
"""Relay a result honestly: unknown is never zero, and the status always goes with it."""
lines = [f"Status: {result['status']}"]
if result["estimated_duty"] is not None:
lines.append(f"Estimated duty: {money(result['estimated_duty'])}")
else:
lines.append(f"Established duties only: {money(result['known_duty_subtotal'])} (total unknown)")
for item in result.get("assumptions") or []:
# What nobody answered took its ordinary case: show it, with what each other answer gives,
# to the user who may know better, and send their answer in ``facts``.
others = ", ".join(
f"{other['value']}: {money(other['estimated_duty'])}" for other in item.get("alternatives") or []
)
assumed = f"Assumed: {item.get('question') or item['fact']} {item['value']}"
lines.append(f"{assumed} (otherwise {others})" if others else assumed)
for question in result.get("input_guidance") or []:
lines.append(f"Question: {question.get('question') or question['label']} ({question['field']})")
for item in result.get("review_pending", []):
lines.append(f"Under review: {item.get('position') or item.get('reference')}: {item['reason']}")
return "\n".join(lines)
def estimate_product(api, as_of=None, facts=None):
"""``as_of`` is the date of entry; without it, the service uses today and records it. The first
call estimates. ``facts`` are your user's own answers: a question without an ordinary case
(``needs_information``, asked in ``input_guidance``) is theirs to answer, never yours in their
place: "no" to "does Section 232 apply?" takes that duty out of the estimate."""
product = {"hts": "6109.10.00.12", "origin": "CN", "customs_value": "10000", "as_of": as_of}
return api.post("/estimates", json={**product, "facts": facts or {}}).raise_for_status().json()
def save_declaration(api, as_of=None, key=None):
"""Ten lines of $1,000: one MPF on the declaration, not ten minimums. ``key`` makes the request
safe to send again, after a timeout say: one per declaration, kept to send it again, for 7 days;
the same key with another request is refused (409)."""
entry = {
"reference": "Example entry",
"as_of": as_of,
"include_fees": True,
"lines": [{"hts": "6109.10.00.12", "origin": "CN", "customs_value": "1000"} for _ in range(10)],
}
headers = {"Idempotency-Key": key or str(uuid.uuid4())}
return api.post("/saved-estimates", json={"entry": entry}, headers=headers).raise_for_status().json()
def main():
with client() as api:
print(describe(estimate_product(api)))
saved = save_declaration(api)
print(f"Saved declaration {saved['entry_id']} (saved estimate {saved['id']})")
print(describe(saved["result"]))
fees = {fee["label"]: money(fee["amount"]) for fee in saved["result"]["fees"]}
print(f"Fees once per declaration: {fees}")
return 0
if __name__ == "__main__":
sys.exit(main())