Search API documentation

Type to search the API docs.

Test Your Integration in an ExhibitDay Workspace

Try a complete Task and attachment workflow in a test Event, confirm a stale update is refused, and choose whether to clean up.

Example use case

You are about to turn on an integration and want to check how it creates, updates and verifies records first.

What you'll end up with

One checked Task and attachment, a downloaded copy, and an explicit choice about removing the test records.

Before you start

Have a workspace API key, an Event reserved for testing, and a small file you can leave unchanged while the test runs.

Good to know

Use a dedicated test Event in a workspace you control. This example sends real requests to the API.

At a glance

Time to try

About 15 minutes

Effect on your data

Creates records

Endpoints

9

The program creates and renames one test Task, adds one file, and saves a verified local download and private journal. It removes only those two records if you explicitly choose cleanup.

How it works

  1. Confirm the workspace and create one Task in the test Event. Save its ID and current revision.
  2. Rename the Task and check that an update using the old revision gets HTTP 409.
  3. Attach, find and download one file. Keep the records by default, or explicitly remove the file and Task created by this run.

Run the Task and attachment checks

Use your test Event ID to create the Task. For the later requests, substitute the Task and attachment IDs from your own responses. Remove records only if you choose cleanup and created them during this test.

Replace the example IDs and values with your own. Use the complete program below to save progress and check each result.

Step 1: Check the workspace

Verify where the test will create data.

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

Example response (shortened)

{
  "id": 98765
}

Check: Confirm the returned id matches the workspace you set aside for the test.

Step 2: Create the test Task

Send your test Event ID and a unique name, using one idempotency key for this create.

curl -X POST "https://api.exhibitday.com/v1/tasks" -H "Authorization: Bearer YOUR_API_KEY" -H "Idempotency-Key: YOUR_CREATE_KEY" -H "Content-Type: application/json" --data-binary "{\"event_id\":12345,\"name\":\"API integration check\"}"

Example response (shortened)

{
  "id": 34567,
  "name": "API integration check"
}

Check: Save the returned Task ID. The complete program derives its test name from your job ID.

Step 3: Read the Task and its revision

Read that exact Task before updating it.

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

Example response (shortened)

{
  "id": 34567,
  "record_revision": "COPY_TASK_REVISION_FROM_YOUR_READ"
}

Check: Keep the full revision from your own read.

Step 4: Rename the Task

Use the revision to rename only the Task created in this test.

