Update Shipment Tracking and Status Automatically

Add tracking numbers and Shipped status to Event Shipments from your shipping system or carrier (for example FedEx or UPS).

Example use case

Your shipping system has issued a tracking number and you want to mark the corresponding Event Shipment as Shipped.

What you'll end up with

An updated Shipment with the new tracking number and status and a verified, unchanged package list.

Before you start

Have a workspace API key, the expected Event ID and the ID of an existing Shipment you can read and edit.

Good to know

The Shipment and its packages have separate tracking numbers. This example updates only the Shipment's tracking number and status.

At a glance

Time to try

About 10 minutes

Effect on your data

Updates records

Endpoints

3

The example updates the Shipment's tracking number and status and writes a private local journal.

How it works

  1. The program reads the Shipment and checks that it belongs to the expected Event.
  2. It saves the tracking number and Shipped status using the revision from that read.
  3. It reads the Shipment again and compares its package list with the original.

Update Shipment tracking

The examples below update one Shipment and verify that its packages are unchanged.

Step 1: Confirm the workspace

Check where the key will make changes so you can confirm the workspace.

curl -X GET "https://api.exhibitday.com/v1/references/workspace_info" -H "Authorization: Bearer YOUR_API_KEY"

Example response (shortened)

{
  "id": 98765
}

Check: Confirm id is the workspace you intended to use.

Step 2: Read the Shipment and its packages

Get its revision and keep the full package list so you can check both the update and the readback.

curl -X GET "https://api.exhibitday.com/v1/events/shipments/info?id=7001&%24include_record_revision=true" -H "Authorization: Bearer YOUR_API_KEY"

Example response (shortened)

{
  "id": 7001,
  "event_id": 5001,
  "tracking_number": "OLD-TRACKING-001",
  "shipment_status_id": 1,
  "components": [
    {
      "id": 12002,
      "component_type_id": null,
      "component_type": "Not Specified",
      "description": "Display stand case",
      "tracking_number": "PACKAGE-1001",
      "dimensions_length": 48.0,
      "dimensions_width": 24.0,
      "dimensions_height": 18.0,
      "weight": 65.0
    },
    {
      "id": 12003,
      "component_type_id": null,
      "component_type": "Not Specified",
      "description": "Brochure carton",
      "tracking_number": "PACKAGE-1002",
      "dimensions_length": 20.0,
      "dimensions_width": 16.0,
      "dimensions_height": 12.0,
      "weight": 18.5
    }
  ],
  "record_revision": "COPY_SHIPMENT_REVISION_FROM_YOUR_READ"
}

Check: Confirm id and event_id, save the components and copy record_revision from your own read.

Step 3: Save the tracking number and Shipped status

Send the new tracking number and status with expected_revision so the API can detect a conflicting change.

