Read and Update Event Custom Fields
Workspace custom fields are identified by field_name, such as custom_67890. Each example discovers the available
fields, reads an event, updates the intended field and reads the event again to show its saved value.
1. Discover the field
/v1/references/event_custom_fields returns field_name, field_label, field_type, event_tab and is_hidden.
Confirm which field you intend to change. The reference list does not include dropdown choices; consult your
workspace's field settings and use a configured choice rather than guessing one.
2. Read its current value
/v1/events/info returns custom_fields with each field's label, value and field_name. For an event list, use
hydrate_custom_fields=true on /v1/events. The example reads before and after the update so you can compare them.
3. Update and verify
Use the field_name as a parameter of PATCH /v1/events. Custom text, dropdown and URL fields support updates;
dropdown values must match a configured choice. JSON null (or the text "null") clears a value. An empty string
leaves it unchanged and adds a warning. Other omitted fields remain unchanged.
So that the update cannot overwrite a change someone made after your read, the example reads the event with
$include_record_revision=true and sends the returned record_revision as expected_revision with the PATCH. If one of the
event's editable fields changed in between, the API saves nothing and answers 409 with error_code record_changed; the
example then reads the event again, prints its current values and stops without retrying. If the PATCH gets no response
or a server error, it may still have been saved, so the example never sends it again blindly: it reads the event again
(with $include_record_revision=true), reports the change as saved if the field already has the new value, sends it once
more with the new record_revision only if the field still has its old value, and otherwise reports it as not saved.
Treat record_revision as opaque. Leave out expected_revision to update without this check.
Set
EXHIBITDAY_API_KEY, EXHIBITDAY_EVENT_ID, EXHIBITDAY_CUSTOM_FIELD (the field_name) and EXHIBITDAY_CUSTOM_VALUE before running the workflow.Code Samples
#!/usr/bin/env bash
# Requires bash, curl and Python 3. Set EXHIBITDAY_API_KEY.
python3 - <<'EXHIBITDAY_PY'
# Python 3; standard library only. Set EXHIBITDAY_API_KEY before running.
import csv
import datetime
import json
import os
import re
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
from pathlib import Path
BASE = "https://api.exhibitday.com/v1"
SPEC = json.loads("{\"preserveNumbers\":false,\"requests\":{\"fields\":{\"method\":\"GET\",\"path\":\"/references/event_custom_fields\"},\"event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"updateEvent\":{\"method\":\"PATCH\",\"path\":\"/events\"},\"events\":{\"method\":\"GET\",\"path\":\"/events\"}}}")
API_KEY = os.environ["EXHIBITDAY_API_KEY"]
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)
# 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)
command = ["curl", "--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, extra_headers=None, key=None):
route = SPEC["requests"][name]
headers = {"api_key": API_KEY, "Accept": "application/json", **(extra_headers or {})}
if route["method"] == "POST":
headers["Idempotency-Key"] = key or str(uuid.uuid4()) # generated ONCE, before retries
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 "")
# A GET, or a POST with its Idempotency-Key, can be sent again. 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"] in ("GET", "POST")
for attempt in range(5):
try:
status, raw, response_headers = transport(route["method"], url, headers, data)
except (urllib.error.URLError, TimeoutError):
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 = status == 429 or status >= 500 or (status == 409 and isinstance(result, dict) and result.get("error_code") == "idempotency_key_in_use")
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}
raise RuntimeError("Retry limit reached")
def pages(name, params=None):
offset = 0
while True:
page = call(name, {**(params or {}), "$limit": 100, "$offset": offset})["body"]
yield from page["list_data"]
if not page["has_more"]:
break
count = int(page["records_found"])
if count <= 0:
raise RuntimeError("Server returned an empty page with has_more=true")
offset += count
def load_json(path, fallback):
return json.loads(path.read_text(encoding="utf-8")) if path.exists() else fallback
def save_json(path, value):
temp = path.with_name(path.name + ".tmp")
temp.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
temp.replace(path)
event_id = os.environ["EXHIBITDAY_EVENT_ID"]
field_name = os.environ["EXHIBITDAY_CUSTOM_FIELD"] # e.g. custom_67890 from your reference list
value = os.environ["EXHIBITDAY_CUSTOM_VALUE"] # use a valid current dropdown choice, or text/URL
fields = call("fields")["body"]["list_data"]
field = next((field for field in fields if field["field_name"] == field_name), None)
if field is None:
raise RuntimeError("Choose a field_name from this workspace's reference list")
kind = field.get("field_type", "").lower()
if field.get("is_hidden") or not (kind.startswith("text") or kind in ("dropdown", "url")):
raise RuntimeError("Choose a visible text, dropdown or URL field")
# Read with $include_record_revision, then update only if the event's editable fields have not changed since that read.
before = call("event", {"id": event_id, "$include_record_revision": "true"})["body"]
print("Before:", before.get("custom_fields", []))
def shown(record): # the field's value as the event shows it ("" when empty)
return next((str(f.get("value") or "") for f in record.get("custom_fields", []) if f.get("field_name") == field_name), "")
def update(revision): # "saved", "changed" (409 record_changed: nothing was saved) or "unknown"
try:
call("updateEvent", body={"id": event_id, field_name: value, "expected_revision": revision})
return "saved"
except ApiError as error:
if error.error_code == "record_changed":
return "changed"
if error.uncertain:
return "unknown"
raise
outcome = update(before["record_revision"])
if outcome == "unknown":
# No response or a server error: the update may have been saved. Read the event again; never resend blindly.
check = call("event", {"id": event_id, "$include_record_revision": "true"})["body"]
wanted = "" if value.lower() == "null" else value.strip().lower()
if shown(check).strip().lower() in (wanted, "http://" + wanted):
outcome = "saved" # the first attempt was saved
elif shown(check) == shown(before):
outcome = update(check["record_revision"]) # not saved, and nobody changed this field: send it once more
else:
outcome = "changed" # someone else changed this field: nothing more is sent
if outcome == "unknown":
raise RuntimeError("The outcome of the update is still unknown; check the event before trying again")
saved = outcome == "saved" # "changed": nothing was saved. Review it; never retry automatically.
after = call("event", {"id": event_id})["body"]
print("After:" if saved else "Not saved; the event changed after it was read. Current:", after.get("custom_fields", []))
if saved and (kind.startswith("text") or kind == "dropdown") and value and value.lower() != "null":
filtered = list(pages("events", {"filter_by_custom_event_field__" + field_name: value}))
print("Matching events:", len(filtered))
# JSON null clears a supported field; an empty string does NOT mean clear.
EXHIBITDAY_PY
// Server-side Node.js with fetch; built-in modules only. Set EXHIBITDAY_API_KEY.
const fs = require("node:fs");
const path = require("node:path");
const { randomUUID } = require("node:crypto");
const BASE = "https://api.exhibitday.com/v1";
const SPEC = JSON.parse("{\"preserveNumbers\":false,\"requests\":{\"fields\":{\"method\":\"GET\",\"path\":\"/references/event_custom_fields\"},\"event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"updateEvent\":{\"method\":\"PATCH\",\"path\":\"/events\"},\"events\":{\"method\":\"GET\",\"path\":\"/events\"}}}");
const API_KEY = process.env.EXHIBITDAY_API_KEY;
if (!API_KEY || !API_KEY.trim()) throw new Error("Set EXHIBITDAY_API_KEY");
const sleep = milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds));
function decodeJson(text) {
if (SPEC.preserveNumbers) {
// Keep raw JSON number tokens exact for CSV; quoted JSON strings remain unchanged.
text = text.replace(/"(?:\\.|[^"\\])*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g,
token => token.startsWith('"') ? token : JSON.stringify(token));
}
return JSON.parse(text);
}
// An API error response. Branch on errorCode (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.
class ApiError extends Error {
constructor(status, result, uncertain = false) {
super(result ? JSON.stringify({ error_code: result.error_code, error_params: result.error_params,
errors: result.errors, request_id: result.request_id }) : status ? "HTTP " + status : "No response");
this.status = status;
this.errorCode = result ? result.error_code : undefined;
this.uncertain = uncertain;
}
}
async function call(name, params = {}, body = null, extraHeaders = {}, key = null) {
const route = SPEC.requests[name];
const headers = { api_key: API_KEY, Accept: "application/json", ...extraHeaders };
if (route.method === "POST") headers["Idempotency-Key"] = key || randomUUID(); // once, before retries
const data = body === null ? undefined : JSON.stringify(body);
if (data !== undefined) headers["Content-Type"] = "application/json";
const query = new URLSearchParams(params).toString();
const url = BASE + route.path + (query ? "?" + query : "");
// A GET, or a POST with its Idempotency-Key, can be sent again. 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.
const resend = route.method === "GET" || route.method === "POST";
for (let attempt = 0; attempt < 5; attempt++) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 30000);
let response, raw;
try {
response = await fetch(url, { method: route.method, headers, body: data, signal: controller.signal, redirect: "error" });
raw = await response.text();
} catch (error) {
if (!resend) throw new ApiError(0, null, true);
if (attempt === 4) throw error;
await sleep(1000 * 2 ** attempt);
continue;
} finally { clearTimeout(timer); }
const resultHeaders = {};
response.headers.forEach((value, name) => { resultHeaders[name.toLowerCase()] = value; });
let result = null;
if (response.status !== 304 && raw) {
try { result = decodeJson(raw); }
catch (error) { if (response.status < 400) throw new Error("Expected a JSON success response"); }
}
if (response.status >= 500 && !resend) throw new ApiError(response.status, result, true);
const retry = response.status === 429 || response.status >= 500
|| (response.status === 409 && result?.error_code === "idempotency_key_in_use");
if (retry) {
if (attempt === 4) throw new Error("Retry limit reached; check the outcome before starting a new create");
const requested = Number(resultHeaders["retry-after"]);
await sleep(1000 * (Number.isFinite(requested) && requested >= 0 ? requested : 2 ** attempt));
continue;
}
if (response.status >= 400) throw new ApiError(response.status, result);
return { status: response.status, body: result, headers: resultHeaders };
}
throw new Error("Retry limit reached");
}
async function* pages(name, params = {}) {
let offset = 0;
while (true) {
const page = (await call(name, { ...params, "$limit": 100, "$offset": offset })).body;
yield* page.list_data;
if (!page.has_more) break;
const count = Number(page.records_found);
if (!Number.isSafeInteger(count) || count <= 0) throw new Error("Invalid pagination count");
offset += count;
}
}
function required(name) {
const value = process.env[name];
if (!value) throw new Error("Set " + name);
return value;
}
function loadJson(file, fallback) { return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, "utf8")) : fallback; }
function saveJson(file, value) {
fs.writeFileSync(file + ".tmp", JSON.stringify(value, null, 2) + "\n", "utf8");
fs.renameSync(file + ".tmp", file);
}
function csvCell(value) { return '"' + String(value ?? "").replace(/"/g, '""') + '"'; }
async function main() {
const eventId = required("EXHIBITDAY_EVENT_ID");
const fieldName = required("EXHIBITDAY_CUSTOM_FIELD");
const value = required("EXHIBITDAY_CUSTOM_VALUE"); // a current dropdown choice, text or URL
const fields = (await call("fields")).body.list_data;
const field = fields.find(field => field.field_name === fieldName);
if (!field) throw new Error("Choose a field_name from this workspace");
const kind = String(field.field_type || "").toLowerCase();
if (field.is_hidden || !(kind.startsWith("text") || kind === "dropdown" || kind === "url"))
throw new Error("Choose a visible text, dropdown or URL field");
// Read with $include_record_revision, then update only if the event's editable fields have not changed since that read.
const before = (await call("event", { id: eventId, $include_record_revision: "true" })).body;
console.log("Before:", before.custom_fields);
// The field's value as the event shows it ("" when empty).
const shown = record => String((record.custom_fields || []).find(f => f.field_name === fieldName)?.value ?? "");
// "saved", "changed" (409 record_changed: nothing was saved) or "unknown".
const update = async revision => {
try {
await call("updateEvent", {}, { id: eventId, [fieldName]: value, expected_revision: revision });
return "saved";
} catch (error) {
if (error instanceof ApiError && error.errorCode === "record_changed") return "changed";
if (error instanceof ApiError && error.uncertain) return "unknown";
throw error;
}
};
let outcome = await update(before.record_revision);
if (outcome === "unknown") {
// No response or a server error: the update may have been saved. Read the event again; never resend blindly.
const check = (await call("event", { id: eventId, $include_record_revision: "true" })).body;
const wanted = value.toLowerCase() === "null" ? "" : value.trim().toLowerCase();
const now = shown(check).trim().toLowerCase();
if (now === wanted || now === "http://" + wanted) outcome = "saved"; // the first attempt was saved
else if (shown(check) === shown(before)) outcome = await update(check.record_revision); // not saved, and nobody changed this field: send it once more
else outcome = "changed"; // someone else changed this field: nothing more is sent
}
if (outcome === "unknown") throw new Error("The outcome of the update is still unknown; check the event before trying again");
const saved = outcome === "saved"; // "changed": nothing was saved. Review it; never retry automatically.
const after = (await call("event", { id: eventId })).body;
console.log(saved ? "After:" : "Not saved; the event changed after it was read. Current:", after.custom_fields);
if (saved && (kind.startsWith("text") || kind === "dropdown") && value.toLowerCase() !== "null") {
let count = 0;
for await (const row of pages("events", { ["filter_by_custom_event_field__" + fieldName]: value })) count++;
console.log("Matching events:", count);
}
// JSON null clears a supported field; an empty string does not mean clear.
}
const completion = main();
completion.catch(error => { console.error(error.message); process.exitCode = 1; });
# Python 3; standard library only. Set EXHIBITDAY_API_KEY before running.
import csv
import datetime
import json
import os
import re
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
from pathlib import Path
BASE = "https://api.exhibitday.com/v1"
SPEC = json.loads("{\"preserveNumbers\":false,\"requests\":{\"fields\":{\"method\":\"GET\",\"path\":\"/references/event_custom_fields\"},\"event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"updateEvent\":{\"method\":\"PATCH\",\"path\":\"/events\"},\"events\":{\"method\":\"GET\",\"path\":\"/events\"}}}")
API_KEY = os.environ["EXHIBITDAY_API_KEY"]
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)
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, request, file, code, message, headers, new_url):
return None
OPENER = urllib.request.build_opener(NoRedirect())
def transport(method, url, headers, data):
request = urllib.request.Request(url, data=data, headers=headers, method=method)
try:
with OPENER.open(request, timeout=30) as response:
return response.status, response.read(), dict(response.headers)
except urllib.error.HTTPError as response:
try:
return response.code, response.read(), dict(response.headers)
finally:
response.close()
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, extra_headers=None, key=None):
route = SPEC["requests"][name]
headers = {"api_key": API_KEY, "Accept": "application/json", **(extra_headers or {})}
if route["method"] == "POST":
headers["Idempotency-Key"] = key or str(uuid.uuid4()) # generated ONCE, before retries
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 "")
# A GET, or a POST with its Idempotency-Key, can be sent again. 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"] in ("GET", "POST")
for attempt in range(5):
try:
status, raw, response_headers = transport(route["method"], url, headers, data)
except (urllib.error.URLError, TimeoutError):
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 = status == 429 or status >= 500 or (status == 409 and isinstance(result, dict) and result.get("error_code") == "idempotency_key_in_use")
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}
raise RuntimeError("Retry limit reached")
def pages(name, params=None):
offset = 0
while True:
page = call(name, {**(params or {}), "$limit": 100, "$offset": offset})["body"]
yield from page["list_data"]
if not page["has_more"]:
break
count = int(page["records_found"])
if count <= 0:
raise RuntimeError("Server returned an empty page with has_more=true")
offset += count
def load_json(path, fallback):
return json.loads(path.read_text(encoding="utf-8")) if path.exists() else fallback
def save_json(path, value):
temp = path.with_name(path.name + ".tmp")
temp.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
temp.replace(path)
event_id = os.environ["EXHIBITDAY_EVENT_ID"]
field_name = os.environ["EXHIBITDAY_CUSTOM_FIELD"] # e.g. custom_67890 from your reference list
value = os.environ["EXHIBITDAY_CUSTOM_VALUE"] # use a valid current dropdown choice, or text/URL
fields = call("fields")["body"]["list_data"]
field = next((field for field in fields if field["field_name"] == field_name), None)
if field is None:
raise RuntimeError("Choose a field_name from this workspace's reference list")
kind = field.get("field_type", "").lower()
if field.get("is_hidden") or not (kind.startswith("text") or kind in ("dropdown", "url")):
raise RuntimeError("Choose a visible text, dropdown or URL field")
# Read with $include_record_revision, then update only if the event's editable fields have not changed since that read.
before = call("event", {"id": event_id, "$include_record_revision": "true"})["body"]
print("Before:", before.get("custom_fields", []))
def shown(record): # the field's value as the event shows it ("" when empty)
return next((str(f.get("value") or "") for f in record.get("custom_fields", []) if f.get("field_name") == field_name), "")
def update(revision): # "saved", "changed" (409 record_changed: nothing was saved) or "unknown"
try:
call("updateEvent", body={"id": event_id, field_name: value, "expected_revision": revision})
return "saved"
except ApiError as error:
if error.error_code == "record_changed":
return "changed"
if error.uncertain:
return "unknown"
raise
outcome = update(before["record_revision"])
if outcome == "unknown":
# No response or a server error: the update may have been saved. Read the event again; never resend blindly.
check = call("event", {"id": event_id, "$include_record_revision": "true"})["body"]
wanted = "" if value.lower() == "null" else value.strip().lower()
if shown(check).strip().lower() in (wanted, "http://" + wanted):
outcome = "saved" # the first attempt was saved
elif shown(check) == shown(before):
outcome = update(check["record_revision"]) # not saved, and nobody changed this field: send it once more
else:
outcome = "changed" # someone else changed this field: nothing more is sent
if outcome == "unknown":
raise RuntimeError("The outcome of the update is still unknown; check the event before trying again")
saved = outcome == "saved" # "changed": nothing was saved. Review it; never retry automatically.
after = call("event", {"id": event_id})["body"]
print("After:" if saved else "Not saved; the event changed after it was read. Current:", after.get("custom_fields", []))
if saved and (kind.startswith("text") or kind == "dropdown") and value and value.lower() != "null":
filtered = list(pages("events", {"filter_by_custom_event_field__" + field_name: value}))
print("Matching events:", len(filtered))
# JSON null clears a supported field; an empty string does NOT mean clear.
// .NET 8 console program; standard library only. Set EXHIBITDAY_API_KEY.
#nullable disable
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
class Program
{
static readonly string BaseUrl = "https://api.exhibitday.com/v1";
static readonly JsonNode Spec = JsonNode.Parse("{\"preserveNumbers\":false,\"requests\":{\"fields\":{\"method\":\"GET\",\"path\":\"/references/event_custom_fields\"},\"event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"updateEvent\":{\"method\":\"PATCH\",\"path\":\"/events\"},\"events\":{\"method\":\"GET\",\"path\":\"/events\"}}}");
static readonly string ApiKey = Required("EXHIBITDAY_API_KEY");
static readonly HttpClient Client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false }) { Timeout = TimeSpan.FromSeconds(30) };
sealed class Result { public int Status; public JsonNode Body; public Dictionary<string, string> Headers; }
// An API error response. Branch on ErrorCode (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.
sealed class ApiException : Exception
{
public int Status { get; }
public string ErrorCode { get; }
public bool Uncertain { get; }
public ApiException(int status, string errorCode, string message, bool uncertain = false) : base(message) { Status = status; ErrorCode = errorCode; Uncertain = uncertain; }
}
static string Required(string name)
{ var value = Environment.GetEnvironmentVariable(name); return string.IsNullOrWhiteSpace(value) ? throw new Exception("Set " + name) : value; }
static string Text(JsonNode value) => value == null ? "" :
value is JsonValue scalar && scalar.TryGetValue<string>(out var text) ? text : value.ToJsonString();
static JsonObject Query(params (string Key, string Value)[] values)
{ var result = new JsonObject(); foreach (var value in values) result[value.Key] = value.Value; return result; }
static async Task<Result> Call(string name, JsonObject query = null, JsonNode body = null,
Dictionary<string, string> extraHeaders = null, string key = null)
{
var route = Spec["requests"][name];
var method = Text(route["method"]);
var headers = new Dictionary<string, string>(extraHeaders ?? new Dictionary<string, string>(), StringComparer.OrdinalIgnoreCase)
{ ["api_key"] = ApiKey, ["Accept"] = "application/json" };
if (method == "POST") headers["Idempotency-Key"] = key ?? Guid.NewGuid().ToString(); // once before retries
var data = body?.ToJsonString();
var suffix = query == null ? "" : string.Join("&", query.Select(p => Uri.EscapeDataString(p.Key) + "=" + Uri.EscapeDataString(Text(p.Value))));
var url = BaseUrl + Text(route["path"]) + (suffix.Length == 0 ? "" : "?" + suffix);
// A GET, or a POST with its Idempotency-Key, can be sent again. 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.
var resend = method == "GET" || method == "POST";
for (var attempt = 0; attempt < 5; attempt++)
{
using var request = new HttpRequestMessage(new HttpMethod(method), url);
foreach (var header in headers) request.Headers.TryAddWithoutValidation(header.Key, header.Value);
if (data != null) request.Content = new StringContent(data, Encoding.UTF8, "application/json");
HttpResponseMessage response;
string raw;
try { response = await Client.SendAsync(request); }
catch (Exception error) when (error is HttpRequestException || error is TaskCanceledException)
{ if (!resend) throw new ApiException(0, null, "No response", true); if (attempt == 4) throw; await Task.Delay(TimeSpan.FromSeconds(Math.Pow(2, attempt))); continue; }
using (response)
{
try { raw = await response.Content.ReadAsStringAsync(); }
catch (Exception error) when (error is HttpRequestException || error is TaskCanceledException)
{ if (!resend) throw new ApiException(0, null, "No response", true); if (attempt == 4) throw; await Task.Delay(TimeSpan.FromSeconds(Math.Pow(2, attempt))); continue; }
var status = (int)response.StatusCode;
var resultHeaders = response.Headers.Concat(response.Content.Headers)
.ToDictionary(h => h.Key.ToLowerInvariant(), h => string.Join(", ", h.Value));
JsonNode result = null;
if (status != 304 && raw.Length > 0)
{
try { result = JsonNode.Parse(raw); }
catch (JsonException) { if (status < 400) throw new Exception("Expected a JSON success response"); }
}
var errorBody = result as JsonObject;
if (status >= 500 && !resend) throw new ApiException(status, errorBody == null ? null : Text(errorBody["error_code"]), "HTTP " + status, true);
var retry = status == 429 || status >= 500 || (status == 409 && Text(errorBody?["error_code"]) == "idempotency_key_in_use");
if (retry)
{
if (attempt == 4) throw new Exception("Retry limit reached; check the outcome before starting a new create");
var seconds = Math.Pow(2, attempt);
if (resultHeaders.TryGetValue("retry-after", out var requested) &&
double.TryParse(requested, NumberStyles.Float, CultureInfo.InvariantCulture, out var delay) &&
double.IsFinite(delay) && delay >= 0) seconds = delay;
await Task.Delay(TimeSpan.FromSeconds(seconds)); continue;
}
if (status >= 400) throw new ApiException(status, errorBody == null ? null : Text(errorBody["error_code"]), errorBody == null ? "HTTP " + status :
$"{Text(errorBody["error_code"])} {errorBody["error_params"]}: {errorBody["errors"]} (request {Text(errorBody["request_id"])})");
return new Result { Status = status, Body = result, Headers = resultHeaders };
}
}
throw new Exception("Retry limit reached");
}
static async IAsyncEnumerable<JsonNode> Pages(string name, JsonObject parameters = null)
{
var offset = 0;
while (true)
{
var query = parameters == null ? new JsonObject() : (JsonObject)parameters.DeepClone();
query["$limit"] = 100; query["$offset"] = offset;
var page = (await Call(name, query)).Body;
foreach (var row in page["list_data"].AsArray()) yield return row;
if (!page["has_more"].GetValue<bool>()) yield break;
var count = int.Parse(Text(page["records_found"]), CultureInfo.InvariantCulture);
if (count <= 0) throw new Exception("Server returned an empty page with has_more=true");
offset += count;
}
}
static JsonNode Load(string file) => File.Exists(file) ? JsonNode.Parse(File.ReadAllText(file)) : new JsonObject();
static void Save(string file, JsonNode value)
{ File.WriteAllText(file + ".tmp", value.ToJsonString(new JsonSerializerOptions { WriteIndented = true }) + "\n", new UTF8Encoding(false)); File.Move(file + ".tmp", file, true); }
static string Csv(string value) => "\"" + (value ?? "").Replace("\"", "\"\"") + "\"";
static async Task Main()
{
var eventId = Required("EXHIBITDAY_EVENT_ID");
var fieldName = Required("EXHIBITDAY_CUSTOM_FIELD");
var value = Required("EXHIBITDAY_CUSTOM_VALUE");
var fields = (await Call("fields")).Body["list_data"].AsArray();
var field = fields.FirstOrDefault(item => Text(item["field_name"]) == fieldName);
if (field == null) throw new Exception("Choose a field_name from this workspace");
var kind = Text(field["field_type"]).ToLowerInvariant();
if ((field["is_hidden"]?.GetValue<bool>() ?? false) || !(kind.StartsWith("text") || kind == "dropdown" || kind == "url"))
throw new Exception("Choose a visible text, dropdown or URL field");
// Read with $include_record_revision, then update only if the event's editable fields have not changed since that read.
var before = (await Call("event", Query(("id", eventId), ("$include_record_revision", "true")))).Body;
Console.WriteLine("Before: " + before["custom_fields"]);
// The field's value as the event shows it ("" when empty).
string Shown(JsonNode record) => Text(record["custom_fields"]?.AsArray().FirstOrDefault(f => Text(f?["field_name"]) == fieldName)?["value"]);
// "saved", "changed" (409 record_changed: nothing was saved) or "unknown".
async Task<string> Update(string revision)
{
try { await Call("updateEvent", body: new JsonObject { ["id"] = eventId, [fieldName] = value, ["expected_revision"] = revision }); return "saved"; }
catch (ApiException error) when (error.ErrorCode == "record_changed") { return "changed"; }
catch (ApiException error) when (error.Uncertain) { return "unknown"; }
}
var outcome = await Update(Text(before["record_revision"]));
if (outcome == "unknown")
{
// No response or a server error: the update may have been saved. Read the event again; never resend blindly.
var check = (await Call("event", Query(("id", eventId), ("$include_record_revision", "true")))).Body;
var wanted = value.Equals("null", StringComparison.OrdinalIgnoreCase) ? "" : value.Trim().ToLowerInvariant();
var now = Shown(check).Trim().ToLowerInvariant();
if (now == wanted || now == "http://" + wanted) outcome = "saved"; // the first attempt was saved
else if (Shown(check) == Shown(before)) outcome = await Update(Text(check["record_revision"])); // not saved, and nobody changed this field: send it once more
else outcome = "changed"; // someone else changed this field: nothing more is sent
}
if (outcome == "unknown") throw new Exception("The outcome of the update is still unknown; check the event before trying again");
var saved = outcome == "saved"; // "changed": nothing was saved. Review it; never retry automatically.
var after = (await Call("event", Query(("id", eventId)))).Body;
Console.WriteLine((saved ? "After: " : "Not saved; the event changed after it was read. Current: ") + after["custom_fields"]);
if (saved && (kind.StartsWith("text") || kind == "dropdown") && value.Length > 0 && !string.Equals(value, "null", StringComparison.OrdinalIgnoreCase))
{
var count = 0;
await foreach (var row in Pages("events", Query(("filter_by_custom_event_field__" + fieldName, value)))) count++;
Console.WriteLine($"Matching events: {count}");
}
// JSON null clears a supported field; an empty string does not mean clear.
}
}
// Java 11+ with Gson on the classpath. Set EXHIBITDAY_API_KEY; save as Main.java.
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.ToNumberPolicy;
import java.io.*;
import java.net.*;
import java.net.http.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.time.*;
import java.util.*;
public class Main {
static final Gson JSON = new GsonBuilder().setObjectToNumberStrategy(ToNumberPolicy.LAZILY_PARSED_NUMBER).create();
static final String BASE = "https://api.exhibitday.com/v1";
static final Map<String,Object> SPEC = JSON.fromJson("{\"preserveNumbers\":false,\"requests\":{\"fields\":{\"method\":\"GET\",\"path\":\"/references/event_custom_fields\"},\"event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"updateEvent\":{\"method\":\"PATCH\",\"path\":\"/events\"},\"events\":{\"method\":\"GET\",\"path\":\"/events\"}}}", Map.class);
static final String API_KEY = required("EXHIBITDAY_API_KEY");
static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).followRedirects(HttpClient.Redirect.NEVER).build();
static class Result { int status; Map<String,Object> body; Map<String,String> headers;
Result(int s, Map<String,Object> b, Map<String,String> h) {status=s;body=b;headers=h;} }
// An API error response. Branch on errorCode (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.
static class ApiException extends IllegalStateException { final int status; final String errorCode; final boolean uncertain;
ApiException(int status,Object errorCode,String message) {this(status,errorCode,message,false);}
ApiException(int status,Object errorCode,String message,boolean uncertain) {super(message);this.status=status;this.errorCode=errorCode==null?null:String.valueOf(errorCode);this.uncertain=uncertain;} }
static String required(String name) {String value=System.getenv(name);if(value==null||value.trim().isEmpty())throw new IllegalArgumentException("Set "+name);return value;}
static String env(String name,String fallback) {String value=System.getenv(name);return value==null||value.isEmpty()?fallback:value;}
static String text(Object value) {return value==null?"":value.toString();}
@SuppressWarnings("unchecked") static Map<String,Object> obj(Object value) {return value==null?new LinkedHashMap<>(): (Map<String,Object>)value;}
@SuppressWarnings("unchecked") static List<Object> list(Object value) {return value==null?Collections.emptyList():(List<Object>)value;}
static Map<String,Object> map(Object... pairs) {Map<String,Object> result=new LinkedHashMap<>();for(int i=0;i<pairs.length;i+=2)result.put((String)pairs[i],pairs[i+1]);return result;}
static void pause(double seconds) {try {Thread.sleep((long)(Math.max(0,seconds)*1000));}catch(InterruptedException error){Thread.currentThread().interrupt();throw new RuntimeException(error);}}
static Result call(String name,Map<String,Object> query,Object body,Map<String,Object> extra,String key) {
Map<String,Object> route=obj(obj(SPEC.get("requests")).get(name));String method=text(route.get("method"));
Map<String,Object> headers=map("api_key",API_KEY,"Accept","application/json");if(extra!=null)headers.putAll(extra);
if(method.equals("POST"))headers.put("Idempotency-Key",key==null?UUID.randomUUID().toString():key); // once before retries
String data=body==null?null:JSON.toJson(body);if(data!=null)headers.put("Content-Type","application/json");
StringJoiner queryString=new StringJoiner("&");
if(query!=null)query.forEach((k,v)->queryString.add(URLEncoder.encode(k,StandardCharsets.UTF_8)+"="+URLEncoder.encode(text(v),StandardCharsets.UTF_8)));
String url=BASE+text(route.get("path"))+(queryString.length()==0?"":"?"+queryString);
// A GET, or a POST with its Idempotency-Key, can be sent again. 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.
boolean resend=method.equals("GET")||method.equals("POST");
for(int attempt=0;attempt<5;attempt++) {
HttpRequest.Builder request=HttpRequest.newBuilder(URI.create(url)).timeout(Duration.ofSeconds(30));
headers.forEach((k,v)->request.header(k,text(v)));
request.method(method,data==null?HttpRequest.BodyPublishers.noBody():HttpRequest.BodyPublishers.ofString(data,StandardCharsets.UTF_8));
HttpResponse<String> response;
try {response=CLIENT.send(request.build(),HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));}
catch(InterruptedException error){Thread.currentThread().interrupt();throw new RuntimeException(error);}
catch(IOException error){if(!resend)throw new ApiException(0,null,"No response",true);if(attempt==4)throw new RuntimeException(error);pause(Math.pow(2,attempt));continue;}
int status=response.statusCode();Map<String,Object> parsed=null;
if(status!=304&&!response.body().isEmpty()) {
try {parsed=JSON.fromJson(response.body(),Map.class);}
catch(RuntimeException error){if(status<400)throw new IllegalStateException("Expected a JSON success response",error);}
}
Map<String,String> responseHeaders=new HashMap<>();response.headers().map().forEach((k,v)->responseHeaders.put(k.toLowerCase(Locale.ROOT),String.join(", ",v)));
if(status>=500&&!resend)throw new ApiException(status,obj(parsed).get("error_code"),"HTTP "+status,true);
boolean retry=status==429||status>=500||(status==409&&"idempotency_key_in_use".equals(obj(parsed).get("error_code")));
if(retry) {
if(attempt==4)throw new IllegalStateException("Retry limit reached; check the outcome before starting a new create");
double seconds=Math.pow(2,attempt);
try {double value=Double.parseDouble(responseHeaders.get("retry-after"));if(Double.isFinite(value)&&value>=0)seconds=value;}catch(Exception ignored){}
pause(seconds);continue;
}
if(status>=400)throw new ApiException(status,obj(parsed).get("error_code"),"HTTP "+status+": "+obj(parsed).get("error_code")+" (request "+obj(parsed).get("request_id")+")");
return new Result(status,parsed,responseHeaders);
}
throw new IllegalStateException("Retry limit reached");
}
static Iterable<Map<String,Object>> pages(String name,Map<String,Object> parameters) {
return ()->new Iterator<Map<String,Object>>() {
int offset=0;boolean more=true;Iterator<Object> rows=Collections.emptyIterator();
public boolean hasNext() {
while(!rows.hasNext()&&more) {
Map<String,Object> query=new LinkedHashMap<>();if(parameters!=null)query.putAll(parameters);
query.put("$limit",100);query.put("$offset",offset);
Map<String,Object> page=call(name,query,null,null,null).body;
rows=list(page.get("list_data")).iterator();more=Boolean.TRUE.equals(page.get("has_more"));
int count=Integer.parseInt(text(page.get("records_found")));
if(more&&count<=0)throw new IllegalStateException("Invalid pagination count");offset+=count;
}
return rows.hasNext();
}
public Map<String,Object> next(){if(!hasNext())throw new NoSuchElementException();return obj(rows.next());}
};
}
static Map<String,Object> load(Path file)throws IOException {return Files.exists(file)?JSON.fromJson(Files.readString(file),Map.class):new LinkedHashMap<>();}
static void save(Path file,Object value)throws IOException {
Path temp=file.resolveSibling(file.getFileName()+".tmp");Files.writeString(temp,JSON.toJson(value)+"\n",StandardCharsets.UTF_8);
try {Files.move(temp,file,StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING);}
catch(AtomicMoveNotSupportedException error){Files.move(temp,file,StandardCopyOption.REPLACE_EXISTING);}
}
static String csv(Object value){return "\""+text(value).replace("\"","\"\"")+"\"";}
static String csvRow(Object... values){StringJoiner row=new StringJoiner(",");for(Object value:values)row.add(csv(value));return row+"\r\n";}
public static void main(String[] args)throws Exception {
String eventId=required("EXHIBITDAY_EVENT_ID"),fieldName=required("EXHIBITDAY_CUSTOM_FIELD"),value=required("EXHIBITDAY_CUSTOM_VALUE");
Map<String,Object> fields=call("fields",null,null,null,null).body,field=null;
for(Object item:list(fields.get("list_data")))if(fieldName.equals(obj(item).get("field_name"))){field=obj(item);break;}
if(field==null)throw new IllegalArgumentException("Choose a field_name from this workspace");
String kind=text(field.get("field_type")).toLowerCase(Locale.ROOT);
if(Boolean.TRUE.equals(field.get("is_hidden"))||!(kind.startsWith("text")||kind.equals("dropdown")||kind.equals("url")))
throw new IllegalArgumentException("Choose a visible text, dropdown or URL field");
// Read with $include_record_revision, then update only if the event's editable fields have not changed since that read.
Map<String,Object> before=call("event",map("id",eventId,"$include_record_revision","true"),null,null,null).body;System.out.println("Before: "+before.get("custom_fields"));
// The field's value as the event shows it ("" when empty).
java.util.function.Function<Map<String,Object>,String> shown=event->{for(Object item:list(event.get("custom_fields")))if(fieldName.equals(obj(item).get("field_name")))return text(obj(item).get("value"));return "";};
// "saved", "changed" (409 record_changed: nothing was saved) or "unknown".
java.util.function.Function<Object,String> update=revision->{
try {call("updateEvent",null,map("id",eventId,fieldName,value,"expected_revision",revision),null,null);return "saved";}
catch(ApiException error) {if("record_changed".equals(error.errorCode))return "changed";if(error.uncertain)return "unknown";throw error;}
};
String outcome=update.apply(before.get("record_revision"));
if(outcome.equals("unknown")) {
// No response or a server error: the update may have been saved. Read the event again; never resend blindly.
Map<String,Object> check=call("event",map("id",eventId,"$include_record_revision","true"),null,null,null).body;
String wanted=value.equalsIgnoreCase("null")?"":value.trim().toLowerCase(Locale.ROOT),now=shown.apply(check).trim().toLowerCase(Locale.ROOT);
if(now.equals(wanted)||now.equals("http://"+wanted))outcome="saved"; // the first attempt was saved
else if(shown.apply(check).equals(shown.apply(before)))outcome=update.apply(check.get("record_revision")); // not saved, and nobody changed this field: send it once more
else outcome="changed"; // someone else changed this field: nothing more is sent
}
if(outcome.equals("unknown"))throw new IllegalStateException("The outcome of the update is still unknown; check the event before trying again");
boolean saved=outcome.equals("saved"); // "changed": nothing was saved. Review it; never retry automatically.
Map<String,Object> after=call("event",map("id",eventId),null,null,null).body;System.out.println((saved?"After: ":"Not saved; the event changed after it was read. Current: ")+after.get("custom_fields"));
if(saved&&(kind.startsWith("text")||kind.equals("dropdown"))&&!value.isEmpty()&&!value.equalsIgnoreCase("null")) {
int count=0;for(Map<String,Object> row:pages("events",map("filter_by_custom_event_field__"+fieldName,value)))count++;
System.out.println("Matching events: "+count);
}
// JSON null clears a supported field; an empty string does not mean clear.
}
}
<?php
// PHP 8.1+ with the cURL extension. Set EXHIBITDAY_API_KEY before running.
declare(strict_types=1);
const BASE = 'https://api.exhibitday.com/v1';
const SPEC = '{"preserveNumbers":false,"requests":{"fields":{"method":"GET","path":"/references/event_custom_fields"},"event":{"method":"GET","path":"/events/info"},"updateEvent":{"method":"PATCH","path":"/events"},"events":{"method":"GET","path":"/events"}}}';
$spec = json_decode(SPEC, true, 512, JSON_THROW_ON_ERROR);
$apiKey = required('EXHIBITDAY_API_KEY');
if (trim($apiKey) === '') throw new RuntimeException('Set EXHIBITDAY_API_KEY');
function required(string $name, bool $allowEmpty = false): string {
$value = getenv($name);
if ($value === false || (!$allowEmpty && $value === '')) {
throw new RuntimeException('Set ' . $name);
}
return $value;
}
function optional(string $name, string $fallback): string {
$value = getenv($name);
return $value === false ? $fallback : $value;
}
function uuid4(): string {
$bytes = random_bytes(16);
$bytes[6] = chr((ord($bytes[6]) & 0x0f) | 0x40);
$bytes[8] = chr((ord($bytes[8]) & 0x3f) | 0x80);
$hex = bin2hex($bytes);
return substr($hex, 0, 8) . '-' . substr($hex, 8, 4) . '-' . substr($hex, 12, 4) . '-' .
substr($hex, 16, 4) . '-' . substr($hex, 20);
}
function decodeJson(string $text): mixed {
global $spec;
if ($spec['preserveNumbers']) {
// Quote NUMBER tokens without changing digits inside JSON strings; CSV decimals stay exact.
$pattern = <<<'JSON_NUMBER'
~"(?:\\.|[^"\\])*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?~
JSON_NUMBER;
$text = preg_replace_callback($pattern, static function (array $match): string {
return str_starts_with($match[0], '"') ? $match[0] : json_encode($match[0], JSON_THROW_ON_ERROR);
}, $text);
if ($text === null) throw new RuntimeException('Unable to preserve decimal tokens');
}
return json_decode($text, true, 512, JSON_THROW_ON_ERROR);
}
function transport(string $method, string $url, array $headers, ?string $data): array {
$responseHeaders = [];
$handle = curl_init($url);
if ($handle === false) throw new RuntimeException('Unable to initialize cURL');
$headerLines = [];
foreach ($headers as $name => $value) $headerLines[] = $name . ': ' . $value;
$options = [CURLOPT_CUSTOMREQUEST => $method, CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => false,
CURLOPT_CONNECTTIMEOUT => 30, CURLOPT_TIMEOUT => 30, CURLOPT_HTTPHEADER => $headerLines,
CURLOPT_HEADERFUNCTION => static function ($handle, string $line) use (&$responseHeaders): int {
if (str_starts_with($line, 'HTTP/')) $responseHeaders = [];
$separator = strpos($line, ':');
if ($separator !== false) {
$responseHeaders[strtolower(trim(substr($line, 0, $separator)))] = trim(substr($line, $separator + 1));
}
return strlen($line);
}];
if ($data !== null) $options[CURLOPT_POSTFIELDS] = $data;
try {
curl_setopt_array($handle, $options);
$raw = curl_exec($handle);
if ($raw === false) throw new RuntimeException('Network request failed: ' . curl_error($handle));
return [(int)curl_getinfo($handle, CURLINFO_RESPONSE_CODE), $raw, $responseHeaders];
} finally {
curl_close($handle);
}
}
function retryDelay(array $headers, int $attempt): float {
$value = $headers['retry-after'] ?? '';
if (is_numeric($value)) return max(0.0, (float)$value);
$date = $value === '' ? false : strtotime($value);
return $date === false ? (float)(2 ** $attempt) : max(0.0, (float)($date - time()));
}
// An API error response. Branch on errorCode (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.
final class ApiException extends RuntimeException {
public function __construct(public readonly int $status, public readonly ?string $errorCode, string $message, public readonly bool $uncertain = false) {
parent::__construct($message);
}
}
function call(string $name, array $params = [], mixed $body = null, array $extraHeaders = [], ?string $key = null): array {
global $spec, $apiKey;
$route = $spec['requests'][$name];
$headers = array_merge(['api_key' => $apiKey, 'Accept' => 'application/json'], $extraHeaders);
if ($route['method'] === 'POST') {
$headers['Idempotency-Key'] = $key ?? uuid4(); // ONCE, before retries.
}
$data = $body === null ? null : json_encode($body, JSON_THROW_ON_ERROR);
if ($data !== null) $headers['Content-Type'] = 'application/json';
$query = http_build_query($params, '', '&', PHP_QUERY_RFC3986);
$url = BASE . $route['path'] . ($query === '' ? '' : '?' . $query);
// A GET, or a POST with its Idempotency-Key, can be sent again. 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 = in_array($route['method'], ['GET', 'POST'], true);
for ($attempt = 0; $attempt < 5; $attempt++) {
try {
[$status, $raw, $responseHeaders] = transport($route['method'], $url, $headers, $data);
} catch (RuntimeException $error) {
if (!$resend) throw new ApiException(0, null, 'No response', true);
if ($attempt === 4) throw $error;
usleep((int)((2 ** $attempt) * 1000000));
continue;
}
$responseHeaders = array_change_key_case($responseHeaders, CASE_LOWER);
$result = null;
if ($status !== 304 && $raw !== '') {
try { $result = decodeJson($raw); }
catch (JsonException $error) {
if ($status < 400) throw new RuntimeException('Expected a JSON success response', 0, $error);
}
}
if ($status >= 500 && !$resend) {
throw new ApiException($status, is_array($result) && isset($result['error_code']) ? (string)$result['error_code'] : null, 'HTTP ' . $status, true);
}
$retry = $status === 429 || $status >= 500 ||
($status === 409 && is_array($result) && ($result['error_code'] ?? '') === 'idempotency_key_in_use');
if ($retry) {
if ($attempt === 4) throw new RuntimeException('Retry limit reached; check the outcome before starting a new create');
usleep((int)(retryDelay($responseHeaders, $attempt) * 1000000));
continue;
}
if ($status >= 400) {
if (!is_array($result)) throw new ApiException($status, null, 'HTTP ' . $status);
throw new ApiException($status, isset($result['error_code']) ? (string)$result['error_code'] : null, json_encode(['error_code' => $result['error_code'] ?? null,
'error_params' => $result['error_params'] ?? null, 'errors' => $result['errors'] ?? null,
'request_id' => $result['request_id'] ?? null], JSON_THROW_ON_ERROR));
}
return ['status' => $status, 'body' => $result, 'headers' => $responseHeaders];
}
throw new RuntimeException('Retry limit reached');
}
function pages(string $name, array $params = []): Generator {
$offset = 0;
while (true) {
$page = call($name, array_merge($params, ['$limit' => 100, '$offset' => $offset]))['body'];
foreach ($page['list_data'] as $record) yield $record;
if (!$page['has_more']) break;
$count = filter_var($page['records_found'], FILTER_VALIDATE_INT);
if ($count === false || $count <= 0) throw new RuntimeException('Server returned an empty or invalid page with has_more=true');
$offset += $count;
}
}
function loadJson(string $path, array $fallback): array {
if (!is_file($path)) return $fallback;
$text = file_get_contents($path);
if ($text === false) throw new RuntimeException('Unable to read ' . $path);
return json_decode($text, true, 512, JSON_THROW_ON_ERROR);
}
function saveJson(string $path, mixed $value): void {
$temporary = $path . '.tmp-' . bin2hex(random_bytes(6));
try {
if (file_put_contents($temporary, json_encode($value, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR) . "\n") === false ||
!rename($temporary, $path)) throw new RuntimeException('Unable to persist ' . $path);
} finally {
if (is_file($temporary)) unlink($temporary);
}
}
$eventId = required('EXHIBITDAY_EVENT_ID');
$fieldName = required('EXHIBITDAY_CUSTOM_FIELD'); // A field_name from your workspace's reference list.
$value = required('EXHIBITDAY_CUSTOM_VALUE', true); // A valid current dropdown choice, text or URL.
$fields = call('fields')['body']['list_data'];
$field = null;
foreach ($fields as $candidate) {
if ($candidate['field_name'] === $fieldName) { $field = $candidate; break; }
}
if ($field === null) throw new RuntimeException('Choose a field_name from this workspace');
$kind = strtolower($field['field_type'] ?? '');
if (($field['is_hidden'] ?? false) || !(str_starts_with($kind, 'text') || in_array($kind, ['dropdown', 'url'], true))) {
throw new RuntimeException('Choose a visible text, dropdown or URL field');
}
// Read with $include_record_revision, then update only if the event's editable fields have not changed since that read.
$before = call('event', ['id' => $eventId, '$include_record_revision' => 'true'])['body'];
echo 'Before: ', json_encode($before['custom_fields'] ?? [], JSON_THROW_ON_ERROR), PHP_EOL;
// The field's value as the event shows it ('' when empty).
$shown = function (array $event) use ($fieldName): string {
foreach ($event['custom_fields'] ?? [] as $candidate) {
if (($candidate['field_name'] ?? null) === $fieldName) return (string)($candidate['value'] ?? '');
}
return '';
};
// 'saved', 'changed' (409 record_changed: nothing was saved) or 'unknown'.
$update = function (?string $revision) use ($eventId, $fieldName, $value): string {
try {
call('updateEvent', [], ['id' => $eventId, $fieldName => $value, 'expected_revision' => $revision]);
return 'saved';
} catch (ApiException $error) {
if ($error->errorCode === 'record_changed') return 'changed';
if ($error->uncertain) return 'unknown';
throw $error;
}
};
$outcome = $update($before['record_revision'] ?? null);
if ($outcome === 'unknown') {
// No response or a server error: the update may have been saved. Read the event again; never resend blindly.
$check = call('event', ['id' => $eventId, '$include_record_revision' => 'true'])['body'];
$wanted = strtolower($value) === 'null' ? '' : strtolower(trim($value));
$now = strtolower(trim($shown($check)));
if ($now === $wanted || $now === 'http://' . $wanted) $outcome = 'saved'; // the first attempt was saved
elseif ($shown($check) === $shown($before)) $outcome = $update($check['record_revision'] ?? null); // not saved, and nobody changed this field: send it once more
else $outcome = 'changed'; // someone else changed this field: nothing more is sent
}
if ($outcome === 'unknown') throw new RuntimeException('The outcome of the update is still unknown; check the event before trying again');
$saved = $outcome === 'saved'; // 'changed': nothing was saved. Review it; never retry automatically.
$after = call('event', ['id' => $eventId])['body'];
echo $saved ? 'After: ' : 'Not saved; the event changed after it was read. Current: ', json_encode($after['custom_fields'] ?? [], JSON_THROW_ON_ERROR), PHP_EOL;
if ($saved && (str_starts_with($kind, 'text') || $kind === 'dropdown') && $value !== '' && strtolower($value) !== 'null') {
$count = 0;
foreach (pages('events', ['filter_by_custom_event_field__' . $fieldName => $value]) as $record) $count++;
echo 'Matching events: ', $count, PHP_EOL;
}
// JSON null clears a supported field; an empty string does NOT mean clear.
# Ruby 3.1+; standard library only. Set EXHIBITDAY_API_KEY before running.
require 'net/http'
require 'json'
require 'uri'
require 'csv'
require 'fileutils'
require 'securerandom'
require 'date'
require 'time'
require 'timeout'
BASE = 'https://api.exhibitday.com/v1'
SPEC = JSON.parse('{"preserveNumbers":false,"requests":{"fields":{"method":"GET","path":"/references/event_custom_fields"},"event":{"method":"GET","path":"/events/info"},"updateEvent":{"method":"PATCH","path":"/events"},"events":{"method":"GET","path":"/events"}}}')
API_KEY = ENV.fetch('EXHIBITDAY_API_KEY')
def decode_json(text)
if SPEC.fetch('preserveNumbers')
# Preserve JSON NUMBER lexemes for CSV, without replacing digits inside JSON strings.
text = text.gsub(/"(?:\\.|[^"\\])*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/) do |token|
token.start_with?('"') ? token : JSON.generate(token)
end
end
JSON.parse(text)
end
def transport(method, url, headers, data)
uri = URI(url)
request_type = { 'GET' => Net::HTTP::Get, 'POST' => Net::HTTP::Post,
'PATCH' => Net::HTTP::Patch }.fetch(method)
request = request_type.new(uri.request_uri, headers)
request.body = data unless data.nil?
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = uri.scheme == 'https'
http.open_timeout = http.read_timeout = http.write_timeout = 30
http.max_retries = 0 # The outer loop owns the bounded retry policy.
response = http.start { |client| client.request(request) }
[response.code.to_i, response.body.to_s, response.each_header.to_h]
end
def retry_delay(headers, attempt)
value = headers['retry-after']
return 2**attempt if value.nil? || value.empty?
begin
[Float(value), 0].max
rescue ArgumentError, TypeError
begin
[Time.httpdate(value) - Time.now, 0].max
rescue ArgumentError
2**attempt
end
end
end
# 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.
class ApiError < RuntimeError
attr_reader :status, :error_code, :uncertain
def initialize(status, error_code, message, uncertain = false)
super(message)
@status = status
@error_code = error_code
@uncertain = uncertain
end
end
def call(name, params = {}, body = nil, extra_headers = {}, key = nil)
route = SPEC.fetch('requests').fetch(name)
headers = { 'api_key' => API_KEY, 'Accept' => 'application/json' }.merge(extra_headers)
if route.fetch('method') == 'POST'
headers['Idempotency-Key'] = key || SecureRandom.uuid # ONCE before retries.
end
data = body.nil? ? nil : JSON.generate(body)
headers['Content-Type'] = 'application/json' unless data.nil?
query = URI.encode_www_form(params)
url = BASE + route.fetch('path') + (query.empty? ? '' : '?' + query)
# A GET, or a POST with its Idempotency-Key, can be sent again. 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 = %w[GET POST].include?(route.fetch('method'))
5.times do |attempt|
begin
status, raw, response_headers = transport(route.fetch('method'), url, headers, data)
rescue IOError, SystemCallError, Timeout::Error, SocketError
raise ApiError.new(0, nil, 'No response', true) unless resend
raise if attempt == 4
sleep(2**attempt)
next
end
response_headers = response_headers.transform_keys(&:downcase)
result = nil
unless status == 304 || raw.empty?
begin
result = decode_json(raw)
rescue JSON::ParserError, EncodingError
raise 'Expected a JSON success response' if status < 400
end
end
if status >= 500 && !resend
raise ApiError.new(status, result.is_a?(Hash) ? result['error_code'] : nil, "HTTP #{status}", true)
end
transient = status == 429 || (500..599).cover?(status) ||
(status == 409 && result.is_a?(Hash) && result['error_code'] == 'idempotency_key_in_use')
if transient
raise 'Retry limit reached; check the outcome before starting a new create' if attempt == 4
sleep(retry_delay(response_headers, attempt))
next
end
if status >= 400
raise ApiError.new(status, nil, "HTTP #{status}") unless result.is_a?(Hash)
raise ApiError.new(status, result['error_code'], "#{result['error_code']} #{result['error_params'].inspect}: #{result['errors'].inspect} (request #{result['request_id']})")
end
return { status: status, body: result, headers: response_headers }
end
raise 'Retry limit reached'
end
def pages(name, params = {})
return enum_for(__method__, name, params) unless block_given?
offset = 0
loop do
page = call(name, params.merge('$limit' => 100, '$offset' => offset)).fetch(:body)
page.fetch('list_data').each { |record| yield record }
break unless page.fetch('has_more')
count = Integer(page.fetch('records_found'))
raise 'Server returned an empty page with has_more=true' if count <= 0
offset += count
end
end
def load_json(path, fallback)
File.exist?(path) ? JSON.parse(File.read(path, encoding: 'UTF-8')) : fallback
end
def save_json(path, value)
temporary = "#{path}.tmp-#{Process.pid}"
File.write(temporary, JSON.pretty_generate(value) + "\n", encoding: 'UTF-8')
File.rename(temporary, path)
end
event_id = ENV.fetch('EXHIBITDAY_EVENT_ID')
field_name = ENV.fetch('EXHIBITDAY_CUSTOM_FIELD') # A field_name from this workspace's reference list.
value = ENV.fetch('EXHIBITDAY_CUSTOM_VALUE') # Valid current dropdown choice, text or URL.
fields = call('fields').fetch(:body).fetch('list_data')
field = fields.find { |entry| entry.fetch('field_name') == field_name }
raise "Choose a field_name from this workspace's reference list" if field.nil?
kind = field.fetch('field_type', '').downcase
if field['is_hidden'] || !(kind.start_with?('text') || %w[dropdown url].include?(kind))
raise 'Choose a visible text, dropdown or URL field'
end
# Read with $include_record_revision, then update only if the event's editable fields have not changed since that read.
before = call('event', { 'id' => event_id, '$include_record_revision' => 'true' }).fetch(:body)
puts "Before: #{before.fetch('custom_fields', []).inspect}"
# The field's value as the event shows it ('' when empty).
shown = ->(record) { (record.fetch('custom_fields', []).find { |entry| entry['field_name'] == field_name } || {})['value'].to_s }
# 'saved', 'changed' (409 record_changed: nothing was saved) or 'unknown'.
update = lambda do |revision|
call('updateEvent', {}, { 'id' => event_id, field_name => value, 'expected_revision' => revision })
'saved'
rescue ApiError => e
raise unless e.error_code == 'record_changed' || e.uncertain
e.error_code == 'record_changed' ? 'changed' : 'unknown'
end
outcome = update.call(before['record_revision'])
if outcome == 'unknown'
# No response or a server error: the update may have been saved. Read the event again; never resend blindly.
check = call('event', { 'id' => event_id, '$include_record_revision' => 'true' }).fetch(:body)
wanted = value.downcase == 'null' ? '' : value.strip.downcase
now = shown.call(check).strip.downcase
outcome = if [wanted, "http://#{wanted}"].include?(now)
'saved' # the first attempt was saved
elsif shown.call(check) == shown.call(before)
update.call(check['record_revision']) # not saved, and nobody changed this field: send it once more
else
'changed' # someone else changed this field: nothing more is sent
end
end
raise 'The outcome of the update is still unknown; check the event before trying again' if outcome == 'unknown'
saved = outcome == 'saved' # 'changed': nothing was saved. Review it; never retry automatically.
after = call('event', { 'id' => event_id }).fetch(:body)
puts "#{saved ? 'After' : 'Not saved; the event changed after it was read. Current'}: #{after.fetch('custom_fields', []).inspect}"
if saved && (kind.start_with?('text') || kind == 'dropdown') && !value.empty? && value.downcase != 'null'
filtered = pages('events', { 'filter_by_custom_event_field__' + field_name => value }).to_a
puts "Matching events: #{filtered.length}"
end
# JSON null clears a supported field; an empty string does NOT mean clear.
// Go 1.18+; standard library only. Set EXHIBITDAY_API_KEY.
package main
import (
"bytes"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
)
const base = "https://api.exhibitday.com/v1"
const specification = "{\"preserveNumbers\":false,\"requests\":{\"fields\":{\"method\":\"GET\",\"path\":\"/references/event_custom_fields\"},\"event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"updateEvent\":{\"method\":\"PATCH\",\"path\":\"/events\"},\"events\":{\"method\":\"GET\",\"path\":\"/events\"}}}"
var spec map[string]any
var apiKey string
var client = &http.Client{Timeout: 30 * time.Second, CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }}
type result struct { status int; body any; headers http.Header }
// An API error response (raised with panic). Branch on 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.
type apiError struct { status int; code string; message string; uncertain bool }
func (failure apiError) Error() string { return failure.message }
func required(name string) string {
value := os.Getenv(name); if strings.TrimSpace(value) == "" { panic("Set " + name) }; return value
}
func text(value any) string { if value == nil { return "" }; return fmt.Sprint(value) }
func object(value any) map[string]any { if value == nil { return map[string]any{} }; return value.(map[string]any) }
func array(value any) []any { if value == nil { return nil }; return value.([]any) }
func decode(raw []byte) (any, error) {
var value any
decoder := json.NewDecoder(bytes.NewReader(raw)); decoder.UseNumber() // keeps exact decimal tokens
err := decoder.Decode(&value); return value, err
}
func uuid() string {
value := make([]byte, 16); if _, err := rand.Read(value); err != nil { panic(err) }
value[6] = (value[6] & 0x0f) | 0x40; value[8] = (value[8] & 0x3f) | 0x80
encoded := hex.EncodeToString(value)
return encoded[:8]+"-"+encoded[8:12]+"-"+encoded[12:16]+"-"+encoded[16:20]+"-"+encoded[20:]
}
func call(name string, query map[string]string, body any, extra map[string]string, key string) result {
route := object(object(spec["requests"])[name]); method := text(route["method"])
headers := map[string]string{"api_key": apiKey, "Accept": "application/json"}
for k, v := range extra { headers[k] = v }
if method == "POST" { if key == "" { key = uuid() }; headers["Idempotency-Key"] = key } // before retry loop
var data []byte
if body != nil { var err error; data, err = json.Marshal(body); if err != nil { panic(err) }; headers["Content-Type"] = "application/json" }
values := url.Values{}; for k,v := range query { values.Set(k,v) }
address := base + text(route["path"]); if len(values) > 0 { address += "?" + values.Encode() }
// A GET, or a POST with its Idempotency-Key, can be sent again. 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 := method == "GET" || method == "POST"
for attempt := 0; attempt < 5; attempt++ {
request, err := http.NewRequest(method, address, bytes.NewReader(data)); if err != nil { panic(err) }
for k,v := range headers { request.Header.Set(k,v) }
response, err := client.Do(request)
if err != nil { if !resend { panic(apiError{0, "", "No response", true}) }; if attempt == 4 { panic(err) }; time.Sleep(time.Second*time.Duration(1<<attempt)); continue }
raw, readErr := io.ReadAll(response.Body); response.Body.Close()
if readErr != nil { if !resend { panic(apiError{0, "", "No response", true}) }; if attempt == 4 { panic(readErr) }; time.Sleep(time.Second*time.Duration(1<<attempt)); continue }
var parsed any
if response.StatusCode != 304 && len(raw)>0 {
parsed, err = decode(raw)
if err != nil && response.StatusCode < 400 { panic("Expected a JSON success response") }
}
errorBody, _ := parsed.(map[string]any)
if response.StatusCode >= 500 && !resend { panic(apiError{response.StatusCode, text(errorBody["error_code"]), fmt.Sprintf("HTTP %d", response.StatusCode), true}) }
retry := response.StatusCode == 429 || response.StatusCode >= 500 || (response.StatusCode == 409 && text(errorBody["error_code"]) == "idempotency_key_in_use")
if retry {
if attempt == 4 { panic("Retry limit reached; check the outcome before starting a new create") }
seconds := float64(int64(1)<<attempt)
if value, err := strconv.ParseFloat(response.Header.Get("Retry-After"),64); err == nil && value >= 0 { seconds = value }
time.Sleep(time.Duration(seconds*float64(time.Second))); continue
}
if response.StatusCode >= 400 { panic(apiError{response.StatusCode, text(errorBody["error_code"]), fmt.Sprintf("HTTP %d: %v (request %v)",response.StatusCode,errorBody["error_code"],errorBody["request_id"]), false}) }
return result{response.StatusCode, parsed, response.Header}
}
panic("Retry limit reached")
}
func pages(name string, query map[string]string, consume func(map[string]any)) {
offset := 0
for {
params := map[string]string{}; for k,v := range query { params[k]=v }
params["$limit"]="100";params["$offset"]=strconv.Itoa(offset)
page := object(call(name,params,nil,nil,"").body)
for _,row := range array(page["list_data"]) { consume(object(row)) }
if page["has_more"] != true { return }
count, err := strconv.Atoi(text(page["records_found"])); if err != nil || count<=0 { panic("Invalid pagination count") };offset+=count
}
}
func load(file string) map[string]any {
raw, err := os.ReadFile(file); if os.IsNotExist(err) { return map[string]any{} };if err != nil { panic(err) }
value,err:=decode(raw);if err!=nil {panic(err)};return object(value)
}
func save(file string, value any) {
raw,err:=json.MarshalIndent(value,""," ");if err!=nil {panic(err)}
if err=os.WriteFile(file+".tmp",append(raw,'\n'),0600);err!=nil {panic(err)}
if err=os.Rename(file+".tmp",file);err!=nil {panic(err)}
}
func main() {
apiKey=required("EXHIBITDAY_API_KEY")
if err:=json.Unmarshal([]byte(specification),&spec);err!=nil {panic(err)}
eventID:=required("EXHIBITDAY_EVENT_ID");fieldName:=required("EXHIBITDAY_CUSTOM_FIELD");value:=required("EXHIBITDAY_CUSTOM_VALUE")
fields:=object(call("fields",nil,nil,nil,"").body);var selected map[string]any
for _,row:=range array(fields["list_data"]) {field:=object(row);if text(field["field_name"])==fieldName {selected=field;break}}
if selected==nil {panic("Choose a field_name from this workspace")}
kind:=strings.ToLower(text(selected["field_type"]))
if selected["is_hidden"]==true || !(strings.HasPrefix(kind,"text") || kind=="dropdown" || kind=="url") {panic("Choose a visible text, dropdown or URL field")}
// Read with $include_record_revision, then update only if the event's editable fields have not changed since that read.
before:=object(call("event",map[string]string{"id":eventID,"$include_record_revision":"true"},nil,nil,"").body);fmt.Println("Before:",before["custom_fields"])
// The field's value as the event shows it ("" when empty).
shown:=func(event map[string]any) string {
for _,row:=range array(event["custom_fields"]) {if text(object(row)["field_name"])==fieldName {return text(object(row)["value"])}}
return ""
}
// "saved", "changed" (409 record_changed: nothing was saved) or "unknown".
update:=func(revision any) (outcome string) {
defer func() {
if failure:=recover(); failure!=nil {
if problem,isAPI:=failure.(apiError); isAPI && problem.code=="record_changed" {outcome="changed";return}
if problem,isAPI:=failure.(apiError); isAPI && problem.uncertain {outcome="unknown";return}
panic(failure)
}
}()
call("updateEvent",nil,map[string]any{"id":eventID,fieldName:value,"expected_revision":revision},nil,"");return "saved"
}
outcome:=update(before["record_revision"])
if outcome=="unknown" {
// No response or a server error: the update may have been saved. Read the event again; never resend blindly.
check:=object(call("event",map[string]string{"id":eventID,"$include_record_revision":"true"},nil,nil,"").body)
wanted:=strings.ToLower(strings.TrimSpace(value)); if strings.EqualFold(value,"null") {wanted=""}
now:=strings.ToLower(strings.TrimSpace(shown(check)))
if now==wanted || now=="http://"+wanted {
outcome="saved" // the first attempt was saved
} else if shown(check)==shown(before) {
outcome=update(check["record_revision"]) // not saved, and nobody changed this field: send it once more
} else {
outcome="changed" // someone else changed this field: nothing more is sent
}
}
if outcome=="unknown" {panic("The outcome of the update is still unknown; check the event before trying again")}
saved:=outcome=="saved" // "changed": nothing was saved. Review it; never retry automatically.
after:=object(call("event",map[string]string{"id":eventID},nil,nil,"").body)
if saved {fmt.Println("After:",after["custom_fields"])} else {fmt.Println("Not saved; the event changed after it was read. Current:",after["custom_fields"])}
if saved && (strings.HasPrefix(kind,"text") || kind=="dropdown") && !strings.EqualFold(value,"null") {
count:=0;pages("events",map[string]string{"filter_by_custom_event_field__"+fieldName:value},func(row map[string]any){count++})
fmt.Println("Matching events:",count)
}
// JSON null clears a supported field; an empty string does not mean clear.
}
Example HTTP response body (JSON)
GET /v1/events/info - HTTP 200
{
"id": 12345,
"exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=12345",
"name": "Sample Event",
"start_date": "2026-12-14",
"end_date": "2026-12-16",
"participation_type_id": 1,
"participation_type": "Committed",
"format_id": 1,
"format": "In-Person",
"star_rating": 0,
"tags": [],
"website_url": "",
"venue_name": "",
"venue_address": "",
"venue_location_display_name": "",
"venue_address_latitude": "",
"venue_address_longitude": "",
"booth_size": "",
"booth_number": "",
"booth_reservation_status_id": 1,
"booth_reservation_status": "Need to Reserve",
"booth_reserve_by_date": "",
"booth_date_reserved": "",
"budget_booth_reservation": 0.00,
"budget_booth_services": 0.00,
"budget_attendee_registrations": 0.00,
"budget_travel": 0.00,
"budget_giveaways": 0.00,
"budget_shipments": 0.00,
"budget_event_activities": 0.00,
"budget_misc_expenses": 0.00,
"budget_sponsorships": 0.00,
"total_sum_event_budgets": 0.00,
"cost_booth_reservation": 0.00,
"cost_booth_services": 0.00,
"cost_attendee_registrations": 0.00,
"cost_travel_reservations": 0.00,
"cost_giveaways": 0.00,
"cost_shipments": 0.00,
"cost_event_activities": 0.00,
"cost_misc_expenses": 0.00,
"cost_sponsorships": 0.00,
"total_sum_event_costs": 0.00,
"event_notes": "",
"booth_notes": "",
"budget_notes": "",
"roi_notes": "",
"roi_num_leads": 0,
"roi_num_impressions_booth": 0,
"roi_num_impressions_sponsorships": 0,
"roi_num_impressions_media": 0,
"roi_num_meetings_existing_customers": 0,
"roi_num_meetings_new_customers": 0,
"roi_amount_actual_sales": 0.00,
"roi_amount_potential_sales": 0.00,
"event_created_timestamp": "2026-11-14T17:00:00Z",
"event_last_update_timestamp": "2026-11-14T17:00:00Z",
"event_created_by": {
"id": "11111111-2222-4333-8444-555555555555",
"first_name": "Jane",
"last_name": "Smith",
"email": "jane@example.invalid"
},
"custom_fields": [
{
"label": "Integration status",
"value": "Ready",
"notes": "",
"field_name": "custom_67890",
"field_type": "Text (Single-line)",
"field_event_tab": "Info"
}
],
"task_sections": [],
"tasks": [],
"misc_expenses_credits": [],
"integration_metadata_field_1": "",
"integration_metadata_field_2": "",
"integration_metadata_field_3": "",
"integration_metadata_field_4": "",
"integration_metadata_field_5": ""
}
Note: Illustrative response. The event-info GET after the PATCH. Assume event 12345 has a visible Text (Single-line) field custom_67890 labeled Integration status and EXHIBITDAY_CUSTOM_VALUE=Ready. This is the server readback body, not the program's Before/After console formatting. Other field types require their own valid values. Request inputs: {"id":"12345"}.
Requirements: the curl workflow uses Bash, curl and Python 3; JavaScript uses Node.js 18 or later (save it as .cjs);
Python uses its standard library; C# uses a .NET 8 console project (Program.cs). Java needs Java 11 or later,
saved as Main.java, with Gson 2.14.0 on both the compile and runtime classpaths. PHP needs PHP 8.1 or later with cURL;
Ruby 3.1 or later and Go 1.18 or later use their standard libraries.
Multi-line text uses plain-text input like the notes fields. HTML tags are stripped, line breaks become
<br/> and stored text is HTML-encoded, so the API returns HTML: a < b is returned as a < b.
4. Filter by a saved value
filter_by_custom_event_field__custom_67890=Northeast filters text/dropdown fields by that saved value.
The comparison ignores letter case. Replace the example field id and value with your own.