curl -X PATCH "https://api.exhibitday.com/v1/tasks" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" --data-binary "{\"id\":34567,\"name\":\"API integration check updated\",\"expected_revision\":\"COPY_TASK_REVISION_FROM_YOUR_READ\"}"

Example response (shortened)

{
  "record_revision": "NEW_TASK_REVISION"
}

Check: Save the new revision and keep the original for the next check.

Step 5: Try the old revision once

Send a different name with the old revision to check that a stale update is refused.

curl -X PATCH "https://api.exhibitday.com/v1/tasks" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" --data-binary "{\"id\":34567,\"name\":\"API integration check refused\",\"expected_revision\":\"COPY_TASK_REVISION_FROM_YOUR_READ\"}"

Check: Expect record_changed (HTTP 409). The Task keeps the name from Step 4.

Step 6: Confirm the Task kept its new name

Read it again after the conflict.

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

Example response (shortened)

{
  "id": 34567,
  "name": "API integration check updated",
  "record_revision": "NEW_TASK_REVISION"
}

Check: Compare the saved name and revision against the successful update.

Step 7: Attach a test file

Send one file to the Task you just created.

curl -X POST "https://api.exhibitday.com/v1/tasks/attachments" -H "Authorization: Bearer YOUR_API_KEY" -H "Idempotency-Key: YOUR_UPLOAD_KEY" -F "task_id=34567" -F "file=@integration-check.txt"

Example response (shortened)

{
  "list_data": [
    {
      "id": 45678,
      "filename": "integration-check.txt"
    }
  ]
}

Check: Keep the returned attachment ID.

Step 8: Find the file on that Task

Read the attachment list for the Task and look for the ID returned by the upload.

curl -X GET "https://api.exhibitday.com/v1/tasks/attachments?task_id=34567&%24limit=25&%24offset=0" -H "Authorization: Bearer YOUR_API_KEY"

Example response (shortened)

{
  "list_data": [
    {
      "id": 45678,
      "filename": "integration-check.txt"
    }
  ]
}

Check: Confirm both the ID and filename.

Step 9: Download and compare the file

Use the saved attachment ID to fetch the bytes.

curl -X GET "https://api.exhibitday.com/v1/tasks/attachments/download?id=45678" -H "Authorization: Bearer YOUR_API_KEY" --fail --output "downloaded-copy.txt"

The response contains the file bytes.

Check: The program compares length and SHA-256 with the original and saves only a matching file.

Step 10: Remove the test file, if you chose cleanup

Delete only the attachment ID the program saved from Step 7.

curl -X DELETE "https://api.exhibitday.com/v1/tasks/attachments?id=45678" -H "Authorization: Bearer YOUR_API_KEY"

Check: The program skips this step unless you set EXHIBITDAY_TEST_CLEANUP=delete.

Step 11: Remove the test Task, if you chose cleanup

Delete the Task this run created after its file is removed.

curl -X DELETE "https://api.exhibitday.com/v1/tasks?id=34567" -H "Authorization: Bearer YOUR_API_KEY"

Check: The program deletes only the Task it created in this run.

Step 12: Confirm the test Task is gone

Read the same Task after cleanup.

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

Expected status: HTTP 404.

Check: The program expects HTTP 404 after the Task is deleted.

Try it

Before running the example

VariableWhat to put in itRequired?
EXHIBITDAY_API_KEYYour workspace API key.Yes
EXHIBITDAY_EVENT_IDThe ID of an Event reserved for testing.Yes
EXHIBITDAY_FILEPath to a small local file for the test.Yes
EXHIBITDAY_DOWNLOAD_PATHA new path for the downloaded copy.Yes
EXHIBITDAY_JOB_IDA unique ID for this run. Use the same ID to continue it.Yes
EXHIBITDAY_TEST_STATEA private local path for the journal (the run state).Yes
EXHIBITDAY_TEST_CLEANUPUse keep to leave the records for review, or delete to remove them after the checks. Defaults to keep.No
EXHIBITDAY_JOB_MODEUse new to start a run, or resume to continue an existing one. Defaults to resume.No

Bash

export EXHIBITDAY_API_KEY='YOUR_API_KEY'
export EXHIBITDAY_EVENT_ID='12345'
export EXHIBITDAY_FILE='integration-check.txt'
export EXHIBITDAY_DOWNLOAD_PATH='verified-integration-check.txt'
export EXHIBITDAY_JOB_ID='integration-testing-01'
export EXHIBITDAY_TEST_STATE='integration-testing-01.json'
export EXHIBITDAY_JOB_MODE='new'

PowerShell

$env:EXHIBITDAY_API_KEY = 'YOUR_API_KEY'
$env:EXHIBITDAY_EVENT_ID = '12345'
$env:EXHIBITDAY_FILE = 'integration-check.txt'
$env:EXHIBITDAY_DOWNLOAD_PATH = 'verified-integration-check.txt'
$env:EXHIBITDAY_JOB_ID = 'integration-testing-01'
$env:EXHIBITDAY_TEST_STATE = 'integration-testing-01.json'
$env:EXHIBITDAY_JOB_MODE = 'new'

Use your own IDs, file paths and values. Then copy and run the complete program 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\"},\"create\":{\"method\":\"POST\",\"path\":\"/tasks\"},\"read\":{\"method\":\"GET\",\"path\":\"/tasks/info\"},\"edit\":{\"method\":\"PATCH\",\"path\":\"/tasks\"},\"stale\":{\"method\":\"PATCH\",\"path\":\"/tasks\"},\"after_edit\":{\"method\":\"GET\",\"path\":\"/tasks/info\"},\"upload\":{\"method\":\"POST\",\"path\":\"/tasks/attachments\",\"file\":{\"name\":\"file\",\"maximum_bytes\":\"26214400\",\"extensions\":[\"png\",\"jpg\",\"jpeg\",\"bmp\",\"gif\",\"pdf\",\"msg\",\"eml\",\"doc\",\"docx\",\"ppt\",\"pptx\",\"xls\",\"xlsx\",\"csv\",\"rtf\",\"odp\",\"odt\",\"ods\",\"txt\",\"wks\",\"zip\"],\"content_types\":[]}},\"verify_file\":{\"method\":\"GET\",\"path\":\"/tasks/attachments\"},\"download\":{\"method\":\"GET\",\"path\":\"/tasks/attachments/download\",\"binary\":true},\"remove_file\":{\"method\":\"DELETE\",\"path\":\"/tasks/attachments\"},\"remove_task\":{\"method\":\"DELETE\",\"path\":\"/tasks\"},\"verify_removed\":{\"method\":\"GET\",\"path\":\"/tasks/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("Save a 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 add_offset(offset, received):
    result = int(offset) + received
    if received <= 0 or result > 2147483647: raise RuntimeError("Cannot advance this int32 offset; reconcile the query")
    return str(result)

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

def concat(left, right):
    return left + right

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

def count(value):
    return len(items(value))

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 either(left, right):
    if not isinstance(left, bool) or not isinstance(right, bool): raise RuntimeError("Expected Boolean criteria")
    return left or 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]

import hashlib
import secrets
from pathlib import Path

class FileSnapshot:
    def __init__(self, name, data):
        self.name, self.data = name, bytes(data)
        self.sha256 = hashlib.sha256(self.data).hexdigest()


def file_length(value): return str(len(value.data))

def file_name(value): return value.name

def file_sha256(value): return value.sha256


def is_empty(value):
    return count(value) == 0

def is_present(value):
    return value is not None and 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 job")
            if mode=="new" and self.path.exists():raise JournalRefusal("A journal already exists; use resume for the same 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 confirmed 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 new_id_set():
    return set()

def not_value(value):
    if not isinstance(value, bool): raise RuntimeError("Expected a Boolean")
    return not value

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 read_file_snapshot(path, action):
    rule = SPEC['requests'][action].get('file')
    if not rule or rule['name'] != 'file': raise RuntimeError('Use the current declared file input')
    data = Path(path).read_bytes()
    if not data or len(data) > int(rule['maximum_bytes']): raise RuntimeError('The selected file is empty or exceeds this endpoint file limit')
    name = Path(path).name
    if not name or any(c in name for c in '\r\n\0'): raise RuntimeError('Use a filename without header control characters')
    return FileSnapshot(name, data)


def remember_id(seen, value):
    if value in seen: return False
    seen.add(value)
    return True

def request_download(name, params):
    route = SPEC['requests'][name]
    if route['method'] != 'GET' or route.get('binary') is not True: raise RuntimeError('Bind the declared binary GET')
    query = urllib.parse.urlencode(params or {})
    status, raw, headers = transport('GET', BASE + route['path'] + ('?' + query if query else ''), {'Authorization': 'Bearer ' + API_KEY, 'Accept': 'application/octet-stream'}, None)
    if status != 200:
        parsed = None
        try: parsed = decode_json(raw.decode('utf-8'))
        except (ValueError, UnicodeError): pass
        raise ApiError(status, parsed)
    return bytes(raw)


def request_expect(name,query,body,key,expected):
    try:
        call(name,query,body,key)
    except ApiError as observed:
        if observed.uncertain or str(observed.status)!=expected:
            raise
        return str(observed.status)
    raise RuntimeError("Expected HTTP "+expected+" refusal; request unexpectedly succeeded")

def request_upload(name, params, file, key):
    route = SPEC['requests'][name]
    if route['method'] != 'POST' or not route.get('file') or not key: raise RuntimeError('Bind one declared upload and its persisted create key')
    boundary = 'ExhibitDayGuide' + secrets.token_hex(24)
    while boundary.encode('ascii') in file.data: boundary = 'ExhibitDayGuide' + secrets.token_hex(24)
    quoted = file.name.replace('\\', '\\\\').replace('"', '\\"')
    data = ('--' + boundary + '\r\nContent-Disposition: form-data; name="file"; filename="' + quoted + '"\r\nContent-Type: application/octet-stream\r\n\r\n').encode('utf-8') + file.data + ('\r\n--' + boundary + '--\r\n').encode('ascii')
    headers = {'Authorization': 'Bearer ' + API_KEY, 'Accept': 'application/json', 'Idempotency-Key': key, 'Content-Type': 'multipart/form-data; boundary=' + boundary}
    query = urllib.parse.urlencode(params or {})
    url = BASE + route['path'] + ('?' + query if query else '')
    try: status, raw, response_headers = transport('POST', url, headers, data)
    except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException): raise ApiError(0, None, uncertain=True)
    parsed = None
    try: parsed = decode_json(raw.decode('utf-8'))
    except (ValueError, UnicodeError): pass
    if status != 200: raise ApiError(status, parsed, uncertain=status >= 500)
    if not isinstance(parsed, dict): raise RuntimeError('Upload returned no usable JSON receipt; reconcile before retrying')
    return {'status': status, 'body': parsed, 'headers': {k.lower(): v for k,v in response_headers.items()}, 'raw': raw}


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 save_checked_download(data, file, path):
    if len(data) != len(file.data) or hashlib.sha256(data).hexdigest() != file.sha256: raise RuntimeError('Downloaded bytes differ; no output was created')
    descriptor = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | getattr(os, 'O_BINARY', 0), 0o600)
    with os.fdopen(descriptor, 'wb') as output:
        output.write(data); output.flush(); os.fsync(output.fileno())