curl -X PATCH "https://api.exhibitday.com/v1/events/shipments" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" --data-binary "{\"id\":7001,\"tracking_number\":\"TEST-ANNUAL-EXPO-001\",\"shipment_status_id\":2,\"expected_revision\":\"COPY_SHIPMENT_REVISION_FROM_YOUR_READ\"}"

Example response

{
  "status_code": 200,
  "status": "OK",
  "message": "Shipment updated.",
  "errors": [],
  "record_revision": "NEW_SHIPMENT_REVISION"
}

Check: Look for record_revision in the response. Leave components out to keep the existing packages.

Step 4: Verify the Shipment and packages

Read the same Shipment again to confirm the update and compare its packages with your original list.

curl -X GET "https://api.exhibitday.com/v1/events/shipments/info?id=7001" -H "Authorization: Bearer YOUR_API_KEY"

Example response (shortened)

{
  "id": 7001,
  "event_id": 5001,
  "tracking_number": "TEST-ANNUAL-EXPO-001",
  "shipment_status_id": 2,
  "components": [
    {
      "id": 12002,
      "component_type_id": null,
      "component_type": "Not Specified",
      "description": "Display stand case",
      "tracking_number": "PACKAGE-1001",
      "dimensions_length": 48.0,
      "dimensions_width": 24.0,
      "dimensions_height": 18.0,
      "weight": 65.0
    },
    {
      "id": 12003,
      "component_type_id": null,
      "component_type": "Not Specified",
      "description": "Brochure carton",
      "tracking_number": "PACKAGE-1002",
      "dimensions_length": 20.0,
      "dimensions_width": 16.0,
      "dimensions_height": 12.0,
      "weight": 18.5
    }
  ]
}

Check: Confirm the Shipment and Event IDs, tracking number and status. Compare every returned package field with the original list.

Try it

Before running the example

VariableWhat to put in itRequired?
EXHIBITDAY_API_KEYYour workspace API key.Yes
EXHIBITDAY_EVENT_IDThe expected Event ID. The program checks it against the Shipment response.Yes
EXHIBITDAY_SHIPMENT_IDThe ID of an existing Shipment on that Event.Yes
EXHIBITDAY_TRACKING_NUMBERThe tracking number from your shipping system or carrier. Use plain text on one line, up to 125 UTF-16 code units.Yes
EXHIBITDAY_JOB_IDA stable ID for this logical change.Yes
EXHIBITDAY_JOURNALA private local path for this job's journal.Yes
EXHIBITDAY_JOB_MODEUse new for a genuinely new job or resume with the existing journal. The default is resume.No

Bash

export EXHIBITDAY_API_KEY='YOUR_API_KEY'
export EXHIBITDAY_EVENT_ID='5001'
export EXHIBITDAY_SHIPMENT_ID='7001'
export EXHIBITDAY_TRACKING_NUMBER='TEST-ANNUAL-EXPO-001'

PowerShell

$env:EXHIBITDAY_API_KEY = 'YOUR_API_KEY'
$env:EXHIBITDAY_EVENT_ID = '5001'
$env:EXHIBITDAY_SHIPMENT_ID = '7001'
$env:EXHIBITDAY_TRACKING_NUMBER = 'TEST-ANNUAL-EXPO-001'

Use your own Event and Shipment IDs and tracking number. Set a private journal path and job ID. Set EXHIBITDAY_JOB_MODE=new for a new job, then run the complete example in your language.

Complete example program

Code Samples
#!/usr/bin/env bash
# Requires Bash, curl and Python3. No API key is written into the program.
python3 - <<'EXHIBITDAY_PY'
# Python 3; standard library only. Set EXHIBITDAY_API_KEY before running.
import http.client
import json
import os
import re
import time
import urllib.error
import urllib.parse
import urllib.request

BASE = "https://api.exhibitday.com/v1"
SPEC = json.loads("{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"read_shipment\":{\"method\":\"GET\",\"path\":\"/events/shipments/info\"},\"update_tracking\":{\"method\":\"PATCH\",\"path\":\"/events/shipments\"},\"verify_shipment\":{\"method\":\"GET\",\"path\":\"/events/shipments/info\"}}}")
API_KEY = os.environ["EXHIBITDAY_API_KEY"]
if any(ord(char) < 32 or ord(char) > 126 for char in API_KEY):
    raise RuntimeError("Use the API key as one ASCII header value without control characters")
if not API_KEY.strip():
    raise RuntimeError("Set EXHIBITDAY_API_KEY")

def decode_json(text):
    if SPEC["preserveNumbers"]:
        # Quote JSON NUMBER tokens, never text inside a JSON string, to keep CSV decimals exact.
        text = re.sub(r'"(?:\\.|[^"\\])*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?',
                      lambda m: m[0] if m[0].startswith('"') else json.dumps(m[0]), text)
    return json.loads(text)

from pathlib import Path
# This terminal version uses curl for HTTP and Python's standard library for JSON/CSV.
import subprocess
import tempfile

def transport(method, url, headers, data):
    with tempfile.TemporaryDirectory(prefix="exhibitday-guide-") as directory:
        folder = Path(directory)
        # curl may leave no output file for a valid bodyless304 response.
        (folder / "body").write_bytes(b"")
        command = ["curl", "--disable", "--silent", "--show-error", "--request", method, "--url", url,
                   "--max-time", "30", "--dump-header", str(folder / "headers"),
                   "--output", str(folder / "body"), "--write-out", "%{http_code}"]
        for name, value in headers.items():
            command += ["--header", name + ": " + value]
        if data is not None:
            (folder / "request").write_bytes(data)
            command += ["--data-binary", "@" + str(folder / "request")]
        result = subprocess.run(command, capture_output=True, text=True)
        if result.returncode:
            raise urllib.error.URLError(result.stderr.strip())
        response_headers = {}
        blocks = (folder / "headers").read_text(encoding="iso-8859-1").replace("\r\n", "\n").strip().split("\n\n")
        for line in blocks[-1].splitlines()[1:]:
            name, separator, value = line.partition(":")
            if separator:
                response_headers[name] = value.strip()
        return int(result.stdout), (folder / "body").read_bytes(), response_headers


class ApiError(RuntimeError):
    """An API error response. Branch on error_code (and status), never on the message text.
    uncertain is True when a PATCH or DELETE got no response or a server error: it may or may not have been applied."""
    def __init__(self, status, body, uncertain=False):
        self.status = status
        self.uncertain = uncertain
        self.error_code = body.get("error_code") if isinstance(body, dict) else None
        super().__init__(f"{body.get('error_code')} {body.get('error_params')}: {body.get('errors')} (request {body.get('request_id')})"
                         if isinstance(body, dict) else "HTTP " + str(status) if status else "No response")

def call(name, params=None, body=None, key=None):
    route = SPEC["requests"][name]
    headers = {"Authorization": "Bearer " + API_KEY, "Accept": "application/json"}
    if route["method"] == "POST":
        if not key: raise RuntimeError("Persist a logical create key before sending POST")
        headers["Idempotency-Key"] = key
    data = None if body is None else json.dumps(body).encode("utf-8")
    if data is not None:
        headers["Content-Type"] = "application/json"
    query = urllib.parse.urlencode(params or {})
    url = BASE + route["path"] + ("?" + query if query else "")
    # Only GET has automatic retries in this workflow. A PATCH or DELETE that got no response or a
    # server error is never resent blindly: it may already have been applied, so the caller reads the record first.
    resend = route["method"] == "GET"
    for attempt in range(5):
        try:
            status, raw, response_headers = transport(route["method"], url, headers, data)
        except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException):
            if not resend:
                raise ApiError(0, None, uncertain=True)
            if attempt == 4:
                raise
            time.sleep(2 ** attempt)
            continue
        response_headers = {k.lower(): v for k, v in response_headers.items()}
        result = None
        if status != 304 and raw:
            try:
                result = decode_json(raw.decode("utf-8"))
            except (ValueError, UnicodeError):
                if status < 400:
                    raise RuntimeError("Expected a JSON success response")
        if status >= 500 and not resend:
            raise ApiError(status, result, uncertain=True)
        retry = resend and (status == 429 or status >= 500)
        if retry:
            if attempt == 4:
                raise RuntimeError("Retry limit reached; check the request outcome before starting a new create")
            delay = response_headers.get("retry-after", str(2 ** attempt))
            time.sleep(max(0, float(delay)))
            continue
        if status >= 400:
            raise ApiError(status, result)
        return {"status": status, "body": result, "headers": response_headers, "raw": raw}
    raise RuntimeError("Retry limit reached")


def both(left,right):
    return left and right

def deep_equal(left,right):
    if type(left) is not type(right): return False
    if isinstance(left,dict): return left.keys()==right.keys() and all(deep_equal(left[k],right[k]) for k in left)
    if isinstance(left,list): return len(left)==len(right) and all(deep_equal(a,b) for a,b in zip(left,right))
    return left==right

def equal(left, right):
    return type(left) is type(right) and left == right

def field(value, name):
    if not isinstance(value, dict) or name not in value: raise RuntimeError("Missing response field: " + name)
    return value[name]

def is_present(value):
    return value is not None and value != ""

def items(value):
    if not isinstance(value, list): raise RuntimeError("Expected a JSON array")
    return value

"""Strict private client journal reference; no transport or application dependency."""
from pathlib import Path
import hashlib
import os
import re
import secrets
from urllib.parse import urlsplit

PREAMBLE=b'EXHIBITDAY-GUIDE-JOURNAL 1\n'

class JournalRefusal(RuntimeError):
    pass

def utf8(value):
    if not isinstance(value,str):raise JournalRefusal('Journal fields are exact strings')
    return value.encode('utf-8',errors='strict')

def strings(values):
    raw=bytearray()
    for value in values:
        item=utf8(value);raw.extend(str(len(item)).encode('ascii'));raw.extend(b':');raw.extend(item)
    return bytes(raw)