def single(value):
    rows=items(value)
    if len(rows)!=1: raise RuntimeError('Expected exactly one selected record')
    return rows[0]

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():
    integration_event_id = positive_id(required("EXHIBITDAY_EVENT_ID"))
    integration_job_id = required("EXHIBITDAY_JOB_ID")
    integration_job_hash = journal_fingerprint({"job_id": integration_job_id})
    integration_initial_name = concat("API integration check ", integration_job_hash)
    integration_updated_name = concat(integration_initial_name, " updated")
    integration_file = read_file_snapshot(required("EXHIBITDAY_FILE"), "upload")
    integration_output_path = required("EXHIBITDAY_DOWNLOAD_PATH")
    integration_cleanup = optional("EXHIBITDAY_TEST_CLEANUP", "keep")
    require_condition(either(equal(integration_cleanup, "keep"), equal(integration_cleanup, "delete")), "Use keep or delete for EXHIBITDAY_TEST_CLEANUP.")
    integration_workspace_response = call("workspace_binding", {}, None, None)
    require_condition(equal(response_status(integration_workspace_response), "200"), "Expected the documented HTTP 200 response; stop and review any other outcome.")
    integration_workspace = integration_workspace_response["body"]
    integration_workspace_id = positive_id(text(field(integration_workspace, "id")))
    integration_state_path = required("EXHIBITDAY_TEST_STATE")
    integration_job_mode = optional("EXHIBITDAY_JOB_MODE", "resume")
    integration_job = open_journal(integration_state_path, "https://api.exhibitday.com/v1", integration_workspace_id, "integration-testing", integration_job_id, journal_fingerprint({"workflow_contract_sha256": "3808BE3DE866226BE6AAA4C445EBC19FC7903FD96FC8DC2F223F6D6451BA6267", "event_id": integration_event_id, "initial_name": integration_initial_name, "updated_name": integration_updated_name, "filename": file_name(integration_file), "file_length": file_length(integration_file), "file_sha256": file_sha256(integration_file)}), [["create", "POST", "/v1/tasks"], ["edit", "PATCH", "/v1/tasks"], ["stale", "PATCH", "/v1/tasks"], ["upload", "POST", "/v1/tasks/attachments"], ["remove_file", "DELETE", "/v1/tasks/attachments"], ["remove_task", "DELETE", "/v1/tasks"]], integration_job_mode)
    try:
        integration_task_id = ""
        integration_attachment_id = ""
        if not_value(journal_acknowledged(integration_job, "remove_task")):
            if not_value(journal_acknowledged(integration_job, "create")):
                integration_create_intent = journal_begin(integration_job, "create", "POST", "/v1/tasks", journal_fingerprint({"event_id": integration_event_id, "name": integration_initial_name}))
                integration_created_response = call("create", {}, {"event_id": integration_event_id, "name": integration_initial_name}, text(field(integration_create_intent, "idempotency_key")))
                require_condition(equal(response_status(integration_created_response), "200"), "Expected the documented HTTP 200 response; stop and review any other outcome.")
                integration_created = integration_created_response["body"]
                integration_task_id = positive_id(text(field(integration_created, "id")))
                require_condition(both(equal(text(field(integration_created, "id")), integration_task_id), both(equal(text(field(field(integration_created, "event"), "id")), integration_event_id), equal(text(field(integration_created, "name")), integration_initial_name))), "The saved test Task changed or belongs to another Event. Stop; do not create or overwrite another Task.")
                journal_acknowledge(integration_job, "create", {"task_id": integration_task_id, "event_id": integration_event_id, "name": integration_initial_name, "create_key": text(field(integration_create_intent, "idempotency_key"))})
            integration_saved_create = journal_saved(integration_job, "create")
            integration_task_id = positive_id(text(field(integration_saved_create, "task_id")))
            require_condition(both(equal(text(field(integration_saved_create, "event_id")), integration_event_id), equal(text(field(integration_saved_create, "name")), integration_initial_name)), "Saved create state differs from this Event/job.")
            require_condition(either(not_value(journal_acknowledged(integration_job, "remove_file")), equal(integration_cleanup, "delete")), "Cleanup already removed the test file. Continue with EXHIBITDAY_TEST_CLEANUP=delete to finish this Task cleanup.")
            integration_before_response = call("read", {"id": integration_task_id, "$include_record_revision": "true"}, None, None)
            require_condition(equal(response_status(integration_before_response), "200"), "Expected the documented HTTP 200 response; stop and review any other outcome.")
            integration_before = integration_before_response["body"]
            if not_value(journal_acknowledged(integration_job, "edit")):
                require_condition(both(equal(text(field(integration_before, "id")), integration_task_id), both(equal(text(field(field(integration_before, "event"), "id")), integration_event_id), equal(text(field(integration_before, "name")), integration_initial_name))), "The saved test Task changed or belongs to another Event. Stop; do not create or overwrite another Task.")
                integration_original_revision = text(field(integration_before, "record_revision"))
                require_condition(is_present(integration_original_revision), "Read the actual created Task revision before editing.")
                journal_begin(integration_job, "edit", "PATCH", "/v1/tasks", journal_fingerprint({"id": integration_task_id, "name": integration_updated_name, "expected_revision": integration_original_revision}))
                integration_edit_response = call("edit", {}, {"id": integration_task_id, "name": integration_updated_name, "expected_revision": integration_original_revision}, None)
                require_condition(equal(response_status(integration_edit_response), "200"), "Expected the documented HTTP 200 response; stop and review any other outcome.")
                integration_edit_receipt = integration_edit_response["body"]
                integration_saved_revision = text(field(integration_edit_receipt, "record_revision"))
                require_condition(both(is_present(integration_saved_revision), not_value(equal(integration_original_revision, integration_saved_revision))), "The distinct test name must produce a checked new revision before the stale test.")
                journal_acknowledge(integration_job, "edit", {"task_id": integration_task_id, "name": integration_updated_name, "original_revision": integration_original_revision, "record_revision": integration_saved_revision})
            integration_saved_edit = journal_saved(integration_job, "edit")
            require_condition(both(equal(text(field(integration_saved_edit, "task_id")), integration_task_id), equal(text(field(integration_saved_edit, "name")), integration_updated_name)), "Saved edit state differs from this Task/name.")
            if not_value(journal_acknowledged(integration_job, "stale")):
                journal_begin(integration_job, "stale", "PATCH", "/v1/tasks", journal_fingerprint({"id": integration_task_id, "name": "Refused stale test", "expected_revision": text(field(integration_saved_edit, "original_revision"))}))
                integration_stale_status = request_expect("stale", {}, {"id": integration_task_id, "name": "Refused stale test", "expected_revision": text(field(integration_saved_edit, "original_revision"))}, None, "409")
                journal_acknowledge(integration_job, "stale", {"task_id": integration_task_id, "observed_status": integration_stale_status})
            integration_saved_stale = journal_saved(integration_job, "stale")
            require_condition(both(equal(text(field(integration_saved_stale, "task_id")), integration_task_id), equal(text(field(integration_saved_stale, "observed_status")), "409")), "The saved conflict assertion differs from this Task/status.")
            integration_after_edit_response = call("after_edit", {"id": integration_task_id, "$include_record_revision": "true"}, None, None)
            require_condition(equal(response_status(integration_after_edit_response), "200"), "Expected the documented HTTP 200 response; stop and review any other outcome.")
            integration_after_edit = integration_after_edit_response["body"]
            require_condition(both(equal(text(field(integration_after_edit, "id")), integration_task_id), both(equal(text(field(field(integration_after_edit, "event"), "id")), integration_event_id), equal(text(field(integration_after_edit, "name")), integration_updated_name))), "The saved test Task changed or belongs to another Event. Stop; do not create or overwrite another Task.")
            require_condition(equal(text(field(integration_after_edit, "record_revision")), text(field(integration_saved_edit, "record_revision"))), "The test Task's revision changed; stop before file work or cleanup.")
            require_condition(either(not_value(equal(integration_cleanup, "delete")), deep_equal(field(integration_after_edit, "comments"), [])), "The test Task has comments; stop before cleanup.")
            if not_value(journal_acknowledged(integration_job, "upload")):
                require_condition(equal(text(field(integration_after_edit, "record_revision")), text(field(integration_saved_edit, "record_revision"))), "The Task changed after the conditional edit. Review it before uploading.")
                integration_upload_intent = journal_begin(integration_job, "upload", "POST", "/v1/tasks/attachments", journal_fingerprint({"task_id": integration_task_id, "filename": file_name(integration_file), "file_length": file_length(integration_file), "file_sha256": file_sha256(integration_file)}))
                integration_upload_response = request_upload("upload", {"task_id": integration_task_id}, integration_file, text(field(integration_upload_intent, "idempotency_key")))
                require_condition(equal(response_status(integration_upload_response), "200"), "Expected the documented HTTP 200 response; stop and review any other outcome.")
                integration_upload = integration_upload_response["body"]
                require_condition(both(equal(text(field(integration_upload, "records_found")), "1"), both(equal(text(field(integration_upload, "total_records")), "1"), equal(field(integration_upload, "has_more"), False))), "Require exactly one complete uploaded-file receipt.")
                integration_uploaded_file = single(field(integration_upload, "list_data"))
                integration_attachment_id = positive_id(text(field(integration_uploaded_file, "id")))
                require_condition(is_present(text(field(integration_uploaded_file, "filename"))), "The upload receipt needs its actual stored filename.")
                journal_acknowledge(integration_job, "upload", {"task_id": integration_task_id, "attachment_id": integration_attachment_id, "filename": text(field(integration_uploaded_file, "filename")), "attachment_json": json_string(integration_uploaded_file), "file_length": file_length(integration_file), "file_sha256": file_sha256(integration_file)})
            integration_saved_upload = journal_saved(integration_job, "upload")
            integration_attachment_id = positive_id(text(field(integration_saved_upload, "attachment_id")))
            require_condition(both(equal(text(field(integration_saved_upload, "task_id")), integration_task_id), both(equal(text(field(integration_saved_upload, "file_length")), file_length(integration_file)), equal(text(field(integration_saved_upload, "file_sha256")), file_sha256(integration_file)))), "The confirmed file differs from the saved test Task or file details.")
            if not_value(journal_acknowledged(integration_job, "remove_file")):
                integration_list_offset = "0"
                integration_file_count = "0"
                integration_file_found = False
                integration_file_seen = new_id_set()
                integration_list_query = {"task_id": integration_task_id, "$limit": "25", "$offset": "0"}
                while True:
                    integration_list_query["$offset"] = integration_list_offset
                    integration_list_response = call("verify_file", integration_list_query, None, None)
                    require_condition(equal(response_status(integration_list_response), "200"), "Expected the documented HTTP 200 response; stop and review any other outcome.")
                    integration_list = integration_list_response["body"]
                    integration_list_rows = items(field(integration_list, "list_data"))
                    require_condition(equal(text(field(integration_list, "records_found")), text(count(integration_list_rows))), "The Task file page count differs from its rows.")
                    require_condition(is_present(text(field(integration_list, "total_records"))), "The Task file page needs total_records.")
                    require_condition(either(equal(field(integration_list, "has_more"), True), equal(field(integration_list, "has_more"), False)), "The Task file page needs Boolean has_more.")
                    for integration_list_row in items(integration_list_rows):
                        integration_list_id = positive_id(text(field(integration_list_row, "id")))
                        require_condition(remember_id(integration_file_seen, integration_list_id), "A Task file ID repeated while paging.")
                        if equal(integration_list_id, integration_attachment_id):
                            require_condition(deep_equal(integration_list_row, parse_json(text(field(integration_saved_upload, "attachment_json")))), "The saved Task file details changed.")
                            integration_file_found = True
                    integration_file_count = add_offset(integration_file_count, count(integration_list_rows))
                    if equal(field(integration_list, "has_more"), False):
                        break
                    require_condition(not_value(is_empty(integration_list_rows)), "An empty Task file page says has_more=true.")
                    integration_list_offset = add_offset(integration_list_offset, count(integration_list_rows))
                require_condition(integration_file_found, "The saved file is not on this Task; stop before downloading by id or cleaning up.")
                require_condition(either(not_value(equal(integration_cleanup, "delete")), equal(integration_file_count, "1")), "Another Task file exists; stop before deleting the test Task.")
                integration_download_response = request_download("download", {"id": integration_attachment_id})
                save_checked_download(integration_download_response, integration_file, integration_output_path)
            if equal(integration_cleanup, "delete"):
                if not_value(journal_acknowledged(integration_job, "remove_file")):
                    journal_begin(integration_job, "remove_file", "DELETE", "/v1/tasks/attachments", journal_fingerprint({"id": integration_attachment_id}))
                    integration_file_remove_response = call("remove_file", {"id": integration_attachment_id}, None, None)
                    require_condition(equal(response_status(integration_file_remove_response), "200"), "Expected the documented HTTP 200 response; stop and review any other outcome.")
                    journal_acknowledge(integration_job, "remove_file", {"task_id": integration_task_id, "attachment_id": integration_attachment_id})
                if not_value(journal_acknowledged(integration_job, "remove_task")):
                    journal_begin(integration_job, "remove_task", "DELETE", "/v1/tasks", journal_fingerprint({"id": integration_task_id}))
                    integration_task_remove_response = call("remove_task", {"id": integration_task_id}, None, None)
                    require_condition(equal(response_status(integration_task_remove_response), "200"), "Expected the documented HTTP 200 response; stop and review any other outcome.")
                    journal_acknowledge(integration_job, "remove_task", {"task_id": integration_task_id})
            else:
                print_value({"task_id": integration_task_id, "attachment_id": integration_attachment_id, "cleanup": "kept"})
        if journal_acknowledged(integration_job, "remove_task"):
            integration_removed = journal_saved(integration_job, "remove_task")
            integration_task_id = positive_id(text(field(integration_removed, "task_id")))
            integration_missing_status = request_expect("verify_removed", {"id": integration_task_id}, None, None, "404")
            print_value({"task_id": integration_task_id, "cleanup": "removed", "observed_missing_status": integration_missing_status})
    finally:
        integration_job.close()