def read_strings(raw):
    values=[];offset=0
    while offset<len(raw):
        end=raw.find(b':',offset)
        if end<0:raise JournalRefusal('Incomplete journal string length')
        length=raw[offset:end]
        if not re.fullmatch(b'0|[1-9][0-9]*',length):raise JournalRefusal('Noncanonical journal string length')
        size=int(length);offset=end+1
        if size>len(raw)-offset:raise JournalRefusal('Incomplete journal string')
        values.append(raw[offset:offset+size].decode('utf-8',errors='strict'));offset+=size
    return values

def digest(raw):return hashlib.sha256(raw).hexdigest().upper()

def fingerprint(pairs):
    values=[]
    for name,value in sorted(pairs.items()):
        if not re.fullmatch('[A-Za-z0-9_.-]+',name):raise JournalRefusal('Fingerprint field names must be explicit ASCII identifiers')
        if name.lower() in ('api_key','exhibitday_api_key'):raise JournalRefusal('Never fingerprint the API key')
        values.extend((name,value))
    return digest(strings(values))

def frame(values):
    raw=strings(values)
    return str(len(raw)).encode('ascii')+b' '+digest(raw).encode('ascii')+b'\n'+raw+b'\n'

def decode(raw):
    if not raw.startswith(PREAMBLE):raise JournalRefusal('Unknown or incomplete journal version')
    offset=len(PREAMBLE);records=[]
    while offset<len(raw):
        end=raw.find(b'\n',offset)
        if end<0:raise JournalRefusal('Incomplete journal frame header; reconcile before retry')
        match=re.fullmatch(b'(0|[1-9][0-9]*) ([0-9A-F]{64})',raw[offset:end])
        if match is None:raise JournalRefusal('Invalid journal frame header')
        size=int(match[1]);offset=end+1
        if size>=len(raw)-offset:raise JournalRefusal('Incomplete journal frame; reconcile before retry')
        payload=raw[offset:offset+size];offset+=size
        if raw[offset:offset+1]!=b'\n' or digest(payload).encode('ascii')!=match[2]:raise JournalRefusal('Journal integrity check failed; reconcile before retry')
        records.append(read_strings(payload));offset+=1
    return records

class Journal:
    def __init__(self,path,base,workspace,slug,job,input_fingerprint,writes,mode="resume"):
        self.path=Path(path);self.lock=Path(str(self.path)+'.lock');self.fd=None;self.owned=False;self.identity=None;self.tainted=False;self.intents={};self.saved_values={}
        address=urlsplit(base)
        if address.scheme not in ('https','http')or not address.netloc or address.username is not None or address.query or address.fragment or not re.fullmatch('[a-z][a-z0-9-]*',slug):raise JournalRefusal('Use the actual API base and closed guide slug')
        if not job.strip() or not re.fullmatch('[1-9][0-9]*',workspace) or not re.fullmatch('[0-9A-F]{64}',input_fingerprint):raise JournalRefusal('Use an actual workspace, explicit stable job ID and exact input fingerprint')
        if mode not in ("new","resume"):raise JournalRefusal("Choose new or resume for this local job")
        self.allowed={};manifest=[]
        for step,method,route in writes:
            if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.allowed or method not in ('POST','PATCH','DELETE')or not re.fullmatch('/v1/[A-Za-z0-9_/-]+',route)or'//'in route:raise JournalRefusal('Use a closed unique write manifest')
            self.allowed[step]=(method,route);manifest.extend((step,method,route))
        if not self.allowed:raise JournalRefusal('Only write workflows need a restart journal')
        self.header=['H','1',base,workspace,slug,job,input_fingerprint,digest(strings(manifest))]
        strings(self.header)
        try:
            self.fd=os.open(self.lock,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600);self.owned=True
        except FileExistsError:raise JournalRefusal('This journal is locked; do not run overlapping jobs or steal a stale lock')
        try:
            self.owner=secrets.token_hex(16);self.identity=os.fstat(self.fd)
            if os.write(self.fd,self.owner.encode('ascii'))!=len(self.owner):raise OSError('Incomplete lock identity write')
            os.fsync(self.fd)
            if self.path.is_symlink():raise JournalRefusal('Choose a private regular journal file')
            if mode=="resume" and not self.path.exists():raise JournalRefusal("Journal missing: stop and reconcile lost state before starting a new logical job")
            if mode=="new" and self.path.exists():raise JournalRefusal("A journal already exists; use resume for the same logical job")
            if mode=="new":
                with open(self.path,'xb',buffering=0)as target:
                    target.write(PREAMBLE+frame(self.header));os.fsync(target.fileno())
            records=decode(self.path.read_bytes())
            if not records or records[0]!=self.header:raise JournalRefusal('Journal workspace/base/guide/job/input binding differs')
            for record in records[1:]:self.apply(record)
            if any(step not in self.saved_values for step in self.intents):raise JournalRefusal('A saved before-send intent lacks an ACK; stop and reconcile its outcome before retry')
        except BaseException:
            self.close();raise

    def apply(self,record):
        if not record:raise JournalRefusal('Empty journal record')
        if record[0]=='I':
            if len(record)!=6:raise JournalRefusal('Invalid intent shape')
            _,step,method,path,request_fingerprint,key=record
            if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.intents or self.allowed.get(step)!=(method,path)or not re.fullmatch('[0-9A-F]{64}',request_fingerprint)or any(name not in self.saved_values for name in self.intents):raise JournalRefusal('Invalid, future or repeated journal intent')
            if method=='POST'and not re.fullmatch('[0-9a-f]{32}',key)or method!='POST'and key!='':raise JournalRefusal('Invalid persisted action key')
            self.intents[step]={'method':method,'path':path,'request_fingerprint':request_fingerprint,'idempotency_key':key}
        elif record[0]=='A':
            if len(record)<3:raise JournalRefusal('Invalid ACK shape')
            _,step,count,*pairs=record
            if not re.fullmatch('0|[1-9][0-9]*',count)or len(pairs)!=2*int(count)or step not in self.intents or step in self.saved_values:raise JournalRefusal('ACK without exactly one prior intent')
            names=pairs[::2]
            if names!=sorted(set(names))or any(not re.fullmatch('[a-z][a-z0-9_]*',name)or name in ('api_key','exhibitday_api_key')for name in names):raise JournalRefusal('ACK saved fields must be unique sorted secret-free identifiers')
            self.saved_values[step]=dict(zip(names,pairs[1::2]))
        else:raise JournalRefusal('Unknown journal transition')

    def append(self,record):
        # The reader commits state only after complete length/digest recognition.
        # A torn append is retained and refused, never silently truncated.
        self.require_active();raw=frame(record)
        try:
            with open(self.path,'ab',buffering=0)as target:
                view=memoryview(raw)
                while view:
                    written=target.write(view)
                    if not written:raise OSError('Journal write did not advance')
                    view=view[written:]
                os.fsync(target.fileno())
        except BaseException:
            self.tainted=True;raise

    def require_active(self):
        if not self.owned or self.fd is None or self.identity is None or self.tainted:raise JournalRefusal('The journal scope is closed or its IO outcome needs reconciliation')
        current=self.lock.stat(follow_symlinks=False)
        if current.st_dev!=self.identity.st_dev or current.st_ino!=self.identity.st_ino or self.lock.read_text(encoding='ascii')!=self.owner:raise JournalRefusal('The journal lock was replaced; stop without deleting it')
    def acknowledged(self,step):
        self.require_active();return step in self.saved_values
    def saved(self,step):
        self.require_active()
        if step not in self.saved_values:raise JournalRefusal('No acknowledged state exists for this step')
        return dict(self.saved_values[step])
    def begin(self,step,method,path,request_fingerprint):
        self.require_active()
        if step in self.intents:raise JournalRefusal('Never blindly repeat an existing action intent')
        key=secrets.token_hex(16)if method=='POST'else''
        record=['I',step,method,path,request_fingerprint,key]
        # Validate on an isolated state before touching the file.
        old=dict(self.intents)
        try:self.apply(record)
        finally:self.intents=old
        self.append(record);self.apply(record)
        return dict(self.intents[step])
    def acknowledge(self,step,saved):
        self.require_active()
        record=['A',step,str(len(saved))]
        for name,value in sorted(saved.items()):record.extend((name,value))
        old={name:dict(value)for name,value in self.saved_values.items()}
        try:self.apply(record);strings(record)
        finally:self.saved_values=old
        self.append(record);self.apply(record)
    def close(self):
        if self.owned:
            if self.tainted:
                os.close(self.fd);self.fd=None;self.owned=False
                return # Retain this lock after failed journal IO; manual reconciliation is required.
            try:self.require_active()
            except BaseException:
                os.close(self.fd);self.fd=None;self.owned=False;raise
            os.close(self.fd);self.fd=None;self.owned=False
            self.lock.unlink()
    def __enter__(self):return self
    def __exit__(self,*args):self.close()