if __name__ == "__main__":
    main()

EXHIBITDAY_PY

Example response

{
  "id": 34567,
  "exhibitday_url": "https://www.exhibitday.com/Workspace/TaskView/98765?tid=34567",
  "event_task_section_id": null,
  "event_task_section": "Uncategorized",
  "display_rank": 1,
  "name": "API integration check BCE394471E84081015B3CBC18C3E6DAFD6B8C490CA1F678D193666D1B7B7D66C",
  "due_date": null,
  "assignee": null,
  "is_completed": false,
  "task_completed_timestamp": null,
  "task_completed_by": null,
  "details": "",
  "comments": [],
  "event": {
    "id": 12345,
    "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=12345",
    "name": "Spring Expo 2030",
    "start_date": "2030-01-14",
    "end_date": "2030-01-16",
    "participation_type_id": 1,
    "participation_type": "Committed",
    "format_id": 1,
    "format": "In-Person",
    "event_created_timestamp": "2029-12-01T17:00:00Z",
    "event_last_update_timestamp": "2030-01-02T17:00:00Z"
  },
  "task_created_by": {
    "id": null,
    "first_name": "ExhibitDay",
    "last_name": "API",
    "display_name": "ExhibitDay API",
    "email": null,
    "type": null,
    "workspace_role": null,
    "is_active": true
  },
  "task_created_timestamp": "2030-01-03T12:00:00Z",
  "task_last_update_timestamp": "2030-01-03T12:00:00Z",
  "integration_metadata_field_1": "",
  "integration_metadata_field_2": "",
  "integration_metadata_field_3": "",
  "integration_metadata_field_4": "",
  "integration_metadata_field_5": ""
}
Note: Confirmed test Task create. The create response gives the Task ID the program uses for every later request, including optional cleanup. Those later requests have their own responses.

Things to keep in mind

  • The stale-revision check is deliberate. If it gives a different result, stop and inspect the test Task.
  • Cleanup runs only after the checks and uses this run's saved IDs. The journal and downloaded file stay on your machine.
  • Keep the cleanup choice and original file the same when you continue the same job. Review the test records before starting a different run.

If a run stops

  • Keep the journal private. It records which changes the program attempted and confirmed.
  • To continue a run with no unresolved save, use EXHIBITDAY_JOB_MODE=resume with the same job ID, journal path and inputs.
  • If a write has an uncertain outcome, check the affected records in ExhibitDay before making another change. The program stops and leaves the pending step in the journal.
  • Run one copy per journal. If a crash leaves a .lock file, make sure no copy is running or can start with that journal before removing the lock file.