def journal_values(value):
    if not isinstance(value, dict) or any(not isinstance(k, str) or not isinstance(v, str) for k,v in value.items()):
        raise JournalRefusal('Saved/fingerprint values must be exact string fields')
    return dict(value)

def journal_acknowledge(job, step, saved):
    job.acknowledge(step,journal_values(saved))

def journal_acknowledged(job, step):
    return job.acknowledged(step)

def journal_begin(job, step, method, path, request_fingerprint):
    return job.begin(step,method,path,request_fingerprint)

def journal_fingerprint(value):
    return fingerprint(journal_values(value))

def journal_saved(job, step):
    return job.saved(step)

def json_string(value):
    return json.dumps(value,ensure_ascii=False,allow_nan=False,separators=(",",":"))

def open_journal(path, base, workspace, slug, job, input_fingerprint, writes, mode):
    return Journal(path,base,workspace,slug,job,input_fingerprint,writes,mode)

def optional(name, fallback):
    value = os.environ.get(name)
    return fallback if value is None or value == "" else value

def parse_json(value):
    return json.loads(value)

def positive_id(value):
    if not re.fullmatch(r"[1-9][0-9]*", value) or int(value) > 9223372036854775807: raise RuntimeError("Use a positive record ID")
    return value

def print_value(value):
    print(value if isinstance(value, str) else json.dumps(value, ensure_ascii=False))

def require_condition(value, message):
    if value is not True: raise RuntimeError(message)

def required(name):
    value = os.environ.get(name)
    if value is None or not value.strip(): raise RuntimeError("Set " + name)
    return value

def response_status(value):
    return str(value["status"])

def shipment_tracking_number(value):
    utf8(value)
    value = value.strip('\u0009\u000A\u000B\u000C\u000D\u0020\u0085\u00A0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u2028\u2029\u202F\u205F\u3000')
    if any(character in value for character in '<>\r\n'):
        raise JournalRefusal('Enter a single-line tracking number without angle brackets.')
    if not value or len(value.encode('utf-16-le')) // 2 > 125:
        raise JournalRefusal('Enter a nonblank tracking number of at most 125 UTF-16 code units.')
    return value

def text(value):
    if value is None: return ""
    if isinstance(value, str): return value
    if isinstance(value, bool): return "true" if value else "false"
    if isinstance(value, int): return str(value)
    raise RuntimeError("Expected a scalar response value")


def main():
    expected_shipment_event_id = positive_id(required("EXHIBITDAY_EVENT_ID"))
    selected_shipment_id = positive_id(required("EXHIBITDAY_SHIPMENT_ID"))
    desired_tracking_number = shipment_tracking_number(required("EXHIBITDAY_TRACKING_NUMBER"))
    shipment_journal_path = required("EXHIBITDAY_JOURNAL")
    shipment_job_id = required("EXHIBITDAY_JOB_ID")
    shipment_job_mode = optional("EXHIBITDAY_JOB_MODE", "resume")
    shipment_workspace_response = call("workspace_binding", {}, None, None)
    require_condition(equal(response_status(shipment_workspace_response), "200"), "Expected the endpoint's documented HTTP200 response; preserve pending state and reconcile any other outcome.")
    shipment_workspace = shipment_workspace_response["body"]
    shipment_workspace_id = positive_id(text(field(shipment_workspace, "id")))
    initial_shipment_response = call("read_shipment", {"id": selected_shipment_id, "$include_record_revision": "true"}, None, None)
    require_condition(equal(response_status(initial_shipment_response), "200"), "Expected the endpoint's documented HTTP200 response; preserve pending state and reconcile any other outcome.")
    initial_shipment = initial_shipment_response["body"]
    require_condition(both(equal(text(field(initial_shipment, "id")), selected_shipment_id), equal(text(field(initial_shipment, "event_id")), expected_shipment_event_id)), "The selected Shipment does not belong to the expected Event; no write was sent.")
    shipment_revision = text(field(initial_shipment, "record_revision"))
    require_condition(is_present(shipment_revision), "Read the actual Shipment with $include_record_revision=true before attempting the change.")
    original_components = items(field(initial_shipment, "components"))
    shipment_input_fingerprint = journal_fingerprint({"workflow_contract_sha256": "150EE3B0A50D2C1B961E315183D849281F9A38E47247AB7A5D526BB60983BA90", "event_id": expected_shipment_event_id, "shipment_id": selected_shipment_id, "tracking_number": desired_tracking_number, "shipment_status_id": "2"})
    shipment_job = open_journal(shipment_journal_path, "https://api.exhibitday.com/v1", shipment_workspace_id, "shipment-tracking", shipment_job_id, shipment_input_fingerprint, [["update_tracking", "PATCH", "/v1/events/shipments"]], shipment_job_mode)
    try:
        component_snapshot = ""
        if journal_acknowledged(shipment_job, "update_tracking"):
            saved_shipment = journal_saved(shipment_job, "update_tracking")
            require_condition(both(equal(text(field(saved_shipment, "id")), selected_shipment_id), both(equal(text(field(saved_shipment, "event_id")), expected_shipment_event_id), both(equal(text(field(saved_shipment, "tracking_number")), desired_tracking_number), equal(text(field(saved_shipment, "shipment_status_id")), "2")))), "The acknowledged Shipment change belongs to another record, Event or desired tracking state.")
            component_snapshot = text(field(saved_shipment, "components_json"))
        else:
            component_snapshot = json_string(original_components)
            tracking_patch = {"id": selected_shipment_id, "tracking_number": desired_tracking_number, "shipment_status_id": "2", "expected_revision": shipment_revision}
            shipment_write_fingerprint = journal_fingerprint({"id": selected_shipment_id, "tracking_number": desired_tracking_number, "shipment_status_id": "2", "expected_revision": shipment_revision})
            journal_begin(shipment_job, "update_tracking", "PATCH", "/v1/events/shipments", shipment_write_fingerprint)
            tracking_save_response = call("update_tracking", {}, tracking_patch, None)
            require_condition(equal(response_status(tracking_save_response), "200"), "Expected the endpoint's documented HTTP200 response; preserve pending state and reconcile any other outcome.")
            tracking_receipt = tracking_save_response["body"]
            saved_shipment_revision = text(field(tracking_receipt, "record_revision"))
            require_condition(is_present(saved_shipment_revision), "A checked save acknowledgement needs its actual returned record_revision.")
            journal_acknowledge(shipment_job, "update_tracking", {"id": selected_shipment_id, "event_id": expected_shipment_event_id, "tracking_number": desired_tracking_number, "shipment_status_id": "2", "record_revision": saved_shipment_revision, "components_json": component_snapshot})
        shipment_readback_response = call("verify_shipment", {"id": selected_shipment_id}, None, None)
        require_condition(equal(response_status(shipment_readback_response), "200"), "Expected the endpoint's documented HTTP200 response; preserve pending state and reconcile any other outcome.")
        shipment_readback = shipment_readback_response["body"]
        require_condition(both(equal(text(field(shipment_readback, "id")), selected_shipment_id), equal(text(field(shipment_readback, "event_id")), expected_shipment_event_id)), "The final Shipment is missing or rebound; earlier saved state remains in the journal.")
        require_condition(both(equal(text(field(shipment_readback, "tracking_number")), desired_tracking_number), equal(text(field(shipment_readback, "shipment_status_id")), "2")), "The Shipment no longer matches the acknowledged tracking/status; inspect it instead of automatically restoring the change.")
        recorded_components = items(parse_json(component_snapshot))
        require_condition(deep_equal(field(shipment_readback, "components"), recorded_components), "Shipment components differ from the original saved snapshot. Inspect the packages; do not replace or automatically restore them.")
        print_value({"shipment_id": selected_shipment_id, "event_id": expected_shipment_event_id, "tracking_number": desired_tracking_number, "components_unchanged": "true"})
    finally:
        shipment_job.close()


if __name__ == "__main__":
    main()

EXHIBITDAY_PY

Example response

{
  "id": 7001,
  "event_id": 5001,
  "event_name": "Spring Expo 2030",
  "carrier": null,
  "tracking_url": null,
  "shipment_status": "Shipped",
  "payment_status": {
    "id": 0,
    "name": "N/A"
  },
  "dimensions_unit": "in",
  "weight_unit": "lb",
  "components": [
    {
      "id": 12002,
      "component_type_id": null,
      "component_type": "Not Specified",
      "description": "Display stand case",
      "tracking_number": "PACKAGE-1001",
      "dimensions_length": 48.0,
      "dimensions_width": 24.0,
      "dimensions_height": 18.0,
      "weight": 65.0
    },
    {
      "id": 12003,
      "component_type_id": null,
      "component_type": "Not Specified",
      "description": "Brochure carton",
      "tracking_number": "PACKAGE-1002",
      "dimensions_length": 20.0,
      "dimensions_width": 16.0,
      "dimensions_height": 12.0,
      "weight": 18.50
    }
  ],
  "cost": {
    "amount": 0.00,
    "cost_center_breakdown": []
  },
  "name": "Exhibit freight",
  "tracking_number": "TEST-ANNUAL-EXPO-001",
  "carrier_id": null,
  "other_carrier_name": null,
  "pickup_date": null,
  "delivery_date": null,
  "pickup_location": null,
  "delivery_location": null,
  "notes": "",
  "payment_status_id": 0,
  "payment_due_date": null,
  "next_payment_due_date": null,
  "payment_notes": null,
  "invoice_attachment": null,
  "shipment_status_id": 2,
  "service_level": null,
  "shipment_reference_number": null,
  "pickup_contact_name": null,
  "pickup_contact_email": null,
  "pickup_contact_phone": null,
  "pickup_instructions": null,
  "delivery_contact_name": null,
  "delivery_contact_email": null,
  "delivery_contact_phone": null,
  "delivery_instructions": null,
  "packing_handling_requirements": null,
  "received_by": null,
  "delivery_exception_notes": null
}
Note: The Shipment as read after the update. It shows Shipped status and the new Shipment tracking number. Both original packages keep all their fields.

Things to keep in mind

  • Every Shipment request uses the Shipment's own ID. The Event ID is a check that you picked the right Shipment.
  • The program always sets the status to Shipped (status 2).

If a run stops

  • Keep the journal private. It records what the program tried to save and which save it confirmed.
  • To continue a run with no unresolved save, use EXHIBITDAY_JOB_MODE=resume with the same job ID, journal path and inputs.
  • A resumed run skips an acknowledged update and compares the current packages with the original list saved in the journal.
  • If a save stops with a conflict, a lost response or a missing revision, check the Shipment in ExhibitDay before running the program again.
  • If you still need a change after checking the old run, use EXHIBITDAY_JOB_MODE=new with a new job ID and journal path.
  • Run only one copy per journal.
  • If a crash leaves a .lock file, make sure no copy using that journal is running or can start. Then remove the lock file and keep the journal.