# ExhibitDay API: full reference > REST API for ExhibitDay, a trade show and event management platform. Use it to read data from an ExhibitDay workspace or push data into it. This is the complete ExhibitDay API documentation in one Markdown file, generated from the same source as the help pages at https://api.exhibitday.com/Help/V1. The short index is https://api.exhibitday.com/llms.txt and the OpenAPI 3 description is https://api.exhibitday.com/openapi.json. - Base URL: https://api.exhibitday.com/v1 - Authentication: send the workspace API key as `Authorization: Bearer YOUR_API_KEY`. `X-API-Key` and the legacy `api_key` parameter still work. Find the key under Workspace Settings > API & Integrations > API Access. - Rate limit: 50 calls per second per workspace by default. Workspace rate checks return `X-RateLimit-Limit`, `X-RateLimit-Remaining` and `X-RateLimit-Reset` (seconds) headers; a separate IP rate check can refuse a request before those headers are added. A 429 response carries `Retry-After` (seconds). Use the returned limit and retry headers rather than assuming a fixed allowance. - Error responses are JSON with `status_code`, `status`, `message`, `errors`, a stable `error_code`, `error_params` (the parameters the errors refer to), `request_id` (also in the X-Request-Id header) and, when applicable, `warnings`. Successful object responses also include warnings for unknown, unsupported, ignored or defaulted parameters, and for empty values sent on an update. On a create, an empty value means no value and gets no warning. Warnings can also report attachments that could not be copied to an inventory return. - Successful warnings: arrays and 304 responses retain their shape and expose a JSON-array `X-API-Warnings` header. `X-API-Warnings-Count` gives the full count; `X-API-Warnings-Truncated: true` means the 6000-character ASCII header limit was reached. Request the default object format for the full warning list. Invalid values that would be stored return 400. - Lists: use `$limit` and `$offset` on endpoints that support paging (responses include `total_records` and `has_more`). Use `filter_by_last_update_timestamp_greater_than_or_equal_to` where supported to retrieve changes; upsert every returned record by ID, including records at the inclusive timestamp boundary. - Retries: send an `Idempotency-Key` header with a create (POST). Successful responses are retained for 24 hours; retry the same request with the same byte-identical, case-sensitive key during that period to reuse the saved response. Follow the documented 409 handling when a request is still running or its outcome is unknown. DELETE has no idempotency replay contract; after an uncertain response, retrieve the record first and treat a later `not_found` as already absent. Successful API GET responses that return JSON include an `ETag` for `If-None-Match`; file downloads do not. - HTTP methods: send actual documented verbs. Method tunneling is refused with 400 `invalid_request` on every endpoint: `X-HTTP-Method-Override` as a header, a form field or a query-string parameter, and form/query `_method` (a request with no API key in a header, the query string or a form field gets 401 first; a request with a JSON body gets 400, because its key may be inside the body). - Updates: on PATCH requests, omit fields you want to keep. Empty or whitespace-only update values are ignored with a warning. A JSON null or the text `null` clears or resets a supported field; fields that cannot be cleared return an error. The legacy `$ignore_params_with_empty_values=true` option drops empty values and JSON nulls before updates; the text `null` still requests a clear. Related fields can also change to keep the record consistent; see the endpoint's field rules. To update only if none of the fields that PATCH can change has changed since you read the record, read it with `$include_record_revision=true` and send the returned `record_revision` as `expected_revision` (the help page lists what each revision covers; a change undone in between does not count); a 409 `record_changed` then means nothing was saved: read it again and decide whether to send your change again. After no response or a 5xx on a PATCH, read the record before sending it again: it may already have been saved. ## Getting started ### Getting Started with the ExhibitDay API Use this API to programmatically read and update data in your ExhibitDay workspace. The API helps you automate the exchange of information between ExhibitDay and your internal systems or third-party software. To set up integrations, you'll need a working knowledge of REST APIs. New to these terms? See Key terms at the bottom of this page. ### 1. Get your API key In ExhibitDay, go to **Workspace Settings → API & Integrations → API Access** and copy your workspace's API key. Keep it private. Anyone with the key can read and change your workspace's data through the API. ### 2. Make your first request To retrieve the list of Events in your workspace, replace `YOUR_API_KEY` with your key and run this command in a terminal. ```bash curl -X GET "https://api.exhibitday.com/v1/events" -H "Authorization: Bearer YOUR_API_KEY" ``` ### 3. Read the response A successful request returns HTTP `200`. The `list_data` array contains the Events returned by your request. If your workspace has no Events, the request still succeeds and `list_data` is an empty array (`[]`). Got `401`? Check that you replaced `YOUR_API_KEY` with the key from your workspace, that the header reads `Authorization: Bearer` followed by a space and your key, and that API access is enabled for your workspace. ### Authentication Send your API key with every request. We recommend the `Authorization` header: ``` Authorization: Bearer YOUR_API_KEY ``` You can also send the key in an `X-API-Key` header: ``` X-API-Key: YOUR_API_KEY ``` **Older integrations.** Integrations built before November 2026 often send the key as an `api_key` parameter, for example the header `api_key: YOUR_API_KEY`. That still works and you don't need to change it. You can also send `api_key` in the query string, form data or JSON body. Avoid putting the key in the query string, because web addresses are often saved in server logs and browser history. If you use `Authorization: Bearer` or `X-API-Key` and also send the key another way, all copies must be the same key. Different keys return `400` (`invalid_request`) and nothing is changed. If your key is exposed, generate a new one under **Workspace Settings → API & Integrations → API Access**. Integrations that use the old key stop working until they're updated with the new one. ### Sending parameters For a GET request, put filters and paging options in the URL's query string. For a create or update, send field values in a JSON body with the `Content-Type: application/json` header. For a delete, put the record's `id` in the query string. Send your API key in a header, as described in [Authentication](#authentication). ### Parameter formats, repeated values, and size limits - **Where to send a value.** The API accepts parameters in headers, the query string, or a JSON body. For example, send the fields you want to update in a JSON body. You can send a parameter more than once if every copy has the same value. If the copies differ, the API returns `400` (`invalid_request`) and nothing is changed. - **JSON values.** Most fields accept a single value. Use an array or object only when the endpoint specifies that format. Write a JSON number as `12345`. If you need leading zeros, use a quoted string such as `"012345"` where the parameter accepts it. - **Lists.** A parameter that takes a list accepts a real JSON array, for example `["user-id","other-user-id"]`, or the same list written as JSON text inside a string, for example `"[\"user-id\"]"`. In a query string or form, send the list as JSON text. Where a list holds objects, you can send one object instead of a list of one. A list of IDs, such as `tagged_user_ids` or `task_ids`, also takes one ID on its own, for example `"user-id"` or `12345`, as a list of one. On an update, `[]` or `null` removes every item from a list that can be cleared. One exception: Event tags (`tags`) also take plain comma-separated text, so text sent inside a string is read as tag names; send a real JSON array for the list form. - **Event tab options.** Options that choose Event tabs use one naming rule: the tab name, and the tab name followed by `_costs` for its cost details. For example, `POST /v1/events/copy` takes `copy_shipments` and `copy_shipments_costs`, and `GET /v1/events/binder/export` takes `include_shipments` and `include_shipments_costs`. The one exception is objectives: the binder shows them in two sections, `include_roi` and `include_roo`, and copy takes `copy_objectives`. - **Request size.** JSON bodies can be up to 10 MB. For a long filter value, use a JSON body. Keep encoded URLs under roughly 16,000 characters. The server's exact limit can vary. If it rejects a URL before it reaches the API, you may see a plain `414` or `400` response and no entry in the API logs. File uploads use multipart form data and have their own endpoint-specific limits. - **HTTP method.** Send the method shown on the endpoint. Method overrides using `X-HTTP-Method-Override` or `_method` are rejected with `400` (`invalid_request`) on every endpoint, and nothing is changed. A request with no API key in a header, the query string or a form field gets `401` first; a request with a JSON body is refused with `400`, because its key may be inside the body. ### Updating or clearing a field Include the required identifiers with each PATCH request. For editable fields, choose the option that matches what you want to do. | To do this | Send this | | --- | --- | | Keep a value | Omit the field. Its saved value is normally preserved. | | Change a value | Send the field with its new value. | | Clear a value | Send JSON `null` or the string `"null"` if the field supports clearing. The endpoint explains whether that empties the field, removes a value, or restores a default. | For example, this request clears the due date of Task `12345`. The empty string for `details` keeps the saved details and produces a warning. ```bash curl -X PATCH "https://api.exhibitday.com/v1/tasks" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"id\":12345,\"due_date\":null,\"details\":\"\"}" ``` ### Example response and empty-field rules When the due date changes, the response identifies the updated field and includes a warning for `details`. ```json { "status_code": 200, "status": "OK", "message": "Task Update Successful. Task properties that were changed: due_date", "errors": [], "warnings": [ "details was empty, so it was left unchanged." ] } ``` On an update, a blank input usually keeps the saved value and adds a warning. On a create, a blank input simply means no value, and no warning is added. Some changes clear other saved values that no longer apply, for example a status change that removes notes kept only for another status. The response then includes a warning naming each cleared field. A Task comment requires text, so sending a blank comment can return an error. On updates that support `$ignore_params_with_empty_values=true`, empty values and JSON `null` are skipped without a warning. To clear a supported field with that option enabled, send the string `"null"`. Changing one field can affect another. For example, moving a Task to a different Event resets its section unless you also supply a valid section for the new Event. Check the endpoint for rules about related fields. When creating a record, JSON `null` doesn't always mean the same as leaving a field out. Some fields treat it as omitted, and others refuse it. The field's help describes any special rules. Leave out fields you don't want to set. Deleting something that no longer exists, such as a record, a file or an invoice that was already removed, returns `404` Not Found with a message that says what is missing. ### Costs and payments Enter a cost when adding or updating its record, such as a Booth Service or Shipment. You can provide a single amount or divide it between cost centers. Payment details and Invoice Attachments are handled separately. See [Record Costs and Split Them Across Cost Centers](https://api.exhibitday.com/Help/V1?guide=entering-costs) for examples and a walkthrough of changing saved costs. ### Lookup lists Most lookups under `/v1/references` return an object with `records_found`, `list_type` and `list_data`, a list of choices with an `id` and a `name`. Send `$result_format=array` to get just the list. Every new lookup uses this shape. These older lookups keep the shape they have always had: | Lookup | Default response | Common shape | | --- | --- | --- | | `GET /v1/references/cost_centers` | A JSON array of cost centers | Send `$result_format=object` | | `GET /v1/references/budget_years` | A JSON array of `{"id": "2035", "value": "2035"}` items | Send `$result_format=object` (the items keep their `id` and `value`) | | `GET /v1/references/filterable_event_custom_fields` | A JSON array of `id`/`value` items | Send `$result_format=object` (the items keep their `id` and `value`) | | `GET /v1/references/event_start_date_categories` | A JSON array of `id`/`value` items | Send `$result_format=object` (the items keep their `id` and `value`) | | `GET /v1/references/event_tags` | The common wrapper, with tag names (text) in `list_data` | Already the default | ### Paging through results On list endpoints that support paging, `$limit` sets how many records to return and `$offset` sets how many matches to skip. This example requests the first 100 Events. To get the next page, change the offset to `100`. ```bash curl -X GET "https://api.exhibitday.com/v1/events?%24limit=100&%24offset=0" -H "Authorization: Bearer YOUR_API_KEY" ``` In the standard Events list response, `records_found` is the number of Events on this page, `total_records` counts all matching Events, and `has_more` tells you whether another page follows. The `X-Total-Count` header also gives the total. ### Understanding responses For an API error, use `error_code` to decide what to do next. Check `error_params` for the affected fields, and include `request_id` when contacting support. The request ID is also available in the `X-Request-Id` header. If your integration encounters an unfamiliar error code, handle it by HTTP status. | HTTP status | What to do | | --- | --- | | 200 OK | The request succeeded. Check the response for data and any warnings. | | 304 Not Modified | Use your saved copy. Your conditional GET matched the server's current response. | | 400 Bad Request | Read the error to find out which input needs correcting or why the operation is unavailable for this record. | | 401 Unauthorized | Check your API key, how you're sending it (see [Authentication](#authentication)), and your workspace's API access setting. | | 404 Not Found | For `not_found`, check the record ID. For `unknown_endpoint`, check the URL and HTTP method. | | 409 Conflict | Check `error_code` before retrying. For `record_changed`, retrieve the record and review its current values first. | | 429 Too Many Requests | Wait the number of seconds in the `Retry-After` header before retrying. | | 500 Internal Server Error | If you were saving a change, check whether it succeeded before retrying. Include the request ID if you contact support. | See [Handle Errors and Retry Failed Requests](https://api.exhibitday.com/Help/V1?guide=errors-and-retries) for recovery steps. ### Error codes and an example response `error_params` is an empty array when the API cannot identify a specific parameter. ```json { "status_code": 400, "status": "Bad Request", "message": "Invalid Event ID in event_id. Use a valid Event ID, or omit this filter.", "error_code": "invalid_request", "errors": [ "Invalid Event ID in event_id. Use a valid Event ID, or omit this filter." ], "error_params": [ "event_id" ], "request_id": "3f2c9a7e4b1d4c8e9f0a1b2c3d4e5f60" } ``` | Error code | HTTP status | Meaning | | --- | --- | --- | | `invalid_request` | 400 | A parameter is missing or has an invalid value (error_params names it when the API can tell). This includes any parameter sent more than once with different values (matching copies are accepted), and an expected_revision that is blank, null, malformed or sent to an operation that does not support it. | | `malformed_json` | 400 | The request body is not valid JSON. The error message says what the parser found and where (line and position), so you can correct the JSON and send it again. | | `not_allowed` | 400 | The change is not allowed for that record in ExhibitDay (e.g., the event's tasks or its deletion are locked, or its Misc. Expenses & Credits tab is hidden). | | `idempotency_key_reused` | 400 | The Idempotency-Key was already used with a different request. Use a new key for a new request. | | `missing_api_key` | 401 | No API key was provided. Send your key in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter. | | `invalid_api_key` | 401 | The API key is not valid. Check that you copied the whole key from Workspace Settings > API & Integrations > API Access, then send it in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter. | | `api_access_disabled` | 401 | Access to the ExhibitDay API is not enabled for your workspace. Please contact support@exhibitday.com to enable API Access. Once access is enabled, send your key in the Authorization header as 'Bearer YOUR_API_KEY'. | | `not_found` | 404 | No record with that id exists in your workspace. | | `unknown_endpoint` | 404 | The URL or HTTP method is not part of the API. | | `idempotency_key_in_use` | 409 | A request with the same Idempotency-Key is still being processed. Retry after a moment. | | `idempotency_key_indeterminate` | 409 | An earlier request did not finish with a confirmed outcome, or its saved response can no longer be returned safely. This retry was not run. Look for the existing record with a GET before deciding whether another create is needed; use a new Idempotency-Key only after checking. | | `record_changed` | 409 | The record changed while it was being saved or read, or it changed since the read whose record_revision you sent as expected_revision. Nothing was changed by this request. Retrieve its current values, review them and retry only if your change still applies. | | `file_copy_pending` | 409 | This file is still being copied. Try again in a few minutes. | | `inventory_busy` | 409 | Another inventory operation is still finishing. This request did not start its event changes; wait briefly, retrieve the event's current state and retry deletion if still needed. | | `attachment_preservation_failed` | 409 | Required reservation attachment copies could not be created. The event and its inventory were not changed. Check the reservation attachments in ExhibitDay before retrying deletion. | | `rate_limited` | 429 | Too many requests. Wait the number of seconds in the Retry-After header, then retry. | | `internal_error` | 500 | An unexpected error occurred. Please try again later. | ### Warnings and rate-limit headers Check `warnings` in the default object response for inputs the API skipped or defaulted. For example, an unrecognized parameter name produces a warning. An invalid value for a field the API would save returns HTTP `400`. Responses can also report warnings in `X-API-Warnings`, including error responses, array responses and bodyless `304` responses. This ASCII-escaped JSON array is limited to 6,000 characters. `X-API-Warnings-Count` gives the full number of warnings. If `X-API-Warnings-Truncated` is `true`, use the default object format to read the complete list. The default workspace limit is 50 calls per second. `X-RateLimit-Limit` gives your effective limit, `X-RateLimit-Remaining` tells you how many calls are left, and `X-RateLimit-Reset` gives the seconds until the window resets. A request limited earlier by IP may lack the workspace headers. On `429`, follow `Retry-After`. ### How empty fields appear in responses Unset text fields usually return `""`. Dates, related objects, and related IDs usually return `null`. Unset numbers usually return `0`, and empty lists return `[]`. Some fields use older formats: - On Events, unset `booth_date_reserved` and `booth_reserve_by_date` return `""`. - In `/v1/financials/event_costs`, unset `payment_due_date`, `next_payment_due_date`, and `payment_notes` return `""`. A missing `cost_subtype` returns `null`. - On a miscellaneous expense or credit, empty `payment_notes` returns `null` and empty `notes` returns `""`. - With `$return_task_lites`, unset `assignee_user_id` and `task_completed_by_user_id` return `""`. ### Changes made through the API or Zapier When a record is created, completed, or commented on through the API or Zapier, its person field (`event_created_by`, `task_created_by`, `task_completed_by`, or `commenter`) has an `id` of `null`, because no workspace user made the change. Use `display_name` to identify it: `"ExhibitDay API"` for the API and `"ExhibitDay API (Zapier)"` for Zapier. Its `first_name` is `"ExhibitDay"`, its `last_name` is `"API"`, and its `email`, `type`, and `workspace_role` are `null`. With `$return_task_lites`, `task_created_by_user_id` and `task_completed_by_user_id` return the integration's name as text, such as `"ExhibitDay API"` or `"Zapier"`, instead of a user ID. Activity log entries recorded by the API have a `null` `actor_user_id`. Use `actor_display_name` to identify them. ### Retrying requests and checking for changes ### Retry a create request without creating a duplicate For a create endpoint that supports `Idempotency-Key`, send a unique key with the first POST. If you need to retry that create, send the same key, URL, body, and parameter headers exactly as before. Once the API has stored a successful response, an identical retry within 24 hours returns that response with `Idempotent-Replayed: true`. - `idempotency_key_in_use`: the first request is still running. Wait briefly and retry with the same key. - If you receive `idempotency_key_indeterminate`, check whether the first request created the record. Use a new key only after confirming the record was not created. - `idempotency_key_reused`: the key was used with a different request. Give each new create request its own key. For a DELETE with an uncertain outcome, retrieve the record before retrying. A `404` with `not_found` means the record is already absent. ### Check whether a saved GET response is still current Save the `ETag` from a successful data request (GET responses that return JSON include one; file downloads do not). The next time you GET the same URL, send that value in the `If-None-Match` header. If the response still matches, the API returns `304 Not Modified` with no body. You can reuse your saved response. ### Avoid overwriting someone else's changes 1. Retrieve the record using the GET endpoint listed for the operation below. Include `$include_record_revision=true`. 2. In your update or delete request, set `expected_revision` to the exact `record_revision` value returned by GET. Omit it to skip the revision check. If any covered value differs from the one you read, the API saves nothing and returns `409` (`record_changed`). Retrieve the record again, review the current values, and decide whether to retry. A value that changed and was later changed back still matches. A successful conditional update returns the current revision. If you lose the response to an update, read the record before retrying. If a GET cannot return a revision because the record keeps changing, repeat the GET. A blank, null, malformed, or conflicting `expected_revision` returns `400` (`invalid_request`), as does sending it to an operation that does not support it. Each operation lists the values its revision covers. An edit to a covered field can cause a conflict even if your request omits that field. - [`PATCH /v1/events`](https://api.exhibitday.com/Help/V1?epf=1#patch-v1-events) — get the revision from [`GET /v1/events/info`](https://api.exhibitday.com/Help/V1?epf=1#get-v1-events-info). Covered: every field this PATCH can change, tags, custom field values, and the readable Booth Reservation payment fields and complete saved cost allocations. A revision obtained without access to Booth financials can still protect other Event changes; financial values are masked, and a visibility change requires a fresh revision. Not covered: custom field labels or settings, derived venue location fields, Booth reservation status and reservation dates set in ExhibitDay, other cost categories or total_sum_event_costs, current cost center names, invoices, files, tasks, task_sections or misc_expenses_credits. Read a fresh Event revision before using the new Booth cost or payment fields. - [`PATCH /v1/events/misc_expenses_credits`](https://api.exhibitday.com/Help/V1?epf=100#patch-v1-events-misc_expenses_credits) — get the revision from [`GET /v1/events/misc_expenses_credits/info`](https://api.exhibitday.com/Help/V1?epf=100#get-v1-events-misc_expenses_credits-info). Covered: every field this PATCH can change (the amount together with its cost-center allocation), and the expected credit date, credit status and credit notes set in ExhibitDay. - [`PATCH /v1/tasks`](https://api.exhibitday.com/Help/V1?epf=2#patch-v1-tasks) — get the revision from [`GET /v1/tasks/info`](https://api.exhibitday.com/Help/V1?epf=2#get-v1-tasks-info). Covered: every field this PATCH can change, and the task's links to related items in ExhibitDay. Not covered: display_rank (it changes when tasks are reordered), task_completed_by and task_completed_timestamp, and the comments in the response. - [`PATCH /v1/tasks/comments`](https://api.exhibitday.com/Help/V1?epf=2&topic=comments#patch-v1-tasks-comments) — get the revision from [`GET /v1/tasks/comments/info`](https://api.exhibitday.com/Help/V1?epf=2&topic=comments#get-v1-tasks-comments-info). Covered: the comment's text, including formatting changed in ExhibitDay. Not covered: event_id (it is the event of the comment's task, which can move to another event). - [`DELETE /v1/workspace_settings/users/invitations`](https://api.exhibitday.com/Help/V1?epf=6&topic=user-invitations#delete-v1-workspace_settings-users-invitations) — get the revision from [`GET /v1/workspace_settings/users/invitations/info`](https://api.exhibitday.com/Help/V1?epf=6&topic=user-invitations#get-v1-workspace_settings-users-invitations-info). Covered: this invitation, its recipient, intended role, complete saved permission denials and content restrictions, current status, API-origin protocol and saved automatic-email preference. Not covered: invitation links or proof digests, real-inviter attribution or creation, acceptance, send and reminder timestamps. The token protects optional revocation, grants no permission, and is not an email verification link. - [`POST /v1/workspace_settings/users/invitations/resend`](https://api.exhibitday.com/Help/V1?epf=6&topic=user-invitations#post-v1-workspace_settings-users-invitations-resend) — get the revision from [`GET /v1/workspace_settings/users/invitations/info`](https://api.exhibitday.com/Help/V1?epf=6&topic=user-invitations#get-v1-workspace_settings-users-invitations-info). Covered: this invitation, its recipient, intended role, complete saved permission denials and content restrictions, current status, API-origin protocol and saved automatic-email preference. Not covered: invitation links or proof digests, real-inviter attribution or creation, acceptance, send and reminder timestamps. The token protects optional revocation, grants no permission, and is not an email verification link. - [`PATCH /v1/workspace_settings`](https://api.exhibitday.com/Help/V1?epf=6#patch-v1-workspace_settings) — get the revision from [`GET /v1/workspace_settings`](https://api.exhibitday.com/Help/V1?epf=6#get-v1-workspace_settings). Covered: the 15 settings this PATCH can change, including workspace currency and the fiscal-year start month, plus whether Task Workflows and the AI Assistant are available. Saved modes of unavailable features are excluded; changing feature availability changes the token. Not covered: currency display labels, available option labels, settings timestamps, history, notification delivery, billing, membership or other settings. - [`PATCH /v1/assets`](https://api.exhibitday.com/Help/V1?epf=5#patch-v1-assets) — get the revision from [`GET /v1/assets/info`](https://api.exhibitday.com/Help/V1?epf=5#get-v1-assets-info). - [`POST /v1/assets/archive`](https://api.exhibitday.com/Help/V1?epf=5#post-v1-assets-archive) — get the revision from [`GET /v1/assets/info`](https://api.exhibitday.com/Help/V1?epf=5#get-v1-assets-info). - [`POST /v1/assets/unarchive`](https://api.exhibitday.com/Help/V1?epf=5#post-v1-assets-unarchive) — get the revision from [`GET /v1/assets/info`](https://api.exhibitday.com/Help/V1?epf=5#get-v1-assets-info). - [`DELETE /v1/assets/images`](https://api.exhibitday.com/Help/V1?epf=5&topic=images#delete-v1-assets-images) — get the revision from [`GET /v1/assets/images`](https://api.exhibitday.com/Help/V1?epf=5&topic=images#get-v1-assets-images). Covered: this Asset's complete image order, image filenames and saved gallery times. The token belongs to the whole gallery, so adding, deleting or reordering another image can make it stale. Not covered: the image file contents or other Asset details. Use the gallery record_revision from GET /v1/assets/images with $include_record_revision=true. - [`PATCH /v1/assets/images/order`](https://api.exhibitday.com/Help/V1?epf=5&topic=images#patch-v1-assets-images-order) — get the revision from [`GET /v1/assets/images`](https://api.exhibitday.com/Help/V1?epf=5&topic=images#get-v1-assets-images). Covered: this Asset's complete image order, image filenames and saved gallery times. The token belongs to the whole gallery, so adding, deleting or reordering another image can make it stale. Not covered: the image file contents or other Asset details. Use the gallery record_revision from GET /v1/assets/images with $include_record_revision=true. - [`PATCH /v1/assets/reservation_logistical_records`](https://api.exhibitday.com/Help/V1?epf=5&topic=logistical-records#patch-v1-assets-reservation_logistical_records) — get the revision from [`GET /v1/assets/reservations/info`](https://api.exhibitday.com/Help/V1?epf=5&topic=reservations#get-v1-assets-reservations-info). Covered: the selected reservation's Asset and Event associations, logistics status, dates, notes, flags, Optional Accessory quantities, Logistical Records and direct related-item links. For Collateral, this also covers its Storage Location and quantity. Send asset_type_id as well as id, because a Capital reservation and a Collateral reservation can have the same numeric id. Not covered: creation or author timestamps, or attachments. Your current access and the inventory rules are still checked separately. - [`DELETE /v1/assets/reservation_logistical_records`](https://api.exhibitday.com/Help/V1?epf=5&topic=logistical-records#delete-v1-assets-reservation_logistical_records) — get the revision from [`GET /v1/assets/reservations/info`](https://api.exhibitday.com/Help/V1?epf=5&topic=reservations#get-v1-assets-reservations-info). Covered: the selected reservation's Asset and Event associations, logistics status, dates, notes, flags, Optional Accessory quantities, Logistical Records and direct related-item links. For Collateral, this also covers its Storage Location and quantity. Send asset_type_id as well as id, because a Capital reservation and a Collateral reservation can have the same numeric id. Not covered: creation or author timestamps, or attachments. Your current access and the inventory rules are still checked separately. - [`PATCH /v1/assets/reservations`](https://api.exhibitday.com/Help/V1?epf=5&topic=reservations#patch-v1-assets-reservations) — get the revision from [`GET /v1/assets/reservations/info`](https://api.exhibitday.com/Help/V1?epf=5&topic=reservations#get-v1-assets-reservations-info). Covered: the selected reservation's Asset and Event associations, logistics status, dates, notes, flags, Optional Accessory quantities, Logistical Records and direct related-item links. For Collateral, this also covers its Storage Location and quantity. Send asset_type_id as well as id, because a Capital reservation and a Collateral reservation can have the same numeric id. Not covered: creation or author timestamps, or attachments. Your current access and the inventory rules are still checked separately. - [`POST /v1/assets/cancel_reservation`](https://api.exhibitday.com/Help/V1?epf=5&topic=reservations#post-v1-assets-cancel_reservation) — get the revision from [`GET /v1/assets/reservations/info`](https://api.exhibitday.com/Help/V1?epf=5&topic=reservations#get-v1-assets-reservations-info). Covered: the selected reservation's Asset and Event associations, logistics status, dates, notes, flags, Optional Accessory quantities, Logistical Records and direct related-item links. For Collateral, this also covers its Storage Location and quantity. Send asset_type_id as well as id, because a Capital reservation and a Collateral reservation can have the same numeric id. Not covered: creation or author timestamps, or attachments. Your current access and the inventory rules are still checked separately. - [`PATCH /v1/assets/inventory_adjustments`](https://api.exhibitday.com/Help/V1?epf=5&topic=inventory-adjustments#patch-v1-assets-inventory_adjustments) — get the revision from [`GET /v1/assets/inventory_adjustments/info`](https://api.exhibitday.com/Help/V1?epf=5&topic=inventory-adjustments#get-v1-assets-inventory_adjustments-info). - [`DELETE /v1/assets/inventory_adjustments`](https://api.exhibitday.com/Help/V1?epf=5&topic=inventory-adjustments#delete-v1-assets-inventory_adjustments) — get the revision from [`GET /v1/assets/inventory_adjustments/info`](https://api.exhibitday.com/Help/V1?epf=5&topic=inventory-adjustments#get-v1-assets-inventory_adjustments-info). - [`PATCH /v1/assets/storage_locations`](https://api.exhibitday.com/Help/V1?epf=5&topic=storage-locations#patch-v1-assets-storage_locations) — get the revision from [`GET /v1/assets/storage_locations/info`](https://api.exhibitday.com/Help/V1?epf=5&topic=storage-locations#get-v1-assets-storage_locations-info). Covered: the Storage Location name, address and point of contact details. Not covered: map details derived from the address, the creation timestamp, Assets or inventory transactions. - [`PATCH /v1/financials/misc_annual_expenses`](https://api.exhibitday.com/Help/V1?epf=4&topic=misc-annual-expenses-credits#patch-v1-financials-misc_annual_expenses) — get the revision from [`GET /v1/financials/misc_annual_expenses/info`](https://api.exhibitday.com/Help/V1?epf=4&topic=misc-annual-expenses-credits#get-v1-financials-misc_annual_expenses-info). Covered: description, planned amount and the actual cost-center allocation rows, bound to this expense and annual budget. The budget year is checked for a match and cannot be changed by this operation. Not covered: cost-center names and the expense's creation timestamp. - [`PATCH /v1/financials/annual_budgets`](https://api.exhibitday.com/Help/V1?epf=4#patch-v1-financials-annual_budgets) — get the revision from [`GET /v1/financials/annual_budgets`](https://api.exhibitday.com/Help/V1?epf=4#get-v1-financials-annual_budgets). Covered: the saved year and its planned number of Events, planned Exhibit amount, planned Sponsorship amount and raw Budget Notes, including native formatting. The token is bound to its workspace and saved budget row. Not covered: calculated costs, miscellaneous annual expense rows, fiscal labels/dates, creation or last-update timestamps, or display rounding and notes sanitization. Each returned year has its own optional token. - [`PATCH /v1/events/sponsorships`](https://api.exhibitday.com/Help/V1?epf=1&topic=sponsorships#patch-v1-events-sponsorships) — get the revision from [`GET /v1/events/sponsorships/info`](https://api.exhibitday.com/Help/V1?epf=1&topic=sponsorships#get-v1-events-sponsorships-info). - [`PATCH /v1/events/playbook_activities`](https://api.exhibitday.com/Help/V1?epf=1&topic=playbook#patch-v1-events-playbook_activities) — get the revision from [`GET /v1/events/playbook_activities/info`](https://api.exhibitday.com/Help/V1?epf=1&topic=playbook#get-v1-events-playbook_activities-info). Covered: the activity's Event association, title, description, day and times, location, type, status, role, category details, planning fields, tagged people and direct related-item links, including fields currently hidden by the activity's choices. Not covered: separate activity costs, invoice or ordinary attachments, author and creation details, or assignment-notification delivery state. Current choices and access are checked separately. - [`PATCH /v1/events/playbook_activity_costs`](https://api.exhibitday.com/Help/V1?epf=1&topic=playbook#patch-v1-events-playbook_activity_costs) — get the revision from [`GET /v1/events/playbook_activity_costs/info`](https://api.exhibitday.com/Help/V1?epf=1&topic=playbook#get-v1-events-playbook_activity_costs-info). Covered: this cost's activity association, description, vendor/payee, reference number, dates, payment details, Notes and actual cost-center allocations. The token belongs to this one cost; use that cost's Info response, not its activity's revision. Not covered: the invoice attachment or its bytes, cost-center names, creation or last-modified timestamps, or the activity's other costs and details. - [`PATCH /v1/events/staff`](https://api.exhibitday.com/Help/V1?epf=1&topic=staff#patch-v1-events-staff) — get the revision from [`GET /v1/events/staff/info`](https://api.exhibitday.com/Help/V1?epf=1&topic=staff#get-v1-events-staff-info). Covered: this entry's Event and person associations, role, attendance format, registration type, confirmation/reference number, link, Notes, payment details, actual cost-center allocations and direct related-task links. Not covered: the invoice or ordinary attachments, notification delivery/copy/author bookkeeping, creation timestamp, or current person/role/cost-center display names. Current person availability, role choices and Event access are checked separately. - [`PATCH /v1/events/objectives`](https://api.exhibitday.com/Help/V1?epf=1&topic=objectives#patch-v1-events-objectives) — get the revision from [`GET /v1/events/objectives/info`](https://api.exhibitday.com/Help/V1?epf=1&topic=objectives#get-v1-events-objectives-info). Covered: the objective’s Event association, type, Other name, importance and achievement rating. The type and Other name are set when adding it. Not covered: its added timestamp, current objective-type or importance labels, the Event’s other objectives or overall scores. Current access and available custom objectives are checked separately. - [`PATCH /v1/events/booth_services`](https://api.exhibitday.com/Help/V1?epf=1&topic=booth-services#patch-v1-events-booth_services) — get the revision from [`GET /v1/events/booth_services/info`](https://api.exhibitday.com/Help/V1?epf=1&topic=booth-services#get-v1-events-booth_services-info). Covered: the service type, acquisition and order details, vendor information, payment fields, Notes, all saved service details (including previous families and Labor subtypes), actual cost-center allocations and direct related-item links. Not covered: invoice or ordinary attachments, their contents, creation timestamp, cost-center/type labels or the Event's planned budget. Use this service's Info response for its token. - [`PATCH /v1/events/travel_reservations`](https://api.exhibitday.com/Help/V1?epf=1&topic=travel-reservations#patch-v1-events-travel_reservations) — get the revision from [`GET /v1/events/travel_reservations/info`](https://api.exhibitday.com/Help/V1?epf=1&topic=travel-reservations#get-v1-events-travel_reservations-info). Covered: this reservation's Event association, type and booking details, complete outward and return details, Notes, current and dormant stored payment fields, complete tagged-person identities, actual cost allocations and direct related-item links. Not covered: invoice and ordinary attachments or bytes, creation and notification bookkeeping, display rank, duplicate-source identity, current type/person/cost-center labels and related-record display data. Use this reservation's Info revision. Current Event access, available types, membership and related items are checked separately. - [`PATCH /v1/events/giveaways`](https://api.exhibitday.com/Help/V1?epf=1&topic=giveaways#patch-v1-events-giveaways) — get the revision from [`GET /v1/events/giveaways/info`](https://api.exhibitday.com/Help/V1?epf=1&topic=giveaways#get-v1-events-giveaways-info). Covered: this Giveaway's Event association, Name, Source, supplier and acquisition details, all Details and Notes, entry and distribution choices, payment details, complete actual cost allocations and direct related-item links. Not covered: its invoice and ordinary attachments or bytes, creation timestamp, current cost-center names or related-record display data. Use this Giveaway's Info revision; current Event access and related-item availability are checked separately. - [`PATCH /v1/events/shipments`](https://api.exhibitday.com/Help/V1?epf=1&topic=shipments#patch-v1-events-shipments) — get the revision from [`GET /v1/events/shipments/info`](https://api.exhibitday.com/Help/V1?epf=1&topic=shipments#get-v1-events-shipments-info). Covered: Shipment name, carrier, pickup and delivery details, status, payment fields, Notes, every component and its identity, actual cost-center allocations and direct related-item links. Not covered: invoice or ordinary attachment records, captions or file contents, creation timestamps, workspace measurement settings, lookup labels or the Event's planned Shipments budget. A real name change may also refresh the invoice caption; caption edits by themselves do not change this business token. Use this Shipment's Info response for its token. - [`PATCH /v1/tasks/sections`](https://api.exhibitday.com/Help/V1?epf=2#patch-v1-tasks-sections) — get the revision from [`GET /v1/tasks/sections/info`](https://api.exhibitday.com/Help/V1?epf=2#get-v1-tasks-sections-info). Covered: the section name and the Event it belongs to. Not covered: its display order, creation timestamp, tasks, comments or files. Use this section's Info response for the revision; current access and Tasks locks are checked separately. - [`PATCH /v1/events/dates`](https://api.exhibitday.com/Help/V1?epf=1#patch-v1-events-dates) — get the revision from [`GET /v1/events/dates`](https://api.exhibitday.com/Help/V1?epf=1#get-v1-events-dates). Covered: this Event and logical Dates type, and every saved date, start time, end time, time-zone label and description in the selected group, including duplicate rows and an empty list. Not covered: physical Date-row IDs or creation times, either other Dates group, the Event main start/end dates, locks, or history. Use the token from the same Event and date_type_id; it belongs to the complete group, not to an individual Date row. ### Guides ### Get data into ExhibitDay - [Create or Update Events from Your CRM](https://api.exhibitday.com/Help/V1?guide=event-setup-crm) — Create an Event from a CRM record (for example Salesforce, HubSpot or Zoho CRM), or update the Event already linked to it. - [Set an Event's Exhibit Hall Dates and Hours](https://api.exhibitday.com/Help/V1?guide=dates-times-time-zones) — Set an Event's Exhibit Hall days, hours and time zone, then confirm them. - [Reserve Assets (Equipment and Materials) for an Event](https://api.exhibitday.com/Help/V1?guide=reserve-change-cancel-assets) — Reserve equipment or materials for an Event, change the reservation, and see what canceling would do. - [Update Collateral Stock After a Delivery or Recount](https://api.exhibitday.com/Help/V1?guide=collateral-inventory-storage) — Record a stock delivery or recount for Collateral at a Storage Location. - [Add Attendees and Their Travel Reservations to an Event](https://api.exhibitday.com/Help/V1?guide=staff-travel-tags) — Register a person for an Event and record their hotel, then list everything for that person. - [Record Show Results: Leads and Objective Ratings](https://api.exhibitday.com/Help/V1?guide=show-results-objectives) — Record a show's lead count and how well an Objective was met. - [Copy Tasks from a Previous Event](https://api.exhibitday.com/Help/V1?guide=reuse-event-plan) — Copy last year's Tasks into this year's Event instead of rebuilding the checklist. - [Record Costs and Split Them Across Cost Centers](https://api.exhibitday.com/Help/V1?guide=entering-costs) — Record a cost on a record, and optionally split it across cost centers. - [Create Tasks from Forms, Tickets or Other Apps](https://api.exhibitday.com/Help/V1?guide=create-tasks) — Turn a form, ticket or plan item from another app (for example Google Forms, Zendesk or Jira) into an Event Task. - [Fill In Your Custom Event Fields from Another System](https://api.exhibitday.com/Help/V1?guide=custom-fields) — Fill in or read your workspace's own Event fields from another system. ### Get data out - [Get a Complete List of Attendees, Travel and More](https://api.exhibitday.com/Help/V1?guide=find-filter-page) — Pull a complete filtered list, such as everyone registered or traveling for a show, page by page. - [Search Activity Audit Logs to See Who Changed What, and When](https://api.exhibitday.com/Help/V1?guide=workspace-activity) — See who changed what and when, for audits, investigations or monitoring. - [Export Event Costs to Excel or a Reporting Tool](https://api.exhibitday.com/Help/V1?guide=export-event-costs) — Save your Event costs to a CSV for Excel, Google Sheets, Power BI or another reporting tool. ### Keep systems in sync - [Link ExhibitDay Events to Your CRM or ERP Records](https://api.exhibitday.com/Help/V1?guide=match-records) — Link each record in your CRM or ERP (for example Salesforce, HubSpot or NetSuite) to the matching ExhibitDay Event, even after names change. - [Update Shipment Tracking and Status Automatically](https://api.exhibitday.com/Help/V1?guide=shipment-tracking) — Add tracking numbers and Shipped status to Event Shipments from your shipping system or carrier (for example FedEx or UPS). - [Keep Another System Updated with Event and Task Changes](https://api.exhibitday.com/Help/V1?guide=sync-changes) — Keep a copy of your Events and Tasks in another system, refreshed with only what changed. ### Do it safely - [Avoid Overwriting Someone Else's Changes](https://api.exhibitday.com/Help/V1?guide=update-records-safely) — Update a record only if nobody else changed it since you read it. - [Handle Errors and Retry Failed Requests](https://api.exhibitday.com/Help/V1?guide=errors-and-retries) — Know what to do when a request fails: fix it, wait and retry, or check whether it already worked. ### Key terms ### ExhibitDay terms **Workspace** your company's ExhibitDay account. Each API key belongs to one workspace. **Event** a show, conference or meeting you plan for. Most records belong to an Event. **Event tabs** the areas of an Event page, such as Information, Tasks, Staff, Travel and Shipments. Some API calls refer to them. **Task** A to-do item. You can link it to an Event or keep it as a general Task. **Task Section** a group that Tasks are listed under on an Event. **Asset** Equipment or materials your workspace tracks for events. **Capital Asset** an Asset tracked one item at a time, such as a monitor or a booth structure. **Collateral** Assets tracked by quantity, such as brochures or giveaways. **Storage Location** where Assets are kept when they're not at an event. **Reservation** A booking for an Asset. A reservation can be for an Event or another purpose. **Inventory adjustment** a manual change to Collateral stock, such as a delivery or a recount. **Logistical record** a preparation milestone on a reservation, such as "Packed" or "Shipped". **Cost center** a budget category that a cost can be split across. **Budget year** the year a cost counts toward, based on your workspace's fiscal-year start month. **Users and Resources** Users can sign in to ExhibitDay. Resources are entries without sign-in access. **Custom fields** fields your workspace adds to Events or Assets. **Integration fields** Five API-only text fields on Events, Tasks, Misc. Expenses / Credits and Assets, named `integration_metadata_field_1` through `integration_metadata_field_5`. Use them to store another system’s ID so you can find the record again even if its name changes. ### API terms **API key** identifies your workspace on every request. Keep it private. **ID** the value that identifies a record, usually a number and sometimes text. Save it to read or update the record later. **Record revision** a value returned with a record that represents its current saved state. **Expected revision** The record revision you send back with a supported update. The API checks that the values covered by that revision still match. **Idempotency-Key** A value you choose for a supported create request. During the replay window, retry the same request with the same key to avoid a duplicate. **Warnings** notes in the `X-API-Warnings` response header about inputs that were ignored or adjusted. The request still succeeded. **Paging** reading a long list a page at a time with `$limit` (how many) and `$offset` (how many to skip). **error_code / error_params** what went wrong with a request, and which inputs to fix. **Request ID** An identifier in the `X-Request-Id` response header. Include it when contacting support. **Ignore-empty option** `$ignore_params_with_empty_values=true` skips blank values on operations that support it. ## Events Create, read, update, copy and delete Events, with their file attachments and exports. Documentation page: https://api.exhibitday.com/Help/V1?epf=1 ### Retrieve a Single Event by ID `GET https://api.exhibitday.com/v1/events/info` Documentation: https://api.exhibitday.com/Help/V1?epf=1#get-v1-events-info Retrieves an Event by its ID, including its details, Tasks, custom fields and ROO score. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Event you want to retrieve. | | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` | | $on_error_return_empty_result | Boolean | No | Set to `true` to return HTTP 200 for a missing or invalid Event ID. The response is `{}` in object format or `[]` in array format. Authentication, rate-limit, inconsistent invoice state and unexpected server errors keep their normal HTTP status. | default: false | | $include_record_revision | Boolean | No | Set to true to include record_revision for a later Event update. | Default: false. See the revision section below. | | If-None-Match | String | No | An optional header containing the ETag from your previous identical GET. | If the successful response is unchanged, the API returns HTTP 304 without a body. Keep the same URL and options. This header compares GET responses and cannot prevent a conflicting update. | #### Reading the Event details The full Event includes its details, Tasks, Task Sections, custom-field values and Misc. Expenses / Credits. Use the Event URL to open it in ExhibitDay. The saved Booth payment details and booth_reservation_invoice_attachment are included automatically. The invoice metadata contains its ID, original filename and added time; use the separate invoice download method for the file. The invoice is null when no accessible invoice is available. Booth payment details are null when your access does not include them. Included Misc. Expenses / Credits also carry accessible invoice metadata. An invoice is a file; adding one does not record a payment. An invoice with an inconsistent saved reference returns HTTP 409. Retrieve the current Event before deciding what to do next. #### Understanding the ROO score roo_score is the weighted objective score, rounded to one decimal. It is null when the Event has not been rated or its ROI information is unavailable. Change objective ratings and importance through the Event Objectives methods. #### What $include_record_revision covers Set $include_record_revision=true to return record_revision for a later expected_revision on PATCH /v1/events. The revision covers the fields that Event PATCH can edit: Event details, tags, supported custom-field values, Booth Reservation cost and payment fields, budgets, ROI inputs and integration metadata. It does not cover Tasks, Dates and Hours groups, objective ratings or invoice files. Read-only invoice metadata and the calculated ROO score do not add those records to the revision. 1. Retrieve the Event with $include_record_revision=true. 2. Send its record_revision as expected_revision when updating the Event. Treat the value as opaque. 3. If HTTP 409 reports record_changed, read the Event again, review the current values and decide whether to submit another update. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/events/info?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/info?" + new URLSearchParams({ "id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/events/info", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/events/info?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/info?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/info?id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/info?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/events/info - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "id": 12345, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=12345", "name": "Sample Event", "start_date": "2026-12-21", "end_date": "2026-12-23", "participation_type_id": 1, "participation_type": "Committed", "format_id": 1, "format": "In-Person", "star_rating": 0, "tags": [ "International", "Field Marketing" ], "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, "booth_reservation_cost": { "amount": 125.50, "cost_center_breakdown": [ { "cost_center_id": 34567, "cost_center": "Marketing", "charge": 75.50 }, { "cost_center_id": 34568, "cost_center": "Operations", "charge": 50.00 } ] }, "cost_booth_reservation": 125.50, "booth_reservation_payment_status_id": 0, "booth_reservation_payment_status": "", "booth_reservation_payment_due_date": null, "booth_reservation_next_payment_due_date": null, "booth_reservation_payment_notes": null, "booth_reservation_invoice_attachment": { "id": 182345, "filename": "booth-reservation-invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" }, "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": 100.50, "cost_sponsorships": 0.00, "total_sum_event_costs": 226.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, "roo_score": null, "event_created_timestamp": "2026-11-21T17:00:00Z", "event_last_update_timestamp": "2026-11-21T17:00:00Z", "event_created_by": { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, "custom_fields": [ { "label": "Integration status", "value": "Ready", "notes": "", "field_name": "custom_67890", "field_type": "Text (Single-line)", "field_event_tab": "Info" }, { "label": "Setup instructions", "value": "Place the display beside the entrance.", "notes": "", "field_name": "custom_67891", "field_type": "Text (Single-line)", "field_event_tab": "Booth" } ], "task_sections": [ { "id": 13346, "name": "Planning", "display_rank": 1 }, { "id": 13347, "name": "At the Event", "display_rank": 2 } ], "tasks": [ { "id": 14346, "exhibitday_url": "https://www.exhibitday.com/Workspace/TaskView/98765?tid=14346", "event_task_section_id": 13346, "event_task_section": "Planning", "display_rank": 1, "name": "Confirm booth setup", "due_date": "2026-12-12", "assignee": { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, "is_completed": false, "task_completed_timestamp": null, "task_created_timestamp": "2026-11-21T17:01:00Z", "task_last_update_timestamp": "2026-11-21T17:01:00Z" }, { "id": 14347, "exhibitday_url": "https://www.exhibitday.com/Workspace/TaskView/98765?tid=14347", "event_task_section_id": 13347, "event_task_section": "At the Event", "display_rank": 2, "name": "Prepare the staff schedule", "due_date": "2026-12-13", "assignee": { "id": "66666666-7777-4888-8999-aaaaaaaaaaaa", "first_name": "Alex", "last_name": "Jordan", "display_name": "Alex Jordan", "email": "alex@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, "is_completed": false, "task_completed_timestamp": null, "task_created_timestamp": "2026-11-21T17:02:00Z", "task_last_update_timestamp": "2026-11-21T17:02:00Z" } ], "misc_expenses_credits": [ { "id": 15346, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=12345&riType=8&riSub=0&riId=15346", "description": "Conference meals", "is_credit": false, "cost": { "amount": 125.50, "cost_center_breakdown": [ { "cost_center_id": 34567, "cost_center": "Marketing", "charge": 75.50 }, { "cost_center_id": 34568, "cost_center": "Operations", "charge": 50.00 } ] }, "notes": "", "payment_due_date": null, "payment_status": { "id": 0, "name": "Not Specified" }, "next_payment_due_date": null, "payment_notes": null, "invoice_attachment": { "id": 685346, "filename": "expense-invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" }, "event_misc_expense_credit_created_timestamp": "2026-11-21T17:00:00Z", "event_misc_expense_credit_last_update_timestamp": "2026-11-21T17:00:00Z" }, { "id": 15347, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=12345&riType=8&riSub=0&riId=15347", "description": "Supplier refund", "is_credit": true, "cost": { "amount": -25.00, "cost_center_breakdown": [ { "cost_center_id": 34567, "cost_center": "Marketing", "charge": -15.00 }, { "cost_center_id": 34568, "cost_center": "Operations", "charge": -10.00 } ] }, "notes": "", "payment_due_date": null, "payment_status": { "id": 0, "name": "Not Specified" }, "next_payment_due_date": null, "payment_notes": null, "invoice_attachment": { "id": 685347, "filename": "expense-invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" }, "event_misc_expense_credit_created_timestamp": "2026-11-21T17:00:00Z", "event_misc_expense_credit_last_update_timestamp": "2026-11-21T17:00:00Z" } ], "integration_metadata_field_1": "", "integration_metadata_field_2": "", "integration_metadata_field_3": "", "integration_metadata_field_4": "", "integration_metadata_field_5": "" } ``` ### Retrieve Events `GET https://api.exhibitday.com/v1/events` Documentation: https://api.exhibitday.com/Help/V1?epf=1#get-v1-events Retrieves the Events in your workspace, with optional filters, paging and related details. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | filter_by_event_name_contains_text | String | No | Text to find anywhere in the Event name. | The comparison is not case-sensitive. | | filter_by_start_date_greater_than_or_equal_to | Date | No | Include Events that start on or after this date. | Use `YYYY-MM-DD`. | | filter_by_start_date_smaller_than_or_equal_to | Date | No | Include Events that start on or before this date. | Use `YYYY-MM-DD`. | | filter_by_end_date_greater_than_or_equal_to | Date | No | Include Events that end on or after this date. | Use `YYYY-MM-DD`. | | filter_by_end_date_smaller_than_or_equal_to | Date | No | Include Events that end on or before this date. | Use `YYYY-MM-DD`. | | filter_by_event_participation_type_id | Number | No | Only include Events with this participation type ID. | Use a current ID from /v1/references/event_participation_types. Omit it, or send 0, for all participation types. | | filter_by_event_format_id | Number | No | Include Events with this format. Omit or leave blank to include all formats. You can also use a format name, such as `In-Person`. Spaces, hyphens and underscores in format names are ignored. | Allowed values: `0` (all formats) \| `1` (In-Person) \| `2` (Virtual) \| `3` (Hybrid) | | filter_by_event_star_rating | Number | No | Include Events with this star rating. Omit or leave blank to include all ratings. You can also use text such as `3 stars` or `3_star`. Hyphenated forms such as `3-star` return an input error. | Allowed values: `-99` (all ratings) \| `0` (no stars) \| `1` (one star) \| `2` (two stars) \| `3` (three stars) | | filter_by_event_tag | String | No | Only include Events with this tag. | One tag name. Only the first 150 characters are used; saved Event tags have at most 30 characters. | | filter_by_custom_event_field__custom_NNNNNN | String | No | A custom text or dropdown field value to match. | Replace NNNNNN with the field `id` from `GET /v1/references/filterable_event_custom_fields`. Send at most one custom-field filter. The value allows 3,000 characters. | | filter_by_integration_metadata_field_1 | String | No | Only include Events whose integration metadata field 1 matches this value. | Use the value stored in integration_metadata_field_1, up to 3,000 characters. Surrounding spaces are ignored; a blank value means no filter. | | filter_by_integration_metadata_field_2 | String | No | Only include Events whose integration metadata field 2 matches this value. | Use the value stored in integration_metadata_field_2, up to 3,000 characters. Surrounding spaces are ignored; a blank value means no filter. | | filter_by_integration_metadata_field_3 | String | No | Only include Events whose integration metadata field 3 matches this value. | Use the value stored in integration_metadata_field_3, up to 3,000 characters. Surrounding spaces are ignored; a blank value means no filter. | | filter_by_integration_metadata_field_4 | String | No | Only include Events whose integration metadata field 4 matches this value. | Use the value stored in integration_metadata_field_4, up to 3,000 characters. Surrounding spaces are ignored; a blank value means no filter. | | filter_by_integration_metadata_field_5 | String | No | Only include Events whose integration metadata field 5 matches this value. | Use the value stored in integration_metadata_field_5, up to 3,000 characters. Surrounding spaces are ignored; a blank value means no filter. | | hydrate_tasks | Boolean | No | Set to true to include each Event's Tasks. | Default: false. Ignored for Event Lite results. | | hydrate_task_sections_list | Boolean | No | Set to true to include each Event's Task Sections. | Default: false. Ignored for Event Lite results. | | hydrate_event_misc_expenses_and_credits | Boolean | No | Set to true to include each Event's Misc. Expenses / Credits. | Default: false. Ignored for Event Lite results. | | hydrate_roo_score | Boolean | No | Set to true to include the ROO score for each full Event. | Default: false, with roo_score=null. Ignored for Event Lite results. | | hydrate_custom_fields | Boolean | No | Set to true to include each Event's custom-field values. | Default: false. Ignored for Event Lite results. | | event_id | Number | No | Only include the Event with this ID. | The response stays a list containing one Event or none. Use /v1/events/info for a single object. 0 or blank means no Event filter. | | filter_by_event_start_date_category | String | No | Choose `all` for every Event, `upcoming` for Events that end today or later (including Events in progress), or `past` for Events that ended before today. A year selects Events that start in that calendar year. Today is based on your workspace's time zone. When you use this filter, the four date filters are ignored. Category values are case-insensitive and ignore surrounding spaces. See `GET /v1/references/event_start_date_categories` for your workspace's categories. | Allowed values: `all` \| `upcoming` \| `past` \| a year such as `2026` | | filter_by_custom_field_value_setting_id | Number | No | The ID of the custom text or dropdown field to filter. | Use /v1/references/filterable_event_custom_fields. Send its value with filter_by_custom_field_value_setting_value. | | filter_by_custom_field_value_setting_value | String | No | The value to match in the selected custom field. | Up to 3,000 characters. Comparisons ignore letter case and surrounding spaces. Used only together with a supported filter_by_custom_field_value_setting_id. | | $result_sort | String | No | How to sort the Events. Omit, or use an unrecognized value, to keep the default Event start date order, earliest first. | Allowed values: `create_timestamp_asc` (oldest created first) \| `create_timestamp_desc` (newest created first) \| `last_update_timestamp_asc` (least recently updated first) \| `last_update_timestamp_desc` (most recently updated first) | | $return_event_lites | Boolean | No | Set to true to return a shorter Event object. | Default: false. Lite results contain key Event details and integration metadata; hydration options do not apply. | | filter_by_last_update_timestamp_greater_than_or_equal_to | String | No | Only include Events added or updated at or after this date and time. | Use an ISO date/time; a date alone means midnight. A returned UTC timestamp ending in Z can be reused unchanged. Without an offset, the value is read as US Eastern time. | | $limit | Number | No | The maximum number of Events to return. Omit to return all remaining matches. | A whole number of 1 or more. | | $offset | Number | No | How many matching Events to skip. To get the next page, add the number of Events you received to the current offset. | A whole number of 0 or more. Default `0`. | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | | $on_error_return_empty_result | Boolean | No | Set to true to return an empty list for ID, filter or paging validation errors. | Default: false. With true, those errors return HTTP 200 in the chosen format. Authentication, rate limits, inconsistent invoice state and unexpected errors keep their normal status. | | If-None-Match | String | No | An optional header containing the ETag from your previous identical GET. | If the successful response is unchanged, the API returns HTTP 304 without a body. Keep the same URL and options. This header compares GET responses and cannot prevent a conflicting update. | #### Choosing the Events to retrieve An Event must match every filter you send. The date category takes precedence over the four explicit start/end date filters. Upcoming includes Events ending today or later; Past includes Events ending before today. Today uses your workspace's time zone. A year selects Events that start in that year. #### Filtering by a custom field 1. Retrieve the available text and dropdown fields from /v1/references/filterable_event_custom_fields. 2. Send either filter_by_custom_event_field__ followed by its actual custom_ID field name, or the field ID and value pair. Choose one custom field per request. 3. Match the saved text or dropdown choice. The ID must belong to a supported field in your workspace. #### Choosing the response details Full Event results include the saved accessible Booth payment and invoice metadata automatically. Additional Tasks, Task Sections, custom values, Misc. Expenses / Credits and ROO scores are included only when their hydrate option is true. Request only what you need; these collections make the response larger. Event Lite results are shorter and ignore the hydration options. They do not contain the full Event's Booth payment/invoice fields or roo_score. A requested ROO score is rounded to one decimal. Null means Not Rated Yet or unavailable ROI access. An inconsistent saved invoice reference, or a score that changes while the page is read, can return HTTP 409; retrieve the current page before deciding what to do next. #### Reading every page records_found counts the returned page; total_records and X-Total-Count count all matching Events. has_more tells you whether more matches remain. For the next page, increase $offset by the number of returned Events. #### Keeping an integration in sync 1. Choose a page size and retrieve Events with the last-update filter. 2. Process and save every page before advancing your saved timestamp. 3. Save the latest event_last_update_timestamp and reuse it for the next run. The boundary is inclusive, so upsert every result by id, including repeated boundary records. Deleted Events are not returned. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/events" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/events", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/events"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/events - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "event", "list_data": [ { "id": 12345, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=12345", "name": "Sample Event", "start_date": "2026-12-21", "end_date": "2026-12-23", "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, "booth_reservation_cost": { "amount": 125.50, "cost_center_breakdown": [ { "cost_center_id": 34567, "cost_center": "Marketing", "charge": 75.50 }, { "cost_center_id": 34568, "cost_center": "Operations", "charge": 50.00 } ] }, "cost_booth_reservation": 125.50, "booth_reservation_payment_status_id": 0, "booth_reservation_payment_status": "", "booth_reservation_payment_due_date": null, "booth_reservation_next_payment_due_date": null, "booth_reservation_payment_notes": null, "booth_reservation_invoice_attachment": { "id": 182345, "filename": "booth-reservation-invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" }, "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": 125.50, "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, "roo_score": null, "event_created_timestamp": "2026-11-21T17:00:00Z", "event_last_update_timestamp": "2026-11-21T17:00:00Z", "event_created_by": { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, "custom_fields": null, "task_sections": null, "tasks": null, "misc_expenses_credits": null, "integration_metadata_field_1": "", "integration_metadata_field_2": "", "integration_metadata_field_3": "", "integration_metadata_field_4": "", "integration_metadata_field_5": "" } ] } ``` ### Add an Event `POST https://api.exhibitday.com/v1/events` Documentation: https://api.exhibitday.com/Help/V1?epf=1#post-v1-events Creates an Event with a name, date range and optional format, participation type, tags and integration details. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | name | String | Yes | The name of the new Event. | Required and nonblank; up to 500 characters. | | start_date | Date | Yes | The Event's start date. | YYYY-MM-DD. | | end_date | Date | Yes | The Event's end date. | YYYY-MM-DD. | | format_id | Number | No | The Event format. Omit, leave blank or send JSON `null` to use In-Person. Named formats are also accepted; spaces, hyphens and underscores in a name are ignored. | Allowed values: `1` (In-Person) \| `2` (Virtual) \| `3` (Hybrid) | | participation_type_id | Number | No | The Event's participation type ID. | Default: 1 (Committed). Use a current ID from /v1/references/event_participation_types. | | star_rating | Number | No | The Event's star rating. Omit, leave blank or send JSON `null` to create it with no stars. Forms such as `3 stars`, `3-star` or `3_star` are also accepted. | Allowed values: `0` (no stars) \| `1` (one star) \| `2` (two stars) \| `3` (three stars) | | tags | String | No | The new Event's tags, as a comma-separated list or a JSON array of names. | Saved in the supplied order. Each tag is shortened to 30 characters, and duplicates and blank entries are removed. A tag can't contain a comma. A comma inside one entry of a JSON array splits it into separate tags, with a warning. Omit it, or send it blank or `null`, to create the Event without tags. A value with no tag names is ignored with a warning. `event_tags` is an older name for this parameter and is still accepted; send one of them. If both are sent with different tags, both are ignored with a warning and the Event is created without tags. | | booth_reservation_status_id | Number | No | The Booth tab reservation status. | The booth reservation status: 1 (Need to Reserve), 2 (No Reservation Required), 3 (Reserved). Omit it for 1 (Need to Reserve). No Reservation Required clears the reserve-by date, and any status other than Reserved clears the date reserved. | | booth_reserve_by_date | Date | No | The Booth tab reserve-by date. | The date the booth must be reserved by, in YYYY-MM-DD format. It applies only when booth_reservation_status_id is 1 or 3; otherwise it is ignored with a warning. | | booth_date_reserved | Date | No | The Booth tab date reserved. | The date the booth was reserved, in YYYY-MM-DD format. It applies only when booth_reservation_status_id is 3 (Reserved); otherwise it is ignored with a warning. | | integration_metadata_field_1 | String | No | Your integration's own text about this Event. | Up to 3,000 characters. This field is available through the API and can be used as a list filter. | | integration_metadata_field_2 | String | No | Your integration's own text about this Event. | Up to 3,000 characters. This field is available through the API and can be used as a list filter. | | integration_metadata_field_3 | String | No | Your integration's own text about this Event. | Up to 3,000 characters. This field is available through the API and can be used as a list filter. | | integration_metadata_field_4 | String | No | Your integration's own text about this Event. | Up to 3,000 characters. This field is available through the API and can be used as a list filter. | | integration_metadata_field_5 | String | No | Your integration's own text about this Event. | Up to 3,000 characters. This field is available through the API and can be used as a list filter. | | Idempotency-Key | String | No | An optional header identifying this create request. | Reuse the same key only with the same request. See the Getting Started idempotency guidance. | | $request_principal_name | String | No | An optional name to attribute as the Event creator. | Up to 122 characters; omit for ExhibitDay API. This is an API attribution label, not a user ID or permission grant. | #### Creating the Event Send both calendar dates. If the start date is later than the end date, they are swapped before saving. Choose a current participation type, including a custom type when your workspace provides one. #### Receiving the new Event The response contains the new Event and its ID. This request creates no invoice, so its invoice attachment metadata is null. Use Event PATCH for venue details, notes, budgets and other editable fields; use the relevant methods for files and other Event records. #### Repeating a create request Use the optional Idempotency-Key header if you need to repeat the same create request safely. Keep the key and request unchanged. If a save outcome could not be confirmed, retrieve the current state before deciding whether another create is needed. Example — curl: ```bash curl -X POST "https://api.exhibitday.com/v1/events" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"name\":\"Sample Event\",\"start_date\":\"2026-12-21\",\"end_date\":\"2026-12-23\"}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events", { method: "POST", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "name": "Sample Event", "start_date": "2026-12-21", "end_date": "2026-12-23" }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.post( "https://api.exhibitday.com/v1/events", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"name": "Sample Event", "start_date": "2026-12-21", "end_date": "2026-12-23"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PostAsync("https://api.exhibitday.com/v1/events", JsonContent.Create(new { name = "Sample Event", start_date = "2026-12-21", end_date = "2026-12-23" })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("POST", HttpRequest.BodyPublishers.ofString("{\"name\":\"Sample Event\",\"start_date\":\"2026-12-21\",\"end_date\":\"2026-12-23\"}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"name":"Sample Event","start_date":"2026-12-21","end_date":"2026-12-23"}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"name":"Sample Event","start_date":"2026-12-21","end_date":"2026-12-23"}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/events", strings.NewReader("{\"name\":\"Sample Event\",\"start_date\":\"2026-12-21\",\"end_date\":\"2026-12-23\"}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): POST /v1/events - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "id": 23456, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=23456", "name": "Sample Event", "start_date": "2026-12-21", "end_date": "2026-12-23", "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, "booth_reservation_cost": { "amount": 0.00, "cost_center_breakdown": [] }, "cost_booth_reservation": 0.00, "booth_reservation_payment_status_id": 0, "booth_reservation_payment_status": "", "booth_reservation_payment_due_date": null, "booth_reservation_next_payment_due_date": null, "booth_reservation_payment_notes": null, "booth_reservation_invoice_attachment": null, "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, "roo_score": null, "event_created_timestamp": "2026-11-21T17:00:00Z", "event_last_update_timestamp": "2026-11-21T17:00:00Z", "event_created_by": { "id": null, "first_name": "ExhibitDay", "last_name": "API", "display_name": "ExhibitDay API", "email": null, "type": null, "workspace_role": null, "is_active": true }, "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": "" } ``` ### Update an Event `PATCH https://api.exhibitday.com/v1/events` Documentation: https://api.exhibitday.com/Help/V1?epf=1#patch-v1-events Updates an Event's details, notes, tags, budgets, Booth payment information and supported custom fields. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Event you want to update. | | | name | String | No | The new Event name. | Up to 500 characters. It can't be cleared. | | start_date | Date | No | The Event's new start date. | YYYY-MM-DD. An omitted date keeps its saved value. | | end_date | Date | No | The Event's new end date. | YYYY-MM-DD. An omitted date keeps its saved value. | | participation_type_id | Number | No | The new participation type ID. | Use a current ID from /v1/references/event_participation_types. | | format_id | Number | No | The new Event format. Omit or leave blank to keep it. JSON `null` is refused because an Event must have a format. Named formats are also accepted; spaces, hyphens and underscores in a name are ignored. | Allowed values: `1` (In-Person) \| `2` (Virtual) \| `3` (Hybrid) | | star_rating | Number | No | The new star rating. Omit or leave blank to keep it; `null` removes all stars. Forms such as `3 stars`, `3-star` or `3_star` are also accepted. | Allowed values: `0` (no stars) \| `1` (one star) \| `2` (two stars) \| `3` (three stars) | | tags | String | No | The complete list of Event tags, as a comma-separated list or a JSON array of names. | This replaces the saved list in the supplied order. Each tag is shortened to 30 characters, and duplicates and blank entries are removed. A tag can't contain a comma. A comma inside one entry of a JSON array splits it into separate tags, with a warning. Use `null` to clear the list. `event_tags` is an older name for this parameter and is still accepted; send one of them. If you send both, they must have the same value. | | website_url | String | No | The Event website URL. | Use http:// or https://; http:// is added if omitted. The stored URL allows 2,000 characters. See the website rules below. | | venue_name | String | No | The venue name. | Up to 300 characters. | | venue_address | String | No | The venue address. | Up to 1,000 characters; line breaks are allowed. A changed address refreshes its derived location details when lookup succeeds. Clearing it also clears those details. | | booth_size | String | No | Your booth dimensions or size. | Up to 150 characters, for example 10x20. | | booth_number | String | No | Your booth number. | Up to 150 characters. | | event_notes | String | No | The notes shown on the Event's Information tab. | Send plain text. Both saved and editor-formatted text must fit 30,000 characters. See notes and custom-text limits below. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | booth_notes | String | No | The notes shown on the Event's Booth tab. | Send plain text. Both saved and editor-formatted text must fit 30,000 characters. See notes and custom-text limits below. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | budget_notes | String | No | The notes shown on the Event's Budget tab. | Send plain text. Both saved and editor-formatted text must fit 30,000 characters. See notes and custom-text limits below. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | roi_notes | String | No | The notes shown on the Event's ROI tab. | Send plain text. Both saved and editor-formatted text must fit 30,000 characters. See notes and custom-text limits below. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | booth_reservation_cost | Number or cost object | No | The Booth Reservation cost, as a number or cost object. [Record Costs and Split Them Across Cost Centers](/Help/V1?guide=entering-costs). | Omit to keep it. A replacement requires access to the Booth financial details, and the Booth tab must not be locked. | | booth_reservation_payment_status_id | Number | No | The Booth Reservation payment status. Omit or leave blank to keep it; null resets it to N/A. [Record Costs and Split Them Across Cost Centers](/Help/V1?guide=entering-costs). | Allowed values: `0` (N/A) \| `1` (Paid in Full) \| `2` (Partially Paid) \| `3` (Not Paid Yet) | | booth_reservation_payment_due_date | Date | No | The Booth Reservation payment due date. [Record Costs and Split Them Across Cost Centers](/Help/V1?guide=entering-costs). | YYYY-MM-DD. Omit it to keep the saved date. `null` clears it. | | booth_reservation_next_payment_due_date | Date | No | The next partial payment date for the Booth Reservation. [Record Costs and Split Them Across Cost Centers](/Help/V1?guide=entering-costs). | YYYY-MM-DD. Applies only to Partially Paid. See payment rules below. | | booth_reservation_payment_notes | String | No | Notes about the Booth Reservation payment. [Record Costs and Split Them Across Cost Centers](/Help/V1?guide=entering-costs). | Up to 200 characters, excluding surrounding spaces. Omit to keep them; null clears them. | | booth_reservation_status_id | Number | No | The Booth tab reservation status. | The booth reservation status: 1 (Need to Reserve), 2 (No Reservation Required), 3 (Reserved). Omit it or leave it blank to keep the saved value. It can't be cleared. No Reservation Required clears the reserve-by date, and any status other than Reserved clears the date reserved. | | booth_reserve_by_date | Date | No | The Booth tab reserve-by date. | The date the booth must be reserved by, in YYYY-MM-DD format. It applies only when booth_reservation_status_id is 1 or 3; otherwise it is ignored with a warning. Omit it or leave it blank to keep the saved value. null clears it. | | booth_date_reserved | Date | No | The Booth tab date reserved. | The date the booth was reserved, in YYYY-MM-DD format. It applies only when booth_reservation_status_id is 3 (Reserved); otherwise it is ignored with a warning. Omit it or leave it blank to keep the saved value. null clears it. | | budget_booth_reservation | Number | No | The Booth Reservation budget for this Event. | A number greater than or equal to 0.00. | | budget_booth_services | Number | No | The Booth Services budget for this Event. | A number greater than or equal to 0.00. | | budget_attendee_registrations | Number | No | The Attendee / Registration budget for this Event. | A number greater than or equal to 0.00. | | budget_travel | Number | No | The Travel budget for this Event. | A number greater than or equal to 0.00. | | budget_giveaways | Number | No | The Giveaways budget for this Event. | A number greater than or equal to 0.00. | | budget_shipments | Number | No | The Shipments budget for this Event. | A number greater than or equal to 0.00. | | budget_event_activities | Number | No | The Playbook Activities budget for this Event. | A number greater than or equal to 0.00. | | budget_misc_expenses | Number | No | The Misc. Expenses budget for this Event. | A number greater than or equal to 0.00. | | budget_sponsorships | Number | No | The Sponsorships budget for this Event. | A number greater than or equal to 0.00. | | roi_num_leads | Number | No | The number of leads generated attributable to this Event. | A whole number greater than or equal to 0. | | roi_num_impressions_booth | Number | No | The number of Booth impressions or walk-bys attributable to this Event. | A whole number greater than or equal to 0. | | roi_num_impressions_sponsorships | Number | No | The number of Sponsorship impressions attributable to this Event. | A whole number greater than or equal to 0. | | roi_num_impressions_media | Number | No | The number of social or traditional media impressions attributable to this Event. | A whole number greater than or equal to 0. | | roi_num_meetings_existing_customers | Number | No | The number of meetings with existing customers attributable to this Event. | A whole number greater than or equal to 0. | | roi_num_meetings_new_customers | Number | No | The number of meetings with new or potential customers attributable to this Event. | A whole number greater than or equal to 0. | | roi_amount_actual_sales | Number | No | The sales amount already closed and attributable to this Event. | A number from 0.00 through 999999999999999.99. | | roi_amount_potential_sales | Number | No | The additional potential sales amount attributable to this Event. | A number from 0.00 through 999999999999999.99. | | integration_metadata_field_1 | String | No | Your integration's own text about this Event. | Up to 3,000 characters. This field is available through the API and can be used as a list filter. | | integration_metadata_field_2 | String | No | Your integration's own text about this Event. | Up to 3,000 characters. This field is available through the API and can be used as a list filter. | | integration_metadata_field_3 | String | No | Your integration's own text about this Event. | Up to 3,000 characters. This field is available through the API and can be used as a list filter. | | integration_metadata_field_4 | String | No | Your integration's own text about this Event. | Up to 3,000 characters. This field is available through the API and can be used as a list filter. | | integration_metadata_field_5 | String | No | Your integration's own text about this Event. | Up to 3,000 characters. This field is available through the API and can be used as a list filter. | | expected_revision | String | No | The record_revision from your last read. Send it to avoid overwriting a later change. | Omit to skip this check. Blank, null, malformed or conflicting copies return HTTP 400; a stale value returns HTTP 409 with error_code=record_changed. | | custom_NNNNNN | Text | No | A value for a visible Event custom field. | Text, dropdown or URL fields only. Use the `field_name` returned by `GET /v1/references/event_custom_fields`. A supplied hidden field is refused even if the value is blank or null. | | $ignore_params_with_empty_values | Boolean | No | Set to true to leave real JSON null and empty values unchanged. | Default: false. The text null still requests clearing; invalid expected_revision is never ignored. | Declared schema for `booth_reservation_cost` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "anyOf": [ { "type": "number", "minimum": 0, "description": "Shorthand for an object with amount. The amount is rounded to cents before the supported storage range is checked.", "nullable": true }, { "type": "object", "additionalProperties": false, "properties": { "amount": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 }, "cost_center_breakdown": { "type": "array", "items": { "type": "object", "additionalProperties": false, "properties": { "cost_center_id": { "type": "integer", "format": "int64", "nullable": true }, "charge": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 }, "cost_center": { "type": "string", "description": "Optional and read-only: the cost center name a read returns, so a cost can be sent back unchanged. It is ignored; the line is saved by cost_center_id, and a name that doesn't match that cost center is explained in a warning.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "required": [ "charge" ] }, "maxItems": 2147483647 } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "anyOf": [ { "required": [ "amount" ] }, { "required": [ "cost_center_breakdown" ] } ], "nullable": true } ], "x-numeric-shorthand": "A number is equivalent to {amount:number}.", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": { "amount": 125.50 } } ``` #### Choosing what to change Send only the fields you want to change. Omitted fields keep their saved values. Blank values keep them and may add a warning. For a clearable field, JSON null or the text null requests clearing. Name, dates, participation type and format cannot be cleared. With $ignore_params_with_empty_values=true, real JSON null and blank values are omitted; the text null still requests clearing. A blank, null or malformed expected_revision is always refused. Start and end dates are compared after applying your supplied values. If the resulting start date is later, the two dates are swapped. An update that changes nothing returns a success message ending with `Event properties that were changed: None`. #### Changing Booth cost and payment details booth_reservation_cost accepts a number or an object containing amount and/or cost_center_breakdown. A number or amount alone assigns the total to Not Specified. A supplied cost replaces the complete Booth Reservation allocations. When amount and a breakdown are both supplied, their totals must agree after per-charge cent rounding. Zero, null or an empty breakdown clears the cost. Payment status, due date and notes are separate from the cost and invoice. The next partial payment date applies only when the resulting status is Partially Paid. Supplying that date with another status clears it; supplying a non-Partial status also clears it. Omitting both keeps an older saved next date. #### Updating notes and custom fields Notes and multiline custom text take plain text. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. Both the stored value and the notes editor's formatted value must fit 30,000 characters; encoding and formatting count toward those limits. An older over-limit value can be kept or shortened, but not enlarged. Use a current `field_name` returned by `GET /v1/references/event_custom_fields`, such as `custom_12345`. This method supports visible custom text, dropdown and URL fields on Information, Booth and Special. File fields use the Custom File Attachment methods. Visible custom fields follow the same keep and clear rules as other editable fields. Supplying a hidden field, even with a blank value or null, returns HTTP 400 with error_code=invalid_request and the field name in error_params. Nothing is saved. Single-line custom text allows 2,999 cleaned characters, with line breaks replaced by spaces. Multiline text uses the notes limits. A dropdown value must match a current choice. Custom URL values must be valid http:// or https:// URLs; http:// is added when needed. #### Website URLs An explicit http:// or https:// URL longer than 2,000 characters is truncated to the stored limit. A URL without a scheme is rejected if adding http:// would exceed that limit. The result must be a valid HTTP or HTTPS URL. #### Avoiding conflicting updates The Event revision covers all fields this method can edit, including supported custom values, Booth cost and payment fields. It does not cover invoice files, objective ratings or the separate Dates and Hours lists. A successful conditional update returns the new record_revision. 1. Use `GET /v1/events/info` with the Event `id` and `$include_record_revision=true`. 2. Send its record_revision as expected_revision with this update. 3. On HTTP 409 with error_code=record_changed, retrieve the current Event, review it and decide whether to send another update. #### Updating the venue address The address itself can be saved even when its location lookup is unavailable. In that case, the previous derived map and locality details remain. Clearing venue_address clears those derived details. Example — curl: ```bash curl -X PATCH "https://api.exhibitday.com/v1/events" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"id\":12345,\"name\":\"Updated event name\"}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events", { method: "PATCH", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "id": 12345, "name": "Updated event name" }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.patch( "https://api.exhibitday.com/v1/events", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"id": 12345, "name": "Updated event name"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PatchAsync("https://api.exhibitday.com/v1/events", JsonContent.Create(new { id = 12345, name = "Updated event name" })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("PATCH", HttpRequest.BodyPublishers.ofString("{\"id\":12345,\"name\":\"Updated event name\"}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"id":12345,"name":"Updated event name"}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"id":12345,"name":"Updated event name"}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/events", strings.NewReader("{\"id\":12345,\"name\":\"Updated event name\"}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): PATCH /v1/events - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Event Update Successful. Event properties that were changed: name", "errors": [] } ``` ### Delete an Event `DELETE https://api.exhibitday.com/v1/events` Documentation: https://api.exhibitday.com/Help/V1?epf=1#delete-v1-events Deletes an Event and handles its Asset reservations using the automatic cancellation rules. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Event you want to delete. | | #### Before deleting Deleting is refused when Event Settings locks the ability to delete the Event. This action removes the Event and its dependent records. Retrieve or export anything you need to keep before deleting. #### What happens to Asset reservations - Future reservations are undone. - Capital reservations that have already started are kept as inventory history, detached from the deleted Event. - Started Collateral reservations retain their recorded use. A scheduled return is kept; historical movements that cannot be treated as a checkout are preserved. - Necessary reservation file preservation must succeed before deletion. A busy or changed inventory state, or failed required file preservation, refuses the deletion. #### After deletion Confirmed deletion is recorded in history. Event files are scheduled for removal, with immediate cleanup attempted after the change is saved. Storage Location followers may receive reservation-cancellation emails when that feature is enabled; this method has no notification switch. If the outcome could not be confirmed, check the current Event before deciding what to do next. Do not assume a failure means it is safe to repeat the request. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/events?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events?" + new URLSearchParams({ "id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/events", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/events?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events?id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/events?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/events - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Event Deleted", "errors": [] } ``` ### Retrieve Event Dates and Hours `GET https://api.exhibitday.com/v1/events/dates` Documentation: https://api.exhibitday.com/Help/V1?epf=1#get-v1-events-dates Retrieves an Event's Exhibit Hall, Booth Setup and Booth Dismantle dates and hours. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | event_id | Number | Yes | The ID of the Event whose dates you want to retrieve. | | | filter_by_date_type_id | Number | No | The Dates and Hours group to retrieve. Omit or leave blank to return every group, including empty groups. | Allowed values: `1` (Exhibit Hall) \| `2` (Booth Setup) \| `3` (Booth Dismantle) | | $limit | Number | No | The most Dates and Hours groups to return. | A positive whole number. Omit for all remaining groups; this does not limit dates within a group. | | $offset | Number | No | How many matching groups to skip. | A nonnegative whole number; 0 by default. | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | | $include_record_revision | Boolean | No | Set to true to include a record_revision on each returned group. | Default: false. Use the selected group's revision for a later update. | | If-None-Match | String | No | An optional header containing the ETag from your previous identical GET. | If the successful response is unchanged, the API returns HTTP 304 without a body. Keep the same URL and options. This header compares GET responses and cannot prevent a conflicting update. | #### Reading dates and hours The groups appear in type order. Dates within each group are returned in date, start-time and end-time order. Paging counts whole groups, never individual dates. Older saved descriptions are returned in full. Times are local wall-clock values with the saved time-zone label. ExhibitDay does not convert them to UTC or apply daylight-saving rules. #### What $include_record_revision covers Set $include_record_revision=true to return each group's record_revision for a later expected_revision on PATCH /v1/events/dates. Each record_revision belongs to the selected Event and date_type_id, including an empty group. There is no revision on the wrapper. record_revision covers that group's dates and hours. It does not cover the main Event date range or either other group. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/events/dates?event_id=45678" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/dates?" + new URLSearchParams({ "event_id": "45678" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/events/dates", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"event_id": 45678}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/events/dates?event_id=45678"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/dates?event_id=45678")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/dates?event_id=45678') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/dates?event_id=45678", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/events/dates - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "records_found": 3, "total_records": 3, "has_more": false, "list_data": [ { "event_id": 45678, "date_type_id": 1, "date_type": "Exhibit Hall", "dates": [ { "date": "2030-01-15", "start_time": "09:00:00", "end_time": "17:00:00", "timezone": "EST", "description": "Exhibit hours" }, { "date": "2030-01-16", "start_time": "09:00:00", "end_time": "16:00:00", "timezone": "EST", "description": "Final scheduled day" } ] }, { "event_id": 45678, "date_type_id": 2, "date_type": "Booth Setup", "dates": [ { "date": "2030-01-14", "start_time": "09:00:00", "end_time": "17:00:00", "timezone": "EST", "description": "Booth setup" }, { "date": "2030-01-15", "start_time": "09:00:00", "end_time": "16:00:00", "timezone": "EST", "description": "Final scheduled day" } ] }, { "event_id": 45678, "date_type_id": 3, "date_type": "Booth Dismantle", "dates": [ { "date": "2030-01-16", "start_time": "17:00:00", "end_time": "20:00:00", "timezone": "EST", "description": "Booth dismantle" }, { "date": "2030-01-17", "start_time": "09:00:00", "end_time": "12:00:00", "timezone": "EST", "description": "Final scheduled day" } ] } ] } ``` ### Copy an Event `POST https://api.exhibitday.com/v1/events/copy` Documentation: https://api.exhibitday.com/Help/V1?epf=1#post-v1-events-copy Create a new Event in your workspace by copying an existing Event. By default, Information and Tasks are copied; the source stays in place. Choose other areas and costs using the copy options below. Your current plan and access to each area still apply. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | event_id | Number | Yes | The ID of the existing Event to copy in your workspace. Get a current ID from GET /v1/events. | | | name | String | No | The new Event's name. Omit it to use Copy of followed by the source Event's name, shortened to fit if necessary. An explicitly blank or null name is refused unless $ignore_params_with_empty_values is enabled. | Max length: 500. | | start_date | String | No | The new start date in yyyy-MM-dd format. Supply both dates or omit both to keep the source Event's dates. | | | end_date | String | No | The new end date in yyyy-MM-dd format, on or after start_date. Supply both dates or omit both. | | | participation_type_id | Number | No | An available Event participation status ID. Omit it to keep the source status if it is still available, or use Considering when it is no longer available. | | | copy_info | Boolean | No | Copy the Information fields and their saved documents and custom fields. Omitted, blank or null uses the documented default. | Default: true. | | copy_tasks | Boolean | No | Copy Tasks, their named sections and saved attachments. Omitted, blank or null uses the documented default. | Default: true. | | copy_booth | Boolean | No | Copy Booth details, Booth Services and their saved file attachments. Omitted, blank or null uses the documented default. | Default: false. | | copy_staff | Boolean | No | Copy Attendee / Registration records and their saved file attachments. Omitted, blank or null uses the documented default. | Default: false. | | copy_travel | Boolean | No | Copy Travel Reservations and their saved file attachments. Omitted, blank or null uses the documented default. | Default: false. | | copy_shipments | Boolean | No | Copy Shipments, supplier items and their saved file attachments. Omitted, blank or null uses the documented default. | Default: false. | | copy_giveaways | Boolean | No | Copy Giveaways and their saved file attachments. Omitted, blank or null uses the documented default. | Default: false. | | copy_sponsorships | Boolean | No | Copy Sponsorships and their saved file attachments. Omitted, blank or null uses the documented default. | Default: false. | | copy_playbook | Boolean | No | Copy Playbook Activities and their saved file attachments. Omitted, blank or null uses the documented default. | Default: false. | | copy_misc_expenses_credits | Boolean | No | Copy Misc. Expenses / Credits and their saved file attachments. Omitted, blank or null uses the documented default. | Default: false. | | copy_budget | Boolean | No | Copy the Event's budget amounts and budget notes. Omitted, blank or null uses the documented default. | Default: false. | | copy_special_tab | Boolean | No | Copy the Special tab's custom fields. Omitted, blank or null uses the documented default. | Default: false. | | copy_objectives | Boolean | No | Copy the Event Objectives and their priorities. Omitted, blank or null uses the documented default. | Default: false. | | copy_booth_costs | Boolean | No | Also copy Booth Reservation and Booth Service costs, payment information and invoice attachments when copy_booth is true. Omitted, blank or null uses the documented default. | Default: false. | | copy_staff_costs | Boolean | No | Also copy Attendee / Registration costs, payment information and invoice attachments when copy_staff is true. Omitted, blank or null uses the documented default. | Default: false. | | copy_travel_costs | Boolean | No | Also copy Travel costs, payment information and invoice attachments when copy_travel is true. Omitted, blank or null uses the documented default. | Default: false. | | copy_shipments_costs | Boolean | No | Also copy Shipment costs, payment information and invoice attachments when copy_shipments is true. Omitted, blank or null uses the documented default. | Default: false. | | copy_giveaways_costs | Boolean | No | Also copy Giveaway costs, payment information and invoice attachments when copy_giveaways is true. Omitted, blank or null uses the documented default. | Default: false. | | copy_sponsorships_costs | Boolean | No | Also copy Sponsorship costs, payment information and invoice attachments when copy_sponsorships is true. Omitted, blank or null uses the documented default. | Default: false. | | copy_misc_expenses_credits_costs | Boolean | No | Also copy Misc. Expense / Credit amounts, payment information and invoice attachments when copy_misc_expenses_credits is true. Omitted, blank or null uses the documented default. | Default: false. | | copy_playbook_costs | Boolean | No | Also copy Playbook Activity Costs and their invoice attachments when copy_playbook is true. Omitted, blank or null uses the documented default. | Default: false. | | copy_info_dates | Boolean | No | Keep saved Information dates when copy_info is true. Omitted, blank or null uses the documented default. | Default: false. | | keep_task_assignees | Boolean | No | Keep the source Tasks' stored assignee and tagged-people associations when copy_tasks is true. The default creates unassigned Tasks without tagged people. Omitted, blank or null uses the documented default. | Default: false. | | copy_objective_scores | Boolean | No | Keep Objective achievement scores and return-on-objectives notes when copy_objectives is true. Omitted, blank or null uses the documented default. | Default: false. | | notify | Boolean | No | Allow the usual copied-Event notifications for eligible copied people. Send false to suppress that copied batch; due-date reminders remain a separate behavior. Omitted, blank or null uses the documented default. | Default: true. | | task_due_date_mode | String | No | How copied Tasks get due dates when copy_tasks is true. none leaves them empty; same_date keeps the stored dates; same_offset keeps each Task's calendar-day offset from the Event start date, applied to the new start date. Default: none. | Allowed values: `none` \| `same_date` \| `same_offset` | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` \| `object` | **Choosing What to Copy**: Only readable selected areas are copied. Saved file attachments follow their selected records; the Event's general File Attachments and Invoice Attachments collections are not copied. Related links are copied only when both records are copied. Each copied Task starts as Not Started, without comments, completion or workflow actions. Due dates and assignees are omitted unless selected. The result includes source-to-new Task ID mappings, each with exhibitday_url for the created Task, and a files entry for each selected saved file. Each entry's status is queued (id is the new file's ID) or skipped (id is null and reason says why); files_queued and files_skipped count them. Event and Task links use the same pages as their GET responses; sign in with an account that can view them. Access is checked again when the link is opened. Saved files are queued for background copying in the same transaction as their new records. The committed result reports queued or skipped files; queued does not mean the bytes are ready. A download can return 409 file_copy_pending while copying finishes. A skipped invoice does not remove its copied cost or business record. The copy takes the source Event as it is when the copy is saved. Anything deleted from it while the copy runs (for example a Task, a Shipment or a file) is left out, and each one is named in the response warnings, for example "Task 12345 was deleted while the Event was being copied, so it was not copied." If the source Event stays busy with another save for more than a few seconds, or a saved file reference conflicts, the request returns HTTP 409 (error_code record_changed) and nothing is created. A file is skipped, with no new file record, when its saved file name can't be copied in the background, or when it comes from an earlier copy that did not complete, matches more than one earlier copy, or can't be identified safely; its reason explains which. Source records and files are never changed. Optional Idempotency-Key replay applies to this POST. A retry with the same key and identical request replays the original committed result and its original queueing counts, even after background copies finish. If the outcome cannot be confirmed, retrieve current Events before deciding whether to retry. Repeated scalar copies must agree. Use JSON, query or form for text containing commas; text headers must contain one value without commas. This action accepts no uploaded files and does not support expected_revision. Example — curl: ```bash curl -X POST "https://api.exhibitday.com/v1/events/copy" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"event_id\":12345}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/copy", { method: "POST", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "event_id": 12345 }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.post( "https://api.exhibitday.com/v1/events/copy", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"event_id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PostAsync("https://api.exhibitday.com/v1/events/copy", JsonContent.Create(new { event_id = 12345 })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/copy")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("POST", HttpRequest.BodyPublishers.ofString("{\"event_id\":12345}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"event_id":12345}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/copy') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"event_id":12345}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/events/copy", strings.NewReader("{\"event_id\":12345}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): POST /v1/events/copy - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "source_event_id": 12345, "id": 23456, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=23456", "name": "Copy of Sample Trade Show", "start_date": "2027-06-01", "end_date": "2027-06-03", "tasks_copied": 1, "files_queued": 0, "files_skipped": 0, "tasks": [ { "source_task_id": 34567, "id": 45678, "exhibitday_url": "https://www.exhibitday.com/Workspace/TaskView/98765?tid=45678" } ], "files": [] } ``` ### Update Event Dates and Hours `PATCH https://api.exhibitday.com/v1/events/dates` Documentation: https://api.exhibitday.com/Help/V1?epf=1#patch-v1-events-dates Replaces one Event Dates and Hours list while keeping the other groups and main Event dates unchanged. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | event_id | Number | Yes | The ID of the Event whose dates you want to update. | | | date_type_id | Number | Yes | The Dates and Hours group whose schedule is replaced. Other groups stay unchanged. | Allowed values: `1` (Exhibit Hall) \| `2` (Booth Setup) \| `3` (Booth Dismantle) | | dates | JSON object/list | No | The complete list of dates and hours to keep in this group. | Each item needs date. Optional fields are start_time, end_time, timezone and description. Omit or leave blank to keep the saved list; null or [] clears it. | | expected_revision | String | No | The record_revision from your last read. Send it to avoid overwriting a later change. | Omit to skip this check. Blank, null, malformed or conflicting copies return HTTP 400; a stale value returns HTTP 409 with error_code=record_changed. | | $ignore_params_with_empty_values | Boolean | No | Set to true to ignore a whole JSON null dates value. | Default: false. The text null still clears the list, and [] still clears it. Invalid expected_revision is never ignored. | Declared schema for `dates` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "array", "items": { "type": "object", "additionalProperties": false, "properties": { "date": { "type": "string", "maxLength": 10, "minLength": 0, "format": "date" }, "start_time": { "type": "string", "maxLength": 8, "minLength": 0, "nullable": true }, "end_time": { "type": "string", "maxLength": 8, "minLength": 0, "nullable": true }, "timezone": { "type": "string", "maxLength": 20, "minLength": 0, "nullable": true }, "description": { "type": "string", "maxLength": 75, "minLength": 0, "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "required": [ "date" ] }, "maxItems": 2147483647, "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": false, "example": [ { "date": "2030-01-15", "start_time": "09:00", "end_time": "17:00", "timezone": "EST", "description": "Exhibit hours" }, { "date": "2030-01-16", "start_time": "09:00", "end_time": "16:00", "timezone": "EST", "description": "Final exhibit day" } ] } ``` #### Building the replacement list Send every row you want to keep; individual dates have no update IDs. The Event Information tab must be editable. All supplied rows are validated before the group is replaced. Use YYYY-MM-DD for dates. Times use 24-hour HH:mm or HH:mm:ss without a UTC offset. A time-zone label allows 20 characters and a description allows 75. Omitted or null optional fields become empty text or no time. If end_time is earlier than start_time, they are swapped. The time-zone label does not convert times or enforce daylight-saving rules. Duplicate rows are allowed. Input order does not set display order. Request-size limits apply, but there is no additional fixed row-count limit. Send the dates list through JSON, query or form; a supported header must contain one value without commas. #### Clearing or keeping the list Omit dates or leave the whole parameter blank to keep its current list. Send JSON null or [] to remove all rows. With $ignore_params_with_empty_values=true, JSON null is ignored; the text null and [] still clear the list. #### Avoiding conflicting updates The selected group's revision includes its complete list, even when empty. It does not cover the Event's main date range or the other two groups. 1. Use `GET /v1/events/dates` with this `event_id`, the selected `filter_by_date_type_id` and `$include_record_revision=true`. 2. Send the group's record_revision as expected_revision. 3. On HTTP 409 with error_code=record_changed, read the group again, review its current list and decide whether to submit another update. #### After saving A changed list is saved together and recorded in Event history. No notification email is sent. An unchanged list adds no data or history and keeps its revision. If the save outcome could not be confirmed, retrieve this group before deciding whether to retry. The API does not automatically repeat it. Example — curl: ```bash curl -X PATCH "https://api.exhibitday.com/v1/events/dates" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"event_id\":45678,\"date_type_id\":1,\"dates\":[{\"date\":\"2030-01-15\",\"start_time\":\"09:00\",\"end_time\":\"17:00\",\"timezone\":\"EST\",\"description\":\"Exhibit hours\"},{\"date\":\"2030-01-16\",\"start_time\":\"09:00\",\"end_time\":\"16:00\",\"timezone\":\"EST\",\"description\":\"Final exhibit day\"}]}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/dates", { method: "PATCH", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "event_id": 45678, "date_type_id": 1, "dates": [{"date":"2030-01-15","start_time":"09:00","end_time":"17:00","timezone":"EST","description":"Exhibit hours"},{"date":"2030-01-16","start_time":"09:00","end_time":"16:00","timezone":"EST","description":"Final exhibit day"}] }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests import json response = requests.patch( "https://api.exhibitday.com/v1/events/dates", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"event_id": 45678, "date_type_id": 1, "dates": json.loads("[{\"date\":\"2030-01-15\",\"start_time\":\"09:00\",\"end_time\":\"17:00\",\"timezone\":\"EST\",\"description\":\"Exhibit hours\"},{\"date\":\"2030-01-16\",\"start_time\":\"09:00\",\"end_time\":\"16:00\",\"timezone\":\"EST\",\"description\":\"Final exhibit day\"}]")}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Text.Json; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PatchAsync("https://api.exhibitday.com/v1/events/dates", JsonContent.Create(new { event_id = 45678, date_type_id = 1, dates = JsonDocument.Parse("[{\"date\":\"2030-01-15\",\"start_time\":\"09:00\",\"end_time\":\"17:00\",\"timezone\":\"EST\",\"description\":\"Exhibit hours\"},{\"date\":\"2030-01-16\",\"start_time\":\"09:00\",\"end_time\":\"16:00\",\"timezone\":\"EST\",\"description\":\"Final exhibit day\"}]").RootElement.Clone() })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/dates")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("PATCH", HttpRequest.BodyPublishers.ofString("{\"event_id\":45678,\"date_type_id\":1,\"dates\":[{\"date\":\"2030-01-15\",\"start_time\":\"09:00\",\"end_time\":\"17:00\",\"timezone\":\"EST\",\"description\":\"Exhibit hours\"},{\"date\":\"2030-01-16\",\"start_time\":\"09:00\",\"end_time\":\"16:00\",\"timezone\":\"EST\",\"description\":\"Final exhibit day\"}]}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"event_id":45678,"date_type_id":1,"dates":[{"date":"2030-01-15","start_time":"09:00","end_time":"17:00","timezone":"EST","description":"Exhibit hours"},{"date":"2030-01-16","start_time":"09:00","end_time":"16:00","timezone":"EST","description":"Final exhibit day"}]}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/dates') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"event_id":45678,"date_type_id":1,"dates":[{"date":"2030-01-15","start_time":"09:00","end_time":"17:00","timezone":"EST","description":"Exhibit hours"},{"date":"2030-01-16","start_time":"09:00","end_time":"16:00","timezone":"EST","description":"Final exhibit day"}]}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/events/dates", strings.NewReader("{\"event_id\":45678,\"date_type_id\":1,\"dates\":[{\"date\":\"2030-01-15\",\"start_time\":\"09:00\",\"end_time\":\"17:00\",\"timezone\":\"EST\",\"description\":\"Exhibit hours\"},{\"date\":\"2030-01-16\",\"start_time\":\"09:00\",\"end_time\":\"16:00\",\"timezone\":\"EST\",\"description\":\"Final exhibit day\"}]}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): PATCH /v1/events/dates - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Event Dates updated.", "errors": [] } ``` ### Export an Event Binder `GET https://api.exhibitday.com/v1/events/binder/export` Documentation: https://api.exhibitday.com/Help/V1?epf=1#get-v1-events-binder-export Downloads an Event Binder as a PDF or Word document. Choose which sections and cost details to include. Section options are named include_ plus the tab name, and include_ plus the tab name and _costs for its cost details (for example include_shipments and include_shipments_costs), the same rule POST /v1/events/copy uses. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | event_id | Number | Yes | The ID of the Event whose Binder you want to download. | | | format | String | No | The document format. Leave it out to get a PDF. Word requires a plan that includes Event Binders. Values are not case-sensitive. A blank value is refused unless $ignore_params_with_empty_values is true. | Allowed values: `pdf` \| `docx` | | include_cover_page | Boolean | No | Include the cover page. | Default: true. | | include_info | Boolean | No | Include Event Information. | Default: true. | | include_special_tab | Boolean | No | Include the workspace's Special tab. | Default: true. | | include_booth | Boolean | No | Include the Booth section. | Default: true. | | include_booth_costs | Boolean | No | Include permitted Booth cost and payment details. | Default: true. | | include_booth_services | Boolean | No | Include Booth Services. | Default: true. | | include_booth_services_costs | Boolean | No | Include permitted Booth Service cost and payment details. | Default: true. | | include_staff | Boolean | No | Include Staff. | Default: true. | | include_staff_costs | Boolean | No | Include permitted Staff cost and payment details. | Default: true. | | include_travel | Boolean | No | Include Travel Reservations. | Default: true. | | include_travel_costs | Boolean | No | Include permitted Travel cost and payment details. | Default: true. | | include_asset_reservations | Boolean | No | Include Asset Reservations and their Optional Accessories. | Default: true. | | include_giveaways | Boolean | No | Include Giveaways. | Default: true. | | include_giveaways_costs | Boolean | No | Include permitted Giveaway cost and payment details. | Default: true. | | include_shipments | Boolean | No | Include Shipments. | Default: true. | | include_shipments_costs | Boolean | No | Include permitted Shipment cost and payment details. | Default: true. | | include_sponsorships | Boolean | No | Include Sponsorships. | Default: true. | | include_sponsorships_costs | Boolean | No | Include permitted Sponsorship cost and payment details. | Default: true. | | include_tasks | Boolean | No | Include Tasks in the Event's section order. | Default: true. | | include_playbook | Boolean | No | Include Playbook Activities. | Default: true. | | include_playbook_costs | Boolean | No | Include permitted Playbook cost and payment details. | Default: true. | | include_misc_expenses_credits | Boolean | No | Include Miscellaneous Expenses and Credits. | Default: true. | | include_misc_expenses_credits_costs | Boolean | No | Include permitted Miscellaneous Expense and Credit amounts and payment details. | Default: true. | | include_budget | Boolean | No | Include the Event Budget summary when available. | Default: false. | | include_roi | Boolean | No | Include the Event's ROI summary when available. | Default: false. | | include_roo | Boolean | No | Include the Event's Objectives and ROO summary when available. | Default: false. | | $ignore_params_with_empty_values | Boolean | No | Keep defaults for empty optional inputs. | Default: false. With true, an empty format keeps its default (pdf). Empty true/false options always use their defaults. event_id is still required. | #### Creating the Binder 1. Provide the Event's ID in `event_id` and choose `pdf` or `docx` in `format`. 2. Leave the section options at their defaults or set individual options to `false`. Budget, ROI and ROO are off by default; set `include_budget`, `include_roi` or `include_roo` to `true` to add them. 3. Save the returned document. Sections follow the Event Binder's order, including the workspace's Special tab position. #### Choosing sections and cost details A section is included only when it is selected and available for the Event. The cover page and Event Information are always available. Every other section is left out when its tab is hidden on the Event (Booth Services follows the Booth tab). Budget also needs Budgeting in your plan. ROI and ROO need Analytics & ROI in your plan. The Special tab must be turned on for the workspace. The ROO section is included even when the Event's ROI tab is hidden. If none of the selected sections is available, the request returns HTTP `400` with `invalid_request` and no file. Cost options can hide financial details; they do not grant access to them. Budget is a separate section. Optional Accessories appear with Capital Asset reservations. The Binder uses the standard Event Binder layouts and empty-section messages. It does not include attached files or Task comments. #### PDF and Word PDF is the default and uses the normal plan watermark when applicable. Word requires a plan that includes Event Binders. The cover identifies the preparer as ExhibitDay API. Creating a Binder does not change the Event or send notifications. Its contents reflect the data read while it is being prepared; it is not a snapshot of one instant. #### Handling the response A successful response is the file itself, sent as an attachment: `event-binder.pdf` (`application/pdf`) or `event-binder.docx` (`application/vnd.openxmlformats-officedocument.wordprocessingml.document`). It is marked private and is not stored by caches. Errors use the usual JSON API response. If HTTP `409` reports `record_changed`, retrieve the current information before deciding whether to repeat the export. The API does not retry the report automatically. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X GET "https://api.exhibitday.com/v1/events/binder/export?event_id=23456&format=pdf" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi mv response-body.tmp 'event-binder.pdf' ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const response = await fetch("https://api.exhibitday.com/v1/events/binder/export?event_id=23456&format=pdf", { method: "GET", headers: { Authorization: 'Bearer YOUR_API_KEY' } }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); await writeFile("event-binder.pdf", new Uint8Array(await response.arrayBuffer())); ``` Example — Python: ```python import requests import json response = requests.request("GET", "https://api.exhibitday.com/v1/events/binder/export?event_id=23456&format=pdf", headers={'Authorization': 'Bearer YOUR_API_KEY'}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') with open("event-binder.pdf", 'wb') as destination: destination.write(response.content) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.exhibitday.com/v1/events/binder/export?event_id=23456&format=pdf"); using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); await File.WriteAllBytesAsync("event-binder.pdf", await response.Content.ReadAsByteArrayAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/binder/export?event_id=23456&format=pdf")).header("Authorization", "Bearer YOUR_API_KEY"); HttpResponse response = HttpClient.newHttpClient().send(request.method("GET", HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); Files.write(Path.of("event-binder.pdf"), response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); file_put_contents('event-binder.pdf', $response); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/binder/export?event_id=23456&format=pdf') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' File.binwrite('event-binder.pdf', response.body) ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/binder/export?event_id=23456&format=pdf", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } if err := os.WriteFile("event-binder.pdf", data, 0600); err != nil { log.Fatal(err) } fmt.Println("File saved") } ``` HTTP 200: Returns a private PDF or Word download. An unsuccessful request returns the normal JSON API error. Media: application/pdf, application/vnd.openxmlformats-officedocument.wordprocessingml.document. The body is the authorized file's real bytes, not JSON or base64. Errors are JSON status responses; check HTTP status before saving the file. ### Retrieve General File Attachments for an Event `GET https://api.exhibitday.com/v1/events/attachments` Documentation: https://api.exhibitday.com/Help/V1?epf=1#get-v1-events-attachments Retrieves the general File Attachments in this Event's Attachments tab, including files marked as invoices. Each result includes its ID, description, file name, is_invoice flag and added time. Omit filter_by_is_invoice for both kinds, or filter by true or false. Invoice files require current financial access and are left out of results and counts without it. Use download for file contents. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | event_id | Number | Yes | The id of the event whose files you would like to retrieve or add to. The Event must belong to your workspace. | | | $limit | Number | No | The most files to return (a whole number of 1 or more). Leave this out to return all matching files. | | | $offset | Number | No | How many files to skip before the first result (a whole number of 0 or more). Use this with $limit to read the next page. | | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records. | Allowed values: `array` | | filter_by_is_invoice | Boolean | No | Send true to include only files marked as invoices, or false to include only the other general files. Omit this option or leave it blank to include both kinds. Files marked as invoices need financial access; without it they are left out before paging and counts. | | **Event Attachment Lists**: These methods support Events in your workspace. The Exhibitor Prospectus, Exhibit Hall Floor Plan and Exhibit Rules fields under Information use their own file-field methods; custom File fields also use their own methods. General invoice files require financial access. Permitted reads and removals remain available on the Free plan. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/events/attachments?event_id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/attachments?" + new URLSearchParams({ "event_id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/events/attachments", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"event_id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/events/attachments?event_id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/attachments?event_id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/attachments?event_id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/attachments?event_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/events/attachments - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "attachment", "list_data": [ { "id": 12345, "filename": "attachment.txt", "description": "Event document", "is_invoice": false, "attachment_created_timestamp": "2027-01-30T12:00:00Z" } ] } ``` ### Add a General File Attachment to an Event `POST https://api.exhibitday.com/v1/events/attachments` Documentation: https://api.exhibitday.com/Help/V1?epf=1#post-v1-events-attachments Adds one File Attachment to this Event's Attachments tab, with the required description shown below. Send exactly one multipart file within the file and complete-request limits. Current Event access, file-upload permissions, an upload-enabled plan and applicable locks must allow this change. Adding a general invoice does not replace the invoice attached to a particular cost. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | event_id | Number | Yes | The id of the event whose files you would like to retrieve or add to. The Event must belong to your workspace. | | | file | File (multipart) | Yes | The file to attach. Send exactly one complete multipart/form-data part named file. The file size, extension and complete request limits shown here apply. | | | description | String | Yes | A description of this attachment, just like the required Description field in the Event's Attachments tab. Surrounding spaces are ignored. The description must contain 1 to 70 characters; a missing, blank or longer description is refused without adding a file. | Max length: 70. | | is_invoice | Boolean | No | Send true to mark this file as an invoice, or false to upload it as an ordinary file. The default is false when omitted or blank. Current financial invoice access is required for an invoice file. This does not attach a file to any individual cost or change payment details. | Default: false. | Declared schema for `file` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "string", "format": "binary", "x-maximum-bytes": 26214400, "x-allowed-extensions": [ "png", "jpg", "jpeg", "bmp", "gif", "pdf", "msg", "eml", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "rtf", "odp", "odt", "ods", "txt", "wks", "zip" ] } ``` **Event Attachment Lists**: These methods support Events in your workspace. The Exhibitor Prospectus, Exhibit Hall Floor Plan and Exhibit Rules fields under Information use their own file-field methods; custom File fields also use their own methods. General invoice files require financial access. Permitted reads and removals remain available on the Free plan. expected_revision is not supported. If a save outcome cannot be confirmed, retrieve the current files before deciding whether to retry; the API does not automatically repeat the change or remove files that may have been saved. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X POST "https://api.exhibitday.com/v1/events/attachments" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}" --form-string "event_id=12345" --form-string "description=Booth setup instructions" --form "file=@attachment.txt;type=application/octet-stream") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi cat response-body.tmp ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const form = new FormData(); form.append("event_id", "12345"); form.append("description", "Booth setup instructions"); form.append("file", new Blob([await readFile("attachment.txt")], { type: "application/octet-stream" }), "attachment.txt"); const response = await fetch("https://api.exhibitday.com/v1/events/attachments", { method: "POST", headers: { Authorization: 'Bearer YOUR_API_KEY' }, body: form }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); console.log(await response.json()); ``` Example — Python: ```python import requests import json from contextlib import ExitStack with ExitStack() as stack: files = [ ("file", ("attachment.txt", stack.enter_context(open("attachment.txt", 'rb')), "application/octet-stream")), ] response = requests.request("POST", "https://api.exhibitday.com/v1/events/attachments", headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data={"event_id": "12345", "description": "Booth setup instructions"}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') print(response.json()) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.exhibitday.com/v1/events/attachments"); var form = new MultipartFormDataContent(); form.Add(new StringContent("12345"), "event_id"); form.Add(new StringContent("Booth setup instructions"), "description"); var file0 = new StreamContent(File.OpenRead("attachment.txt")); file0.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(file0, "file", "attachment.txt"); request.Content = form; using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/attachments")).header("Authorization", "Bearer YOUR_API_KEY"); String boundary = "ExhibitDay-" + UUID.randomUUID(); ByteArrayOutputStream form = new ByteArrayOutputStream(); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"event_id\"\r\n\r\n" + "12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"description\"\r\n\r\n" + "Booth setup instructions" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"attachment.txt\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8)); form.write(Files.readAllBytes(Path.of("attachment.txt"))); form.write("\r\n".getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); request.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpResponse response = HttpClient.newHttpClient().send(request.method("POST", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); System.out.println(new String(response.body(), StandardCharsets.UTF_8)); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], CURLOPT_POSTFIELDS => [ 'event_id' => '12345', 'description' => 'Booth setup instructions', 'file' => new CURLFile('attachment.txt', 'application/octet-stream', 'attachment.txt'), ], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); echo $response; ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/attachments') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' files = [] begin parts = [ ['event_id', '12345'], ['description', 'Booth setup instructions'], ['file', (files << File.open('attachment.txt', 'rb')).last, {filename: 'attachment.txt', content_type: 'application/octet-stream'}], ] request.set_form(parts, 'multipart/form-data') response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' puts response.body ensure files.each(&:close) end ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" "bytes" "mime/multipart" "net/textproto" ) func main() { var form bytes.Buffer writer := multipart.NewWriter(&form) if err := writer.WriteField("event_id", "12345"); err != nil { log.Fatal(err) } if err := writer.WriteField("description", "Booth setup instructions"); err != nil { log.Fatal(err) } header0 := textproto.MIMEHeader{} header0.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"attachment.txt\"") header0.Set("Content-Type", "application/octet-stream") part0, err := writer.CreatePart(header0) if err != nil { log.Fatal(err) } file0, err := os.Open("attachment.txt") if err != nil { log.Fatal(err) } if _, err = io.Copy(part0, file0); err != nil { log.Fatal(err) } file0.Close() if err := writer.Close(); err != nil { log.Fatal(err) } request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/events/attachments", &form) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", writer.FormDataContentType()) response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } fmt.Printf("%s\n", data) } ``` Example HTTP response body (JSON): POST /v1/events/attachments - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "attachment", "list_data": [ { "id": 12345, "filename": "attachment.txt", "description": "Booth setup instructions", "is_invoice": false, "attachment_created_timestamp": "2027-01-30T12:00:00Z" } ] } ``` ### Remove a General File Attachment From an Event `DELETE https://api.exhibitday.com/v1/events/attachments` Documentation: https://api.exhibitday.com/Help/V1?epf=1#delete-v1-events-attachments Removes one general File Attachment from an Event's Attachments tab. Send only the file ID from the attachment list; the API finds the Event it belongs to. Other Event information, costs and file attachments remain unchanged. Current Event and Attachments-tab permissions and applicable locks must allow removal; physical cleanup may finish after the response. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The id of the file, from an Event's Attachments tab list. The API finds the Event it belongs to. A file from another file field is not accepted. | | **Event Attachment Lists**: These methods support Events in your workspace. The Exhibitor Prospectus, Exhibit Hall Floor Plan and Exhibit Rules fields under Information use their own file-field methods; custom File fields also use their own methods. General invoice files require financial access. Permitted reads and removals remain available on the Free plan. expected_revision is not supported. If a save outcome cannot be confirmed, retrieve the current files before deciding whether to retry; the API does not automatically repeat the change or remove files that may have been saved. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/events/attachments?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/attachments?" + new URLSearchParams({ "id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/events/attachments", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/events/attachments?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/attachments?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/attachments?id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/events/attachments?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/events/attachments - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Attachment removed.", "errors": [] } ``` ### Download an Event's General File Attachment `GET https://api.exhibitday.com/v1/events/attachments/download` Documentation: https://api.exhibitday.com/Help/V1?epf=1#get-v1-events-attachments-download Downloads one original File Attachment from an Event's Attachments tab. Send only the file ID returned by that list; the API finds the Event it belongs to. Current Event and Attachments-tab permissions apply; general invoice files also require financial access. If this file is still being copied, the download returns HTTP 409 with file_copy_pending. Try the download again in a few minutes. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The id of the file, from an Event's Attachments tab list. The API finds the Event it belongs to. A file from another file field is not accepted. | | **Event Attachment Lists**: These methods support Events in your workspace. The Exhibitor Prospectus, Exhibit Hall Floor Plan and Exhibit Rules fields under Information use their own file-field methods; custom File fields also use their own methods. General invoice files require financial access. Permitted reads and removals remain available on the Free plan. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X GET "https://api.exhibitday.com/v1/events/attachments/download?id=12345" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi mv response-body.tmp 'attachment.txt' ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const response = await fetch("https://api.exhibitday.com/v1/events/attachments/download?id=12345", { method: "GET", headers: { Authorization: 'Bearer YOUR_API_KEY' } }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); await writeFile("attachment.txt", new Uint8Array(await response.arrayBuffer())); ``` Example — Python: ```python import requests import json response = requests.request("GET", "https://api.exhibitday.com/v1/events/attachments/download?id=12345", headers={'Authorization': 'Bearer YOUR_API_KEY'}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') with open("attachment.txt", 'wb') as destination: destination.write(response.content) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.exhibitday.com/v1/events/attachments/download?id=12345"); using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); await File.WriteAllBytesAsync("attachment.txt", await response.Content.ReadAsByteArrayAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/attachments/download?id=12345")).header("Authorization", "Bearer YOUR_API_KEY"); HttpResponse response = HttpClient.newHttpClient().send(request.method("GET", HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); Files.write(Path.of("attachment.txt"), response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); file_put_contents('attachment.txt', $response); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/attachments/download?id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' File.binwrite('attachment.txt', response.body) ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/attachments/download?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } if err := os.WriteFile("attachment.txt", data, 0600); err != nil { log.Fatal(err) } fmt.Println("File saved") } ``` HTTP 200: Returns the original uploaded file as a private download, using a safe filename. If the file cannot be downloaded, the response contains the usual JSON API error instead. Media: application/octet-stream. The body is the authorized file's real bytes, not JSON or base64. Errors are JSON status responses; check HTTP status before saving the file. ### Retrieve Custom File Attachments for an Event `GET https://api.exhibitday.com/v1/events/custom_fields/file_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=1#get-v1-events-custom_fields-file_attachment Retrieves the File Attachments saved in this Event's custom File fields on the Info, Booth and Special tabs. Empty fields and fields in unavailable tabs are excluded. Each result identifies its field_name, field_label, layout visibility and attached-file metadata. A readable field with conflicting or unavailable saved contents is refused rather than silently omitted. Results use tab order Information, Booth, Special, then each field's display order and ID. Filtering happens before the count and paging. A field's is_hidden flag describes its form layout; it does not replace current permissions. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | event_id | Number | Yes | The ID of the Event. | | | $limit | Number | No | The most populated fields to return. Use a positive whole number; omit this parameter to return all readable matching fields. | | | $offset | Number | No | How many results to skip. The default is zero. Use a nonnegative whole number. | | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records. | Allowed values: `array` | **Choose a Custom File Field**: Use `GET /v1/references/event_custom_fields` with `hydrate_file_fields=true` to find field names such as `custom_12345`. These methods support regular Events in your workspace. Assets, the three standard Information documents and each cost record's Invoice Attachment use their own methods. Event custom File methods do not support PATCH or revision tokens. Each successful change adds one history entry on the selected field's actual tab; the three possible audit tabs are alternatives, not three entries per change. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/events/custom_fields/file_attachment?event_id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/custom_fields/file_attachment?" + new URLSearchParams({ "event_id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/events/custom_fields/file_attachment", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"event_id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/events/custom_fields/file_attachment?event_id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/custom_fields/file_attachment?event_id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/custom_fields/file_attachment?event_id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/custom_fields/file_attachment?event_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/events/custom_fields/file_attachment - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "custom_file_attachment", "list_data": [ { "field_name": "custom_12345", "field_label": "Supporting Document", "is_hidden": false, "file_attachment": { "id": 23456, "filename": "attachment.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } } ] } ``` ### Add a Custom File Attachment to an Event `POST https://api.exhibitday.com/v1/events/custom_fields/file_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=1#post-v1-events-custom_fields-file_attachment Adds one File Attachment to an empty custom File field on this Event's Info, Booth or Special tab. Select the field with its custom_ID name; its current definition determines whether Information, Booth or Special Tab permissions apply. A paid plan, current edit access and an unlocked applicable tab are required. An occupied field returns HTTP 409, including a field with an unavailable saved reference. This method does not replace a file. To replace one, remove its current attachment and then upload the new file; these are two separate requests, so a failed upload can leave the field empty. A successful upload returns the selected field and the new file's metadata. Optional Idempotency-Key replay applies to this POST. Reuse the same key and identical request only for a retry. If the outcome cannot be confirmed, retrieve the current files before deciding whether to retry. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | event_id | Number | Yes | The ID of the Event. | | | field_name | String | Yes | The exact custom_ID name of the Event's custom File field, such as custom_12345. Its current definition selects the tab; do not send a tab flag. Use the query string, form or a header. Matching copies of a selector count once. Cookies and JSON-body selectors do not select these file fields. | Max length: 26. | | file | File (multipart) | Yes | One complete multipart/form-data file part named file. The supported extensions, 25 MiB file limit and complete-request limit apply. A website link is not accepted. | | Declared schema for `file` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "string", "format": "binary", "x-maximum-bytes": 26214400, "x-allowed-extensions": [ "png", "jpg", "jpeg", "bmp", "gif", "pdf", "msg", "eml", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "rtf", "odp", "odt", "ods", "txt", "wks", "zip" ] } ``` **Choose a Custom File Field**: Use `GET /v1/references/event_custom_fields` with `hydrate_file_fields=true` to find field names such as `custom_12345`. These methods support regular Events in your workspace. Assets, the three standard Information documents and each cost record's Invoice Attachment use their own methods. Event custom File methods do not support PATCH or revision tokens. Each successful change adds one history entry on the selected field's actual tab; the three possible audit tabs are alternatives, not three entries per change. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X POST "https://api.exhibitday.com/v1/events/custom_fields/file_attachment" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}" --form-string "event_id=12345" --form-string "field_name=custom_12345" --form "file=@attachment.pdf;type=application/octet-stream") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi cat response-body.tmp ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const form = new FormData(); form.append("event_id", "12345"); form.append("field_name", "custom_12345"); form.append("file", new Blob([await readFile("attachment.pdf")], { type: "application/octet-stream" }), "attachment.pdf"); const response = await fetch("https://api.exhibitday.com/v1/events/custom_fields/file_attachment", { method: "POST", headers: { Authorization: 'Bearer YOUR_API_KEY' }, body: form }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); console.log(await response.json()); ``` Example — Python: ```python import requests import json from contextlib import ExitStack with ExitStack() as stack: files = [ ("file", ("attachment.pdf", stack.enter_context(open("attachment.pdf", 'rb')), "application/octet-stream")), ] response = requests.request("POST", "https://api.exhibitday.com/v1/events/custom_fields/file_attachment", headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data={"event_id": "12345", "field_name": "custom_12345"}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') print(response.json()) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.exhibitday.com/v1/events/custom_fields/file_attachment"); var form = new MultipartFormDataContent(); form.Add(new StringContent("12345"), "event_id"); form.Add(new StringContent("custom_12345"), "field_name"); var file0 = new StreamContent(File.OpenRead("attachment.pdf")); file0.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(file0, "file", "attachment.pdf"); request.Content = form; using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/custom_fields/file_attachment")).header("Authorization", "Bearer YOUR_API_KEY"); String boundary = "ExhibitDay-" + UUID.randomUUID(); ByteArrayOutputStream form = new ByteArrayOutputStream(); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"event_id\"\r\n\r\n" + "12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"field_name\"\r\n\r\n" + "custom_12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"attachment.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8)); form.write(Files.readAllBytes(Path.of("attachment.pdf"))); form.write("\r\n".getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); request.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpResponse response = HttpClient.newHttpClient().send(request.method("POST", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); System.out.println(new String(response.body(), StandardCharsets.UTF_8)); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], CURLOPT_POSTFIELDS => [ 'event_id' => '12345', 'field_name' => 'custom_12345', 'file' => new CURLFile('attachment.pdf', 'application/octet-stream', 'attachment.pdf'), ], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); echo $response; ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/custom_fields/file_attachment') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' files = [] begin parts = [ ['event_id', '12345'], ['field_name', 'custom_12345'], ['file', (files << File.open('attachment.pdf', 'rb')).last, {filename: 'attachment.pdf', content_type: 'application/octet-stream'}], ] request.set_form(parts, 'multipart/form-data') response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' puts response.body ensure files.each(&:close) end ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" "bytes" "mime/multipart" "net/textproto" ) func main() { var form bytes.Buffer writer := multipart.NewWriter(&form) if err := writer.WriteField("event_id", "12345"); err != nil { log.Fatal(err) } if err := writer.WriteField("field_name", "custom_12345"); err != nil { log.Fatal(err) } header0 := textproto.MIMEHeader{} header0.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"attachment.pdf\"") header0.Set("Content-Type", "application/octet-stream") part0, err := writer.CreatePart(header0) if err != nil { log.Fatal(err) } file0, err := os.Open("attachment.pdf") if err != nil { log.Fatal(err) } if _, err = io.Copy(part0, file0); err != nil { log.Fatal(err) } file0.Close() if err := writer.Close(); err != nil { log.Fatal(err) } request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/events/custom_fields/file_attachment", &form) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", writer.FormDataContentType()) response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } fmt.Printf("%s\n", data) } ``` Example HTTP response body (JSON): POST /v1/events/custom_fields/file_attachment - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "field_name": "custom_12345", "field_label": "Integration status", "is_hidden": false, "file_attachment": { "id": 12345, "filename": "attachment.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } } ``` ### Remove a Custom File Attachment From an Event `DELETE https://api.exhibitday.com/v1/events/custom_fields/file_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=1#delete-v1-events-custom_fields-file_attachment Clears the selected custom File field on this Event's Info, Booth or Special tab, removing its File Attachment. Its current definition determines the tab and required edit, attachment-removal and lock permissions. If the field is already empty, DELETE returns 404 Not Found and changes no saved metadata or history. Permitted removals remain available on the Free plan. DELETE can clear one malformed, dangling or foreign saved reference, leaving the other file untouched. A file shared by another field or a structured record is preserved. Duplicate saved values are refused. Physical cleanup of an unshared owned file may finish after the response. Other fields and standard documents remain unchanged. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | event_id | Number | Yes | The ID of the Event. | | | field_name | String | Yes | The exact custom_ID name of the Event's custom File field, such as custom_12345. Its current definition selects the tab; do not send a tab flag. Use the query string, form or a header. Matching copies of a selector count once. Cookies and JSON-body selectors do not select these file fields. | Max length: 26. | **Choose a Custom File Field**: Use `GET /v1/references/event_custom_fields` with `hydrate_file_fields=true` to find field names such as `custom_12345`. These methods support regular Events in your workspace. Assets, the three standard Information documents and each cost record's Invoice Attachment use their own methods. Event custom File methods do not support PATCH or revision tokens. Each successful change adds one history entry on the selected field's actual tab; the three possible audit tabs are alternatives, not three entries per change. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/events/custom_fields/file_attachment?event_id=12345&field_name=custom_12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/custom_fields/file_attachment?" + new URLSearchParams({ "event_id": "12345", "field_name": "custom_12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/events/custom_fields/file_attachment", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"event_id": 12345, "field_name": "custom_12345"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/events/custom_fields/file_attachment?event_id=12345&field_name=custom_12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/custom_fields/file_attachment?event_id=12345&field_name=custom_12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/custom_fields/file_attachment?event_id=12345&field_name=custom_12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/events/custom_fields/file_attachment?event_id=12345&field_name=custom_12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/events/custom_fields/file_attachment - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Custom File field cleared.", "errors": [] } ``` ### Download a Custom File Attachment of an Event `GET https://api.exhibitday.com/v1/events/custom_fields/file_attachment/download` Documentation: https://api.exhibitday.com/Help/V1?epf=1#get-v1-events-custom_fields-file_attachment-download Downloads the original File Attachment in the selected custom File field on this Event's Info, Booth or Special tab. Select the field with its custom_ID name; its current definition determines the tab and applicable permissions. An empty field has no file to download and returns HTTP 404. Conflicting or unavailable saved references return HTTP 409. Use the field_name from the list or the workspace's custom field definitions. No tab flag or attachment ID is needed. If this file is still being copied, the download returns HTTP 409 with file_copy_pending. Try the download again in a few minutes. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | event_id | Number | Yes | The ID of the Event. | | | field_name | String | Yes | The exact custom_ID name of the Event's custom File field, such as custom_12345. Its current definition selects the tab; do not send a tab flag. Use the query string, form or a header. Matching copies of a selector count once. Cookies and JSON-body selectors do not select these file fields. | Max length: 26. | **Choose a Custom File Field**: Use `GET /v1/references/event_custom_fields` with `hydrate_file_fields=true` to find field names such as `custom_12345`. These methods support regular Events in your workspace. Assets, the three standard Information documents and each cost record's Invoice Attachment use their own methods. Event custom File methods do not support PATCH or revision tokens. Each successful change adds one history entry on the selected field's actual tab; the three possible audit tabs are alternatives, not three entries per change. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X GET "https://api.exhibitday.com/v1/events/custom_fields/file_attachment/download?event_id=12345&field_name=custom_12345" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi mv response-body.tmp 'attachment.pdf' ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const response = await fetch("https://api.exhibitday.com/v1/events/custom_fields/file_attachment/download?event_id=12345&field_name=custom_12345", { method: "GET", headers: { Authorization: 'Bearer YOUR_API_KEY' } }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); await writeFile("attachment.pdf", new Uint8Array(await response.arrayBuffer())); ``` Example — Python: ```python import requests import json response = requests.request("GET", "https://api.exhibitday.com/v1/events/custom_fields/file_attachment/download?event_id=12345&field_name=custom_12345", headers={'Authorization': 'Bearer YOUR_API_KEY'}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') with open("attachment.pdf", 'wb') as destination: destination.write(response.content) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.exhibitday.com/v1/events/custom_fields/file_attachment/download?event_id=12345&field_name=custom_12345"); using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); await File.WriteAllBytesAsync("attachment.pdf", await response.Content.ReadAsByteArrayAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/custom_fields/file_attachment/download?event_id=12345&field_name=custom_12345")).header("Authorization", "Bearer YOUR_API_KEY"); HttpResponse response = HttpClient.newHttpClient().send(request.method("GET", HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); Files.write(Path.of("attachment.pdf"), response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); file_put_contents('attachment.pdf', $response); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/custom_fields/file_attachment/download?event_id=12345&field_name=custom_12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' File.binwrite('attachment.pdf', response.body) ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/custom_fields/file_attachment/download?event_id=12345&field_name=custom_12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } if err := os.WriteFile("attachment.pdf", data, 0600); err != nil { log.Fatal(err) } fmt.Println("File saved") } ``` HTTP 200: Downloads the selected custom field's original uploaded file. Errors return the usual JSON API response. Media: application/octet-stream. The body is the authorized file's real bytes, not JSON or base64. Errors are JSON status responses; check HTTP status before saving the file. ### Retrieve an Event Prospectus/Floor Plan/Exhibit Rules File Attachment `GET https://api.exhibitday.com/v1/events/information/file_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=1#get-v1-events-information-file_attachment Retrieves the file or website link saved in one of the Event's Info tab fields: Exhibitor Prospectus, Exhibit Hall Floor Plan or Exhibit Rules. Select the field with field_name. An empty field has no file or link; a saved link appears in this response. Reading requires current access to the Event. For general files in the Event's Attachments tab, use /v1/events/attachments. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | event_id | Number | Yes | The id of the Event whose Information document you would like to retrieve or change. The Event must belong to your workspace. | | | field_name | String | Yes | The Information document to retrieve or change. Use the field name exactly as shown; it is case-sensitive. | Allowed values: `exhibitor_prospectus` (Exhibitor Prospectus) \| `exhibit_hall_floor_plan` (Exhibit Hall Floor Plan) \| `exhibit_rules` (Exhibit Rules) | Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/events/information/file_attachment?event_id=12345&field_name=exhibitor_prospectus" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/information/file_attachment?" + new URLSearchParams({ "event_id": "12345", "field_name": "exhibitor_prospectus" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/events/information/file_attachment", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"event_id": 12345, "field_name": "exhibitor_prospectus"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/events/information/file_attachment?event_id=12345&field_name=exhibitor_prospectus"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/information/file_attachment?event_id=12345&field_name=exhibitor_prospectus")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/information/file_attachment?event_id=12345&field_name=exhibitor_prospectus') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/information/file_attachment?event_id=12345&field_name=exhibitor_prospectus", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/events/information/file_attachment - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "field_name": "exhibitor_prospectus", "url": null, "file_attachment": { "id": 12345, "filename": "document.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } } ``` ### Add an Event Prospectus/Floor Plan/Exhibit Rules File Attachment `POST https://api.exhibitday.com/v1/events/information/file_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=1#post-v1-events-information-file_attachment Adds one complete file or website link to an empty Exhibitor Prospectus, Exhibit Hall Floor Plan or Exhibit Rules field on the Event's Info tab. Send multipart/form-data with either one file or a nonblank url. The field holds one file or one link. Permission to edit Information and an unlocked Info tab are required; uploads for these three fields are also supported on the Free plan. A successful change updates the Event's last-update time and adds Event history. An occupied or conflicting field is refused. POST supports an optional Idempotency-Key; expected_revision is not supported. If the save cannot be confirmed, read the current field before submitting another change. A field the workspace has set to Hidden (Workspace Settings > Customize Event Information Tab) cannot be changed: the request is refused with 400 (invalid_request, error_params field_name). Make the field visible first. Supply url in the query string, form or a request header. Matching copies count once. Different copies are refused, even when one is blank. A cookie cannot supply this value. A URL containing a comma works in the query string or form. For a URL header, write a comma as %2C; a literal comma is refused because it could represent repeated header values. Percent-encoded URLs are supported. If the URL cannot be saved with its characters intact, the request is refused and the previous file or link is kept. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | event_id | Number | Yes | The id of the Event whose Information document you would like to retrieve or change. The Event must belong to your workspace. | | | field_name | String | Yes | The Information document to retrieve or change. Use the field name exactly as shown; it is case-sensitive. | Allowed values: `exhibitor_prospectus` (Exhibitor Prospectus) \| `exhibit_hall_floor_plan` (Exhibit Hall Floor Plan) \| `exhibit_rules` (Exhibit Rules) | | file | File (multipart) | No | Send one complete file, or use url with no file part. The same supported file types and size limit as the Web app apply, including documents, images, email files and ZIP files; these fields are not limited to PDF and images. The full extension list and size limit are shown below. The Free plan also supports uploads for these three Information fields. | | | url | String | No | An HTTP(S) link in multipart form data, with no file part. http:// is added if omitted. The link must fit within 2,000 characters. Use DELETE to clear the field; null or empty url is invalid here. The server does not open the link. | Max length: 2000. | Declared schema for `file` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "string", "format": "binary", "x-maximum-bytes": 26214400, "x-allowed-extensions": [ "png", "jpg", "jpeg", "bmp", "gif", "pdf", "msg", "eml", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "rtf", "odp", "odt", "ods", "txt", "wks", "zip" ] } ``` Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X POST "https://api.exhibitday.com/v1/events/information/file_attachment" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}" --form-string "event_id=12345" --form-string "field_name=exhibitor_prospectus" --form "file=@document.pdf;type=application/octet-stream") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi cat response-body.tmp ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const form = new FormData(); form.append("event_id", "12345"); form.append("field_name", "exhibitor_prospectus"); form.append("file", new Blob([await readFile("document.pdf")], { type: "application/octet-stream" }), "document.pdf"); const response = await fetch("https://api.exhibitday.com/v1/events/information/file_attachment", { method: "POST", headers: { Authorization: 'Bearer YOUR_API_KEY' }, body: form }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); console.log(await response.json()); ``` Example — Python: ```python import requests import json from contextlib import ExitStack with ExitStack() as stack: files = [ ("file", ("document.pdf", stack.enter_context(open("document.pdf", 'rb')), "application/octet-stream")), ] response = requests.request("POST", "https://api.exhibitday.com/v1/events/information/file_attachment", headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data={"event_id": "12345", "field_name": "exhibitor_prospectus"}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') print(response.json()) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.exhibitday.com/v1/events/information/file_attachment"); var form = new MultipartFormDataContent(); form.Add(new StringContent("12345"), "event_id"); form.Add(new StringContent("exhibitor_prospectus"), "field_name"); var file0 = new StreamContent(File.OpenRead("document.pdf")); file0.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(file0, "file", "document.pdf"); request.Content = form; using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/information/file_attachment")).header("Authorization", "Bearer YOUR_API_KEY"); String boundary = "ExhibitDay-" + UUID.randomUUID(); ByteArrayOutputStream form = new ByteArrayOutputStream(); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"event_id\"\r\n\r\n" + "12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"field_name\"\r\n\r\n" + "exhibitor_prospectus" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"document.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8)); form.write(Files.readAllBytes(Path.of("document.pdf"))); form.write("\r\n".getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); request.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpResponse response = HttpClient.newHttpClient().send(request.method("POST", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); System.out.println(new String(response.body(), StandardCharsets.UTF_8)); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], CURLOPT_POSTFIELDS => [ 'event_id' => '12345', 'field_name' => 'exhibitor_prospectus', 'file' => new CURLFile('document.pdf', 'application/octet-stream', 'document.pdf'), ], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); echo $response; ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/information/file_attachment') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' files = [] begin parts = [ ['event_id', '12345'], ['field_name', 'exhibitor_prospectus'], ['file', (files << File.open('document.pdf', 'rb')).last, {filename: 'document.pdf', content_type: 'application/octet-stream'}], ] request.set_form(parts, 'multipart/form-data') response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' puts response.body ensure files.each(&:close) end ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" "bytes" "mime/multipart" "net/textproto" ) func main() { var form bytes.Buffer writer := multipart.NewWriter(&form) if err := writer.WriteField("event_id", "12345"); err != nil { log.Fatal(err) } if err := writer.WriteField("field_name", "exhibitor_prospectus"); err != nil { log.Fatal(err) } header0 := textproto.MIMEHeader{} header0.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"document.pdf\"") header0.Set("Content-Type", "application/octet-stream") part0, err := writer.CreatePart(header0) if err != nil { log.Fatal(err) } file0, err := os.Open("document.pdf") if err != nil { log.Fatal(err) } if _, err = io.Copy(part0, file0); err != nil { log.Fatal(err) } file0.Close() if err := writer.Close(); err != nil { log.Fatal(err) } request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/events/information/file_attachment", &form) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", writer.FormDataContentType()) response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } fmt.Printf("%s\n", data) } ``` Example HTTP response body (JSON): POST /v1/events/information/file_attachment - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "field_name": "exhibitor_prospectus", "url": null, "file_attachment": { "id": 12345, "filename": "document.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } } ``` ### Replace an Event Prospectus/Floor Plan/Exhibit Rules File Attachment `PATCH https://api.exhibitday.com/v1/events/information/file_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=1#patch-v1-events-information-file_attachment Replaces the current file or website link in the selected Exhibitor Prospectus, Exhibit Hall Floor Plan or Exhibit Rules field on the Event's Info tab. Send multipart/form-data with either one complete file or a nonblank url. Permission to edit Information and an unlocked Info tab are required; uploads for these three fields are also supported on the Free plan. Sending the same link after the documented cleanup changes nothing and adds no history. Replacing a file creates a new attachment ID. Other changes update the Event's last-update time and add Event history. Conflicting saved files, or a simultaneous saved file and link, are refused. expected_revision is not supported. If the save cannot be confirmed, read the current field before submitting another change. A field the workspace has set to Hidden (Workspace Settings > Customize Event Information Tab) cannot be changed: the request is refused with 400 (invalid_request, error_params field_name). Make the field visible first. Supply url in the query string, form or a request header. Matching copies count once. Different copies are refused, even when one is blank. A cookie cannot supply this value. A URL containing a comma works in the query string or form. For a URL header, write a comma as %2C; a literal comma is refused because it could represent repeated header values. Percent-encoded URLs are supported. If the URL cannot be saved with its characters intact, the request is refused and the previous file or link is kept. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | event_id | Number | Yes | The id of the Event whose Information document you would like to retrieve or change. The Event must belong to your workspace. | | | field_name | String | Yes | The Information document to retrieve or change. Use the field name exactly as shown; it is case-sensitive. | Allowed values: `exhibitor_prospectus` (Exhibitor Prospectus) \| `exhibit_hall_floor_plan` (Exhibit Hall Floor Plan) \| `exhibit_rules` (Exhibit Rules) | | file | File (multipart) | No | Send one complete file, or use url with no file part. The same supported file types and size limit as the Web app apply, including documents, images, email files and ZIP files; these fields are not limited to PDF and images. The full extension list and size limit are shown below. The Free plan also supports uploads for these three Information fields. | | | url | String | No | An HTTP(S) link in multipart form data, with no file part. http:// is added if omitted. The link must fit within 2,000 characters. Use DELETE to clear the field; null or empty url is invalid here. The server does not open the link. | Max length: 2000. | Declared schema for `file` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "string", "format": "binary", "x-maximum-bytes": 26214400, "x-allowed-extensions": [ "png", "jpg", "jpeg", "bmp", "gif", "pdf", "msg", "eml", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "rtf", "odp", "odt", "ods", "txt", "wks", "zip" ] } ``` Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X PATCH "https://api.exhibitday.com/v1/events/information/file_attachment" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}" --form-string "event_id=12345" --form-string "field_name=exhibitor_prospectus" --form "file=@document.pdf;type=application/octet-stream") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi cat response-body.tmp ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const form = new FormData(); form.append("event_id", "12345"); form.append("field_name", "exhibitor_prospectus"); form.append("file", new Blob([await readFile("document.pdf")], { type: "application/octet-stream" }), "document.pdf"); const response = await fetch("https://api.exhibitday.com/v1/events/information/file_attachment", { method: "PATCH", headers: { Authorization: 'Bearer YOUR_API_KEY' }, body: form }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); console.log(await response.json()); ``` Example — Python: ```python import requests import json from contextlib import ExitStack with ExitStack() as stack: files = [ ("file", ("document.pdf", stack.enter_context(open("document.pdf", 'rb')), "application/octet-stream")), ] response = requests.request("PATCH", "https://api.exhibitday.com/v1/events/information/file_attachment", headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data={"event_id": "12345", "field_name": "exhibitor_prospectus"}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') print(response.json()) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("PATCH"), "https://api.exhibitday.com/v1/events/information/file_attachment"); var form = new MultipartFormDataContent(); form.Add(new StringContent("12345"), "event_id"); form.Add(new StringContent("exhibitor_prospectus"), "field_name"); var file0 = new StreamContent(File.OpenRead("document.pdf")); file0.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(file0, "file", "document.pdf"); request.Content = form; using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/information/file_attachment")).header("Authorization", "Bearer YOUR_API_KEY"); String boundary = "ExhibitDay-" + UUID.randomUUID(); ByteArrayOutputStream form = new ByteArrayOutputStream(); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"event_id\"\r\n\r\n" + "12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"field_name\"\r\n\r\n" + "exhibitor_prospectus" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"document.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8)); form.write(Files.readAllBytes(Path.of("document.pdf"))); form.write("\r\n".getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); request.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpResponse response = HttpClient.newHttpClient().send(request.method("PATCH", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); System.out.println(new String(response.body(), StandardCharsets.UTF_8)); } } ``` Example — PHP: ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], CURLOPT_POSTFIELDS => [ 'event_id' => '12345', 'field_name' => 'exhibitor_prospectus', 'file' => new CURLFile('document.pdf', 'application/octet-stream', 'document.pdf'), ], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); echo $response; ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/information/file_attachment') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' files = [] begin parts = [ ['event_id', '12345'], ['field_name', 'exhibitor_prospectus'], ['file', (files << File.open('document.pdf', 'rb')).last, {filename: 'document.pdf', content_type: 'application/octet-stream'}], ] request.set_form(parts, 'multipart/form-data') response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' puts response.body ensure files.each(&:close) end ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" "bytes" "mime/multipart" "net/textproto" ) func main() { var form bytes.Buffer writer := multipart.NewWriter(&form) if err := writer.WriteField("event_id", "12345"); err != nil { log.Fatal(err) } if err := writer.WriteField("field_name", "exhibitor_prospectus"); err != nil { log.Fatal(err) } header0 := textproto.MIMEHeader{} header0.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"document.pdf\"") header0.Set("Content-Type", "application/octet-stream") part0, err := writer.CreatePart(header0) if err != nil { log.Fatal(err) } file0, err := os.Open("document.pdf") if err != nil { log.Fatal(err) } if _, err = io.Copy(part0, file0); err != nil { log.Fatal(err) } file0.Close() if err := writer.Close(); err != nil { log.Fatal(err) } request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/events/information/file_attachment", &form) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", writer.FormDataContentType()) response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } fmt.Printf("%s\n", data) } ``` Example HTTP response body (JSON): PATCH /v1/events/information/file_attachment - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "field_name": "exhibitor_prospectus", "url": null, "file_attachment": { "id": 12345, "filename": "document.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } } ``` ### Remove an Event Prospectus/Floor Plan/Exhibit Rules File Attachment `DELETE https://api.exhibitday.com/v1/events/information/file_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=1#delete-v1-events-information-file_attachment Clears the selected Exhibitor Prospectus, Exhibit Hall Floor Plan or Exhibit Rules field on the Event's Info tab, removing its file or website link. Permission to edit Information and an unlocked Info tab are required. If the field is already empty, DELETE returns 404 Not Found and changes nothing. A real change updates the Event's last-update time and adds Event history. Conflicting saved files, or a simultaneous saved file and link, are refused. expected_revision is not supported. If the save cannot be confirmed, read the current field before submitting another change. A field the workspace has set to Hidden (Workspace Settings > Customize Event Information Tab) cannot be changed: the request is refused with 400 (invalid_request, error_params field_name). Make the field visible first. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | event_id | Number | Yes | The id of the Event whose Information document you would like to retrieve or change. The Event must belong to your workspace. | | | field_name | String | Yes | The Information document to retrieve or change. Use the field name exactly as shown; it is case-sensitive. | Allowed values: `exhibitor_prospectus` (Exhibitor Prospectus) \| `exhibit_hall_floor_plan` (Exhibit Hall Floor Plan) \| `exhibit_rules` (Exhibit Rules) | Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/events/information/file_attachment?event_id=12345&field_name=exhibitor_prospectus" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/information/file_attachment?" + new URLSearchParams({ "event_id": "12345", "field_name": "exhibitor_prospectus" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/events/information/file_attachment", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"event_id": 12345, "field_name": "exhibitor_prospectus"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/events/information/file_attachment?event_id=12345&field_name=exhibitor_prospectus"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/information/file_attachment?event_id=12345&field_name=exhibitor_prospectus")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/information/file_attachment?event_id=12345&field_name=exhibitor_prospectus') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/events/information/file_attachment?event_id=12345&field_name=exhibitor_prospectus", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/events/information/file_attachment - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Information document cleared.", "errors": [] } ``` ### Download an Event Prospectus/Floor Plan/Exhibit Rules File Attachment `GET https://api.exhibitday.com/v1/events/information/file_attachment/download` Documentation: https://api.exhibitday.com/Help/V1?epf=1#get-v1-events-information-file_attachment-download Downloads the original file saved in the selected Exhibitor Prospectus, Exhibit Hall Floor Plan or Exhibit Rules field on the Event's Info tab. A field containing only a website link, or an empty field, has no file to download. Reading requires current access to the Event. Use the metadata GET to read a saved website link. If this file is still being copied, the download returns HTTP 409 with file_copy_pending. Try the download again in a few minutes. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | event_id | Number | Yes | The id of the Event whose Information document you would like to retrieve or change. The Event must belong to your workspace. | | | field_name | String | Yes | The Information document to retrieve or change. Use the field name exactly as shown; it is case-sensitive. | Allowed values: `exhibitor_prospectus` (Exhibitor Prospectus) \| `exhibit_hall_floor_plan` (Exhibit Hall Floor Plan) \| `exhibit_rules` (Exhibit Rules) | Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X GET "https://api.exhibitday.com/v1/events/information/file_attachment/download?event_id=12345&field_name=exhibitor_prospectus" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi mv response-body.tmp 'document.pdf' ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const response = await fetch("https://api.exhibitday.com/v1/events/information/file_attachment/download?event_id=12345&field_name=exhibitor_prospectus", { method: "GET", headers: { Authorization: 'Bearer YOUR_API_KEY' } }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); await writeFile("document.pdf", new Uint8Array(await response.arrayBuffer())); ``` Example — Python: ```python import requests import json response = requests.request("GET", "https://api.exhibitday.com/v1/events/information/file_attachment/download?event_id=12345&field_name=exhibitor_prospectus", headers={'Authorization': 'Bearer YOUR_API_KEY'}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') with open("document.pdf", 'wb') as destination: destination.write(response.content) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.exhibitday.com/v1/events/information/file_attachment/download?event_id=12345&field_name=exhibitor_prospectus"); using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); await File.WriteAllBytesAsync("document.pdf", await response.Content.ReadAsByteArrayAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/information/file_attachment/download?event_id=12345&field_name=exhibitor_prospectus")).header("Authorization", "Bearer YOUR_API_KEY"); HttpResponse response = HttpClient.newHttpClient().send(request.method("GET", HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); Files.write(Path.of("document.pdf"), response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); file_put_contents('document.pdf', $response); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/information/file_attachment/download?event_id=12345&field_name=exhibitor_prospectus') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' File.binwrite('document.pdf', response.body) ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/information/file_attachment/download?event_id=12345&field_name=exhibitor_prospectus", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } if err := os.WriteFile("document.pdf", data, 0600); err != nil { log.Fatal(err) } fmt.Println("File saved") } ``` HTTP 200: Downloads the original uploaded file. A field containing only a link, or an empty field, has no file to download. Media: application/octet-stream. The body is the authorized file's real bytes, not JSON or base64. Errors are JSON status responses; check HTTP status before saving the file. ### Download Booth Reservation Invoice Attachment `GET https://api.exhibitday.com/v1/events/booth/invoice_attachment/download` Documentation: https://api.exhibitday.com/Help/V1?epf=1#get-v1-events-booth-invoice_attachment-download Downloads the original Invoice Attachment for this Booth Reservation. Use this method to retrieve the file itself. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | event_id | Number | Yes | The ID of the Event. | Select the Event whose Booth Reservation invoice you want to manage. | #### Finding the file In the web app, this is the invoice control beside the Booth reservation's cost and payment details on the Event's Booth tab. Each cost has one Invoice Attachment even when its amount is split among cost centers. For file metadata, retrieve the parent record with GET /v1/events/info and read booth_reservation_invoice_attachment. Use this download method for the contents. No attachment ID or invoice flag is needed. #### Download response A successful response contains the original uploaded file, with a safe download filename. API errors use the usual JSON response. If no invoice is attached, this method returns HTTP 404. Current record, financial and invoice permissions apply. A locked tab can still be read. Permitted downloads remain available on the Free plan. #### Files still being copied If this file is still being copied, the download returns HTTP 409 with file_copy_pending. Try the download again in a few minutes. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X GET "https://api.exhibitday.com/v1/events/booth/invoice_attachment/download?event_id=12345" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi mv response-body.tmp 'invoice.pdf' ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const response = await fetch("https://api.exhibitday.com/v1/events/booth/invoice_attachment/download?event_id=12345", { method: "GET", headers: { Authorization: 'Bearer YOUR_API_KEY' } }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); await writeFile("invoice.pdf", new Uint8Array(await response.arrayBuffer())); ``` Example — Python: ```python import requests import json response = requests.request("GET", "https://api.exhibitday.com/v1/events/booth/invoice_attachment/download?event_id=12345", headers={'Authorization': 'Bearer YOUR_API_KEY'}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') with open("invoice.pdf", 'wb') as destination: destination.write(response.content) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.exhibitday.com/v1/events/booth/invoice_attachment/download?event_id=12345"); using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); await File.WriteAllBytesAsync("invoice.pdf", await response.Content.ReadAsByteArrayAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/booth/invoice_attachment/download?event_id=12345")).header("Authorization", "Bearer YOUR_API_KEY"); HttpResponse response = HttpClient.newHttpClient().send(request.method("GET", HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); Files.write(Path.of("invoice.pdf"), response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); file_put_contents('invoice.pdf', $response); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/booth/invoice_attachment/download?event_id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' File.binwrite('invoice.pdf', response.body) ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/booth/invoice_attachment/download?event_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } if err := os.WriteFile("invoice.pdf", data, 0600); err != nil { log.Fatal(err) } fmt.Println("File saved") } ``` HTTP 200: Returns the original invoice as a private download, using a safe filename. If it cannot be downloaded, the response contains the usual JSON API error instead. Media: application/octet-stream. The body is the authorized file's real bytes, not JSON or base64. Errors are JSON status responses; check HTTP status before saving the file. ### Add Booth Reservation Invoice Attachment `POST https://api.exhibitday.com/v1/events/booth/invoice_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=1#post-v1-events-booth-invoice_attachment Adds one Invoice Attachment to this Booth Reservation. You can attach an invoice, receipt or other payment document when no invoice file is currently attached. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | event_id | Number | Yes | The ID of the Event. | Select the Event whose Booth Reservation invoice you want to manage. | | file | File (multipart) | Yes | The Invoice Attachment to upload. | Send exactly one complete, nonempty multipart/form-data file part named file. The supported extensions and current per-file limit are shown below; the complete request limit also includes multipart overhead. A missing or null file is invalid and does not remove an existing invoice. | | Idempotency-Key | String | No | A unique key for safely retrying this upload. | Optional HTTP header: 1 to 255 visible ASCII characters without spaces or commas. Retry the identical request with the same key to replay its first saved response. Use a new key for a different upload. | Declared schema for `file` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "string", "format": "binary", "x-maximum-bytes": 26214400, "x-allowed-extensions": [ "png", "jpg", "jpeg", "bmp", "gif", "pdf", "msg", "eml", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "rtf", "odp", "odt", "ods", "txt", "wks", "zip" ] } ``` #### Before you upload POST requires an empty invoice slot. If an invoice is already attached, the API returns HTTP 409; use PATCH to replace it. An Invoice Attachment is separate from the record's supporting File Attachments. Use the invoice control beside the Booth reservation's cost and payment details on the Event's Booth tab in the web app. #### After the upload The response's invoice_attachment contains the attached file's id, filename and attachment_created_timestamp. The amount, payment fields, cost-center breakdown and other files are unchanged. The upload is recorded in Event history. Attaching an invoice does not mark the record as paid. #### Access and retries A current upload-enabled plan, record and financial permissions, and an editable applicable tab are required. Each uploaded file must fit its supported type and size limits. expected_revision is not supported by this file method. If the save outcome cannot be confirmed, retrieve the current parent record with GET /v1/events/info and inspect booth_reservation_invoice_attachment before deciding whether to retry. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X POST "https://api.exhibitday.com/v1/events/booth/invoice_attachment" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}" --form-string "event_id=12345" --form "file=@invoice.pdf;type=application/octet-stream") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi cat response-body.tmp ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const form = new FormData(); form.append("event_id", "12345"); form.append("file", new Blob([await readFile("invoice.pdf")], { type: "application/octet-stream" }), "invoice.pdf"); const response = await fetch("https://api.exhibitday.com/v1/events/booth/invoice_attachment", { method: "POST", headers: { Authorization: 'Bearer YOUR_API_KEY' }, body: form }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); console.log(await response.json()); ``` Example — Python: ```python import requests import json from contextlib import ExitStack with ExitStack() as stack: files = [ ("file", ("invoice.pdf", stack.enter_context(open("invoice.pdf", 'rb')), "application/octet-stream")), ] response = requests.request("POST", "https://api.exhibitday.com/v1/events/booth/invoice_attachment", headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data={"event_id": "12345"}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') print(response.json()) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.exhibitday.com/v1/events/booth/invoice_attachment"); var form = new MultipartFormDataContent(); form.Add(new StringContent("12345"), "event_id"); var file0 = new StreamContent(File.OpenRead("invoice.pdf")); file0.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(file0, "file", "invoice.pdf"); request.Content = form; using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/booth/invoice_attachment")).header("Authorization", "Bearer YOUR_API_KEY"); String boundary = "ExhibitDay-" + UUID.randomUUID(); ByteArrayOutputStream form = new ByteArrayOutputStream(); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"event_id\"\r\n\r\n" + "12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"invoice.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8)); form.write(Files.readAllBytes(Path.of("invoice.pdf"))); form.write("\r\n".getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); request.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpResponse response = HttpClient.newHttpClient().send(request.method("POST", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); System.out.println(new String(response.body(), StandardCharsets.UTF_8)); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], CURLOPT_POSTFIELDS => [ 'event_id' => '12345', 'file' => new CURLFile('invoice.pdf', 'application/octet-stream', 'invoice.pdf'), ], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); echo $response; ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/booth/invoice_attachment') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' files = [] begin parts = [ ['event_id', '12345'], ['file', (files << File.open('invoice.pdf', 'rb')).last, {filename: 'invoice.pdf', content_type: 'application/octet-stream'}], ] request.set_form(parts, 'multipart/form-data') response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' puts response.body ensure files.each(&:close) end ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" "bytes" "mime/multipart" "net/textproto" ) func main() { var form bytes.Buffer writer := multipart.NewWriter(&form) if err := writer.WriteField("event_id", "12345"); err != nil { log.Fatal(err) } header0 := textproto.MIMEHeader{} header0.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"invoice.pdf\"") header0.Set("Content-Type", "application/octet-stream") part0, err := writer.CreatePart(header0) if err != nil { log.Fatal(err) } file0, err := os.Open("invoice.pdf") if err != nil { log.Fatal(err) } if _, err = io.Copy(part0, file0); err != nil { log.Fatal(err) } file0.Close() if err := writer.Close(); err != nil { log.Fatal(err) } request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/events/booth/invoice_attachment", &form) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", writer.FormDataContentType()) response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } fmt.Printf("%s\n", data) } ``` Example HTTP response body (JSON): POST /v1/events/booth/invoice_attachment - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "invoice_attachment": { "id": 12345, "filename": "invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } } ``` ### Replace Booth Reservation Invoice Attachment `PATCH https://api.exhibitday.com/v1/events/booth/invoice_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=1#patch-v1-events-booth-invoice_attachment Replaces this Booth Reservation's current Invoice Attachment with one uploaded file. Use this method when an invoice file is already attached. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | event_id | Number | Yes | The ID of the Event. | Select the Event whose Booth Reservation invoice you want to manage. | | file | File (multipart) | Yes | The Invoice Attachment to upload. | Send exactly one complete, nonempty multipart/form-data file part named file. The supported extensions and current per-file limit are shown below; the complete request limit also includes multipart overhead. A missing or null file is invalid and does not remove an existing invoice. | Declared schema for `file` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "string", "format": "binary", "x-maximum-bytes": 26214400, "x-allowed-extensions": [ "png", "jpg", "jpeg", "bmp", "gif", "pdf", "msg", "eml", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "rtf", "odp", "odt", "ods", "txt", "wks", "zip" ] } ``` #### Replacing the current file PATCH requires a current invoice file. If none is attached, the API returns HTTP 404. Upload exactly one file; the previous attachment ID is not needed. If another request changes the current invoice during your upload, the API refuses this request instead of replacing a different file. Even identical replacement contents receive a new attachment ID. #### After the replacement The response's invoice_attachment contains the attached file's id, filename and attachment_created_timestamp. The amount, payment fields, cost-center breakdown and other files are unchanged. The previous file is scheduled for physical cleanup after a confirmed save; cleanup may finish later. The replacement is recorded in Event history. #### Access and retries A current upload-enabled plan, record and financial permissions, and an editable applicable tab are required. Each uploaded file must fit its supported type and size limits. expected_revision is not supported by this file method. PATCH does not use Idempotency-Key replay. If the save outcome cannot be confirmed, retrieve the current parent record with GET /v1/events/info and inspect booth_reservation_invoice_attachment before deciding whether to retry. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X PATCH "https://api.exhibitday.com/v1/events/booth/invoice_attachment" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}" --form-string "event_id=12345" --form "file=@invoice.pdf;type=application/octet-stream") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi cat response-body.tmp ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const form = new FormData(); form.append("event_id", "12345"); form.append("file", new Blob([await readFile("invoice.pdf")], { type: "application/octet-stream" }), "invoice.pdf"); const response = await fetch("https://api.exhibitday.com/v1/events/booth/invoice_attachment", { method: "PATCH", headers: { Authorization: 'Bearer YOUR_API_KEY' }, body: form }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); console.log(await response.json()); ``` Example — Python: ```python import requests import json from contextlib import ExitStack with ExitStack() as stack: files = [ ("file", ("invoice.pdf", stack.enter_context(open("invoice.pdf", 'rb')), "application/octet-stream")), ] response = requests.request("PATCH", "https://api.exhibitday.com/v1/events/booth/invoice_attachment", headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data={"event_id": "12345"}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') print(response.json()) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("PATCH"), "https://api.exhibitday.com/v1/events/booth/invoice_attachment"); var form = new MultipartFormDataContent(); form.Add(new StringContent("12345"), "event_id"); var file0 = new StreamContent(File.OpenRead("invoice.pdf")); file0.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(file0, "file", "invoice.pdf"); request.Content = form; using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/booth/invoice_attachment")).header("Authorization", "Bearer YOUR_API_KEY"); String boundary = "ExhibitDay-" + UUID.randomUUID(); ByteArrayOutputStream form = new ByteArrayOutputStream(); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"event_id\"\r\n\r\n" + "12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"invoice.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8)); form.write(Files.readAllBytes(Path.of("invoice.pdf"))); form.write("\r\n".getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); request.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpResponse response = HttpClient.newHttpClient().send(request.method("PATCH", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); System.out.println(new String(response.body(), StandardCharsets.UTF_8)); } } ``` Example — PHP: ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], CURLOPT_POSTFIELDS => [ 'event_id' => '12345', 'file' => new CURLFile('invoice.pdf', 'application/octet-stream', 'invoice.pdf'), ], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); echo $response; ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/booth/invoice_attachment') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' files = [] begin parts = [ ['event_id', '12345'], ['file', (files << File.open('invoice.pdf', 'rb')).last, {filename: 'invoice.pdf', content_type: 'application/octet-stream'}], ] request.set_form(parts, 'multipart/form-data') response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' puts response.body ensure files.each(&:close) end ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" "bytes" "mime/multipart" "net/textproto" ) func main() { var form bytes.Buffer writer := multipart.NewWriter(&form) if err := writer.WriteField("event_id", "12345"); err != nil { log.Fatal(err) } header0 := textproto.MIMEHeader{} header0.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"invoice.pdf\"") header0.Set("Content-Type", "application/octet-stream") part0, err := writer.CreatePart(header0) if err != nil { log.Fatal(err) } file0, err := os.Open("invoice.pdf") if err != nil { log.Fatal(err) } if _, err = io.Copy(part0, file0); err != nil { log.Fatal(err) } file0.Close() if err := writer.Close(); err != nil { log.Fatal(err) } request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/events/booth/invoice_attachment", &form) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", writer.FormDataContentType()) response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } fmt.Printf("%s\n", data) } ``` Example HTTP response body (JSON): PATCH /v1/events/booth/invoice_attachment - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "invoice_attachment": { "id": 12345, "filename": "invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } } ``` ### Remove Booth Reservation Invoice Attachment `DELETE https://api.exhibitday.com/v1/events/booth/invoice_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=1#delete-v1-events-booth-invoice_attachment Removes this Booth Reservation's Invoice Attachment. The cost, payment details and other File Attachments stay in place. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | event_id | Number | Yes | The ID of the Event. | Select the Event whose Booth Reservation invoice you want to manage. | #### After the removal The Invoice Attachment is cleared and the removal is recorded in Event history. Its physical file is scheduled for cleanup after a confirmed save; cleanup may finish later. Costs, payment fields, cost-center allocations and supporting files stay unchanged. If no invoice is attached, DELETE returns HTTP 404 Not Found with the message "This Booth Reservation has no invoice to remove." No saved data or history is changed. Current access and the record's binding are still checked. Do not send file parts with this request. #### Access and retries Current record, financial and invoice permissions and applicable tab-edit access are required. Permitted removals remain available on the Free plan. expected_revision is not supported, and DELETE does not use Idempotency-Key replay. If the save outcome cannot be confirmed, retrieve the current parent record with GET /v1/events/info and inspect booth_reservation_invoice_attachment before deciding whether to retry. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/events/booth/invoice_attachment?event_id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/booth/invoice_attachment?" + new URLSearchParams({ "event_id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/events/booth/invoice_attachment", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"event_id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/events/booth/invoice_attachment?event_id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/booth/invoice_attachment?event_id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/booth/invoice_attachment?event_id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/events/booth/invoice_attachment?event_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/events/booth/invoice_attachment - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Attachment removed.", "errors": [] } ``` ## Events - Booth Services Booth Services on an Event: their details and costs, invoices, file attachments and exports. Documentation page: https://api.exhibitday.com/Help/V1?epf=1&topic=booth-services ### Retrieve a Single Booth Service by ID `GET https://api.exhibitday.com/v1/events/booth_services/info` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=booth-services#get-v1-events-booth_services-info Retrieves a Booth Service by its ID, including its reservation status, applicable service details, vendor, costs and payment information. Booth Services are arranged on the Event's Booth tab. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Booth Service. | Use the id from Retrieve Booth Services (GET /v1/events/booth_services) or from the add response. You don't send the Event ID; the record's Event is found automatically. | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` \| `object` | | $include_record_revision | Boolean | No | Whether to include record_revision in the response. | Default: false. Send true to get record_revision, then send that value as expected_revision when you update this service. See What $include_record_revision covers below. | | $on_error_return_empty_result | Boolean | No | Whether an invalid or unavailable Booth Service should return an empty result. | Default: false. True returns HTTP 200 with {} (or [] for array format) for invalid IDs or an unavailable service. API key errors, ambiguous headers, conflicts with a change in progress and unexpected errors keep their normal status. | | If-None-Match | String | No | An ETag from an earlier response to this GET. | Optional HTTP header. If the successful response is unchanged, the API returns HTTP 304 with no body. | #### What $include_record_revision covers Setting $include_record_revision=true returns record_revision for use as expected_revision on a later update. record_revision covers this service's type, reservation and payment fields, vendor, notes, all saved service details, cost allocations, related-item links and Event binding. It does not cover File Attachment or Invoice Attachment metadata or contents. #### Files and access Invoice Attachment metadata is included as invoice_attachment, or null if none is attached. Ordinary File Attachments have their own collection. The Event's Booth tab must be visible. A locked tab can still be read. #### Formatted text in the response Notes and other rich-text values in the response contain the stored HTML, including encoded characters and line breaks such as `
`. #### Open in ExhibitDay Each record includes exhibitday_url, the record's page in ExhibitDay. It opens the record in view mode on its Event's tab. Sign in with an account that can view the record; ExhibitDay checks access when the link is opened. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/events/booth_services/info?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/booth_services/info?" + new URLSearchParams({ "id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/events/booth_services/info", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/events/booth_services/info?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/booth_services/info?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/booth_services/info?id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/booth_services/info?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/events/booth_services/info - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "id": 12345, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=23456&riType=3&riSub=0&riId=12345", "event_id": 23456, "event_name": "Sample Event", "booth_service_type_id": 1, "booth_service_type": "Other", "acquisition_status_id": 1, "acquisition_status": "Need to Reserve", "description": "Illustrative service", "notes": "", "reserve_by_date": null, "order_date": null, "order_confirmation_number": "", "vendor_name": null, "vendor_point_of_contact": null, "vendor_phone": null, "vendor_email": null, "vendor_website_url": null, "payment_status_id": 0, "payment_status": { "id": 0, "name": "N/A" }, "payment_due_date": null, "next_payment_due_date": null, "payment_notes": null, "invoice_attachment": { "id": 282345, "filename": "booth-service-invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" }, "cost": { "amount": 125.50, "cost_center_breakdown": [ { "cost_center_id": 34567, "cost_center": "Marketing", "charge": 75.50 }, { "cost_center_id": 34568, "cost_center": "Operations", "charge": 50.00 } ] }, "related_items": [ { "id": 5551, "related_item_id": 67890, "related_item_exhibitday_url": "https://www.exhibitday.com/Workspace/TaskView/98765?tid=67890", "related_item_type_id": 1, "related_item_type": "Task", "related_item_asset_type_id": null, "related_item_name": "Confirm booth graphics with the printer", "related_item_created_timestamp": "2030-01-10T14:03:00Z" }, { "id": 5552, "related_item_id": 45678, "related_item_exhibitday_url": "https://www.exhibitday.com/Workspace/RelatedItemView/98765?typeId=4&subTypeId=0&rid=45678", "related_item_type_id": 4, "related_item_type": "Shipment", "related_item_asset_type_id": null, "related_item_name": "Booth crates to convention center", "related_item_created_timestamp": "2030-01-10T14:03:00Z" } ] } ``` ### Retrieve Booth Services `GET https://api.exhibitday.com/v1/events/booth_services` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=booth-services#get-v1-events-booth_services Retrieves records across your workspace's readable Event tabs. Use filter_by_event_id to narrow the results to one Event, or omit it for the workspace list. Each record includes its event_id and Event name. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | filter_by_event_id | Number | No | Return records for this Event only. Omit for all readable Events in your workspace. | | | $limit | Number | No | The most services to return, as a whole number of 1 or more. Omit it to return all remaining matching services. | | | $offset | Number | No | How many services to skip, as a whole number of 0 or more; 0 by default. | | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | | hydrate_related_items | Boolean | No | Set to true to include each record's related_items: the Tasks and items linked to it, with the key to use when adding or removing a link. Omit it or send false to leave related_items out of list results. Single-record GETs always include related_items. | Default: false. | #### Choosing Events Omit `filter_by_event_id` to retrieve records across readable Event tabs, or supply one Event ID to narrow the list. Each result retains its own `event_id` and Event name. Hidden or unavailable Event tabs are not included. A locked tab can still be read. If no records match, the response is an empty list. #### Reading pages The Event filter and any people filter are applied before the total count and paging. Results are ordered by Event start date ascending, Event ID ascending, then record ID ascending. Use `$limit` and `$offset` for successive pages. Omit `$limit` to return all remaining matches. `total_records` and `X-Total-Count` describe all matches; `records_found` counts this response. Omit `$result_format` for the normal list wrapper. `array` returns only the records; `wrapped_in_array` places the normal wrapper in a one-item array. #### Handling input and changes Unrecognized parameters are ignored and listed in the `X-API-Warnings` response header. Conflicting or malformed filter values return HTTP `400`; send arrays in JSON, query parameters or form fields rather than comma-bearing headers. Current API access is checked even when the list is empty. A concurrent change can return HTTP `409`; retrieve the list again. These filters retrieve records and do not change tags, assignments or notification settings. #### Related items Set `hydrate_related_items=true` to include each record's `related_items`: the Tasks and items linked to it. Add or remove links with POST and DELETE /v1/related_items. It is left out by default to keep lists fast. Retrieving one record always includes `related_items`. #### Formatted text in the response Notes and other rich-text values in the response contain the stored HTML, including encoded characters and line breaks such as `
`. #### Events with a hidden Booth tab Records on Events whose Booth tab is hidden are not listed. If filter_by_event_id names such an Event, the response is HTTP 200 with no records for it and a warning that names the tab and the Event. #### Open in ExhibitDay Each record includes exhibitday_url, the record's page in ExhibitDay. It opens the record in view mode on its Event's tab. Sign in with an account that can view the record; ExhibitDay checks access when the link is opened. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/events/booth_services" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/booth_services", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/events/booth_services", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/events/booth_services"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/booth_services")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/booth_services') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/booth_services", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/events/booth_services - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "booth_service", "list_data": [ { "id": 12345, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=23456&riType=3&riSub=0&riId=12345", "event_id": 23456, "event_name": "Sample Event", "booth_service_type_id": 1, "booth_service_type": "Other", "acquisition_status_id": 1, "acquisition_status": "Need to Reserve", "description": "Illustrative service", "notes": "", "reserve_by_date": null, "order_date": null, "order_confirmation_number": "", "vendor_name": null, "vendor_point_of_contact": null, "vendor_phone": null, "vendor_email": null, "vendor_website_url": null, "payment_status_id": 0, "payment_status": { "id": 0, "name": "N/A" }, "payment_due_date": null, "next_payment_due_date": null, "payment_notes": null, "invoice_attachment": { "id": 282345, "filename": "booth-service-invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" }, "cost": { "amount": 0.00, "cost_center_breakdown": [] } } ] } ``` ### Add a Booth Service `POST https://api.exhibitday.com/v1/events/booth_services` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=booth-services#post-v1-events-booth_services Adds a Booth Service to an Event's Booth tab. Choose its service type and reservation status, then supply any vendor, order or service details you want to record. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | event_id | Number | Yes | The ID of the Event. | | | booth_service_type_id | Number | Yes | The type of Booth Service. Choose an ID from this supported set that is also present in the current GET /v1/references/booth_service_types lookup; use that lookup for the current names. The selected type determines which service-detail object and members apply. Required when adding a service. | Allowed values: `1` \| `2` \| `3` \| `4` \| `5` \| `6` \| `7` \| `8` \| `9` \| `10` \| `11` \| `12` \| `13` \| `14` \| `15` \| `16` \| `17` \| `18` \| `19` \| `20` \| `21` \| `22` \| `23` \| `24` \| `25` \| `26` \| `27` | | acquisition_status_id | Number | Yes | Whether the service still needs to be reserved. Required when adding a service; blank or null is refused as missing. Order date and confirmation number apply only to Already Reserved. | Allowed values: `1` (Need to Reserve) \| `2` (Already Reserved) | | description | String | No | A description of this service. | Up to 200 characters, excluding surrounding spaces. Omit for no value. | | notes | String | No | Notes about this Booth Service. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Both the saved text and the ExhibitDay editor's character count must fit within 30,000 characters; line breaks and characters such as & and < take extra space when saved. Omit for no value. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | reserve_by_date | String | No | The date by which this service should be reserved or ordered. | Use a calendar date in YYYY-MM-DD format. This date can remain after the service is reserved. Omit for no value. | | order_date | String | No | The date the service was ordered. | Use a calendar date in YYYY-MM-DD format. Applies only to Already Reserved (2). Supplying this or another order field while the status is Need to Reserve clears the order date and confirmation number. Omit for no value. | | order_confirmation_number | String | No | The order confirmation or reference number. | Up to 200 characters, excluding surrounding spaces. Applies only to Already Reserved (2). Supplying it or another order field while the status is Need to Reserve clears both order fields. Omit for no value. | | vendor_name | String | No | The service vendor's name. | Up to 200 characters, excluding surrounding spaces. Omit for no value. | | vendor_point_of_contact | String | No | The vendor contact's name. | Up to 200 characters, excluding surrounding spaces. Omit for no value. | | vendor_phone | String | No | The vendor contact's phone number. | Up to 200 characters, excluding surrounding spaces. Omit for no value. | | vendor_email | String | No | The vendor contact's email address. | Up to 200 characters, excluding surrounding spaces. Omit for no value. | | vendor_website_url | String | No | The vendor's website or portal link. | Up to 2,000 characters, excluding surrounding spaces. Omit for no value. | | payment_status_id | Number | No | The service's payment status. Omit for N/A. A status other than Partially Paid clears the next partial payment due date. | Allowed values: `0` (N/A) \| `1` (Paid in Full) \| `2` (Partially Paid) \| `3` (Not Paid Yet) | | payment_due_date | String | No | The service payment due date. | Use a calendar date in YYYY-MM-DD format. Applies to either reservation status. Omit for no value. | | next_payment_due_date | Date | No | The next partial payment due date. | Use a calendar date in YYYY-MM-DD format. Applies only to Partially Paid (2). Supplying this date with another payment status clears it; choosing another status also clears it. Omit for no value. | | payment_notes | String | No | Notes about the service payment. | Up to 200 characters, excluding surrounding spaces. Omit for no value. | | audio_video | JSON object/list | No | The service's audio video details. | A JSON object for service type IDs 2. Each member's format, choices and limits appear in the value format below. Supply the object that applies to booth_service_type_id. Inactive families and members are not applied. Omit for no details. | | signage | JSON object/list | No | The service's signage details. | A JSON object for service type IDs 3. Each member's format, choices and limits appear in the value format below. Supply the object that applies to booth_service_type_id. Inactive families and members are not applied. Omit for no details. | | signage.artwork_status_id | integer or null | No | Artwork Approval Status. Send a JSON integer, or JSON null to clear the choice when the field applies. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused. | Allowed values: `1` (Not Submitted) \| `2` (Submitted) \| `3` (Under Review) \| `4` (Changes Requested) \| `5` (Approved) | | flooring | JSON object/list | No | The service's flooring details. | A JSON object for service type IDs 4. Each member's format, choices and limits appear in the value format below. Supply the object that applies to booth_service_type_id. Inactive families and members are not applied. Omit for no details. | | floral | JSON object/list | No | The service's floral details. | A JSON object for service type IDs 5. Each member's format, choices and limits appear in the value format below. Supply the object that applies to booth_service_type_id. Inactive families and members are not applied. Omit for no details. | | furniture | JSON object/list | No | The service's furniture details. | A JSON object for service type IDs 6. Each member's format, choices and limits appear in the value format below. Supply the object that applies to booth_service_type_id. Inactive families and members are not applied. Omit for no details. | | lead_retrieval | JSON object/list | No | The service's lead retrieval details. | A JSON object for service type IDs 7. Each member's format, choices and limits appear in the value format below. Supply the object that applies to booth_service_type_id. Inactive families and members are not applied. Omit for no details. | | utility | JSON object/list | No | The service's utility details. | A JSON object for service type IDs 8, 9, 17, 18, 26. Each member's format, choices and limits appear in the value format below. Supply the object that applies to booth_service_type_id. Inactive families and members are not applied. Omit for no details. | | material_handling | JSON object/list | No | The service's material handling details. | A JSON object for service type IDs 10. Each member's format, choices and limits appear in the value format below. Supply the object that applies to booth_service_type_id. Inactive families and members are not applied. Omit for no details. | | material_handling.freight_routing_id | integer or null | No | Inbound Freight Route. Send a JSON integer, or JSON null to clear the choice when the field applies. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused. | Allowed values: `1` (Advance Warehouse) \| `2` (Direct to Show) \| `3` (Both) \| `4` (Other) | | labor | JSON object/list | No | The service's labor details. | A JSON object for service type IDs 11, 12, 13, 14, 15, 16, 19, 21, 23. Each member's format, choices and limits appear in the value format below. Supply the object that applies to booth_service_type_id. Inactive families and members are not applied. Omit for no details. | | labor.work_phase_id | integer or null | No | Work Phase. Send a JSON integer, or JSON null to clear the choice when the field applies. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused. | Allowed values: `1` (Installation) \| `2` (Dismantle) \| `3` (Both) | | labor.approval_status_id | integer or null | No | Rigging Drawing Approval Status. Send a JSON integer, or JSON null to clear the choice when the field applies. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused. | Allowed values: `1` (Not Submitted) \| `2` (Submitted) \| `3` (Under Review) \| `4` (Changes Requested) \| `5` (Approved) | | labor.cleaning_services_required[] | array of integers or null | No | Cleaning Services Required. Send an array of JSON integers. JSON null or an empty array leaves the selection empty. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused. | Allowed values: `1` (Vacuuming) \| `2` (Trash Removal) \| `3` (Surface Cleaning) \| `4` (Porter Service) \| `5` (Other) | | meeting_space | JSON object/list | No | The service's meeting space details. | A JSON object for service type IDs 20. Each member's format, choices and limits appear in the value format below. Supply the object that applies to booth_service_type_id. Inactive families and members are not applied. Omit for no details. | | catering | JSON object/list | No | The service's catering details. | A JSON object for service type IDs 22. Each member's format, choices and limits appear in the value format below. Supply the object that applies to booth_service_type_id. Inactive families and members are not applied. Omit for no details. | | booth_structure | JSON object/list | No | The service's booth structure details. | A JSON object for service type IDs 24. Each member's format, choices and limits appear in the value format below. Supply the object that applies to booth_service_type_id. Inactive families and members are not applied. Omit for no details. | | booth_structure.exhibit_structure_type_id | integer or null | No | Exhibit / Structure Type. Send a JSON integer, or JSON null to clear the choice when the field applies. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused. | Allowed values: `1` (Turnkey Booth Package) \| `2` (Modular Rental Exhibit) \| `3` (Custom Rental Exhibit) \| `4` (Custom Fabricated Exhibit) \| `5` (Other) | | booth_structure.drawing_rendering_approval_status_id | integer or null | No | Drawing / Rendering Approval Status. Send a JSON integer, or JSON null to clear the choice when the field applies. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused. | Allowed values: `1` (Not Submitted) \| `2` (Submitted) \| `3` (Under Review) \| `4` (Changes Requested) \| `5` (Approved) | | booth_structure.installation_dismantle_coverage_id | integer or null | No | Installation / Dismantle Coverage. Send a JSON integer, or JSON null to clear the choice when the field applies. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused. | Allowed values: `1` (Not Included) \| `2` (Installation Only) \| `3` (Dismantle Only) \| `4` (Both) | | media | JSON object/list | No | The service's media details. | A JSON object for service type IDs 25. Each member's format, choices and limits appear in the value format below. Supply the object that applies to booth_service_type_id. Inactive families and members are not applied. Omit for no details. | | media.coverage_type_id | integer or null | No | Coverage Type. Send a JSON integer, or JSON null to clear the choice when the field applies. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused. | Allowed values: `1` (Photography) \| `2` (Videography) \| `3` (Photography and Videography) \| `4` (Other) | | refrigeration | JSON object/list | No | The service's refrigeration details. | A JSON object for service type IDs 27. Each member's format, choices and limits appear in the value format below. Supply the object that applies to booth_service_type_id. Inactive families and members are not applied. Omit for no details. | | cost | Number or cost object | No | The full cost, as a number or an object with amount and/or cost_center_breakdown. [Record Costs and Split Them Across Cost Centers](/Help/V1?guide=entering-costs). | Optional; defaults to zero. | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` \| `object` | | Idempotency-Key | String | No | A unique key for safely retrying this add request. | Optional HTTP header: 1 to 255 visible ASCII characters without spaces. Retry the identical request with the same key to replay its first saved response. Use a new key for a different request. | Declared schema for `audio_video` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "equipment_services_required": { "type": "string", "description": "Equipment / Services Required. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 2. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "display_screen_requirements": { "type": "string", "description": "Display / Screen Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 2. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "audio_microphone_requirements": { "type": "string", "description": "Audio / Microphone Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 2. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "playback_source_requirements": { "type": "string", "description": "Playback / Input Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 2. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "mounting_placement_requirements": { "type": "string", "description": "Mounting / Placement Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 2. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "power_connectivity_requirements": { "type": "string", "description": "Power / Network Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 2. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "setup_testing_requirements": { "type": "string", "description": "Installation / Testing Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 2. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `signage` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "sign_graphic_type": { "type": "string", "description": "Graphic / Printed Item Type. Optional text; up to 400 characters. Applies to service type 3. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "quantity": { "type": "string", "description": "Quantity. Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service type 3. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "dimensions": { "type": "string", "description": "Finished Dimensions. Optional text; up to 400 characters. Applies to service type 3. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "material_finish": { "type": "string", "description": "Material / Finish. Optional text; up to 400 characters. Applies to service type 3. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "placement_location": { "type": "string", "description": "Display / Placement Location. Optional text; up to 400 characters. Applies to service type 3. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "mounting_installation_requirements": { "type": "string", "description": "Delivery / Installation Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 3. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "artwork_specifications": { "type": "string", "description": "Artwork File Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 3. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "artwork_due_date": { "type": "string", "description": "Artwork Submission Due Date. Use YYYY-MM-DD without a time or time zone. Applies to service type 3. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "format": "date", "nullable": true }, "artwork_status_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4, 5 ], "description": "Artwork Approval Status. Send a JSON integer, or JSON null to clear the choice when the field applies. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused.\n\nAllowed values: `1` (Not Submitted) | `2` (Submitted) | `3` (Under Review) | `4` (Changes Requested) | `5` (Approved)", "nullable": true }, "delivery_installation_due_date": { "type": "string", "description": "Delivery / Installation Due Date. Use YYYY-MM-DD without a time or time zone. Applies to service type 3. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "format": "date", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `flooring` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "flooring_type": { "type": "string", "description": "Flooring Type. Optional text; up to 400 characters. Applies to service type 4. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "color_finish": { "type": "string", "description": "Color / Finish. Optional text; up to 400 characters. Applies to service type 4. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "area_dimensions": { "type": "string", "description": "Flooring Area / Dimensions. Optional text; up to 400 characters. Applies to service type 4. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "padding_required": { "type": "boolean", "description": "Padding Required. Use true, false or JSON null for Not Specified. Applies to service type 4. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "edge_transition_requirements": { "type": "string", "description": "Edge / Transition Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 4. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "installation_requirements": { "type": "string", "description": "Installation Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 4. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "removal_requirements": { "type": "string", "description": "Removal Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 4. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `floral` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "arrangement_decor_type": { "type": "string", "description": "Arrangement / Decor Type. Optional text; up to 400 characters. Applies to service type 5. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "quantity": { "type": "string", "description": "Quantity. Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service type 5. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "color_theme": { "type": "string", "description": "Color / Theme. Optional text; up to 400 characters. Applies to service type 5. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "placement": { "type": "string", "description": "Placement. Optional text; up to 400 characters. Applies to service type 5. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "container_planter_requirements": { "type": "string", "description": "Container / Planter Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 5. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "refresh_maintenance_requirements": { "type": "string", "description": "Refresh / Maintenance Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 5. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "removal_pickup_requirements": { "type": "string", "description": "Removal / Pickup Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 5. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `furniture` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "furniture_items_required": { "type": "string", "description": "Furniture / Items Needed. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 6. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "dimensions_size": { "type": "string", "description": "Size / Dimensions. Optional text; up to 400 characters. Applies to service type 6. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "color_finish": { "type": "string", "description": "Color / Finish. Optional text; up to 400 characters. Applies to service type 6. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "placement_area": { "type": "string", "description": "Placement Location. Optional text; up to 400 characters. Applies to service type 6. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "assembly_placement_requirements": { "type": "string", "description": "Assembly / Placement Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 6. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "return_pickup_requirements": { "type": "string", "description": "Return / Pickup Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 6. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `lead_retrieval` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "provider_platform": { "type": "string", "description": "Platform / System. Optional text; up to 400 characters. Applies to service type 7. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "device_license_type": { "type": "string", "description": "Device / License Type. Optional text; up to 400 characters. Applies to service type 7. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "number_of_devices_licenses": { "type": "string", "description": "Number of Devices / Licenses. Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service type 7. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "pickup_delivery_method": { "type": "string", "description": "Device Delivery / Pickup Method. Optional text; up to 400 characters. Applies to service type 7. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "training_requirements": { "type": "string", "description": "Training Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 7. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "data_export_integration_requirements": { "type": "string", "description": "Data Export / Integration Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 7. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "return_required": { "type": "boolean", "description": "Device Return Required. Use true, false or JSON null for Not Specified. Applies to service type 7. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "return_deadline": { "type": "string", "description": "Device Return Deadline. Use YYYY-MM-DD without a time or time zone. Applies to service type 7. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. This field applies only when return_required is true; saving its controlling choice otherwise clears it.", "format": "date", "nullable": true }, "return_drop_off_instructions": { "type": "string", "description": "Device Return / Drop-off Instructions. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 7. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. This field applies only when return_required is true; saving its controlling choice otherwise clears it.", "nullable": true }, "app_access_instructions": { "type": "string", "description": "App / Access Instructions. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 7. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `utility` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "quantity": { "type": "string", "description": "Number of Outlets / Power Drops. Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service type 8. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "service_location": { "type": "string", "description": "Power Connection Location(s). Optional text; up to 400 characters. Applies to service types 8, 9, 17, 18, 26. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "installation_requirements": { "type": "string", "description": "Power Drop / Installation Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service types 8, 9, 17, 18, 26. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "equipment_served": { "type": "string", "description": "Equipment Being Powered. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service types 8, 9, 17, 18, 26. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "service_outlet_type": { "type": "string", "description": "Service / Outlet Type. Optional text; up to 400 characters. Applies to service type 8. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "voltage": { "type": "string", "description": "Voltage (V). Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service type 8. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "amperage": { "type": "string", "description": "Amperage (A). Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service type 8. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "distribution_power_requirements": { "type": "string", "description": "Power Distribution Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 8. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "water_service_type": { "type": "string", "description": "Water Service Type. Optional text; up to 400 characters. Applies to service type 9. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "supply_required": { "type": "boolean", "description": "Water Supply Required. Use true, false or JSON null for Not Specified. Applies to service type 9. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "drain_required": { "type": "boolean", "description": "Drain Connection Required. Use true, false or JSON null for Not Specified. Applies to service type 9. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "connection_type": { "type": "string", "description": "Connection Type. Optional text; up to 400 characters. Applies to service type 18. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "number_of_connections": { "type": "string", "description": "Number of Water / Drain Connections. Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service types 9, 17, 18, 26. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "bandwidth_requirement": { "type": "string", "description": "Bandwidth / Speed Requirement. Optional text; up to 400 characters. Applies to service type 18. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "dedicated_connection_required": { "type": "boolean", "description": "Dedicated Connection Required. Use true, false or JSON null for Not Specified. Applies to service type 18. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "static_ip_required": { "type": "boolean", "description": "Static IP Required. Use true, false or JSON null for Not Specified. Applies to service type 18. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "public_ip_required": { "type": "boolean", "description": "Public IP Required. Use true, false or JSON null for Not Specified. Applies to service type 18. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "utility_requirements": { "type": "string", "description": "Utility Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 17. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "supply_connection_requirements": { "type": "string", "description": "Water Supply Connection Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 9. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. This field applies only when supply_required is true; saving its controlling choice otherwise clears it.", "nullable": true }, "drain_connection_requirements": { "type": "string", "description": "Drain Connection Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 9. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. This field applies only when drain_required is true; saving its controlling choice otherwise clears it.", "nullable": true }, "pressure_flow_requirements": { "type": "string", "description": "Pressure / Flow Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 9. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. This field applies only when supply_required is true; saving its controlling choice otherwise clears it.", "nullable": true }, "utility_type": { "type": "string", "description": "Utility Type. Optional text; up to 400 characters. Applies to service type 17. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "twenty_four_hour_power_required": { "type": "boolean", "description": "24-Hour Power Required. Use true, false or JSON null for Not Specified. Applies to service type 8. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "required_air_pressure": { "type": "string", "description": "Required Air Pressure. Optional text; up to 300 characters. Applies to service type 26. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "required_airflow": { "type": "string", "description": "Required Airflow. Optional text; up to 300 characters. Applies to service type 26. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "air_supply_requirements": { "type": "string", "description": "Air Supply Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 26. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "service_power_rating": { "type": "string", "description": "Service Power Rating (W / kW). Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service type 8. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "air_connection_size_type": { "type": "string", "description": "Connection Size / Type. Optional text; up to 300 characters. Applies to service type 26. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `material_handling` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "material_freight_description": { "type": "string", "description": "Material / Freight Description. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 10. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "number_of_pieces": { "type": "string", "description": "Number of Pieces. Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service type 10. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "estimated_weight": { "type": "string", "description": "Estimated Total Weight. Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service type 10. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "freight_handling_classification": { "type": "string", "description": "Freight Packaging / Handling Category. Optional text; up to 400 characters. Applies to service type 10. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "freight_routing_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4 ], "description": "Inbound Freight Route. Send a JSON integer, or JSON null to clear the choice when the field applies. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused.\n\nAllowed values: `1` (Advance Warehouse) | `2` (Direct to Show) | `3` (Both) | `4` (Other)", "nullable": true }, "empty_container_storage_required": { "type": "boolean", "description": "Empty Container Storage Required. Use true, false or JSON null for Not Specified. Applies to service type 10. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "return_handling_required": { "type": "boolean", "description": "Outbound Handling Required. Use true, false or JSON null for Not Specified. Applies to service type 10. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "special_equipment_handling_requirements": { "type": "string", "description": "Special Equipment / Handling Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 10. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "storage_retrieval_requirements": { "type": "string", "description": "Storage / Retrieval Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 10. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `labor` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "scope_of_work": { "type": "string", "description": "Scope of Work. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service types 11, 12, 13, 14, 15, 16, 19, 21. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "crew_size": { "type": "string", "description": "Vendor Crew Size. Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service types 11, 12, 14, 15, 16, 19, 21, 23. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "estimated_labor_hours": { "type": "string", "description": "Estimated Total Labor Hours. Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service types 11, 12, 14, 15, 16, 19, 21, 23. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "work_area": { "type": "string", "description": "Work Area. Optional text; up to 400 characters. Applies to service types 11, 12, 13, 14, 15, 16, 19, 21, 23. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "skill_classification_requirements": { "type": "string", "description": "Required Trade / Skills. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service types 11, 13, 15, 16, 19, 23. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "tools_equipment_requirements": { "type": "string", "description": "Tools / Equipment Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service types 11, 12, 13, 15, 16, 19, 21, 23. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "special_instructions": { "type": "string", "description": "Additional Vendor Instructions. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service types 11, 12, 13, 14, 15, 16, 19, 21, 23. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "work_phase_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3 ], "description": "Work Phase. Send a JSON integer, or JSON null to clear the choice when the field applies. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused.\n\nAllowed values: `1` (Installation) | `2` (Dismantle) | `3` (Both)", "nullable": true }, "booth_components_materials": { "type": "string", "description": "Booth Components / Materials Involved. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 11. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "specialty_discipline": { "type": "string", "description": "Specialty / Discipline. Optional text; up to 400 characters. Applies to service type 12. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "required_credentials": { "type": "string", "description": "Required Credentials / Certifications. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 12. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "forklift_type_capacity": { "type": "string", "description": "Forklift Type / Capacity. Optional text; up to 400 characters. Applies to service type 13. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "operator_included": { "type": "boolean", "description": "Operator Included. Use true, false or JSON null for Not Specified. Applies to service type 13. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "lift_material_description": { "type": "string", "description": "Items / Materials to Be Lifted. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 13. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "pickup_placement_requirements": { "type": "string", "description": "Pickup / Placement Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 13. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "service_frequency": { "type": "string", "description": "Cleaning Frequency. Optional text; up to 400 characters. Applies to service type 14. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "transportation_type": { "type": "string", "description": "Transport Method. Optional text; up to 400 characters. Applies to service type 15. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "people_materials_transported": { "type": "string", "description": "Materials / Equipment Being Transported. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 15. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "vehicle_capacity_requirements": { "type": "string", "description": "Transport Equipment / Capacity Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 15. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "pickup_drop_off_requirements": { "type": "string", "description": "Pickup / Drop-off Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 15. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "security_service_type": { "type": "string", "description": "Security Service Type. Optional text; up to 400 characters. Applies to service type 16. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "access_coverage_requirements": { "type": "string", "description": "Access / Coverage Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 16. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "role_function": { "type": "string", "description": "Staff Role(s). Optional text; up to 400 characters. Applies to service type 21. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "skills_qualifications": { "type": "string", "description": "Skills / Qualifications. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 21. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "language_requirements": { "type": "string", "description": "Language Requirements. Optional text; up to 400 characters. Applies to service type 21. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "dress_uniform_requirements": { "type": "string", "description": "Dress / Uniform Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 21. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "training_briefing_requirements": { "type": "string", "description": "Training / Briefing Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 21. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "rigging_scope": { "type": "string", "description": "Rigging Scope. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 23. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "suspended_item_structure": { "type": "string", "description": "Suspended Item / Structure. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 23. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "number_of_rigging_points": { "type": "string", "description": "Number of Rigging Points. Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service type 23. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "height": { "type": "string", "description": "Required Hanging Height. Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service type 23. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "motor_hoist_requirements": { "type": "string", "description": "Motor / Hoist Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 23. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "engineering_drawing_required": { "type": "boolean", "description": "Engineering / Rigging Drawing Required. Use true, false or JSON null for Not Specified. Applies to service type 23. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "drawing_due_date": { "type": "string", "description": "Drawing Due Date. Use YYYY-MM-DD without a time or time zone. Applies to service type 23. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. This field applies only when engineering_drawing_required is true; saving its controlling choice otherwise clears it.", "format": "date", "nullable": true }, "approval_status_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4, 5 ], "description": "Rigging Drawing Approval Status. Send a JSON integer, or JSON null to clear the choice when the field applies. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused.\n\nAllowed values: `1` (Not Submitted) | `2` (Submitted) | `3` (Under Review) | `4` (Changes Requested) | `5` (Approved)", "nullable": true }, "cleaning_services_required": { "type": "array", "items": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4, 5 ] }, "maxItems": 2147483647, "description": "Cleaning Services Required. Send an array of JSON integers. JSON null or an empty array leaves the selection empty. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused.\n\nAllowed values: `1` (Vacuuming) | `2` (Trash Removal) | `3` (Surface Cleaning) | `4` (Porter Service) | `5` (Other)", "nullable": true }, "forklift_service_hours": { "type": "string", "description": "Estimated Forklift Service Hours. Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service type 13. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "heaviest_load_weight": { "type": "string", "description": "Heaviest Load Weight. Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service type 13. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "total_suspended_weight": { "type": "string", "description": "Estimated Total Suspended Weight. Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service type 23. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `meeting_space` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "room_space_name": { "type": "string", "description": "Room / Space Name. Optional text; up to 400 characters. Applies to service type 20. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "capacity": { "type": "string", "description": "Room Capacity. Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service type 20. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "room_setup_seating_arrangement": { "type": "string", "description": "Room Setup / Seating Arrangement. Optional text; up to 400 characters. Applies to service type 20. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "access_credential_requirements": { "type": "string", "description": "Access / Credential Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 20. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "signage_requirements": { "type": "string", "description": "Room Signage Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 20. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "other_space_requirements": { "type": "string", "description": "Other Space Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 20. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "room_space_location": { "type": "string", "description": "Room / Space Location. Optional text; up to 400 characters. Applies to service type 20. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "av_included": { "type": "boolean", "description": "A/V Included. Use true, false or JSON null for Not Specified. Applies to service type 20. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "internet_included": { "type": "boolean", "description": "Internet Included. Use true, false or JSON null for Not Specified. Applies to service type 20. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "catering_included": { "type": "boolean", "description": "Catering Included. Use true, false or JSON null for Not Specified. Applies to service type 20. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "included_services_amenities_details": { "type": "string", "description": "Included Services / Amenities Details. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 20. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `catering` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "service_meal_period": { "type": "string", "description": "Meal / Service Type. Optional text; up to 400 characters. Applies to service type 22. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "food_beverage_menu_requirements": { "type": "string", "description": "Food / Beverage / Menu Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 22. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "expected_guest_count": { "type": "string", "description": "Number of People to Serve. Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service type 22. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "service_style": { "type": "string", "description": "Service Style. Optional text; up to 400 characters. Applies to service type 22. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "dietary_allergy_requirements": { "type": "string", "description": "Dietary / Allergy Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 22. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "serving_supplies_requirements": { "type": "string", "description": "Serving Supplies Needed. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 22. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "equipment_requirements": { "type": "string", "description": "Equipment Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 22. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "utility_requirements": { "type": "string", "description": "Utility Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 22. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "service_area_placement": { "type": "string", "description": "Serving / Setup Location. Optional text; up to 400 characters. Applies to service type 22. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "replenishment_service_requirements": { "type": "string", "description": "Vendor Replenishment / Cleanup Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 22. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "service_staff_requirements": { "type": "string", "description": "Vendor Service Staff Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 22. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `booth_structure` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "exhibit_structure_type_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4, 5 ], "description": "Exhibit / Structure Type. Send a JSON integer, or JSON null to clear the choice when the field applies. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused.\n\nAllowed values: `1` (Turnkey Booth Package) | `2` (Modular Rental Exhibit) | `3` (Custom Rental Exhibit) | `4` (Custom Fabricated Exhibit) | `5` (Other)", "nullable": true }, "booth_size_footprint": { "type": "string", "description": "Exhibit Footprint / Dimensions. Optional text; up to 400 characters. Applies to service type 24. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "structure_components": { "type": "string", "description": "Structural Components Supplied. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 24. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "configuration_layout_requirements": { "type": "string", "description": "Layout Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 24. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "height_structural_requirements": { "type": "string", "description": "Height / Structural Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 24. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "graphics_included": { "type": "boolean", "description": "Graphics Included. Use true, false or JSON null for Not Specified. Applies to service type 24. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "flooring_included": { "type": "boolean", "description": "Flooring Included. Use true, false or JSON null for Not Specified. Applies to service type 24. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "furniture_included": { "type": "boolean", "description": "Furniture Included. Use true, false or JSON null for Not Specified. Applies to service type 24. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "included_components_services": { "type": "string", "description": "Included Items / Services. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 24. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "drawing_rendering_required": { "type": "boolean", "description": "Drawing / Rendering Required. Use true, false or JSON null for Not Specified. Applies to service type 24. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "drawing_rendering_due_date": { "type": "string", "description": "Drawing / Rendering Due Date. Use YYYY-MM-DD without a time or time zone. Applies to service type 24. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. This field applies only when drawing_rendering_required is true; saving its controlling choice otherwise clears it.", "format": "date", "nullable": true }, "drawing_rendering_approval_status_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4, 5 ], "description": "Drawing / Rendering Approval Status. Send a JSON integer, or JSON null to clear the choice when the field applies. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused.\n\nAllowed values: `1` (Not Submitted) | `2` (Submitted) | `3` (Under Review) | `4` (Changes Requested) | `5` (Approved)", "nullable": true }, "other_structure_requirements": { "type": "string", "description": "Additional Structure Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 24. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "installation_dismantle_coverage_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4 ], "description": "Installation / Dismantle Coverage. Send a JSON integer, or JSON null to clear the choice when the field applies. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused.\n\nAllowed values: `1` (Not Included) | `2` (Installation Only) | `3` (Dismantle Only) | `4` (Both)", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `media` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "coverage_type_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4 ], "description": "Coverage Type. Send a JSON integer, or JSON null to clear the choice when the field applies. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused.\n\nAllowed values: `1` (Photography) | `2` (Videography) | `3` (Photography and Videography) | `4` (Other)", "nullable": true }, "coverage_scope_requirements": { "type": "string", "description": "Coverage Scope / Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 25. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "shot_list_key_moments": { "type": "string", "description": "Subjects / Shot List / Key Moments. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 25. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "estimated_coverage_hours": { "type": "number", "description": "Estimated Coverage Hours. Use a nonnegative number up to 9,999,999.99 with at most two decimal places. Applies to service type 25. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "deliverables": { "type": "string", "description": "Deliverables. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 25. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "editing_post_production_requirements": { "type": "string", "description": "Editing / Post-Production Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 25. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "delivery_format_resolution": { "type": "string", "description": "Delivery Format / Resolution. Optional text; up to 400 characters. Applies to service type 25. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "delivery_due_date": { "type": "string", "description": "Media Delivery Due Date. Use YYYY-MM-DD without a time or time zone. Applies to service type 25. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "format": "date", "nullable": true }, "usage_licensing_requirements": { "type": "string", "description": "Usage / Licensing Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 25. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "special_instructions": { "type": "string", "description": "Special Instructions. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 25. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `refrigeration` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "equipment_items_required": { "type": "string", "description": "Equipment / Items Required. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 27. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "capacity_dimension_requirements": { "type": "string", "description": "Capacity / Dimension Requirements. Optional text; up to 400 characters. Applies to service type 27. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "temperature_requirements": { "type": "string", "description": "Temperature Requirements. Optional text; up to 400 characters. Applies to service type 27. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "power_requirements": { "type": "string", "description": "Power Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 27. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "water_drain_requirements": { "type": "string", "description": "Water / Drain Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 27. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "placement_installation_requirements": { "type": "string", "description": "Placement / Installation Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 27. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "delivery_pickup_requirements": { "type": "string", "description": "Delivery / Pickup Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 27. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true }, "return_cleaning_requirements": { "type": "string", "description": "Return / Cleaning Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 27. JSON null or an empty string leaves an applicable text field empty. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `cost` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "anyOf": [ { "type": "number", "minimum": 0, "description": "Shorthand for an object with amount. The amount is rounded to cents before the supported storage range is checked.", "nullable": true }, { "type": "object", "additionalProperties": false, "properties": { "amount": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 }, "cost_center_breakdown": { "type": "array", "items": { "type": "object", "additionalProperties": false, "properties": { "cost_center_id": { "type": "integer", "format": "int64", "nullable": true }, "charge": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 }, "cost_center": { "type": "string", "description": "Optional and read-only: the cost center name a read returns, so a cost can be sent back unchanged. It is ignored; the line is saved by cost_center_id, and a name that doesn't match that cost center is explained in a warning.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "required": [ "charge" ] }, "maxItems": 2147483647 } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "anyOf": [ { "required": [ "amount" ] }, { "required": [ "cost_center_breakdown" ] } ], "nullable": true } ], "x-numeric-shorthand": "A number is equivalent to {amount:number}.", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": { "amount": 125.50 } } ``` #### Choosing the service and its details Choose booth_service_type_id from GET /v1/references/booth_service_types, then supply its applicable detail object. For example, a furniture order uses furniture details; a catering order uses catering details. Use Booth Services for the orders and services you arrange. Use the Playbook for scheduled activities and their progress. #### After the add The response includes the new service and its id. The change is added to Event history. This operation sends no vendor or assignment email. Files and the Invoice Attachment are uploaded through separate file operations. Recording costs does not attach an invoice, mark a payment complete or change the planned Booth Services budget. #### Access The Event's Booth tab must be visible and unlocked, and you need permission to update it. #### If the save cannot be confirmed Retrieve the Booth Services before deciding whether to retry. The API does not automatically repeat an unconfirmed save. #### Sending values Use JSON, a form field or a query parameter for text containing commas, detail objects, cost lists and related-item lists. #### Sending text Send plain text for Notes and other rich-text fields. Characters such as `&`, `<` and quotes, along with line breaks, are encoded for storage. Notes and other rich-text values in the response contain the stored HTML, including encoded characters and line breaks such as `
`. #### Hidden or locked tab If the Event's Booth tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. An Event that is not in your workspace returns HTTP 404. #### Detail groups for each service type Each detail group applies only to some service types. A group sent for a different booth_service_type_id is not saved, and the response includes a warning that names the group and the type. - audio_video: booth_service_type_id 2 - signage: booth_service_type_id 3 - flooring: booth_service_type_id 4 - floral: booth_service_type_id 5 - furniture: booth_service_type_id 6 - lead_retrieval: booth_service_type_id 7 - material_handling: booth_service_type_id 10 - utility: booth_service_type_id 8, 9, 17, 18, 26 - labor: booth_service_type_id 11, 12, 13, 14, 15, 16, 19, 21, 23 - meeting_space: booth_service_type_id 20 - catering: booth_service_type_id 22 - booth_structure: booth_service_type_id 24 - media: booth_service_type_id 25 - refrigeration: booth_service_type_id 27 #### Open in ExhibitDay The created record includes exhibitday_url, the record's page in ExhibitDay. It is the same link that GET /v1/events/booth_services/info returns for this record and opens the record in view mode on its Event's tab. Sign in with an account that can view the record; ExhibitDay checks access when the link is opened. Example — curl: ```bash curl -X POST "https://api.exhibitday.com/v1/events/booth_services" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"event_id\":12345,\"booth_service_type_id\":1,\"acquisition_status_id\":1}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/booth_services", { method: "POST", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "event_id": 12345, "booth_service_type_id": 1, "acquisition_status_id": 1 }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.post( "https://api.exhibitday.com/v1/events/booth_services", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"event_id": 12345, "booth_service_type_id": 1, "acquisition_status_id": 1}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PostAsync("https://api.exhibitday.com/v1/events/booth_services", JsonContent.Create(new { event_id = 12345, booth_service_type_id = 1, acquisition_status_id = 1 })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/booth_services")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("POST", HttpRequest.BodyPublishers.ofString("{\"event_id\":12345,\"booth_service_type_id\":1,\"acquisition_status_id\":1}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"event_id":12345,"booth_service_type_id":1,"acquisition_status_id":1}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/booth_services') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"event_id":12345,"booth_service_type_id":1,"acquisition_status_id":1}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/events/booth_services", strings.NewReader("{\"event_id\":12345,\"booth_service_type_id\":1,\"acquisition_status_id\":1}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): POST /v1/events/booth_services - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "id": 12345, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=12345&riType=3&riSub=0&riId=12345", "event_id": 12345, "event_name": "Sample Event", "booth_service_type_id": 1, "booth_service_type": "Other", "acquisition_status_id": 1, "acquisition_status": "Need to Reserve", "description": "Illustrative service", "notes": "", "reserve_by_date": null, "order_date": null, "order_confirmation_number": "", "vendor_name": null, "vendor_point_of_contact": null, "vendor_phone": null, "vendor_email": null, "vendor_website_url": null, "payment_status_id": 0, "payment_status": { "id": 0, "name": "N/A" }, "payment_due_date": null, "next_payment_due_date": null, "payment_notes": null, "invoice_attachment": null, "cost": { "amount": 0.00, "cost_center_breakdown": [] } } ``` ### Update a Booth Service `PATCH https://api.exhibitday.com/v1/events/booth_services` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=booth-services#patch-v1-events-booth_services Updates a Booth Service on an Event's Booth tab. Send only the fields or detail members you want to change, such as its reservation status, vendor or payment information. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Booth Service. | Use the service's id from its list, add or single-record response. | | booth_service_type_id | Number | No | The type of Booth Service. Choose an ID from this supported set that is also present in the current GET /v1/references/booth_service_types lookup; use that lookup for the current names. The selected type determines which service-detail object and members apply. Omit or leave blank to keep it; `null` cannot clear it. | Allowed values: `1` \| `2` \| `3` \| `4` \| `5` \| `6` \| `7` \| `8` \| `9` \| `10` \| `11` \| `12` \| `13` \| `14` \| `15` \| `16` \| `17` \| `18` \| `19` \| `20` \| `21` \| `22` \| `23` \| `24` \| `25` \| `26` \| `27` | | acquisition_status_id | Number | No | Whether the service still needs to be reserved. Omit or leave blank to keep it; null cannot clear it. Choosing Need to Reserve clears the order date and confirmation number. | Allowed values: `1` (Need to Reserve) \| `2` (Already Reserved) | | description | String | No | A description of this service. | Up to 200 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. | | notes | String | No | Notes about this Booth Service. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Both the saved text and the ExhibitDay editor's character count must fit within 30,000 characters; line breaks and characters such as & and < take extra space when saved. Omit or leave blank to keep it; null clears it. Existing over-limit notes may stay unchanged or be shortened, but neither count may grow. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | reserve_by_date | String | No | The date by which this service should be reserved or ordered. | Use a calendar date in YYYY-MM-DD format. This date can remain after the service is reserved. Omit or leave blank to keep it; null clears it. | | order_date | String | No | The date the service was ordered. | Use a calendar date in YYYY-MM-DD format. Applies only to Already Reserved (2). Supplying this or another order field while the status is Need to Reserve clears the order date and confirmation number. Omit or leave blank to keep it; null clears it. | | order_confirmation_number | String | No | The order confirmation or reference number. | Up to 200 characters, excluding surrounding spaces. Applies only to Already Reserved (2). Supplying it or another order field while the status is Need to Reserve clears both order fields. Omit or leave blank to keep it; null clears it. | | vendor_name | String | No | The service vendor's name. | Up to 200 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. | | vendor_point_of_contact | String | No | The vendor contact's name. | Up to 200 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. | | vendor_phone | String | No | The vendor contact's phone number. | Up to 200 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. | | vendor_email | String | No | The vendor contact's email address. | Up to 200 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. | | vendor_website_url | String | No | The vendor's website or portal link. | Up to 2,000 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. | | payment_status_id | Number | No | The service's payment status. Omit or leave blank to keep it; null resets it to N/A. A status other than Partially Paid clears the next partial payment due date. | Allowed values: `0` (N/A) \| `1` (Paid in Full) \| `2` (Partially Paid) \| `3` (Not Paid Yet) | | payment_due_date | String | No | The service payment due date. | Use a calendar date in YYYY-MM-DD format. Applies to either reservation status. Omit or leave blank to keep it; null clears it. | | next_payment_due_date | Date | No | The next partial payment due date. | Use a calendar date in YYYY-MM-DD format. Applies only to Partially Paid (2). Supplying this date with another payment status clears it; choosing another status also clears it. Omit or leave blank to keep it; null clears it. | | payment_notes | String | No | Notes about the service payment. | Up to 200 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. | | audio_video | JSON object/list | No | The service's audio video details. | A JSON object for service type IDs 2. Each member's format, choices and limits appear in the value format below. Omitted members keep their values. An empty object changes no members; null clears the details offered by the selected type. Details for other families or Labor subtypes are retained. See Changing service details below. | | signage | JSON object/list | No | The service's signage details. | A JSON object for service type IDs 3. Each member's format, choices and limits appear in the value format below. Omitted members keep their values. An empty object changes no members; null clears the details offered by the selected type. Details for other families or Labor subtypes are retained. See Changing service details below. | | signage.artwork_status_id | integer or null | No | Artwork Approval Status. Send a JSON integer, or JSON null to clear the choice when the field applies. Omit this member on PATCH to keep its value, subject to changes to its controlling fields. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused. | Allowed values: `1` (Not Submitted) \| `2` (Submitted) \| `3` (Under Review) \| `4` (Changes Requested) \| `5` (Approved) | | flooring | JSON object/list | No | The service's flooring details. | A JSON object for service type IDs 4. Each member's format, choices and limits appear in the value format below. Omitted members keep their values. An empty object changes no members; null clears the details offered by the selected type. Details for other families or Labor subtypes are retained. See Changing service details below. | | floral | JSON object/list | No | The service's floral details. | A JSON object for service type IDs 5. Each member's format, choices and limits appear in the value format below. Omitted members keep their values. An empty object changes no members; null clears the details offered by the selected type. Details for other families or Labor subtypes are retained. See Changing service details below. | | furniture | JSON object/list | No | The service's furniture details. | A JSON object for service type IDs 6. Each member's format, choices and limits appear in the value format below. Omitted members keep their values. An empty object changes no members; null clears the details offered by the selected type. Details for other families or Labor subtypes are retained. See Changing service details below. | | lead_retrieval | JSON object/list | No | The service's lead retrieval details. | A JSON object for service type IDs 7. Each member's format, choices and limits appear in the value format below. Omitted members keep their values. An empty object changes no members; null clears the details offered by the selected type. Details for other families or Labor subtypes are retained. See Changing service details below. | | utility | JSON object/list | No | The service's utility details. | A JSON object for service type IDs 8, 9, 17, 18, 26. Each member's format, choices and limits appear in the value format below. Omitted members keep their values. An empty object changes no members; null clears the details offered by the selected type. Details for other families or Labor subtypes are retained. See Changing service details below. | | material_handling | JSON object/list | No | The service's material handling details. | A JSON object for service type IDs 10. Each member's format, choices and limits appear in the value format below. Omitted members keep their values. An empty object changes no members; null clears the details offered by the selected type. Details for other families or Labor subtypes are retained. See Changing service details below. | | material_handling.freight_routing_id | integer or null | No | Inbound Freight Route. Send a JSON integer, or JSON null to clear the choice when the field applies. Omit this member on PATCH to keep its value, subject to changes to its controlling fields. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused. | Allowed values: `1` (Advance Warehouse) \| `2` (Direct to Show) \| `3` (Both) \| `4` (Other) | | labor | JSON object/list | No | The service's labor details. | A JSON object for service type IDs 11, 12, 13, 14, 15, 16, 19, 21, 23. Each member's format, choices and limits appear in the value format below. Omitted members keep their values. An empty object changes no members; null clears the details offered by the selected type. Details for other families or Labor subtypes are retained. See Changing service details below. | | labor.work_phase_id | integer or null | No | Work Phase. Send a JSON integer, or JSON null to clear the choice when the field applies. Omit this member on PATCH to keep its value, subject to changes to its controlling fields. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused. | Allowed values: `1` (Installation) \| `2` (Dismantle) \| `3` (Both) | | labor.approval_status_id | integer or null | No | Rigging Drawing Approval Status. Send a JSON integer, or JSON null to clear the choice when the field applies. Omit this member on PATCH to keep its value, subject to changes to its controlling fields. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused. | Allowed values: `1` (Not Submitted) \| `2` (Submitted) \| `3` (Under Review) \| `4` (Changes Requested) \| `5` (Approved) | | labor.cleaning_services_required[] | array of integers or null | No | Cleaning Services Required. Send an array of JSON integers. Omit this member on PATCH to keep the saved selection; JSON null or an empty array removes the selection when the field applies. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused. | Allowed values: `1` (Vacuuming) \| `2` (Trash Removal) \| `3` (Surface Cleaning) \| `4` (Porter Service) \| `5` (Other) | | meeting_space | JSON object/list | No | The service's meeting space details. | A JSON object for service type IDs 20. Each member's format, choices and limits appear in the value format below. Omitted members keep their values. An empty object changes no members; null clears the details offered by the selected type. Details for other families or Labor subtypes are retained. See Changing service details below. | | catering | JSON object/list | No | The service's catering details. | A JSON object for service type IDs 22. Each member's format, choices and limits appear in the value format below. Omitted members keep their values. An empty object changes no members; null clears the details offered by the selected type. Details for other families or Labor subtypes are retained. See Changing service details below. | | booth_structure | JSON object/list | No | The service's booth structure details. | A JSON object for service type IDs 24. Each member's format, choices and limits appear in the value format below. Omitted members keep their values. An empty object changes no members; null clears the details offered by the selected type. Details for other families or Labor subtypes are retained. See Changing service details below. | | booth_structure.exhibit_structure_type_id | integer or null | No | Exhibit / Structure Type. Send a JSON integer, or JSON null to clear the choice when the field applies. Omit this member on PATCH to keep its value, subject to changes to its controlling fields. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused. | Allowed values: `1` (Turnkey Booth Package) \| `2` (Modular Rental Exhibit) \| `3` (Custom Rental Exhibit) \| `4` (Custom Fabricated Exhibit) \| `5` (Other) | | booth_structure.drawing_rendering_approval_status_id | integer or null | No | Drawing / Rendering Approval Status. Send a JSON integer, or JSON null to clear the choice when the field applies. Omit this member on PATCH to keep its value, subject to changes to its controlling fields. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused. | Allowed values: `1` (Not Submitted) \| `2` (Submitted) \| `3` (Under Review) \| `4` (Changes Requested) \| `5` (Approved) | | booth_structure.installation_dismantle_coverage_id | integer or null | No | Installation / Dismantle Coverage. Send a JSON integer, or JSON null to clear the choice when the field applies. Omit this member on PATCH to keep its value, subject to changes to its controlling fields. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused. | Allowed values: `1` (Not Included) \| `2` (Installation Only) \| `3` (Dismantle Only) \| `4` (Both) | | media | JSON object/list | No | The service's media details. | A JSON object for service type IDs 25. Each member's format, choices and limits appear in the value format below. Omitted members keep their values. An empty object changes no members; null clears the details offered by the selected type. Details for other families or Labor subtypes are retained. See Changing service details below. | | media.coverage_type_id | integer or null | No | Coverage Type. Send a JSON integer, or JSON null to clear the choice when the field applies. Omit this member on PATCH to keep its value, subject to changes to its controlling fields. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused. | Allowed values: `1` (Photography) \| `2` (Videography) \| `3` (Photography and Videography) \| `4` (Other) | | refrigeration | JSON object/list | No | The service's refrigeration details. | A JSON object for service type IDs 27. Each member's format, choices and limits appear in the value format below. Omitted members keep their values. An empty object changes no members; null clears the details offered by the selected type. Details for other families or Labor subtypes are retained. See Changing service details below. | | cost | Number or cost object | No | The full cost, as a number or an object with amount and/or cost_center_breakdown. [Record Costs and Split Them Across Cost Centers](/Help/V1?guide=entering-costs). | Omit to keep the saved cost. A supplied value replaces its full allocation. | | expected_revision | String | No | The record_revision from an earlier read of this Booth Service. | Optional. Obtain it from GET /v1/events/booth_services/info with $include_record_revision=true. A changed service returns HTTP 409 without saving this update. Omission skips the check; blank, null and malformed values are refused. | | $ignore_params_with_empty_values | Boolean | No | Whether empty supplied values should leave their current values unchanged. | Default: false. With true, whole JSON nulls are ignored; empty strings and JSON null members inside detail objects are also ignored. The text null at the top level still requests clearing where supported. Inside a detail object, the text null is ordinary text. | Declared schema for `audio_video` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "equipment_services_required": { "type": "string", "description": "Equipment / Services Required. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 2. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "display_screen_requirements": { "type": "string", "description": "Display / Screen Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 2. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "audio_microphone_requirements": { "type": "string", "description": "Audio / Microphone Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 2. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "playback_source_requirements": { "type": "string", "description": "Playback / Input Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 2. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "mounting_placement_requirements": { "type": "string", "description": "Mounting / Placement Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 2. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "power_connectivity_requirements": { "type": "string", "description": "Power / Network Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 2. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "setup_testing_requirements": { "type": "string", "description": "Installation / Testing Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 2. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `signage` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "sign_graphic_type": { "type": "string", "description": "Graphic / Printed Item Type. Optional text; up to 400 characters. Applies to service type 3. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "quantity": { "type": "string", "description": "Quantity. Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service type 3. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "dimensions": { "type": "string", "description": "Finished Dimensions. Optional text; up to 400 characters. Applies to service type 3. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "material_finish": { "type": "string", "description": "Material / Finish. Optional text; up to 400 characters. Applies to service type 3. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "placement_location": { "type": "string", "description": "Display / Placement Location. Optional text; up to 400 characters. Applies to service type 3. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "mounting_installation_requirements": { "type": "string", "description": "Delivery / Installation Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 3. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "artwork_specifications": { "type": "string", "description": "Artwork File Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 3. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "artwork_due_date": { "type": "string", "description": "Artwork Submission Due Date. Use YYYY-MM-DD without a time or time zone. Applies to service type 3. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "format": "date", "nullable": true }, "artwork_status_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4, 5 ], "description": "Artwork Approval Status. Send a JSON integer, or JSON null to clear the choice when the field applies. Omit this member on PATCH to keep its value, subject to changes to its controlling fields. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused.\n\nAllowed values: `1` (Not Submitted) | `2` (Submitted) | `3` (Under Review) | `4` (Changes Requested) | `5` (Approved)", "nullable": true }, "delivery_installation_due_date": { "type": "string", "description": "Delivery / Installation Due Date. Use YYYY-MM-DD without a time or time zone. Applies to service type 3. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "format": "date", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `flooring` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "flooring_type": { "type": "string", "description": "Flooring Type. Optional text; up to 400 characters. Applies to service type 4. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "color_finish": { "type": "string", "description": "Color / Finish. Optional text; up to 400 characters. Applies to service type 4. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "area_dimensions": { "type": "string", "description": "Flooring Area / Dimensions. Optional text; up to 400 characters. Applies to service type 4. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "padding_required": { "type": "boolean", "description": "Padding Required. Use true, false or JSON null for Not Specified. Applies to service type 4. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "edge_transition_requirements": { "type": "string", "description": "Edge / Transition Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 4. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "installation_requirements": { "type": "string", "description": "Installation Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 4. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "removal_requirements": { "type": "string", "description": "Removal Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 4. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `floral` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "arrangement_decor_type": { "type": "string", "description": "Arrangement / Decor Type. Optional text; up to 400 characters. Applies to service type 5. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "quantity": { "type": "string", "description": "Quantity. Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service type 5. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "color_theme": { "type": "string", "description": "Color / Theme. Optional text; up to 400 characters. Applies to service type 5. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "placement": { "type": "string", "description": "Placement. Optional text; up to 400 characters. Applies to service type 5. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "container_planter_requirements": { "type": "string", "description": "Container / Planter Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 5. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "refresh_maintenance_requirements": { "type": "string", "description": "Refresh / Maintenance Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 5. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "removal_pickup_requirements": { "type": "string", "description": "Removal / Pickup Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 5. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `furniture` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "furniture_items_required": { "type": "string", "description": "Furniture / Items Needed. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 6. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "dimensions_size": { "type": "string", "description": "Size / Dimensions. Optional text; up to 400 characters. Applies to service type 6. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "color_finish": { "type": "string", "description": "Color / Finish. Optional text; up to 400 characters. Applies to service type 6. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "placement_area": { "type": "string", "description": "Placement Location. Optional text; up to 400 characters. Applies to service type 6. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "assembly_placement_requirements": { "type": "string", "description": "Assembly / Placement Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 6. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "return_pickup_requirements": { "type": "string", "description": "Return / Pickup Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 6. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `lead_retrieval` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "provider_platform": { "type": "string", "description": "Platform / System. Optional text; up to 400 characters. Applies to service type 7. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "device_license_type": { "type": "string", "description": "Device / License Type. Optional text; up to 400 characters. Applies to service type 7. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "number_of_devices_licenses": { "type": "string", "description": "Number of Devices / Licenses. Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service type 7. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "pickup_delivery_method": { "type": "string", "description": "Device Delivery / Pickup Method. Optional text; up to 400 characters. Applies to service type 7. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "training_requirements": { "type": "string", "description": "Training Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 7. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "data_export_integration_requirements": { "type": "string", "description": "Data Export / Integration Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 7. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "return_required": { "type": "boolean", "description": "Device Return Required. Use true, false or JSON null for Not Specified. Applies to service type 7. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "return_deadline": { "type": "string", "description": "Device Return Deadline. Use YYYY-MM-DD without a time or time zone. Applies to service type 7. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values. This field applies only when return_required is true; saving its controlling choice otherwise clears it.", "format": "date", "nullable": true }, "return_drop_off_instructions": { "type": "string", "description": "Device Return / Drop-off Instructions. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 7. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values. This field applies only when return_required is true; saving its controlling choice otherwise clears it.", "nullable": true }, "app_access_instructions": { "type": "string", "description": "App / Access Instructions. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 7. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `utility` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "quantity": { "type": "string", "description": "Number of Outlets / Power Drops. Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service type 8. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "service_location": { "type": "string", "description": "Power Connection Location(s). Optional text; up to 400 characters. Applies to service types 8, 9, 17, 18, 26. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "installation_requirements": { "type": "string", "description": "Power Drop / Installation Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service types 8, 9, 17, 18, 26. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "equipment_served": { "type": "string", "description": "Equipment Being Powered. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service types 8, 9, 17, 18, 26. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "service_outlet_type": { "type": "string", "description": "Service / Outlet Type. Optional text; up to 400 characters. Applies to service type 8. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "voltage": { "type": "string", "description": "Voltage (V). Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service type 8. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "amperage": { "type": "string", "description": "Amperage (A). Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service type 8. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "distribution_power_requirements": { "type": "string", "description": "Power Distribution Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 8. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "water_service_type": { "type": "string", "description": "Water Service Type. Optional text; up to 400 characters. Applies to service type 9. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "supply_required": { "type": "boolean", "description": "Water Supply Required. Use true, false or JSON null for Not Specified. Applies to service type 9. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "drain_required": { "type": "boolean", "description": "Drain Connection Required. Use true, false or JSON null for Not Specified. Applies to service type 9. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "connection_type": { "type": "string", "description": "Connection Type. Optional text; up to 400 characters. Applies to service type 18. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "number_of_connections": { "type": "string", "description": "Number of Water / Drain Connections. Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service types 9, 17, 18, 26. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "bandwidth_requirement": { "type": "string", "description": "Bandwidth / Speed Requirement. Optional text; up to 400 characters. Applies to service type 18. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "dedicated_connection_required": { "type": "boolean", "description": "Dedicated Connection Required. Use true, false or JSON null for Not Specified. Applies to service type 18. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "static_ip_required": { "type": "boolean", "description": "Static IP Required. Use true, false or JSON null for Not Specified. Applies to service type 18. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "public_ip_required": { "type": "boolean", "description": "Public IP Required. Use true, false or JSON null for Not Specified. Applies to service type 18. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "utility_requirements": { "type": "string", "description": "Utility Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 17. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "supply_connection_requirements": { "type": "string", "description": "Water Supply Connection Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 9. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values. This field applies only when supply_required is true; saving its controlling choice otherwise clears it.", "nullable": true }, "drain_connection_requirements": { "type": "string", "description": "Drain Connection Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 9. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values. This field applies only when drain_required is true; saving its controlling choice otherwise clears it.", "nullable": true }, "pressure_flow_requirements": { "type": "string", "description": "Pressure / Flow Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 9. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values. This field applies only when supply_required is true; saving its controlling choice otherwise clears it.", "nullable": true }, "utility_type": { "type": "string", "description": "Utility Type. Optional text; up to 400 characters. Applies to service type 17. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "twenty_four_hour_power_required": { "type": "boolean", "description": "24-Hour Power Required. Use true, false or JSON null for Not Specified. Applies to service type 8. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "required_air_pressure": { "type": "string", "description": "Required Air Pressure. Optional text; up to 300 characters. Applies to service type 26. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "required_airflow": { "type": "string", "description": "Required Airflow. Optional text; up to 300 characters. Applies to service type 26. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "air_supply_requirements": { "type": "string", "description": "Air Supply Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 26. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "service_power_rating": { "type": "string", "description": "Service Power Rating (W / kW). Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service type 8. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "air_connection_size_type": { "type": "string", "description": "Connection Size / Type. Optional text; up to 300 characters. Applies to service type 26. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `material_handling` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "material_freight_description": { "type": "string", "description": "Material / Freight Description. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 10. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "number_of_pieces": { "type": "string", "description": "Number of Pieces. Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service type 10. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "estimated_weight": { "type": "string", "description": "Estimated Total Weight. Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service type 10. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "freight_handling_classification": { "type": "string", "description": "Freight Packaging / Handling Category. Optional text; up to 400 characters. Applies to service type 10. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "freight_routing_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4 ], "description": "Inbound Freight Route. Send a JSON integer, or JSON null to clear the choice when the field applies. Omit this member on PATCH to keep its value, subject to changes to its controlling fields. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused.\n\nAllowed values: `1` (Advance Warehouse) | `2` (Direct to Show) | `3` (Both) | `4` (Other)", "nullable": true }, "empty_container_storage_required": { "type": "boolean", "description": "Empty Container Storage Required. Use true, false or JSON null for Not Specified. Applies to service type 10. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "return_handling_required": { "type": "boolean", "description": "Outbound Handling Required. Use true, false or JSON null for Not Specified. Applies to service type 10. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "special_equipment_handling_requirements": { "type": "string", "description": "Special Equipment / Handling Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 10. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "storage_retrieval_requirements": { "type": "string", "description": "Storage / Retrieval Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 10. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `labor` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "scope_of_work": { "type": "string", "description": "Scope of Work. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service types 11, 12, 13, 14, 15, 16, 19, 21. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "crew_size": { "type": "string", "description": "Vendor Crew Size. Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service types 11, 12, 14, 15, 16, 19, 21, 23. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "estimated_labor_hours": { "type": "string", "description": "Estimated Total Labor Hours. Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service types 11, 12, 14, 15, 16, 19, 21, 23. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "work_area": { "type": "string", "description": "Work Area. Optional text; up to 400 characters. Applies to service types 11, 12, 13, 14, 15, 16, 19, 21, 23. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "skill_classification_requirements": { "type": "string", "description": "Required Trade / Skills. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service types 11, 13, 15, 16, 19, 23. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "tools_equipment_requirements": { "type": "string", "description": "Tools / Equipment Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service types 11, 12, 13, 15, 16, 19, 21, 23. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "special_instructions": { "type": "string", "description": "Additional Vendor Instructions. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service types 11, 12, 13, 14, 15, 16, 19, 21, 23. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "work_phase_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3 ], "description": "Work Phase. Send a JSON integer, or JSON null to clear the choice when the field applies. Omit this member on PATCH to keep its value, subject to changes to its controlling fields. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused.\n\nAllowed values: `1` (Installation) | `2` (Dismantle) | `3` (Both)", "nullable": true }, "booth_components_materials": { "type": "string", "description": "Booth Components / Materials Involved. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 11. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "specialty_discipline": { "type": "string", "description": "Specialty / Discipline. Optional text; up to 400 characters. Applies to service type 12. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "required_credentials": { "type": "string", "description": "Required Credentials / Certifications. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 12. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "forklift_type_capacity": { "type": "string", "description": "Forklift Type / Capacity. Optional text; up to 400 characters. Applies to service type 13. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "operator_included": { "type": "boolean", "description": "Operator Included. Use true, false or JSON null for Not Specified. Applies to service type 13. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "lift_material_description": { "type": "string", "description": "Items / Materials to Be Lifted. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 13. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "pickup_placement_requirements": { "type": "string", "description": "Pickup / Placement Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 13. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "service_frequency": { "type": "string", "description": "Cleaning Frequency. Optional text; up to 400 characters. Applies to service type 14. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "transportation_type": { "type": "string", "description": "Transport Method. Optional text; up to 400 characters. Applies to service type 15. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "people_materials_transported": { "type": "string", "description": "Materials / Equipment Being Transported. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 15. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "vehicle_capacity_requirements": { "type": "string", "description": "Transport Equipment / Capacity Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 15. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "pickup_drop_off_requirements": { "type": "string", "description": "Pickup / Drop-off Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 15. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "security_service_type": { "type": "string", "description": "Security Service Type. Optional text; up to 400 characters. Applies to service type 16. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "access_coverage_requirements": { "type": "string", "description": "Access / Coverage Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 16. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "role_function": { "type": "string", "description": "Staff Role(s). Optional text; up to 400 characters. Applies to service type 21. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "skills_qualifications": { "type": "string", "description": "Skills / Qualifications. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 21. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "language_requirements": { "type": "string", "description": "Language Requirements. Optional text; up to 400 characters. Applies to service type 21. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "dress_uniform_requirements": { "type": "string", "description": "Dress / Uniform Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 21. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "training_briefing_requirements": { "type": "string", "description": "Training / Briefing Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 21. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "rigging_scope": { "type": "string", "description": "Rigging Scope. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 23. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "suspended_item_structure": { "type": "string", "description": "Suspended Item / Structure. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 23. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "number_of_rigging_points": { "type": "string", "description": "Number of Rigging Points. Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service type 23. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "height": { "type": "string", "description": "Required Hanging Height. Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service type 23. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "motor_hoist_requirements": { "type": "string", "description": "Motor / Hoist Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 23. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "engineering_drawing_required": { "type": "boolean", "description": "Engineering / Rigging Drawing Required. Use true, false or JSON null for Not Specified. Applies to service type 23. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "drawing_due_date": { "type": "string", "description": "Drawing Due Date. Use YYYY-MM-DD without a time or time zone. Applies to service type 23. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values. This field applies only when engineering_drawing_required is true; saving its controlling choice otherwise clears it.", "format": "date", "nullable": true }, "approval_status_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4, 5 ], "description": "Rigging Drawing Approval Status. Send a JSON integer, or JSON null to clear the choice when the field applies. Omit this member on PATCH to keep its value, subject to changes to its controlling fields. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused.\n\nAllowed values: `1` (Not Submitted) | `2` (Submitted) | `3` (Under Review) | `4` (Changes Requested) | `5` (Approved)", "nullable": true }, "cleaning_services_required": { "type": "array", "items": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4, 5 ] }, "maxItems": 2147483647, "description": "Cleaning Services Required. Send an array of JSON integers. Omit this member on PATCH to keep the saved selection; JSON null or an empty array removes the selection when the field applies. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused.\n\nAllowed values: `1` (Vacuuming) | `2` (Trash Removal) | `3` (Surface Cleaning) | `4` (Porter Service) | `5` (Other)", "nullable": true }, "forklift_service_hours": { "type": "string", "description": "Estimated Forklift Service Hours. Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service type 13. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "heaviest_load_weight": { "type": "string", "description": "Heaviest Load Weight. Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service type 13. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "total_suspended_weight": { "type": "string", "description": "Estimated Total Suspended Weight. Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service type 23. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `meeting_space` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "room_space_name": { "type": "string", "description": "Room / Space Name. Optional text; up to 400 characters. Applies to service type 20. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "capacity": { "type": "string", "description": "Room Capacity. Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service type 20. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "room_setup_seating_arrangement": { "type": "string", "description": "Room Setup / Seating Arrangement. Optional text; up to 400 characters. Applies to service type 20. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "access_credential_requirements": { "type": "string", "description": "Access / Credential Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 20. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "signage_requirements": { "type": "string", "description": "Room Signage Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 20. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "other_space_requirements": { "type": "string", "description": "Other Space Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 20. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "room_space_location": { "type": "string", "description": "Room / Space Location. Optional text; up to 400 characters. Applies to service type 20. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "av_included": { "type": "boolean", "description": "A/V Included. Use true, false or JSON null for Not Specified. Applies to service type 20. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "internet_included": { "type": "boolean", "description": "Internet Included. Use true, false or JSON null for Not Specified. Applies to service type 20. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "catering_included": { "type": "boolean", "description": "Catering Included. Use true, false or JSON null for Not Specified. Applies to service type 20. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "included_services_amenities_details": { "type": "string", "description": "Included Services / Amenities Details. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 20. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `catering` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "service_meal_period": { "type": "string", "description": "Meal / Service Type. Optional text; up to 400 characters. Applies to service type 22. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "food_beverage_menu_requirements": { "type": "string", "description": "Food / Beverage / Menu Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 22. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "expected_guest_count": { "type": "string", "description": "Number of People to Serve. Free-text quantity, such as 2-3 or Approx. 500; up to 150 characters. Applies to service type 22. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "service_style": { "type": "string", "description": "Service Style. Optional text; up to 400 characters. Applies to service type 22. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "dietary_allergy_requirements": { "type": "string", "description": "Dietary / Allergy Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 22. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "serving_supplies_requirements": { "type": "string", "description": "Serving Supplies Needed. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 22. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "equipment_requirements": { "type": "string", "description": "Equipment Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 22. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "utility_requirements": { "type": "string", "description": "Utility Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 22. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "service_area_placement": { "type": "string", "description": "Serving / Setup Location. Optional text; up to 400 characters. Applies to service type 22. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "replenishment_service_requirements": { "type": "string", "description": "Vendor Replenishment / Cleanup Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 22. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "service_staff_requirements": { "type": "string", "description": "Vendor Service Staff Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 22. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `booth_structure` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "exhibit_structure_type_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4, 5 ], "description": "Exhibit / Structure Type. Send a JSON integer, or JSON null to clear the choice when the field applies. Omit this member on PATCH to keep its value, subject to changes to its controlling fields. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused.\n\nAllowed values: `1` (Turnkey Booth Package) | `2` (Modular Rental Exhibit) | `3` (Custom Rental Exhibit) | `4` (Custom Fabricated Exhibit) | `5` (Other)", "nullable": true }, "booth_size_footprint": { "type": "string", "description": "Exhibit Footprint / Dimensions. Optional text; up to 400 characters. Applies to service type 24. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "structure_components": { "type": "string", "description": "Structural Components Supplied. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 24. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "configuration_layout_requirements": { "type": "string", "description": "Layout Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 24. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "height_structural_requirements": { "type": "string", "description": "Height / Structural Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 24. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "graphics_included": { "type": "boolean", "description": "Graphics Included. Use true, false or JSON null for Not Specified. Applies to service type 24. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "flooring_included": { "type": "boolean", "description": "Flooring Included. Use true, false or JSON null for Not Specified. Applies to service type 24. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "furniture_included": { "type": "boolean", "description": "Furniture Included. Use true, false or JSON null for Not Specified. Applies to service type 24. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "included_components_services": { "type": "string", "description": "Included Items / Services. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 24. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "drawing_rendering_required": { "type": "boolean", "description": "Drawing / Rendering Required. Use true, false or JSON null for Not Specified. Applies to service type 24. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "drawing_rendering_due_date": { "type": "string", "description": "Drawing / Rendering Due Date. Use YYYY-MM-DD without a time or time zone. Applies to service type 24. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values. This field applies only when drawing_rendering_required is true; saving its controlling choice otherwise clears it.", "format": "date", "nullable": true }, "drawing_rendering_approval_status_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4, 5 ], "description": "Drawing / Rendering Approval Status. Send a JSON integer, or JSON null to clear the choice when the field applies. Omit this member on PATCH to keep its value, subject to changes to its controlling fields. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused.\n\nAllowed values: `1` (Not Submitted) | `2` (Submitted) | `3` (Under Review) | `4` (Changes Requested) | `5` (Approved)", "nullable": true }, "other_structure_requirements": { "type": "string", "description": "Additional Structure Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 24. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "installation_dismantle_coverage_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4 ], "description": "Installation / Dismantle Coverage. Send a JSON integer, or JSON null to clear the choice when the field applies. Omit this member on PATCH to keep its value, subject to changes to its controlling fields. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused.\n\nAllowed values: `1` (Not Included) | `2` (Installation Only) | `3` (Dismantle Only) | `4` (Both)", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `media` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "coverage_type_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4 ], "description": "Coverage Type. Send a JSON integer, or JSON null to clear the choice when the field applies. Omit this member on PATCH to keep its value, subject to changes to its controlling fields. The service type and its controlling choices determine whether the field is used. With $ignore_params_with_empty_values=true, a JSON null member is ignored. Quoted values and empty strings are refused.\n\nAllowed values: `1` (Photography) | `2` (Videography) | `3` (Photography and Videography) | `4` (Other)", "nullable": true }, "coverage_scope_requirements": { "type": "string", "description": "Coverage Scope / Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 25. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "shot_list_key_moments": { "type": "string", "description": "Subjects / Shot List / Key Moments. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 25. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "estimated_coverage_hours": { "type": "number", "description": "Estimated Coverage Hours. Use a nonnegative number up to 9,999,999.99 with at most two decimal places. Applies to service type 25. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "deliverables": { "type": "string", "description": "Deliverables. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 25. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "editing_post_production_requirements": { "type": "string", "description": "Editing / Post-Production Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 25. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "delivery_format_resolution": { "type": "string", "description": "Delivery Format / Resolution. Optional text; up to 400 characters. Applies to service type 25. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "delivery_due_date": { "type": "string", "description": "Media Delivery Due Date. Use YYYY-MM-DD without a time or time zone. Applies to service type 25. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "format": "date", "nullable": true }, "usage_licensing_requirements": { "type": "string", "description": "Usage / Licensing Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 25. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "special_instructions": { "type": "string", "description": "Special Instructions. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 25. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `refrigeration` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "equipment_items_required": { "type": "string", "description": "Equipment / Items Required. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 27. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "capacity_dimension_requirements": { "type": "string", "description": "Capacity / Dimension Requirements. Optional text; up to 400 characters. Applies to service type 27. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "temperature_requirements": { "type": "string", "description": "Temperature Requirements. Optional text; up to 400 characters. Applies to service type 27. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "power_requirements": { "type": "string", "description": "Power Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 27. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "water_drain_requirements": { "type": "string", "description": "Water / Drain Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 27. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "placement_installation_requirements": { "type": "string", "description": "Placement / Installation Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 27. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "delivery_pickup_requirements": { "type": "string", "description": "Delivery / Pickup Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 27. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true }, "return_cleaning_requirements": { "type": "string", "description": "Return / Cleaning Requirements. Optional plain text with line breaks. Both saved text and its ExhibitDay editor count must fit within 30,000 characters, including formatting. Existing over-limit text may be kept or shortened, but cannot grow. Applies to service type 27. Omit this member to keep it on PATCH; JSON null or an empty string clears an applicable text field. With $ignore_params_with_empty_values=true, empty strings and JSON null members are ignored. The text \"null\" inside a detail object is ordinary text. Inapplicable members keep their stored values.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `cost` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "anyOf": [ { "type": "number", "minimum": 0, "description": "Shorthand for an object with amount. The amount is rounded to cents before the supported storage range is checked.", "nullable": true }, { "type": "object", "additionalProperties": false, "properties": { "amount": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 }, "cost_center_breakdown": { "type": "array", "items": { "type": "object", "additionalProperties": false, "properties": { "cost_center_id": { "type": "integer", "format": "int64", "nullable": true }, "charge": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 }, "cost_center": { "type": "string", "description": "Optional and read-only: the cost center name a read returns, so a cost can be sent back unchanged. It is ignored; the line is saved by cost_center_id, and a name that doesn't match that cost center is explained in a warning.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "required": [ "charge" ] }, "maxItems": 2147483647 } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "anyOf": [ { "required": [ "amount" ] }, { "required": [ "cost_center_breakdown" ] } ], "nullable": true } ], "x-numeric-shorthand": "A number is equivalent to {amount:number}.", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": { "amount": 125.50 } } ``` #### Choosing what to change Omitted or blank top-level fields stay unchanged. Send null to clear supported fields; booth_service_type_id and acquisition_status_id cannot be cleared. Payment status resets to N/A when cleared. An unchanged request saves no business data, invoice caption or history and keeps its revision. A real service-type change updates its existing Invoice Attachment caption to the current type without replacing the file. Other File Attachments are managed separately. #### Changing service details Send only the members you want to change in the applicable detail object. JSON null clears an applicable member; an empty string clears an applicable text value. An unanswered yes/no is different from false. The text null inside the object is ordinary text. Changing a controlling choice can clear dependent fields that no longer apply. Changing the service type retains earlier families and other Labor subtype details for a later switch back. Clearing a whole detail object affects only the members offered by the selected type. #### Using expected_revision 1. Retrieve this service with GET /v1/events/booth_services/info and $include_record_revision=true. 2. Send the returned record_revision unchanged as expected_revision with this update. 3. If the API reports that the service changed, read its current values and decide what to update. #### Access The Event's Booth tab must be visible and unlocked, and you need permission to update it. #### After the update A real change is added to Event history. This operation sends no vendor or assignment email. If the save outcome cannot be confirmed, retrieve the service before deciding whether to retry. #### Sending values Use JSON, a form field or a query parameter for text containing commas, detail objects, cost lists and related-item lists. #### Sending text Send plain text for Notes and other rich-text fields. Characters such as `&`, `<` and quotes, along with line breaks, are encoded for storage. #### Hidden or locked tab If the Event's Booth tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. An Event that is not in your workspace returns HTTP 404. #### Detail groups for each service type Each detail group applies only to some service types. A group sent for a different booth_service_type_id is not saved, and the response includes a warning that names the group and the type. - audio_video: booth_service_type_id 2 - signage: booth_service_type_id 3 - flooring: booth_service_type_id 4 - floral: booth_service_type_id 5 - furniture: booth_service_type_id 6 - lead_retrieval: booth_service_type_id 7 - material_handling: booth_service_type_id 10 - utility: booth_service_type_id 8, 9, 17, 18, 26 - labor: booth_service_type_id 11, 12, 13, 14, 15, 16, 19, 21, 23 - meeting_space: booth_service_type_id 20 - catering: booth_service_type_id 22 - booth_structure: booth_service_type_id 24 - media: booth_service_type_id 25 - refrigeration: booth_service_type_id 27 Example — curl: ```bash curl -X PATCH "https://api.exhibitday.com/v1/events/booth_services" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"id\":12345,\"description\":\"Updated description\"}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/booth_services", { method: "PATCH", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "id": 12345, "description": "Updated description" }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.patch( "https://api.exhibitday.com/v1/events/booth_services", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"id": 12345, "description": "Updated description"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PatchAsync("https://api.exhibitday.com/v1/events/booth_services", JsonContent.Create(new { id = 12345, description = "Updated description" })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/booth_services")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("PATCH", HttpRequest.BodyPublishers.ofString("{\"id\":12345,\"description\":\"Updated description\"}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"id":12345,"description":"Updated description"}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/booth_services') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"id":12345,"description":"Updated description"}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/events/booth_services", strings.NewReader("{\"id\":12345,\"description\":\"Updated description\"}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): PATCH /v1/events/booth_services - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Booth Service updated.", "errors": [] } ``` ### Delete a Booth Service `DELETE https://api.exhibitday.com/v1/events/booth_services` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=booth-services#delete-v1-events-booth_services Deletes a Booth Service and its saved service details, costs, related-item links, File Attachments and Invoice Attachment. Linked Tasks, Playbook activities and other related records remain in place. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Booth Service. | Use the service's id from its list, add or single-record response. | #### After the deletion The service, all its saved detail families, costs, related-item links and attachment records are removed together. Only its files are scheduled for physical cleanup after the save. Linked records remain. The deletion is recorded in Event history and sends no vendor or assignment email. An unavailable service returns HTTP 404. If the save outcome cannot be confirmed, retrieve the current services before deciding whether to retry. #### Access The Event's Booth tab must be visible and unlocked, and you need permission to update it. #### Hidden or locked tab If the Event's Booth tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. An Event that is not in your workspace returns HTTP 404. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/events/booth_services?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/booth_services?" + new URLSearchParams({ "id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/events/booth_services", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/events/booth_services?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/booth_services?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/booth_services?id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/events/booth_services?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/events/booth_services - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Booth Service removed.", "errors": [] } ``` ### Download Booth Service Invoice Attachment `GET https://api.exhibitday.com/v1/events/booth_services/invoice_attachment/download` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=booth-services#get-v1-events-booth_services-invoice_attachment-download Downloads the original Invoice Attachment for this Booth Service. Use this method to retrieve the file itself. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | booth_service_id | Number | Yes | The ID of the Booth Service, from Retrieve Booth Services (GET /v1/events/booth_services) or its add response. | | #### Finding the file In the web app, this is the invoice control beside the Booth Service's cost and payment details on the Event's Booth tab. Each cost has one Invoice Attachment even when its amount is split among cost centers. For file metadata, retrieve the parent record with GET /v1/events/booth_services/info and read invoice_attachment. Use this download method for the contents. No attachment ID or invoice flag is needed. #### Download response A successful response contains the original uploaded file, with a safe download filename. API errors use the usual JSON response. If no invoice is attached, this method returns HTTP 404. Current record, financial and invoice permissions apply. A locked tab can still be read. Permitted downloads remain available on the Free plan. #### Files still being copied If this file is still being copied, the download returns HTTP 409 with file_copy_pending. Try the download again in a few minutes. #### Hidden tab If the Event's Booth tab is hidden, this request returns HTTP 400 (not_allowed), and the message says the tab is hidden. Show the tab in ExhibitDay first. A locked tab can still be read. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X GET "https://api.exhibitday.com/v1/events/booth_services/invoice_attachment/download?booth_service_id=12345" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi mv response-body.tmp 'invoice.pdf' ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const response = await fetch("https://api.exhibitday.com/v1/events/booth_services/invoice_attachment/download?booth_service_id=12345", { method: "GET", headers: { Authorization: 'Bearer YOUR_API_KEY' } }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); await writeFile("invoice.pdf", new Uint8Array(await response.arrayBuffer())); ``` Example — Python: ```python import requests import json response = requests.request("GET", "https://api.exhibitday.com/v1/events/booth_services/invoice_attachment/download?booth_service_id=12345", headers={'Authorization': 'Bearer YOUR_API_KEY'}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') with open("invoice.pdf", 'wb') as destination: destination.write(response.content) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.exhibitday.com/v1/events/booth_services/invoice_attachment/download?booth_service_id=12345"); using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); await File.WriteAllBytesAsync("invoice.pdf", await response.Content.ReadAsByteArrayAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/booth_services/invoice_attachment/download?booth_service_id=12345")).header("Authorization", "Bearer YOUR_API_KEY"); HttpResponse response = HttpClient.newHttpClient().send(request.method("GET", HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); Files.write(Path.of("invoice.pdf"), response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); file_put_contents('invoice.pdf', $response); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/booth_services/invoice_attachment/download?booth_service_id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' File.binwrite('invoice.pdf', response.body) ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/booth_services/invoice_attachment/download?booth_service_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } if err := os.WriteFile("invoice.pdf", data, 0600); err != nil { log.Fatal(err) } fmt.Println("File saved") } ``` HTTP 200: Returns the original uploaded file as a private download, using a safe filename. A download failure returns the usual JSON API error. Media: application/octet-stream. The body is the authorized file's real bytes, not JSON or base64. Errors are JSON status responses; check HTTP status before saving the file. ### Add Booth Service Invoice Attachment `POST https://api.exhibitday.com/v1/events/booth_services/invoice_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=booth-services#post-v1-events-booth_services-invoice_attachment Adds one Invoice Attachment to this Booth Service. You can attach an invoice, receipt or other payment document when no invoice file is currently attached. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | booth_service_id | Number | Yes | The ID of the Booth Service, from Retrieve Booth Services (GET /v1/events/booth_services) or its add response. | | | file | File (multipart) | Yes | The Invoice Attachment to upload. | Send exactly one complete, nonempty multipart/form-data file part named file. The supported extensions and current per-file limit are shown below; the complete request limit also includes multipart overhead. A missing or null file is invalid and does not remove an existing invoice. | | Idempotency-Key | String | No | A unique key for safely retrying this upload. | Optional HTTP header: 1 to 255 visible ASCII characters without spaces or commas. Retry the identical request with the same key to replay its first saved response. Use a new key for a different upload. | Declared schema for `file` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "string", "format": "binary", "x-maximum-bytes": 26214400, "x-allowed-extensions": [ "png", "jpg", "jpeg", "bmp", "gif", "pdf", "msg", "eml", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "rtf", "odp", "odt", "ods", "txt", "wks", "zip" ] } ``` #### Before you upload POST requires an empty invoice slot. If an invoice is already attached, the API returns HTTP 409; use PATCH to replace it. An Invoice Attachment is separate from the record's supporting File Attachments. Use the invoice control beside the Booth Service's cost and payment details on the Event's Booth tab in the web app. #### After the upload The response's invoice_attachment contains the attached file's id, filename and attachment_created_timestamp. The amount, payment fields, cost-center breakdown and other files are unchanged. The upload is recorded in Event history. Attaching an invoice does not mark the record as paid. #### Access and retries A current upload-enabled plan, record and financial permissions, and an editable applicable tab are required. Each uploaded file must fit its supported type and size limits. expected_revision is not supported by this file method. If the save outcome cannot be confirmed, retrieve the current parent record with GET /v1/events/booth_services/info and inspect invoice_attachment before deciding whether to retry. #### Hidden or locked tab If the Event's Booth tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X POST "https://api.exhibitday.com/v1/events/booth_services/invoice_attachment" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}" --form-string "booth_service_id=12345" --form "file=@invoice.pdf;type=application/octet-stream") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi cat response-body.tmp ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const form = new FormData(); form.append("booth_service_id", "12345"); form.append("file", new Blob([await readFile("invoice.pdf")], { type: "application/octet-stream" }), "invoice.pdf"); const response = await fetch("https://api.exhibitday.com/v1/events/booth_services/invoice_attachment", { method: "POST", headers: { Authorization: 'Bearer YOUR_API_KEY' }, body: form }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); console.log(await response.json()); ``` Example — Python: ```python import requests import json from contextlib import ExitStack with ExitStack() as stack: files = [ ("file", ("invoice.pdf", stack.enter_context(open("invoice.pdf", 'rb')), "application/octet-stream")), ] response = requests.request("POST", "https://api.exhibitday.com/v1/events/booth_services/invoice_attachment", headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data={"booth_service_id": "12345"}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') print(response.json()) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.exhibitday.com/v1/events/booth_services/invoice_attachment"); var form = new MultipartFormDataContent(); form.Add(new StringContent("12345"), "booth_service_id"); var file0 = new StreamContent(File.OpenRead("invoice.pdf")); file0.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(file0, "file", "invoice.pdf"); request.Content = form; using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/booth_services/invoice_attachment")).header("Authorization", "Bearer YOUR_API_KEY"); String boundary = "ExhibitDay-" + UUID.randomUUID(); ByteArrayOutputStream form = new ByteArrayOutputStream(); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"booth_service_id\"\r\n\r\n" + "12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"invoice.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8)); form.write(Files.readAllBytes(Path.of("invoice.pdf"))); form.write("\r\n".getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); request.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpResponse response = HttpClient.newHttpClient().send(request.method("POST", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); System.out.println(new String(response.body(), StandardCharsets.UTF_8)); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], CURLOPT_POSTFIELDS => [ 'booth_service_id' => '12345', 'file' => new CURLFile('invoice.pdf', 'application/octet-stream', 'invoice.pdf'), ], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); echo $response; ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/booth_services/invoice_attachment') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' files = [] begin parts = [ ['booth_service_id', '12345'], ['file', (files << File.open('invoice.pdf', 'rb')).last, {filename: 'invoice.pdf', content_type: 'application/octet-stream'}], ] request.set_form(parts, 'multipart/form-data') response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' puts response.body ensure files.each(&:close) end ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" "bytes" "mime/multipart" "net/textproto" ) func main() { var form bytes.Buffer writer := multipart.NewWriter(&form) if err := writer.WriteField("booth_service_id", "12345"); err != nil { log.Fatal(err) } header0 := textproto.MIMEHeader{} header0.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"invoice.pdf\"") header0.Set("Content-Type", "application/octet-stream") part0, err := writer.CreatePart(header0) if err != nil { log.Fatal(err) } file0, err := os.Open("invoice.pdf") if err != nil { log.Fatal(err) } if _, err = io.Copy(part0, file0); err != nil { log.Fatal(err) } file0.Close() if err := writer.Close(); err != nil { log.Fatal(err) } request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/events/booth_services/invoice_attachment", &form) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", writer.FormDataContentType()) response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } fmt.Printf("%s\n", data) } ``` Example HTTP response body (JSON): POST /v1/events/booth_services/invoice_attachment - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "invoice_attachment": { "id": 12345, "filename": "invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } } ``` ### Replace Booth Service Invoice Attachment `PATCH https://api.exhibitday.com/v1/events/booth_services/invoice_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=booth-services#patch-v1-events-booth_services-invoice_attachment Replaces this Booth Service's current Invoice Attachment with one uploaded file. Use this method when an invoice file is already attached. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | booth_service_id | Number | Yes | The ID of the Booth Service, from Retrieve Booth Services (GET /v1/events/booth_services) or its add response. | | | file | File (multipart) | Yes | The Invoice Attachment to upload. | Send exactly one complete, nonempty multipart/form-data file part named file. The supported extensions and current per-file limit are shown below; the complete request limit also includes multipart overhead. A missing or null file is invalid and does not remove an existing invoice. | Declared schema for `file` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "string", "format": "binary", "x-maximum-bytes": 26214400, "x-allowed-extensions": [ "png", "jpg", "jpeg", "bmp", "gif", "pdf", "msg", "eml", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "rtf", "odp", "odt", "ods", "txt", "wks", "zip" ] } ``` #### Replacing the current file PATCH requires a current invoice file. If none is attached, the API returns HTTP 404. Upload exactly one file; the previous attachment ID is not needed. If another request changes the current invoice during your upload, the API refuses this request instead of replacing a different file. Even identical replacement contents receive a new attachment ID. #### After the replacement The response's invoice_attachment contains the attached file's id, filename and attachment_created_timestamp. The amount, payment fields, cost-center breakdown and other files are unchanged. The previous file is scheduled for physical cleanup after a confirmed save; cleanup may finish later. The replacement is recorded in Event history. #### Access and retries A current upload-enabled plan, record and financial permissions, and an editable applicable tab are required. Each uploaded file must fit its supported type and size limits. expected_revision is not supported by this file method. PATCH does not use Idempotency-Key replay. If the save outcome cannot be confirmed, retrieve the current parent record with GET /v1/events/booth_services/info and inspect invoice_attachment before deciding whether to retry. #### Hidden or locked tab If the Event's Booth tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X PATCH "https://api.exhibitday.com/v1/events/booth_services/invoice_attachment" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}" --form-string "booth_service_id=12345" --form "file=@invoice.pdf;type=application/octet-stream") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi cat response-body.tmp ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const form = new FormData(); form.append("booth_service_id", "12345"); form.append("file", new Blob([await readFile("invoice.pdf")], { type: "application/octet-stream" }), "invoice.pdf"); const response = await fetch("https://api.exhibitday.com/v1/events/booth_services/invoice_attachment", { method: "PATCH", headers: { Authorization: 'Bearer YOUR_API_KEY' }, body: form }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); console.log(await response.json()); ``` Example — Python: ```python import requests import json from contextlib import ExitStack with ExitStack() as stack: files = [ ("file", ("invoice.pdf", stack.enter_context(open("invoice.pdf", 'rb')), "application/octet-stream")), ] response = requests.request("PATCH", "https://api.exhibitday.com/v1/events/booth_services/invoice_attachment", headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data={"booth_service_id": "12345"}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') print(response.json()) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("PATCH"), "https://api.exhibitday.com/v1/events/booth_services/invoice_attachment"); var form = new MultipartFormDataContent(); form.Add(new StringContent("12345"), "booth_service_id"); var file0 = new StreamContent(File.OpenRead("invoice.pdf")); file0.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(file0, "file", "invoice.pdf"); request.Content = form; using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/booth_services/invoice_attachment")).header("Authorization", "Bearer YOUR_API_KEY"); String boundary = "ExhibitDay-" + UUID.randomUUID(); ByteArrayOutputStream form = new ByteArrayOutputStream(); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"booth_service_id\"\r\n\r\n" + "12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"invoice.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8)); form.write(Files.readAllBytes(Path.of("invoice.pdf"))); form.write("\r\n".getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); request.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpResponse response = HttpClient.newHttpClient().send(request.method("PATCH", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); System.out.println(new String(response.body(), StandardCharsets.UTF_8)); } } ``` Example — PHP: ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], CURLOPT_POSTFIELDS => [ 'booth_service_id' => '12345', 'file' => new CURLFile('invoice.pdf', 'application/octet-stream', 'invoice.pdf'), ], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); echo $response; ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/booth_services/invoice_attachment') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' files = [] begin parts = [ ['booth_service_id', '12345'], ['file', (files << File.open('invoice.pdf', 'rb')).last, {filename: 'invoice.pdf', content_type: 'application/octet-stream'}], ] request.set_form(parts, 'multipart/form-data') response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' puts response.body ensure files.each(&:close) end ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" "bytes" "mime/multipart" "net/textproto" ) func main() { var form bytes.Buffer writer := multipart.NewWriter(&form) if err := writer.WriteField("booth_service_id", "12345"); err != nil { log.Fatal(err) } header0 := textproto.MIMEHeader{} header0.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"invoice.pdf\"") header0.Set("Content-Type", "application/octet-stream") part0, err := writer.CreatePart(header0) if err != nil { log.Fatal(err) } file0, err := os.Open("invoice.pdf") if err != nil { log.Fatal(err) } if _, err = io.Copy(part0, file0); err != nil { log.Fatal(err) } file0.Close() if err := writer.Close(); err != nil { log.Fatal(err) } request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/events/booth_services/invoice_attachment", &form) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", writer.FormDataContentType()) response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } fmt.Printf("%s\n", data) } ``` Example HTTP response body (JSON): PATCH /v1/events/booth_services/invoice_attachment - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "invoice_attachment": { "id": 12345, "filename": "invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } } ``` ### Remove Booth Service Invoice Attachment `DELETE https://api.exhibitday.com/v1/events/booth_services/invoice_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=booth-services#delete-v1-events-booth_services-invoice_attachment Removes this Booth Service's Invoice Attachment. The cost, payment details and other File Attachments stay in place. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | booth_service_id | Number | Yes | The ID of the Booth Service, from Retrieve Booth Services (GET /v1/events/booth_services) or its add response. | | #### After the removal The Invoice Attachment is cleared and the removal is recorded in Event history. Its physical file is scheduled for cleanup after a confirmed save; cleanup may finish later. Costs, payment fields, cost-center allocations and supporting files stay unchanged. If no invoice is attached, DELETE returns HTTP 404 Not Found with the message "This Booth Service has no invoice to remove." No saved data or history is changed. Current access and the record's binding are still checked. Do not send file parts with this request. #### Access and retries Current record, financial and invoice permissions and applicable tab-edit access are required. Permitted removals remain available on the Free plan. expected_revision is not supported, and DELETE does not use Idempotency-Key replay. If the save outcome cannot be confirmed, retrieve the current parent record with GET /v1/events/booth_services/info and inspect invoice_attachment before deciding whether to retry. #### Hidden or locked tab If the Event's Booth tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/events/booth_services/invoice_attachment?booth_service_id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/booth_services/invoice_attachment?" + new URLSearchParams({ "booth_service_id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/events/booth_services/invoice_attachment", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"booth_service_id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/events/booth_services/invoice_attachment?booth_service_id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/booth_services/invoice_attachment?booth_service_id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/booth_services/invoice_attachment?booth_service_id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/events/booth_services/invoice_attachment?booth_service_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/events/booth_services/invoice_attachment - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Attachment removed.", "errors": [] } ``` ### Retrieve Booth Service General File Attachments `GET https://api.exhibitday.com/v1/events/booth_services/attachments` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=booth-services#get-v1-events-booth_services-attachments Retrieves the General File Attachments on this Booth Service. Each result includes the file's ID, name and added time; use the download method for its contents. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | booth_service_id | Number | Yes | The ID of the Booth Service, from Retrieve Booth Services (GET /v1/events/booth_services) or its add response. | | | $limit | Number | No | The most File Attachments to return. | A positive whole number. Omit for all remaining matching files. | | $offset | Number | No | The number of matching File Attachments to skip. | A whole number of 0 or more. Default: 0. | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records. | Allowed values: `array` | | If-None-Match | String | No | An ETag from an earlier response to this GET. | Optional HTTP header. If the successful response is unchanged, the API returns HTTP 304 with no body. | #### Reading the file list Files are ordered by added time, then attachment ID, lowest first. Only files available under your current access are included. Paging totals and X-Total-Count count all matching files before $limit and $offset are applied. A record with no files you can view returns an empty list. This list does not return edit revisions or support changed-since filtering. #### Supporting files and invoices These are the record's General File Attachments. Its cost Invoice Attachment is separate and has its own download and upload methods. Use this list's id values for these supporting-file downloads and removals. #### Access The record's Event and tab must be available, and the tab must not be hidden. A locked tab can still be read. #### Hidden tab If the Event's Booth tab is hidden, this request returns HTTP 400 (not_allowed), and the message says the tab is hidden. Show the tab in ExhibitDay first. A locked tab can still be read. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/events/booth_services/attachments?booth_service_id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/booth_services/attachments?" + new URLSearchParams({ "booth_service_id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/events/booth_services/attachments", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"booth_service_id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/events/booth_services/attachments?booth_service_id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/booth_services/attachments?booth_service_id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/booth_services/attachments?booth_service_id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/booth_services/attachments?booth_service_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/events/booth_services/attachments - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "attachment", "list_data": [ { "id": 12345, "filename": "attachment.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } ] } ``` ### Add Booth Service General File Attachments `POST https://api.exhibitday.com/v1/events/booth_services/attachments` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=booth-services#post-v1-events-booth_services-attachments Adds one or more General File Attachments to this Booth Service. Send each file as a multipart upload part named file. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | booth_service_id | Number | Yes | The ID of the Booth Service, from Retrieve Booth Services (GET /v1/events/booth_services) or its add response. | | | file | File (multipart) | Yes | The File Attachments to upload. | Send one or more complete, nonempty multipart/form-data parts, each named file. Supported types and the current per-file limit are shown below. The complete request limit includes all files and multipart overhead; split larger batches. A missing or null upload is not a removal request. | | Idempotency-Key | String | No | A unique key for safely retrying this upload. | Optional HTTP header: 1 to 255 visible ASCII characters without spaces or commas. Retry the identical request with the same key to replay its first saved response. Use a new key for a different upload. | Declared schema for `file` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "array", "items": { "type": "string", "format": "binary", "x-maximum-bytes": 26214400, "x-allowed-extensions": [ "png", "jpg", "jpeg", "bmp", "gif", "pdf", "msg", "eml", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "rtf", "odp", "odt", "ods", "txt", "wks", "zip" ] } } ``` #### After the upload The response's list_data contains the newly attached files, including each id, filename and attachment_created_timestamp. Existing files are kept. Use each returned id to download or remove that file. Identical repeated files in one request are attached once when their cleaned filename, length and contents match. Files with different contents remain separate even when their names match. This does not remove or replace files already attached to the record. #### Choosing the right file method These uploads add General File Attachments. Use this record's Invoice Attachment methods for its cost invoice or receipt. Adding supporting files does not change amounts, payments or cost-center allocations. #### Access Current record and file-change permissions and applicable Event/tab locks must allow this upload. An upload-enabled paid plan is required. #### History and retries A confirmed file change is recorded in history. expected_revision is not supported by these file methods. If the save outcome cannot be confirmed, retrieve the current file list before deciding whether to retry; the API does not automatically repeat an uncertain change. Supporting File Attachments have no PATCH replacement. To replace one, add the new file and remove the old one using their separate requests; each request has its own outcome. #### Hidden or locked tab If the Event's Booth tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X POST "https://api.exhibitday.com/v1/events/booth_services/attachments" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}" --form-string "booth_service_id=12345" --form "file=@attachment.pdf;type=application/octet-stream") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi cat response-body.tmp ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const form = new FormData(); form.append("booth_service_id", "12345"); form.append("file", new Blob([await readFile("attachment.pdf")], { type: "application/octet-stream" }), "attachment.pdf"); const response = await fetch("https://api.exhibitday.com/v1/events/booth_services/attachments", { method: "POST", headers: { Authorization: 'Bearer YOUR_API_KEY' }, body: form }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); console.log(await response.json()); ``` Example — Python: ```python import requests import json from contextlib import ExitStack with ExitStack() as stack: files = [ ("file", ("attachment.pdf", stack.enter_context(open("attachment.pdf", 'rb')), "application/octet-stream")), ] response = requests.request("POST", "https://api.exhibitday.com/v1/events/booth_services/attachments", headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data={"booth_service_id": "12345"}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') print(response.json()) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.exhibitday.com/v1/events/booth_services/attachments"); var form = new MultipartFormDataContent(); form.Add(new StringContent("12345"), "booth_service_id"); var file0 = new StreamContent(File.OpenRead("attachment.pdf")); file0.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(file0, "file", "attachment.pdf"); request.Content = form; using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/booth_services/attachments")).header("Authorization", "Bearer YOUR_API_KEY"); String boundary = "ExhibitDay-" + UUID.randomUUID(); ByteArrayOutputStream form = new ByteArrayOutputStream(); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"booth_service_id\"\r\n\r\n" + "12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"attachment.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8)); form.write(Files.readAllBytes(Path.of("attachment.pdf"))); form.write("\r\n".getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); request.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpResponse response = HttpClient.newHttpClient().send(request.method("POST", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); System.out.println(new String(response.body(), StandardCharsets.UTF_8)); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], CURLOPT_POSTFIELDS => [ 'booth_service_id' => '12345', 'file' => new CURLFile('attachment.pdf', 'application/octet-stream', 'attachment.pdf'), ], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); echo $response; ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/booth_services/attachments') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' files = [] begin parts = [ ['booth_service_id', '12345'], ['file', (files << File.open('attachment.pdf', 'rb')).last, {filename: 'attachment.pdf', content_type: 'application/octet-stream'}], ] request.set_form(parts, 'multipart/form-data') response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' puts response.body ensure files.each(&:close) end ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" "bytes" "mime/multipart" "net/textproto" ) func main() { var form bytes.Buffer writer := multipart.NewWriter(&form) if err := writer.WriteField("booth_service_id", "12345"); err != nil { log.Fatal(err) } header0 := textproto.MIMEHeader{} header0.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"attachment.pdf\"") header0.Set("Content-Type", "application/octet-stream") part0, err := writer.CreatePart(header0) if err != nil { log.Fatal(err) } file0, err := os.Open("attachment.pdf") if err != nil { log.Fatal(err) } if _, err = io.Copy(part0, file0); err != nil { log.Fatal(err) } file0.Close() if err := writer.Close(); err != nil { log.Fatal(err) } request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/events/booth_services/attachments", &form) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", writer.FormDataContentType()) response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } fmt.Printf("%s\n", data) } ``` Example HTTP response body (JSON): POST /v1/events/booth_services/attachments - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "attachment", "list_data": [ { "id": 12345, "filename": "attachment.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } ] } ``` ### Remove a Booth Service General File Attachment `DELETE https://api.exhibitday.com/v1/events/booth_services/attachments` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=booth-services#delete-v1-events-booth_services-attachments Removes one General File Attachment from this Booth Service. Other attached files and the record's details stay in place. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the File Attachment. | Use the id from the attachment list. The API finds the record the file belongs to, so no record ID is sent. An Invoice Attachment is not selected by this method. | #### After the removal Only the selected file association is removed. Its physical file is scheduled for cleanup after a confirmed save; cleanup may finish later. Other attached files stay in place. Send only the file's id; the API finds the record it belongs to. A missing, already removed or unavailable attachment returns HTTP 404 Not Found. Do not send file parts with DELETE. #### Access Current record and file-removal permissions and applicable Event/tab locks must allow this change. Permitted removals remain available on the Free plan. #### History and retries A confirmed file change is recorded in history. expected_revision is not supported by these file methods. DELETE does not use Idempotency-Key replay. If the save outcome cannot be confirmed, retrieve the current file list before deciding whether to retry; the API does not automatically repeat an uncertain change. Supporting File Attachments have no PATCH replacement. To replace one, add the new file and remove the old one using their separate requests; each request has its own outcome. #### Hidden or locked tab If the Event's Booth tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/events/booth_services/attachments?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/booth_services/attachments?" + new URLSearchParams({ "id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/events/booth_services/attachments", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/events/booth_services/attachments?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/booth_services/attachments?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/booth_services/attachments?id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/events/booth_services/attachments?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/events/booth_services/attachments - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Attachment removed.", "errors": [] } ``` ### Download a Booth Service General File Attachment `GET https://api.exhibitday.com/v1/events/booth_services/attachments/download` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=booth-services#get-v1-events-booth_services-attachments-download Downloads one original General File Attachment from this Booth Service. Select the file using its ID from the attachment list. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the File Attachment. | Use the id from the attachment list. The API finds the record the file belongs to, so no record ID is sent. An Invoice Attachment is not selected by this method. | #### Download response A successful response contains the original uploaded file with a safe download filename. API errors use the usual JSON response. A missing or unavailable file returns HTTP 404. Send only the file's id from the attachment list to download that one file; the API finds the record it belongs to. The download leaves the record unchanged. #### Access The record's Event and tab must be available, and the tab must not be hidden. A locked tab can still be read. #### Files still being copied If this file is still being copied, the download returns HTTP 409 with file_copy_pending. Try the download again in a few minutes. #### Hidden tab If the Event's Booth tab is hidden, this request returns HTTP 400 (not_allowed), and the message says the tab is hidden. Show the tab in ExhibitDay first. A locked tab can still be read. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X GET "https://api.exhibitday.com/v1/events/booth_services/attachments/download?id=12345" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi mv response-body.tmp 'attachment.pdf' ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const response = await fetch("https://api.exhibitday.com/v1/events/booth_services/attachments/download?id=12345", { method: "GET", headers: { Authorization: 'Bearer YOUR_API_KEY' } }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); await writeFile("attachment.pdf", new Uint8Array(await response.arrayBuffer())); ``` Example — Python: ```python import requests import json response = requests.request("GET", "https://api.exhibitday.com/v1/events/booth_services/attachments/download?id=12345", headers={'Authorization': 'Bearer YOUR_API_KEY'}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') with open("attachment.pdf", 'wb') as destination: destination.write(response.content) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.exhibitday.com/v1/events/booth_services/attachments/download?id=12345"); using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); await File.WriteAllBytesAsync("attachment.pdf", await response.Content.ReadAsByteArrayAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/booth_services/attachments/download?id=12345")).header("Authorization", "Bearer YOUR_API_KEY"); HttpResponse response = HttpClient.newHttpClient().send(request.method("GET", HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); Files.write(Path.of("attachment.pdf"), response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); file_put_contents('attachment.pdf', $response); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/booth_services/attachments/download?id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' File.binwrite('attachment.pdf', response.body) ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/booth_services/attachments/download?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } if err := os.WriteFile("attachment.pdf", data, 0600); err != nil { log.Fatal(err) } fmt.Println("File saved") } ``` HTTP 200: Returns the original uploaded file as a private download, using a safe filename. A download failure returns the usual JSON API error. Media: application/octet-stream. The body is the authorized file's real bytes, not JSON or base64. Errors are JSON status responses; check HTTP status before saving the file. ## Events - Staff Event Staff (attendees and registrations): roles, registration details and costs, invoices, file attachments and exports. Documentation page: https://api.exhibitday.com/Help/V1?epf=1&topic=staff ### Retrieve a Single Attendee / Registration by ID `GET https://api.exhibitday.com/v1/events/staff/info` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=staff#get-v1-events-staff-info Retrieves an attendee or registration by its ID, including the assigned person or resource, role, attendance format, registration details, costs and payment information. You can find this record on the Event's Staff tab. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the attendee / registration record. | Use the id from Retrieve Attendees / Registrations (GET /v1/events/staff) or from the add response. You don't send the Event ID; the record's Event is found automatically. | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` \| `object` | | $include_record_revision | Boolean | No | Whether to include record_revision in the response. | Default: false. Send true to get record_revision, then send that value as expected_revision when you update this registration. See What $include_record_revision covers below. | | $on_error_return_empty_result | Boolean | No | Whether an invalid or unavailable registration should return an empty result. | Default: false. True returns HTTP 200 with {} (or [] for array format) for invalid IDs or an unavailable registration. API key errors, conflicts with a change in progress and unexpected errors keep their normal status. | | If-None-Match | String | No | An ETag from an earlier response to this GET. | Optional HTTP header. If the successful response is unchanged, the API returns HTTP 304 with no body. | #### What $include_record_revision covers Setting $include_record_revision=true returns record_revision for use as expected_revision on a later update. record_revision covers the registration's assigned person, role, attendance format, notes, registration and payment fields, cost allocations, related-item links and Event binding. It does not cover File Attachments or Invoice Attachment metadata or contents. #### File Attachments and the Invoice Attachment invoice_attachment contains the registration's Invoice Attachment metadata, or null when no invoice is attached. Ordinary File Attachments are retrieved separately through the registration's File Attachment collection. #### Access The Event's Staff tab must be visible, and access to registration financial details is required. The tab can be locked while you read it. #### Formatted text in the response Notes and other rich-text values in the response contain the stored HTML, including encoded characters and line breaks such as `
`. #### Open in ExhibitDay Each record includes exhibitday_url, the record's page in ExhibitDay. It opens the record in view mode on its Event's tab. Sign in with an account that can view the record; ExhibitDay checks access when the link is opened. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/events/staff/info?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/staff/info?" + new URLSearchParams({ "id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/events/staff/info", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/events/staff/info?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/staff/info?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/staff/info?id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/staff/info?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/events/staff/info - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "id": 12345, "event_id": 23456, "event_name": "Sample Event", "attendee": { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, "attendee_role_id": 1, "attendee_role": "Not Specified", "attendance_format_id": null, "attendance_format": "Not Specified", "registration_type": "Conference pass", "registration_confirmation_number": "", "registration_url": null, "notes": "", "payment_status_id": 0, "payment_status": { "id": 0, "name": "N/A" }, "payment_due_date": null, "next_payment_due_date": null, "payment_notes": null, "invoice_attachment": { "id": 782345, "filename": "registration-invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" }, "cost": { "amount": 125.50, "cost_center_breakdown": [ { "cost_center_id": 34567, "cost_center": "Marketing", "charge": 75.50 }, { "cost_center_id": 34568, "cost_center": "Operations", "charge": 50.00 } ] }, "created_by": { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=23456&riType=10&riSub=0&riId=12345", "related_items": [ { "id": 5551, "related_item_id": 67890, "related_item_exhibitday_url": "https://www.exhibitday.com/Workspace/TaskView/98765?tid=67890", "related_item_type_id": 1, "related_item_type": "Task", "related_item_asset_type_id": null, "related_item_name": "Confirm booth graphics with the printer", "related_item_created_timestamp": "2030-01-10T14:03:00Z" }, { "id": 5552, "related_item_id": 45678, "related_item_exhibitday_url": "https://www.exhibitday.com/Workspace/RelatedItemView/98765?typeId=4&subTypeId=0&rid=45678", "related_item_type_id": 4, "related_item_type": "Shipment", "related_item_asset_type_id": null, "related_item_name": "Booth crates to convention center", "related_item_created_timestamp": "2030-01-10T14:03:00Z" } ] } ``` ### Retrieve Attendees / Registrations `GET https://api.exhibitday.com/v1/events/staff` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=staff#get-v1-events-staff Retrieves records across your workspace's readable Event tabs. Use filter_by_event_id to narrow the results to one Event, or omit it for the workspace list. Each record includes its event_id and Event name. Use filter_by_attendee_user_ids to match any assigned user or Resource in your selection. Omit the filter to include unassigned entries too. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | filter_by_event_id | Number | No | Return records for this Event only. Omit for all readable Events in your workspace. | | | filter_by_attendee_user_ids | String or JSON array | No | Return entries assigned to any of these users or resources. Send one user ID or an array of user IDs, for example "user-id" or ["user-id","other-user-id"]. Omit, leave blank or send [] for no user filter. Duplicate IDs collapse. Inactive and deactivated people, and people no longer in this workspace, still match the entries they are assigned to; IDs never assigned in this workspace match nothing. This filter combines with the other filters before counting and paging. | | | $limit | Number | No | The most registrations to return: a whole number of 1 or more. Omit it for all remaining matches; a blank value or null is refused, so leave the parameter out instead. | | | $offset | Number | No | How many matching registrations to skip: a whole number of 0 or more. Default: 0. A blank value or null is refused. | | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | | hydrate_related_items | Boolean | No | Set to true to include each record's related_items: the Tasks and items linked to it, with the key to use when adding or removing a link. Omit it or send false to leave related_items out of list results. Single-record GETs always include related_items. | Default: false. | Declared schema for `filter_by_attendee_user_ids` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "oneOf": [ { "type": "string", "minLength": 1, "maxLength": 128, "pattern": "\\S" }, { "type": "array", "items": { "type": "string", "minLength": 1, "maxLength": 128, "pattern": "\\S" } } ], "x-normalization": "one string becomes a one-item array; trimmed distinct IDs; no record-count cap", "nullable": false, "x-maximum-depth": 1, "x-empty-create-means-omitted": false, "example": [ "user-id" ] } ``` #### Choosing Events Omit `filter_by_event_id` to retrieve records across readable Event tabs, or supply one Event ID to narrow the list. Each result retains its own `event_id` and Event name. Hidden or unavailable Event tabs are not included. A locked tab can still be read. If no records match, the response is an empty list. #### Filtering assigned people `filter_by_attendee_user_ids` accepts one user ID string or an array of user IDs. A record matches any selected assigned user or Resource. Unassigned entries are excluded while this filter is set. Omit it or send `[]` for no user filter. Stored assignments and tags match directly: inactive and deactivated people, Resources and people no longer in this workspace still match the records they are on. IDs never used on this workspace's records match nothing; this is not an error. The people and Event filters combine with AND before counting and paging. #### Reading pages The Event filter and any people filter are applied before the total count and paging. Results are ordered by Event start date ascending, Event ID ascending, then record ID ascending. Use `$limit` and `$offset` for successive pages. Omit `$limit` to return all remaining matches. `total_records` and `X-Total-Count` describe all matches; `records_found` counts this response. Omit `$result_format` for the normal list wrapper. `array` returns only the records; `wrapped_in_array` places the normal wrapper in a one-item array. #### Handling input and changes Unrecognized parameters are ignored and listed in the `X-API-Warnings` response header. Conflicting or malformed filter values return HTTP `400`; send arrays in JSON, query parameters or form fields rather than comma-bearing headers. Current API access is checked even when the list is empty. A concurrent change can return HTTP `409`; retrieve the list again. These filters retrieve records and do not change tags, assignments or notification settings. #### Related items Set `hydrate_related_items=true` to include each record's `related_items`: the Tasks and items linked to it. Add or remove links with POST and DELETE /v1/related_items. It is left out by default to keep lists fast. Retrieving one record always includes `related_items`. #### Formatted text in the response Notes and other rich-text values in the response contain the stored HTML, including encoded characters and line breaks such as `
`. #### Events with a hidden Staff tab Records on Events whose Staff tab is hidden are not listed. If filter_by_event_id names such an Event, the response is HTTP 200 with no records for it and a warning that names the tab and the Event. #### Open in ExhibitDay Each record includes exhibitday_url, the record's page in ExhibitDay. It opens the record in view mode on its Event's tab. Sign in with an account that can view the record; ExhibitDay checks access when the link is opened. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/events/staff" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/staff", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/events/staff", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/events/staff"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/staff")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/staff') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/staff", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/events/staff - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "list_type": "staff_entry", "list_data": [ { "id": 12345, "event_id": 23456, "event_name": "Sample Event", "attendee": { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, "attendee_role_id": 1, "attendee_role": "Not Specified", "attendance_format_id": null, "attendance_format": "Not Specified", "registration_type": "Conference pass", "registration_confirmation_number": "", "registration_url": null, "notes": "", "payment_status_id": 0, "payment_status": { "id": 0, "name": "N/A" }, "payment_due_date": null, "next_payment_due_date": null, "payment_notes": null, "invoice_attachment": { "id": 782345, "filename": "registration-invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" }, "cost": { "amount": 0.00, "cost_center_breakdown": [] }, "created_by": { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=23456&riType=10&riSub=0&riId=12345" } ], "records_found": 1, "total_records": 1, "has_more": false } ``` ### Add an Attendee / Registration `POST https://api.exhibitday.com/v1/events/staff` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=staff#post-v1-events-staff Adds an attendee or registration record to an Event's Staff tab. Supply attendee_user_id to assign it to a person or resource, or leave attendee_user_id out to track an unassigned registration. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | event_id | Number | Yes | The ID of the Event. | | | attendee_user_id | String | No | The person or resource assigned to this registration. | Use a current, active workspace user or resource ID. Omit or send null for an unassigned registration. A person or resource can appear only once in an Event's Staff list. Maximum: 128 characters. | | attendee_role_id | Number | No | The assigned person's attendee role. | Use a currently available Attendee Role ID. Omit to use the selected person's configured default, or Not Specified (1) if that default is unavailable. With no person assigned, attendee_role_id is ignored, the role is Not Specified (1), and the response includes a warning saying so. | | attendance_format_id | Number | No | Whether the assigned person attends onsite or remotely. Null means Not Specified. For an assigned person, omission uses the workspace's default. An unassigned entry always has no attendance format; a value sent for one is ignored, and the response includes a warning saying so. | Allowed values: `1` (Onsite) \| `2` (Remote) | | notes | String | No | Notes about this attendee or registration. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Up to 4,000 characters as saved: characters such as & and < and each line break take extra space. Longer text is refused rather than shortened. Omit for no value. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | registration_url | String | No | The registration or ticket link. | Up to 2,000 characters after surrounding spaces are removed. Kept as typed; the API does not add or rewrite a URL scheme. Omit for no value. | | registration_type | String | No | The registration or ticket type. | Up to 300 characters, excluding surrounding spaces. Omit for no value. | | registration_confirmation_number | String | No | The registration confirmation or reference number. | Up to 200 characters, excluding surrounding spaces. Omit for no value. | | payment_status_id | Number | No | The registration's payment status. Omit or send null for N/A. A status other than Partially Paid clears the next partial payment due date. | Allowed values: `0` (N/A) \| `1` (Paid in Full) \| `2` (Partially Paid) \| `3` (Not Paid Yet) | | payment_due_date | String | No | The registration payment due date. | Use a calendar date in YYYY-MM-DD format. Omit for no value. | | next_payment_due_date | Date | No | The next partial payment due date. | Use a calendar date in YYYY-MM-DD format. Applies when payment_status_id is Partially Paid (2). Supplying this date with another status clears it; choosing another status also clears it. Omit for no value. | | payment_notes | String | No | Notes about the registration payment. | Up to 200 characters, excluding surrounding spaces. Omit for no value. | | cost | Number or cost object | No | The full cost, as a number or an object with amount and/or cost_center_breakdown. [Record Costs and Split Them Across Cost Centers](/Help/V1?guide=entering-costs). | Optional; defaults to zero. | | notify_attendee | Boolean | No | Whether to send the usual assignment email to a newly assigned person. | Default: true when omitted or blank. Send false to skip that new notification. It does not resend or cancel notifications for an unchanged person. Resources and unassigned entries receive no email; delivery also depends on the person's current account, access and email preferences. JSON null is refused. | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` \| `object` | | Idempotency-Key | String | No | A unique key for safely retrying this add request. | Optional HTTP header: 1 to 255 visible ASCII characters without spaces. Retry the identical request with the same key to replay its first saved response. Use a new key for a different request. | | $request_principal_name | String | No | A display label for the API origin of a new assignment. | Optional, up to 122 characters. Default: ExhibitDay API. Used when this operation creates or reassigns the registration. It does not identify a workspace user or change permissions. | Declared schema for `cost` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "anyOf": [ { "type": "number", "minimum": 0, "description": "Shorthand for an object with amount. The amount is rounded to cents before the supported storage range is checked.", "nullable": true }, { "type": "object", "additionalProperties": false, "properties": { "amount": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 }, "cost_center_breakdown": { "type": "array", "items": { "type": "object", "additionalProperties": false, "properties": { "cost_center_id": { "type": "integer", "format": "int64", "nullable": true }, "charge": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 }, "cost_center": { "type": "string", "description": "Optional and read-only: the cost center name a read returns, so a cost can be sent back unchanged. It is ignored; the line is saved by cost_center_id, and a name that doesn't match that cost center is explained in a warning.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "required": [ "charge" ] }, "maxItems": 2147483647 } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "anyOf": [ { "required": [ "amount" ] }, { "required": [ "cost_center_breakdown" ] } ], "nullable": true } ], "x-numeric-shorthand": "A number is equivalent to {amount:number}.", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": { "amount": 125.50 } } ``` #### Choosing who attends Use attendee_user_id for a person or resource, or omit it to record an unassigned registration. A person or resource can be added only once per Event. For an assigned person, omit attendee_role_id and attendance_format_id to use the applicable defaults described in the table. Unassigned registrations have no role or attendance format. #### After the add The response contains the new registration and its id. No File Attachment or Invoice Attachment is uploaded by this operation; those use their separate file operations. The change is recorded in Event history. A newly assigned person may receive an assignment email unless notify_attendee is false. If the save outcome cannot be confirmed, retrieve the registrations before deciding whether to retry. #### Access The Event's Staff tab must be visible and unlocked. You need permission to manage its attendees / registrations and access their registration financial details. #### Sending values Use JSON, a form field or a query parameter for text or lists containing commas. #### Sending text Send plain text for Notes and other rich-text fields. Characters such as `&`, `<` and quotes, along with line breaks, are encoded for storage. Notes and other rich-text values in the response contain the stored HTML, including encoded characters and line breaks such as `
`. #### Hidden or locked tab If the Event's Staff tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. An Event that is not in your workspace returns HTTP 404. #### Open in ExhibitDay The created record includes exhibitday_url, the record's page in ExhibitDay. It is the same link that GET /v1/events/staff/info returns for this record and opens the record in view mode on its Event's tab. Sign in with an account that can view the record; ExhibitDay checks access when the link is opened. Example — curl: ```bash curl -X POST "https://api.exhibitday.com/v1/events/staff" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"event_id\":23456,\"registration_type\":\"Conference pass\"}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/staff", { method: "POST", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "event_id": 23456, "registration_type": "Conference pass" }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.post( "https://api.exhibitday.com/v1/events/staff", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"event_id": 23456, "registration_type": "Conference pass"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PostAsync("https://api.exhibitday.com/v1/events/staff", JsonContent.Create(new { event_id = 23456, registration_type = "Conference pass" })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/staff")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("POST", HttpRequest.BodyPublishers.ofString("{\"event_id\":23456,\"registration_type\":\"Conference pass\"}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"event_id":23456,"registration_type":"Conference pass"}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/staff') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"event_id":23456,"registration_type":"Conference pass"}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/events/staff", strings.NewReader("{\"event_id\":23456,\"registration_type\":\"Conference pass\"}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): POST /v1/events/staff - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "id": 12345, "event_id": 23456, "event_name": "Sample Event", "attendee": { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, "attendee_role_id": 1, "attendee_role": "Not Specified", "attendance_format_id": null, "attendance_format": "Not Specified", "registration_type": "Conference pass", "registration_confirmation_number": "", "registration_url": null, "notes": "", "payment_status_id": 0, "payment_status": { "id": 0, "name": "N/A" }, "payment_due_date": null, "next_payment_due_date": null, "payment_notes": null, "invoice_attachment": null, "cost": { "amount": 0.00, "cost_center_breakdown": [] }, "created_by": { "id": null, "first_name": "ExhibitDay", "last_name": "API", "display_name": "ExhibitDay API", "email": null, "type": null, "workspace_role": null, "is_active": true }, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=23456&riType=10&riSub=0&riId=12345" } ``` ### Update an Attendee / Registration `PATCH https://api.exhibitday.com/v1/events/staff` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=staff#patch-v1-events-staff Updates an attendee or registration on an Event's Staff tab. Send only the values you want to change, such as the assigned person, registration details or payment information. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the attendee / registration record. | Use the record's id from GET /v1/events/staff or from its add or single-record response. It is not the person's ID: the assigned person or Resource is the attendee object in those responses. | | attendee_user_id | String | No | The person or resource assigned to this registration. | Use a current, active workspace user or resource ID to change the assignment. Maximum: 128 characters. Omit or leave blank to keep it; null makes the entry unassigned. An existing inactive or former member can remain assigned while you edit other fields. | | attendee_role_id | Number | No | The assigned person's attendee role. | Use a currently available Attendee Role ID. Omit or leave blank to keep the role, except that assigning a different person uses their default role when this is omitted. Null cannot clear the role. With no person assigned, a role you send is ignored, the role stays Not Specified (1), and the response includes a warning saying so. | | attendance_format_id | Number | No | Whether the assigned person attends onsite or remotely. Omit or leave blank to keep it; null means Not Specified. An unassigned entry always has no attendance format; a value sent for one is ignored, and the response includes a warning saying so. | Allowed values: `1` (Onsite) \| `2` (Remote) | | notes | String | No | Notes about this attendee or registration. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Up to 4,000 characters as saved: characters such as & and < and each line break take extra space. Longer text is refused rather than shortened. Omit or leave blank to keep it; null clears it. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | registration_url | String | No | The registration or ticket link. | Up to 2,000 characters after surrounding spaces are removed. Kept as typed; the API does not add or rewrite a URL scheme. Omit or leave blank to keep it; null clears it. | | registration_type | String | No | The registration or ticket type. | Up to 300 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. | | registration_confirmation_number | String | No | The registration confirmation or reference number. | Up to 200 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. | | payment_status_id | Number | No | The registration's payment status. Omit or leave blank to keep it; null cannot clear it. A status other than Partially Paid clears the next partial payment due date. | Allowed values: `0` (N/A) \| `1` (Paid in Full) \| `2` (Partially Paid) \| `3` (Not Paid Yet) | | payment_due_date | String | No | The registration payment due date. | Use a calendar date in YYYY-MM-DD format. Omit or leave blank to keep it; null clears it. | | next_payment_due_date | Date | No | The next partial payment due date. | Use a calendar date in YYYY-MM-DD format. Applies when payment_status_id is Partially Paid (2). Supplying this date with another status clears it; choosing another status also clears it. Omit or leave blank to keep it; null clears it. | | payment_notes | String | No | Notes about the registration payment. | Up to 200 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. | | cost | Number or cost object | No | The full cost, as a number or an object with amount and/or cost_center_breakdown. [Record Costs and Split Them Across Cost Centers](/Help/V1?guide=entering-costs). | Omit to keep the saved cost. A supplied value replaces its full allocation. | | notify_attendee | Boolean | No | Whether to send the usual assignment email to a newly assigned person. | Default: true when omitted or blank. Send false to skip that new notification. It does not resend or cancel notifications for an unchanged person. Resources and unassigned entries receive no email; delivery also depends on the person's current account, access and email preferences. JSON null is refused. | | expected_revision | String | No | The record_revision from an earlier read of this registration. | Optional. Obtain it from GET /v1/events/staff/info with $include_record_revision=true. If the covered values changed, the update returns HTTP 409 without saving it. Omission skips this conflict check; blank, null and malformed values are refused. | | $ignore_params_with_empty_values | Boolean | No | Whether JSON null should leave the current value unchanged. | Default: false. With true, whole JSON null values are ignored. The text null still clears a field that supports clearing. Blank ordinary values already leave their fields unchanged. This does not relax notify_attendee validation. | | $request_principal_name | String | No | A display label for the API origin of a new assignment. | Optional, up to 122 characters. Default: ExhibitDay API. Used when this operation creates or reassigns the registration. It does not identify a workspace user or change permissions. | Declared schema for `cost` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "anyOf": [ { "type": "number", "minimum": 0, "description": "Shorthand for an object with amount. The amount is rounded to cents before the supported storage range is checked.", "nullable": true }, { "type": "object", "additionalProperties": false, "properties": { "amount": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 }, "cost_center_breakdown": { "type": "array", "items": { "type": "object", "additionalProperties": false, "properties": { "cost_center_id": { "type": "integer", "format": "int64", "nullable": true }, "charge": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 }, "cost_center": { "type": "string", "description": "Optional and read-only: the cost center name a read returns, so a cost can be sent back unchanged. It is ignored; the line is saved by cost_center_id, and a name that doesn't match that cost center is explained in a warning.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "required": [ "charge" ] }, "maxItems": 2147483647 } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "anyOf": [ { "required": [ "amount" ] }, { "required": [ "cost_center_breakdown" ] } ], "nullable": true } ], "x-numeric-shorthand": "A number is equivalent to {amount:number}.", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": { "amount": 125.50 } } ``` #### Choosing what to change Omitted or blank ordinary values stay unchanged. Send null to clear a field that supports it; attendee_role_id and payment_status_id cannot be cleared. Costs and related-item links have the separate rules in the table. Clearing attendee_user_id makes the registration unassigned and resets its role and attendance format. Changing the person can schedule a new assignment email; notify_attendee=false skips that new notification. A real change adds one Event history entry. An unchanged request saves no business data or history and keeps its revision. Files and the Invoice Attachment are managed separately. #### Using expected_revision 1. Retrieve this registration with GET /v1/events/staff/info and $include_record_revision=true. 2. Send the returned record_revision unchanged as expected_revision with this update. 3. If the API reports that the registration changed, read its current values and decide what to update. #### Access The Event's Staff tab must be visible and unlocked. You need permission to manage its attendees / registrations and access their registration financial details. #### If the save cannot be confirmed Read the registration before deciding whether to retry. The API does not automatically repeat an unconfirmed save. #### Sending values Use JSON, a form field or a query parameter for text or lists containing commas. #### Sending text Send plain text for Notes and other rich-text fields. Characters such as `&`, `<` and quotes, along with line breaks, are encoded for storage. #### Hidden or locked tab If the Event's Staff tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. An Event that is not in your workspace returns HTTP 404. Example — curl: ```bash curl -X PATCH "https://api.exhibitday.com/v1/events/staff" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"id\":12345,\"notes\":\"Updated text\"}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/staff", { method: "PATCH", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "id": 12345, "notes": "Updated text" }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.patch( "https://api.exhibitday.com/v1/events/staff", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"id": 12345, "notes": "Updated text"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PatchAsync("https://api.exhibitday.com/v1/events/staff", JsonContent.Create(new { id = 12345, notes = "Updated text" })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/staff")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("PATCH", HttpRequest.BodyPublishers.ofString("{\"id\":12345,\"notes\":\"Updated text\"}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"id":12345,"notes":"Updated text"}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/staff') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"id":12345,"notes":"Updated text"}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/events/staff", strings.NewReader("{\"id\":12345,\"notes\":\"Updated text\"}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): PATCH /v1/events/staff - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Staff / Registration entry updated.", "errors": [] } ``` ### Delete an Attendee / Registration `DELETE https://api.exhibitday.com/v1/events/staff` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=staff#delete-v1-events-staff Deletes an attendee or registration from an Event's Staff tab, together with its costs, related-item links, File Attachments and Invoice Attachment. It does not remove the person or resource from your workspace. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the attendee / registration record. | Use the record's id from GET /v1/events/staff or from its add or single-record response. It is not the person's ID: the assigned person or Resource is the attendee object in those responses. | #### After the deletion The registration, its costs, related-item links, File Attachment records and Invoice Attachment are removed together. Its files are scheduled for physical cleanup after the save. The deletion is recorded in Event history; it sends no assignment email. The workspace person or resource and the linked Tasks remain. A registration that is no longer available returns HTTP 404. If the save outcome cannot be confirmed, retrieve the current registrations before deciding whether to retry. #### Access The Event's Staff tab must be visible and unlocked. You need permission to manage its attendees / registrations and access their registration financial details. #### Hidden or locked tab If the Event's Staff tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. An Event that is not in your workspace returns HTTP 404. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/events/staff?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/staff?" + new URLSearchParams({ "id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/events/staff", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/events/staff?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/staff?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/staff?id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/events/staff?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/events/staff - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Staff / Registration entry removed.", "errors": [] } ``` ### Download Attendee / Registration Invoice Attachment `GET https://api.exhibitday.com/v1/events/staff/invoice_attachment/download` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=staff#get-v1-events-staff-invoice_attachment-download Downloads the original Invoice Attachment for this Attendee / Registration. Use this method to retrieve the file itself. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | staff_entry_id | Number | Yes | The ID of the Attendee / Registration record, from Retrieve Attendees / Registrations (GET /v1/events/staff) or its add response. | | #### Finding the file In the web app, this is the invoice control beside the Attendee / Registration record's cost and payment details. Each cost has one Invoice Attachment even when its amount is split among cost centers. For file metadata, retrieve the parent record with GET /v1/events/staff/info and read invoice_attachment. Use this download method for the contents. No attachment ID or invoice flag is needed. #### Download response A successful response contains the original uploaded file, with a safe download filename. API errors use the usual JSON response. If no invoice is attached, this method returns HTTP 404. Current record, financial and invoice permissions apply. A locked tab can still be read. Permitted downloads remain available on the Free plan. #### Files still being copied If this file is still being copied, the download returns HTTP 409 with file_copy_pending. Try the download again in a few minutes. #### Hidden tab If the Event's Staff tab is hidden, this request returns HTTP 400 (not_allowed), and the message says the tab is hidden. Show the tab in ExhibitDay first. A locked tab can still be read. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X GET "https://api.exhibitday.com/v1/events/staff/invoice_attachment/download?staff_entry_id=12345" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi mv response-body.tmp 'invoice.pdf' ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const response = await fetch("https://api.exhibitday.com/v1/events/staff/invoice_attachment/download?staff_entry_id=12345", { method: "GET", headers: { Authorization: 'Bearer YOUR_API_KEY' } }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); await writeFile("invoice.pdf", new Uint8Array(await response.arrayBuffer())); ``` Example — Python: ```python import requests import json response = requests.request("GET", "https://api.exhibitday.com/v1/events/staff/invoice_attachment/download?staff_entry_id=12345", headers={'Authorization': 'Bearer YOUR_API_KEY'}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') with open("invoice.pdf", 'wb') as destination: destination.write(response.content) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.exhibitday.com/v1/events/staff/invoice_attachment/download?staff_entry_id=12345"); using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); await File.WriteAllBytesAsync("invoice.pdf", await response.Content.ReadAsByteArrayAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/staff/invoice_attachment/download?staff_entry_id=12345")).header("Authorization", "Bearer YOUR_API_KEY"); HttpResponse response = HttpClient.newHttpClient().send(request.method("GET", HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); Files.write(Path.of("invoice.pdf"), response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); file_put_contents('invoice.pdf', $response); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/staff/invoice_attachment/download?staff_entry_id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' File.binwrite('invoice.pdf', response.body) ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/staff/invoice_attachment/download?staff_entry_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } if err := os.WriteFile("invoice.pdf", data, 0600); err != nil { log.Fatal(err) } fmt.Println("File saved") } ``` HTTP 200: Returns the original uploaded file as a private download, using a safe filename. If the file cannot be downloaded, the response contains the usual JSON API error instead. Media: application/octet-stream. The body is the authorized file's real bytes, not JSON or base64. Errors are JSON status responses; check HTTP status before saving the file. ### Add Attendee / Registration Invoice Attachment `POST https://api.exhibitday.com/v1/events/staff/invoice_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=staff#post-v1-events-staff-invoice_attachment Adds one Invoice Attachment to this Attendee / Registration. You can attach an invoice, receipt or other payment document when no invoice file is currently attached. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | staff_entry_id | Number | Yes | The ID of the Attendee / Registration record, from Retrieve Attendees / Registrations (GET /v1/events/staff) or its add response. | | | file | File (multipart) | Yes | The Invoice Attachment to upload. | Send exactly one complete, nonempty multipart/form-data file part named file. The supported extensions and current per-file limit are shown below; the complete request limit also includes multipart overhead. A missing or null file is invalid and does not remove an existing invoice. | | Idempotency-Key | String | No | A unique key for safely retrying this upload. | Optional HTTP header: 1 to 255 visible ASCII characters without spaces or commas. Retry the identical request with the same key to replay its first saved response. Use a new key for a different upload. | Declared schema for `file` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "string", "format": "binary", "x-maximum-bytes": 26214400, "x-allowed-extensions": [ "png", "jpg", "jpeg", "bmp", "gif", "pdf", "msg", "eml", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "rtf", "odp", "odt", "ods", "txt", "wks", "zip" ] } ``` #### Before you upload POST requires an empty invoice slot. If an invoice is already attached, the API returns HTTP 409; use PATCH to replace it. An Invoice Attachment is separate from the record's supporting File Attachments. Use the invoice control beside the Attendee / Registration record's cost and payment details in the web app. #### After the upload The response's invoice_attachment contains the attached file's id, filename and attachment_created_timestamp. The amount, payment fields, cost-center breakdown and other files are unchanged. The upload is recorded in Event history. Attaching an invoice does not mark the record as paid. #### Access and retries A current upload-enabled plan, record and financial permissions, and an editable applicable tab are required. Each uploaded file must fit its supported type and size limits. expected_revision is not supported by this file method. If the save outcome cannot be confirmed, retrieve the current parent record with GET /v1/events/staff/info and inspect invoice_attachment before deciding whether to retry. #### Hidden or locked tab If the Event's Staff tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X POST "https://api.exhibitday.com/v1/events/staff/invoice_attachment" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}" --form-string "staff_entry_id=12345" --form "file=@invoice.pdf;type=application/octet-stream") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi cat response-body.tmp ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const form = new FormData(); form.append("staff_entry_id", "12345"); form.append("file", new Blob([await readFile("invoice.pdf")], { type: "application/octet-stream" }), "invoice.pdf"); const response = await fetch("https://api.exhibitday.com/v1/events/staff/invoice_attachment", { method: "POST", headers: { Authorization: 'Bearer YOUR_API_KEY' }, body: form }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); console.log(await response.json()); ``` Example — Python: ```python import requests import json from contextlib import ExitStack with ExitStack() as stack: files = [ ("file", ("invoice.pdf", stack.enter_context(open("invoice.pdf", 'rb')), "application/octet-stream")), ] response = requests.request("POST", "https://api.exhibitday.com/v1/events/staff/invoice_attachment", headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data={"staff_entry_id": "12345"}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') print(response.json()) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.exhibitday.com/v1/events/staff/invoice_attachment"); var form = new MultipartFormDataContent(); form.Add(new StringContent("12345"), "staff_entry_id"); var file0 = new StreamContent(File.OpenRead("invoice.pdf")); file0.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(file0, "file", "invoice.pdf"); request.Content = form; using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/staff/invoice_attachment")).header("Authorization", "Bearer YOUR_API_KEY"); String boundary = "ExhibitDay-" + UUID.randomUUID(); ByteArrayOutputStream form = new ByteArrayOutputStream(); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"staff_entry_id\"\r\n\r\n" + "12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"invoice.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8)); form.write(Files.readAllBytes(Path.of("invoice.pdf"))); form.write("\r\n".getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); request.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpResponse response = HttpClient.newHttpClient().send(request.method("POST", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); System.out.println(new String(response.body(), StandardCharsets.UTF_8)); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], CURLOPT_POSTFIELDS => [ 'staff_entry_id' => '12345', 'file' => new CURLFile('invoice.pdf', 'application/octet-stream', 'invoice.pdf'), ], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); echo $response; ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/staff/invoice_attachment') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' files = [] begin parts = [ ['staff_entry_id', '12345'], ['file', (files << File.open('invoice.pdf', 'rb')).last, {filename: 'invoice.pdf', content_type: 'application/octet-stream'}], ] request.set_form(parts, 'multipart/form-data') response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' puts response.body ensure files.each(&:close) end ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" "bytes" "mime/multipart" "net/textproto" ) func main() { var form bytes.Buffer writer := multipart.NewWriter(&form) if err := writer.WriteField("staff_entry_id", "12345"); err != nil { log.Fatal(err) } header0 := textproto.MIMEHeader{} header0.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"invoice.pdf\"") header0.Set("Content-Type", "application/octet-stream") part0, err := writer.CreatePart(header0) if err != nil { log.Fatal(err) } file0, err := os.Open("invoice.pdf") if err != nil { log.Fatal(err) } if _, err = io.Copy(part0, file0); err != nil { log.Fatal(err) } file0.Close() if err := writer.Close(); err != nil { log.Fatal(err) } request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/events/staff/invoice_attachment", &form) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", writer.FormDataContentType()) response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } fmt.Printf("%s\n", data) } ``` Example HTTP response body (JSON): POST /v1/events/staff/invoice_attachment - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "invoice_attachment": { "id": 12345, "filename": "invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } } ``` ### Replace Attendee / Registration Invoice Attachment `PATCH https://api.exhibitday.com/v1/events/staff/invoice_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=staff#patch-v1-events-staff-invoice_attachment Replaces this Attendee / Registration's current Invoice Attachment with one uploaded file. Use this method when an invoice file is already attached. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | staff_entry_id | Number | Yes | The ID of the Attendee / Registration record, from Retrieve Attendees / Registrations (GET /v1/events/staff) or its add response. | | | file | File (multipart) | Yes | The Invoice Attachment to upload. | Send exactly one complete, nonempty multipart/form-data file part named file. The supported extensions and current per-file limit are shown below; the complete request limit also includes multipart overhead. A missing or null file is invalid and does not remove an existing invoice. | Declared schema for `file` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "string", "format": "binary", "x-maximum-bytes": 26214400, "x-allowed-extensions": [ "png", "jpg", "jpeg", "bmp", "gif", "pdf", "msg", "eml", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "rtf", "odp", "odt", "ods", "txt", "wks", "zip" ] } ``` #### Replacing the current file PATCH requires a current invoice file. If none is attached, the API returns HTTP 404. Upload exactly one file; the previous attachment ID is not needed. If another request changes the current invoice during your upload, the API refuses this request instead of replacing a different file. Even identical replacement contents receive a new attachment ID. #### After the replacement The response's invoice_attachment contains the attached file's id, filename and attachment_created_timestamp. The amount, payment fields, cost-center breakdown and other files are unchanged. The previous file is scheduled for physical cleanup after a confirmed save; cleanup may finish later. The replacement is recorded in Event history. #### Access and retries A current upload-enabled plan, record and financial permissions, and an editable applicable tab are required. Each uploaded file must fit its supported type and size limits. expected_revision is not supported by this file method. PATCH does not use Idempotency-Key replay. If the save outcome cannot be confirmed, retrieve the current parent record with GET /v1/events/staff/info and inspect invoice_attachment before deciding whether to retry. #### Hidden or locked tab If the Event's Staff tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X PATCH "https://api.exhibitday.com/v1/events/staff/invoice_attachment" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}" --form-string "staff_entry_id=12345" --form "file=@invoice.pdf;type=application/octet-stream") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi cat response-body.tmp ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const form = new FormData(); form.append("staff_entry_id", "12345"); form.append("file", new Blob([await readFile("invoice.pdf")], { type: "application/octet-stream" }), "invoice.pdf"); const response = await fetch("https://api.exhibitday.com/v1/events/staff/invoice_attachment", { method: "PATCH", headers: { Authorization: 'Bearer YOUR_API_KEY' }, body: form }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); console.log(await response.json()); ``` Example — Python: ```python import requests import json from contextlib import ExitStack with ExitStack() as stack: files = [ ("file", ("invoice.pdf", stack.enter_context(open("invoice.pdf", 'rb')), "application/octet-stream")), ] response = requests.request("PATCH", "https://api.exhibitday.com/v1/events/staff/invoice_attachment", headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data={"staff_entry_id": "12345"}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') print(response.json()) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("PATCH"), "https://api.exhibitday.com/v1/events/staff/invoice_attachment"); var form = new MultipartFormDataContent(); form.Add(new StringContent("12345"), "staff_entry_id"); var file0 = new StreamContent(File.OpenRead("invoice.pdf")); file0.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(file0, "file", "invoice.pdf"); request.Content = form; using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/staff/invoice_attachment")).header("Authorization", "Bearer YOUR_API_KEY"); String boundary = "ExhibitDay-" + UUID.randomUUID(); ByteArrayOutputStream form = new ByteArrayOutputStream(); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"staff_entry_id\"\r\n\r\n" + "12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"invoice.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8)); form.write(Files.readAllBytes(Path.of("invoice.pdf"))); form.write("\r\n".getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); request.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpResponse response = HttpClient.newHttpClient().send(request.method("PATCH", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); System.out.println(new String(response.body(), StandardCharsets.UTF_8)); } } ``` Example — PHP: ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], CURLOPT_POSTFIELDS => [ 'staff_entry_id' => '12345', 'file' => new CURLFile('invoice.pdf', 'application/octet-stream', 'invoice.pdf'), ], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); echo $response; ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/staff/invoice_attachment') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' files = [] begin parts = [ ['staff_entry_id', '12345'], ['file', (files << File.open('invoice.pdf', 'rb')).last, {filename: 'invoice.pdf', content_type: 'application/octet-stream'}], ] request.set_form(parts, 'multipart/form-data') response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' puts response.body ensure files.each(&:close) end ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" "bytes" "mime/multipart" "net/textproto" ) func main() { var form bytes.Buffer writer := multipart.NewWriter(&form) if err := writer.WriteField("staff_entry_id", "12345"); err != nil { log.Fatal(err) } header0 := textproto.MIMEHeader{} header0.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"invoice.pdf\"") header0.Set("Content-Type", "application/octet-stream") part0, err := writer.CreatePart(header0) if err != nil { log.Fatal(err) } file0, err := os.Open("invoice.pdf") if err != nil { log.Fatal(err) } if _, err = io.Copy(part0, file0); err != nil { log.Fatal(err) } file0.Close() if err := writer.Close(); err != nil { log.Fatal(err) } request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/events/staff/invoice_attachment", &form) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", writer.FormDataContentType()) response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } fmt.Printf("%s\n", data) } ``` Example HTTP response body (JSON): PATCH /v1/events/staff/invoice_attachment - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "invoice_attachment": { "id": 12345, "filename": "invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } } ``` ### Remove Attendee / Registration Invoice Attachment `DELETE https://api.exhibitday.com/v1/events/staff/invoice_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=staff#delete-v1-events-staff-invoice_attachment Removes this Attendee / Registration's Invoice Attachment. The cost, payment details and other File Attachments stay in place. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | staff_entry_id | Number | Yes | The ID of the Attendee / Registration record, from Retrieve Attendees / Registrations (GET /v1/events/staff) or its add response. | | #### After the removal The Invoice Attachment is cleared and the removal is recorded in Event history. Its physical file is scheduled for cleanup after a confirmed save; cleanup may finish later. Costs, payment fields, cost-center allocations and supporting files stay unchanged. If no invoice is attached, DELETE returns HTTP 404 Not Found with the message "This Attendee / Registration has no invoice to remove." No saved data or history is changed. Current access and the record's binding are still checked. Do not send file parts with this request. #### Access and retries Current record, financial and invoice permissions and applicable tab-edit access are required. Permitted removals remain available on the Free plan. expected_revision is not supported, and DELETE does not use Idempotency-Key replay. If the save outcome cannot be confirmed, retrieve the current parent record with GET /v1/events/staff/info and inspect invoice_attachment before deciding whether to retry. #### Hidden or locked tab If the Event's Staff tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/events/staff/invoice_attachment?staff_entry_id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/staff/invoice_attachment?" + new URLSearchParams({ "staff_entry_id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/events/staff/invoice_attachment", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"staff_entry_id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/events/staff/invoice_attachment?staff_entry_id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/staff/invoice_attachment?staff_entry_id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/staff/invoice_attachment?staff_entry_id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/events/staff/invoice_attachment?staff_entry_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/events/staff/invoice_attachment - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Attachment removed.", "errors": [] } ``` ### Retrieve Attendee / Registration General File Attachments `GET https://api.exhibitday.com/v1/events/staff/attachments` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=staff#get-v1-events-staff-attachments Retrieves the General File Attachments on this Attendee / Registration. Each result includes the file's ID, name and added time; use the download method for its contents. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | staff_entry_id | Number | Yes | The ID of the Attendee / Registration record, from Retrieve Attendees / Registrations (GET /v1/events/staff) or its add response. | | | $limit | Number | No | The most File Attachments to return. | A positive whole number. Omit for all remaining matching files. | | $offset | Number | No | The number of matching File Attachments to skip. | A whole number of 0 or more. Default: 0. | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records. | Allowed values: `array` | | If-None-Match | String | No | An ETag from an earlier response to this GET. | Optional HTTP header. If the successful response is unchanged, the API returns HTTP 304 with no body. | #### Reading the file list Files are ordered by added time, then attachment ID, lowest first. Only files available under your current access are included. Paging totals and X-Total-Count count all matching files before $limit and $offset are applied. A record with no files you can view returns an empty list. This list does not return edit revisions or support changed-since filtering. #### Supporting files and invoices These are the record's General File Attachments. Its cost Invoice Attachment is separate and has its own download and upload methods. Use this list's id values for these supporting-file downloads and removals. #### Access The record's Event and tab must be available, and the tab must not be hidden. A locked tab can still be read. #### Hidden tab If the Event's Staff tab is hidden, this request returns HTTP 400 (not_allowed), and the message says the tab is hidden. Show the tab in ExhibitDay first. A locked tab can still be read. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/events/staff/attachments?staff_entry_id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/staff/attachments?" + new URLSearchParams({ "staff_entry_id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/events/staff/attachments", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"staff_entry_id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/events/staff/attachments?staff_entry_id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/staff/attachments?staff_entry_id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/staff/attachments?staff_entry_id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/staff/attachments?staff_entry_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/events/staff/attachments - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "attachment", "list_data": [ { "id": 12345, "filename": "attachment.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } ] } ``` ### Add Attendee / Registration General File Attachments `POST https://api.exhibitday.com/v1/events/staff/attachments` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=staff#post-v1-events-staff-attachments Adds one or more General File Attachments to this Attendee / Registration. Send each file as a multipart upload part named file. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | staff_entry_id | Number | Yes | The ID of the Attendee / Registration record, from Retrieve Attendees / Registrations (GET /v1/events/staff) or its add response. | | | file | File (multipart) | Yes | The File Attachments to upload. | Send one or more complete, nonempty multipart/form-data parts, each named file. Supported types and the current per-file limit are shown below. The complete request limit includes all files and multipart overhead; split larger batches. A missing or null upload is not a removal request. | | Idempotency-Key | String | No | A unique key for safely retrying this upload. | Optional HTTP header: 1 to 255 visible ASCII characters without spaces or commas. Retry the identical request with the same key to replay its first saved response. Use a new key for a different upload. | Declared schema for `file` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "array", "items": { "type": "string", "format": "binary", "x-maximum-bytes": 26214400, "x-allowed-extensions": [ "png", "jpg", "jpeg", "bmp", "gif", "pdf", "msg", "eml", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "rtf", "odp", "odt", "ods", "txt", "wks", "zip" ] } } ``` #### After the upload The response's list_data contains the newly attached files, including each id, filename and attachment_created_timestamp. Existing files are kept. Use each returned id to download or remove that file. Identical repeated files in one request are attached once when their cleaned filename, length and contents match. Files with different contents remain separate even when their names match. This does not remove or replace files already attached to the record. #### Choosing the right file method These uploads add General File Attachments. Use this record's Invoice Attachment methods for its cost invoice or receipt. Adding supporting files does not change amounts, payments or cost-center allocations. #### Access Current record and file-change permissions and applicable Event/tab locks must allow this upload. An upload-enabled paid plan is required. #### History and retries A confirmed file change is recorded in history. expected_revision is not supported by these file methods. If the save outcome cannot be confirmed, retrieve the current file list before deciding whether to retry; the API does not automatically repeat an uncertain change. Supporting File Attachments have no PATCH replacement. To replace one, add the new file and remove the old one using their separate requests; each request has its own outcome. #### Hidden or locked tab If the Event's Staff tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X POST "https://api.exhibitday.com/v1/events/staff/attachments" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}" --form-string "staff_entry_id=12345" --form "file=@attachment.pdf;type=application/octet-stream") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi cat response-body.tmp ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const form = new FormData(); form.append("staff_entry_id", "12345"); form.append("file", new Blob([await readFile("attachment.pdf")], { type: "application/octet-stream" }), "attachment.pdf"); const response = await fetch("https://api.exhibitday.com/v1/events/staff/attachments", { method: "POST", headers: { Authorization: 'Bearer YOUR_API_KEY' }, body: form }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); console.log(await response.json()); ``` Example — Python: ```python import requests import json from contextlib import ExitStack with ExitStack() as stack: files = [ ("file", ("attachment.pdf", stack.enter_context(open("attachment.pdf", 'rb')), "application/octet-stream")), ] response = requests.request("POST", "https://api.exhibitday.com/v1/events/staff/attachments", headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data={"staff_entry_id": "12345"}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') print(response.json()) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.exhibitday.com/v1/events/staff/attachments"); var form = new MultipartFormDataContent(); form.Add(new StringContent("12345"), "staff_entry_id"); var file0 = new StreamContent(File.OpenRead("attachment.pdf")); file0.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(file0, "file", "attachment.pdf"); request.Content = form; using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/staff/attachments")).header("Authorization", "Bearer YOUR_API_KEY"); String boundary = "ExhibitDay-" + UUID.randomUUID(); ByteArrayOutputStream form = new ByteArrayOutputStream(); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"staff_entry_id\"\r\n\r\n" + "12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"attachment.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8)); form.write(Files.readAllBytes(Path.of("attachment.pdf"))); form.write("\r\n".getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); request.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpResponse response = HttpClient.newHttpClient().send(request.method("POST", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); System.out.println(new String(response.body(), StandardCharsets.UTF_8)); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], CURLOPT_POSTFIELDS => [ 'staff_entry_id' => '12345', 'file' => new CURLFile('attachment.pdf', 'application/octet-stream', 'attachment.pdf'), ], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); echo $response; ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/staff/attachments') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' files = [] begin parts = [ ['staff_entry_id', '12345'], ['file', (files << File.open('attachment.pdf', 'rb')).last, {filename: 'attachment.pdf', content_type: 'application/octet-stream'}], ] request.set_form(parts, 'multipart/form-data') response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' puts response.body ensure files.each(&:close) end ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" "bytes" "mime/multipart" "net/textproto" ) func main() { var form bytes.Buffer writer := multipart.NewWriter(&form) if err := writer.WriteField("staff_entry_id", "12345"); err != nil { log.Fatal(err) } header0 := textproto.MIMEHeader{} header0.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"attachment.pdf\"") header0.Set("Content-Type", "application/octet-stream") part0, err := writer.CreatePart(header0) if err != nil { log.Fatal(err) } file0, err := os.Open("attachment.pdf") if err != nil { log.Fatal(err) } if _, err = io.Copy(part0, file0); err != nil { log.Fatal(err) } file0.Close() if err := writer.Close(); err != nil { log.Fatal(err) } request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/events/staff/attachments", &form) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", writer.FormDataContentType()) response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } fmt.Printf("%s\n", data) } ``` Example HTTP response body (JSON): POST /v1/events/staff/attachments - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "attachment", "list_data": [ { "id": 12345, "filename": "attachment.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } ] } ``` ### Remove an Attendee / Registration General File Attachment `DELETE https://api.exhibitday.com/v1/events/staff/attachments` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=staff#delete-v1-events-staff-attachments Removes one General File Attachment from this Attendee / Registration. Other attached files and the record's details stay in place. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the File Attachment. | Use the id from the attachment list. The API finds the record the file belongs to, so no record ID is sent. An Invoice Attachment is not selected by this method. | #### After the removal Only the selected file association is removed. Its physical file is scheduled for cleanup after a confirmed save; cleanup may finish later. Other attached files stay in place. Send only the file's id; the API finds the record it belongs to. A missing, already removed or unavailable attachment returns HTTP 404 Not Found. Do not send file parts with DELETE. #### Access Current record and file-removal permissions and applicable Event/tab locks must allow this change. Permitted removals remain available on the Free plan. #### History and retries A confirmed file change is recorded in history. expected_revision is not supported by these file methods. DELETE does not use Idempotency-Key replay. If the save outcome cannot be confirmed, retrieve the current file list before deciding whether to retry; the API does not automatically repeat an uncertain change. Supporting File Attachments have no PATCH replacement. To replace one, add the new file and remove the old one using their separate requests; each request has its own outcome. #### Hidden or locked tab If the Event's Staff tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/events/staff/attachments?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/staff/attachments?" + new URLSearchParams({ "id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/events/staff/attachments", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/events/staff/attachments?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/staff/attachments?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/staff/attachments?id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/events/staff/attachments?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/events/staff/attachments - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Attachment removed.", "errors": [] } ``` ### Download an Attendee / Registration General File Attachment `GET https://api.exhibitday.com/v1/events/staff/attachments/download` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=staff#get-v1-events-staff-attachments-download Downloads one original General File Attachment from this Attendee / Registration. Select the file using its ID from the attachment list. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the File Attachment. | Use the id from the attachment list. The API finds the record the file belongs to, so no record ID is sent. An Invoice Attachment is not selected by this method. | #### Download response A successful response contains the original uploaded file with a safe download filename. API errors use the usual JSON response. A missing or unavailable file returns HTTP 404. Send only the file's id from the attachment list to download that one file; the API finds the record it belongs to. The download leaves the record unchanged. #### Access The record's Event and tab must be available, and the tab must not be hidden. A locked tab can still be read. #### Files still being copied If this file is still being copied, the download returns HTTP 409 with file_copy_pending. Try the download again in a few minutes. #### Hidden tab If the Event's Staff tab is hidden, this request returns HTTP 400 (not_allowed), and the message says the tab is hidden. Show the tab in ExhibitDay first. A locked tab can still be read. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X GET "https://api.exhibitday.com/v1/events/staff/attachments/download?id=12345" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi mv response-body.tmp 'attachment.pdf' ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const response = await fetch("https://api.exhibitday.com/v1/events/staff/attachments/download?id=12345", { method: "GET", headers: { Authorization: 'Bearer YOUR_API_KEY' } }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); await writeFile("attachment.pdf", new Uint8Array(await response.arrayBuffer())); ``` Example — Python: ```python import requests import json response = requests.request("GET", "https://api.exhibitday.com/v1/events/staff/attachments/download?id=12345", headers={'Authorization': 'Bearer YOUR_API_KEY'}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') with open("attachment.pdf", 'wb') as destination: destination.write(response.content) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.exhibitday.com/v1/events/staff/attachments/download?id=12345"); using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); await File.WriteAllBytesAsync("attachment.pdf", await response.Content.ReadAsByteArrayAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/staff/attachments/download?id=12345")).header("Authorization", "Bearer YOUR_API_KEY"); HttpResponse response = HttpClient.newHttpClient().send(request.method("GET", HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); Files.write(Path.of("attachment.pdf"), response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); file_put_contents('attachment.pdf', $response); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/staff/attachments/download?id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' File.binwrite('attachment.pdf', response.body) ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/staff/attachments/download?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } if err := os.WriteFile("attachment.pdf", data, 0600); err != nil { log.Fatal(err) } fmt.Println("File saved") } ``` HTTP 200: Returns the original uploaded file as a private download, using a safe filename. If the file cannot be downloaded, the response contains the usual JSON API error instead. Media: application/octet-stream. The body is the authorized file's real bytes, not JSON or base64. Errors are JSON status responses; check HTTP status before saving the file. ## Events - Travel Reservations Travel Reservations on an Event: transportation and lodging bookings, tagged people, costs, invoices, file attachments and exports. Documentation page: https://api.exhibitday.com/Help/V1?epf=1&topic=travel-reservations ### Retrieve a Single Travel Reservation by ID `GET https://api.exhibitday.com/v1/events/travel_reservations/info` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=travel-reservations#get-v1-events-travel_reservations-info Retrieves a Travel Reservation by its ID, including its booking details, tagged people, costs and payment information. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Travel Reservation. | Use the id from Retrieve Travel Reservations (GET /v1/events/travel_reservations) or from the add response. You don't send the Event ID; the record's Event is found automatically. | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` \| `object` | | $include_record_revision | Boolean | No | Whether to include record_revision in the response. | Default: false. Send true to get record_revision, then send that value as expected_revision when you update this reservation. See What $include_record_revision covers below. | | $on_error_return_empty_result | Boolean | No | Whether an invalid or unavailable reservation should return an empty result. | Default: false. True returns HTTP 200 with {} (or [] for array format) for invalid IDs or an unavailable reservation. API key errors, conflicts with a change in progress, inconsistent invoice information and unexpected errors keep their normal status. | | If-None-Match | String | No | An ETag from an earlier response to this GET. | Optional HTTP header. If the successful response is unchanged, the API returns HTTP 304 with no body. | #### What $include_record_revision covers Setting $include_record_revision=true returns record_revision for use as expected_revision on a later update. record_revision covers the saved reservation details, payment fields, cost allocations, tagged-person IDs, related-item links and Event binding. File Attachment or Invoice Attachment metadata/contents and notification delivery state are not included. #### Files and access Invoice Attachment metadata is included as invoice_attachment, or null if no invoice is attached. Supporting File Attachments have their own collection and download operation. The Event's Travel Reservations tab must be available and readable. A locked tab can still be read. Inconsistent invoice information returns HTTP 409 instead of exposing another record's file. #### Formatted text in the response Notes and other rich-text values in the response contain the stored HTML, including encoded characters and line breaks such as `
`. #### Open in ExhibitDay Each record includes exhibitday_url, the record's page in ExhibitDay. It opens the record in view mode on its Event's tab. Sign in with an account that can view the record; ExhibitDay checks access when the link is opened. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/events/travel_reservations/info?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/travel_reservations/info?" + new URLSearchParams({ "id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/events/travel_reservations/info", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/events/travel_reservations/info?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/travel_reservations/info?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/travel_reservations/info?id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/travel_reservations/info?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/events/travel_reservations/info - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "id": 12345, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=23456&riType=9&riSub=0&riId=12345", "event_id": 23456, "event_name": "Sample Event", "reservation_type_id": 1, "booking_status_id": null, "book_by_date": null, "date_booked": null, "booking_url": null, "cancellation_instructions": null, "vehicle_drop_off_location": null, "reservation_number": "AB123", "origin_vendor_name": "Example Airline", "origin_flight_number": null, "origin_reservation_item_info": null, "origin_checkin_location": null, "origin_checkin_date": "2027-02-03", "origin_checkin_time": "09:30", "origin_reservation_details": null, "origin_destination_location": null, "origin_destination_date": null, "origin_destination_time": null, "origin_reservation_final_details": null, "return_vendor_name": null, "return_flight_number": null, "return_reservation_item_info": null, "return_checkin_location": null, "return_checkin_date": null, "return_checkin_time": null, "return_reservation_details": null, "return_destination_location": null, "return_destination_date": null, "return_destination_time": null, "return_reservation_final_details": null, "origin_vendor_address": null, "notes": "", "payment_status_id": 0, "payment_due_date": null, "next_payment_due_date": null, "payment_notes": null, "invoice_attachment": { "id": 882345, "filename": "travel-reservation-invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" }, "reservation_type": "Flight", "reservation_group": "Transportation", "booking_status": "Not Specified", "payment_status": { "id": 0, "name": "N/A" }, "cost": { "amount": 200.00, "cost_center_breakdown": [ { "cost_center_id": 54321, "cost_center": "Marketing", "charge": 125.50 }, { "cost_center_id": 54322, "cost_center": "Operations", "charge": 74.50 } ] }, "tagged_users": [ { "id": "11111111-2222-4333-8444-555555555551", "first_name": "Alex", "last_name": "Rivera", "display_name": "Alex Rivera", "email": "alex@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, { "id": "11111111-2222-4333-8444-555555555552", "first_name": "Jamie", "last_name": "Chen", "display_name": "Jamie Chen", "email": "jamie@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true } ], "created_by": { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, "related_items": [ { "id": 5551, "related_item_id": 67890, "related_item_exhibitday_url": "https://www.exhibitday.com/Workspace/TaskView/98765?tid=67890", "related_item_type_id": 1, "related_item_type": "Task", "related_item_asset_type_id": null, "related_item_name": "Confirm booth graphics with the printer", "related_item_created_timestamp": "2030-01-10T14:03:00Z" }, { "id": 5552, "related_item_id": 45678, "related_item_exhibitday_url": "https://www.exhibitday.com/Workspace/RelatedItemView/98765?typeId=4&subTypeId=0&rid=45678", "related_item_type_id": 4, "related_item_type": "Shipment", "related_item_asset_type_id": null, "related_item_name": "Booth crates to convention center", "related_item_created_timestamp": "2030-01-10T14:03:00Z" } ] } ``` ### Retrieve Travel Reservations `GET https://api.exhibitday.com/v1/events/travel_reservations` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=travel-reservations#get-v1-events-travel_reservations Retrieves records across your workspace's readable Event tabs. Use filter_by_event_id to narrow the results to one Event, or omit it for the workspace list. Each record includes its event_id and Event name. Use filter_by_tagged_user_ids to select tagged people or Resources. any is the default; all requires every selected ID and permits additional tags. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | filter_by_event_id | Number | No | Return records for this Event only. Omit for all readable Events in your workspace. | | | filter_by_tagged_user_ids | String or JSON array | No | Return records tagged with these users or resources. Send one user ID or an array of user IDs, for example "user-id" or ["user-id","other-user-id"]. Omit, leave blank or send [] for no tagged-user filter. Duplicate IDs collapse. Inactive and deactivated people, and people no longer in this workspace, still match the records they are tagged on; IDs never tagged in this workspace match nothing. Use filter_by_tagged_user_ids_match_type to require at least one or every selected person. This filter combines with the other filters before counting and paging. | | | filter_by_tagged_user_ids_match_type | String | No | How to match the selected tagged people. Omit or leave blank to return records tagged with at least one selected person (the default), or require every selected person; records can have other tags too. This combines with the other filters before counting and paging. If filter_by_tagged_user_ids has no IDs, this option is ignored and the response includes a warning. Values are case-insensitive. | Allowed values: `any` \| `all` | | $limit | Number | No | The most Travel Reservations to return: a whole number of 1 or more. Omit it for all remaining matches; a blank value or null is refused, so leave the parameter out instead. | | | $offset | Number | No | How many matching Travel Reservations to skip: a whole number of 0 or more. Default: 0. A blank value or null is refused. | | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | | hydrate_related_items | Boolean | No | Set to true to include each record's related_items: the Tasks and items linked to it, with the key to use when adding or removing a link. Omit it or send false to leave related_items out of list results. Single-record GETs always include related_items. | Default: false. | Declared schema for `filter_by_tagged_user_ids` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "oneOf": [ { "type": "string", "minLength": 1, "maxLength": 128, "pattern": "\\S" }, { "type": "array", "items": { "type": "string", "minLength": 1, "maxLength": 128, "pattern": "\\S" } } ], "x-normalization": "one string becomes a one-item array; trimmed distinct IDs; no record-count cap", "nullable": false, "x-maximum-depth": 1, "x-empty-create-means-omitted": false, "example": [ "user-id" ] } ``` #### Choosing Events Omit `filter_by_event_id` to retrieve records across readable Event tabs, or supply one Event ID to narrow the list. Each result retains its own `event_id` and Event name. Hidden or unavailable Event tabs are not included. A locked tab can still be read. If no records match, the response is an empty list. #### Filtering tagged people `filter_by_tagged_user_ids` accepts one user ID string or an array. Set `filter_by_tagged_user_ids_match_type=any` (the default) to match at least one selected ID, or `all` to require every selected ID. Additional tags are allowed. Omit the IDs, leave them blank or send `[]` for no tag filter. Sending `filter_by_tagged_user_ids_match_type` without IDs is ignored with a warning. Stored assignments and tags match directly: inactive and deactivated people, Resources and people no longer in this workspace still match the records they are on. IDs never used on this workspace's records match nothing; this is not an error. The people and Event filters combine with AND before counting and paging. #### Reading pages The Event filter and any people filter are applied before the total count and paging. Results are ordered by Event start date ascending, Event ID ascending, then Travel display order, then Travel ID descending. Use `$limit` and `$offset` for successive pages. Omit `$limit` to return all remaining matches. `total_records` and `X-Total-Count` describe all matches; `records_found` counts this response. Omit `$result_format` for the normal list wrapper. `array` returns only the records; `wrapped_in_array` places the normal wrapper in a one-item array. #### Handling input and changes Unrecognized parameters are ignored and listed in the `X-API-Warnings` response header. Conflicting or malformed filter values return HTTP `400`; send arrays in JSON, query parameters or form fields rather than comma-bearing headers. Current API access is checked even when the list is empty. A concurrent change can return HTTP `409`; retrieve the list again. These filters retrieve records and do not change tags, assignments or notification settings. #### Related items Set `hydrate_related_items=true` to include each record's `related_items`: the Tasks and items linked to it. Add or remove links with POST and DELETE /v1/related_items. It is left out by default to keep lists fast. Retrieving one record always includes `related_items`. #### Formatted text in the response Notes and other rich-text values in the response contain the stored HTML, including encoded characters and line breaks such as `
`. #### Events with a hidden Travel tab Records on Events whose Travel tab is hidden are not listed. If filter_by_event_id names such an Event, the response is HTTP 200 with no records for it and a warning that names the tab and the Event. #### Open in ExhibitDay Each record includes exhibitday_url, the record's page in ExhibitDay. It opens the record in view mode on its Event's tab. Sign in with an account that can view the record; ExhibitDay checks access when the link is opened. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/events/travel_reservations" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/travel_reservations", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/events/travel_reservations", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/events/travel_reservations"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/travel_reservations")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/travel_reservations') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/travel_reservations", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/events/travel_reservations - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "list_type": "travel_reservation", "list_data": [ { "id": 12345, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=23456&riType=9&riSub=0&riId=12345", "event_id": 23456, "event_name": "Sample Event", "reservation_type_id": 1, "booking_status_id": null, "book_by_date": null, "date_booked": null, "booking_url": null, "cancellation_instructions": null, "vehicle_drop_off_location": null, "reservation_number": "AB123", "origin_vendor_name": "Example Airline", "origin_flight_number": null, "origin_reservation_item_info": null, "origin_checkin_location": null, "origin_checkin_date": "2027-02-03", "origin_checkin_time": "09:30", "origin_reservation_details": null, "origin_destination_location": null, "origin_destination_date": null, "origin_destination_time": null, "origin_reservation_final_details": null, "return_vendor_name": null, "return_flight_number": null, "return_reservation_item_info": null, "return_checkin_location": null, "return_checkin_date": null, "return_checkin_time": null, "return_reservation_details": null, "return_destination_location": null, "return_destination_date": null, "return_destination_time": null, "return_reservation_final_details": null, "origin_vendor_address": null, "notes": "", "payment_status_id": 0, "payment_due_date": null, "next_payment_due_date": null, "payment_notes": null, "invoice_attachment": { "id": 882345, "filename": "travel-reservation-invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" }, "reservation_type": "Flight", "reservation_group": "Transportation", "booking_status": "Not Specified", "payment_status": { "id": 0, "name": "N/A" }, "cost": { "amount": 200.00, "cost_center_breakdown": [ { "cost_center_id": 54321, "cost_center": "Marketing", "charge": 125.50 }, { "cost_center_id": 54322, "cost_center": "Operations", "charge": 74.50 } ] }, "tagged_users": [ { "id": "11111111-2222-4333-8444-555555555551", "first_name": "Alex", "last_name": "Rivera", "display_name": "Alex Rivera", "email": "alex@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, { "id": "11111111-2222-4333-8444-555555555552", "first_name": "Jamie", "last_name": "Chen", "display_name": "Jamie Chen", "email": "jamie@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true } ], "created_by": { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true } }, { "id": 12346, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=23456&riType=9&riSub=0&riId=12346", "event_id": 23456, "event_name": "Sample Event", "reservation_type_id": 6, "booking_status_id": null, "book_by_date": null, "date_booked": null, "booking_url": null, "cancellation_instructions": null, "vehicle_drop_off_location": null, "reservation_number": "HOTEL456", "origin_vendor_name": "Example Hotel", "origin_flight_number": null, "origin_reservation_item_info": null, "origin_checkin_location": null, "origin_checkin_date": "2027-02-03", "origin_checkin_time": "09:30", "origin_reservation_details": null, "origin_destination_location": null, "origin_destination_date": null, "origin_destination_time": null, "origin_reservation_final_details": null, "return_vendor_name": null, "return_flight_number": null, "return_reservation_item_info": null, "return_checkin_location": null, "return_checkin_date": null, "return_checkin_time": null, "return_reservation_details": null, "return_destination_location": null, "return_destination_date": null, "return_destination_time": null, "return_reservation_final_details": null, "origin_vendor_address": null, "notes": "", "payment_status_id": 0, "payment_due_date": null, "next_payment_due_date": null, "payment_notes": null, "invoice_attachment": { "id": 882346, "filename": "travel-reservation-invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" }, "reservation_type": "Hotel", "reservation_group": "Lodging", "booking_status": "Not Specified", "payment_status": { "id": 0, "name": "N/A" }, "cost": { "amount": 200.00, "cost_center_breakdown": [ { "cost_center_id": 54321, "cost_center": "Marketing", "charge": 125.50 }, { "cost_center_id": 54322, "cost_center": "Operations", "charge": 74.50 } ] }, "tagged_users": [ { "id": "11111111-2222-4333-8444-555555555551", "first_name": "Alex", "last_name": "Rivera", "display_name": "Alex Rivera", "email": "alex@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, { "id": "11111111-2222-4333-8444-555555555552", "first_name": "Jamie", "last_name": "Chen", "display_name": "Jamie Chen", "email": "jamie@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true } ], "created_by": { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true } } ], "records_found": 2, "total_records": 2, "has_more": false } ``` ### Add a Travel Reservation `POST https://api.exhibitday.com/v1/events/travel_reservations` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=travel-reservations#post-v1-events-travel_reservations Adds a Travel Reservation to an Event. Choose the transportation or lodging type, then record its booking details and the people it is for. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | event_id | Number | Yes | The ID of the Event. | The reservation will be added to this Event. | | reservation_type_id | Number | Yes | The transportation or lodging type. Required when adding a reservation. Choose a type currently returned by GET /v1/references/travel_reservation_types. The selected type determines which travel-detail fields apply; blank or null is refused as missing. | Allowed values: `1` (Flight) \| `2` (Train) \| `3` (Bus) \| `4` (Automobile) \| `5` (Other Transportation) \| `6` (Hotel) \| `7` (Other Lodging) \| `8` (Bed and Breakfast) | | booking_status_id | Number | No | The reservation's booking status. Omit or send null for Not Specified. | Allowed values: `10` (Not Booked Yet) \| `20` (Booked) \| `30` (Canceled) | | book_by_date | String | No | The date by which you want to book the reservation. | Use a calendar date in YYYY-MM-DD format. Omit for no value. | | date_booked | String | No | The date the reservation was booked. | Use a calendar date in YYYY-MM-DD format. Omit for no value. | | booking_url | String | No | A link to book or manage the reservation. | Up to 2,000 characters, excluding surrounding spaces. Omit for no value. | | cancellation_instructions | String | No | Instructions for canceling the reservation. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Both the saved text and the ExhibitDay editor's character count must fit within 30,000 characters; line breaks and characters such as & and < take extra space when saved. Omit for no value. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | vehicle_drop_off_location | String | No | The drop-off location for Automobile or Other Transportation. | Up to 1,000 characters, excluding surrounding spaces. Omit for no value. Applies to Automobile (4), Other Transportation (5). | | reservation_number | String | No | The confirmation or reservation number. | Up to 125 characters, excluding surrounding spaces. Omit for no value. | | origin_vendor_name | String | No | The outbound airline, transport operator, rental company or lodging name. | Up to 125 characters, excluding surrounding spaces. Omit for no value. | | origin_flight_number | String | No | The outbound flight number. | Up to 100 characters, excluding surrounding spaces. Omit for no value. Applies to Flight (1). | | origin_reservation_item_info | String | No | The outbound class or seat information, vehicle type or lodging room information. | Up to 125 characters, excluding surrounding spaces. Omit for no value. Applies to Flight (1), Train (2), Bus (3), Automobile (4), Hotel (6), Other Lodging (7), Bed and Breakfast (8). | | origin_checkin_location | String | No | The outbound departure airport or station. | Up to 250 characters, excluding surrounding spaces. Omit for no value. Applies to Flight (1), Train (2), Bus (3). | | origin_checkin_date | String | No | The outbound departure, vehicle pickup or lodging check-in date. | Use a calendar date in YYYY-MM-DD format. Omit for no value. | | origin_checkin_time | String | No | The local outbound departure, vehicle pickup or lodging check-in time. | Use local HH:mm, from 00:00 through 23:59, with no time zone conversion. See Dates and local times below. Omit for no value. | | origin_reservation_details | String | No | Outbound layover or connection information. | Up to 750 characters, excluding surrounding spaces. Omit for no value. Applies to Flight (1). | | origin_destination_location | String | No | The outbound arrival airport or station. | Up to 250 characters, excluding surrounding spaces. Omit for no value. Applies to Flight (1), Train (2), Bus (3). | | origin_destination_date | String | No | The outbound arrival date. | Use a calendar date in YYYY-MM-DD format. Omit for no value. Applies to Flight (1), Train (2), Bus (3). | | origin_destination_time | String | No | The local outbound arrival time. | Use local HH:mm, from 00:00 through 23:59, with no time zone conversion. See Dates and local times below. Omit for no value. Applies to Flight (1), Train (2), Bus (3). | | origin_reservation_final_details | String | No | Outbound arrival information, pickup notes or lodging check-in information. | Up to 750 characters, excluding surrounding spaces. Omit for no value. | | return_vendor_name | String | No | The return airline or transport operator. | Up to 125 characters, excluding surrounding spaces. Omit for no value. Applies to Flight (1), Train (2), Bus (3). | | return_flight_number | String | No | The return flight number. | Up to 100 characters, excluding surrounding spaces. Omit for no value. Applies to Flight (1). | | return_reservation_item_info | String | No | The return class, cabin or seat information. | Up to 125 characters, excluding surrounding spaces. Omit for no value. Applies to Flight (1), Train (2), Bus (3). | | return_checkin_location | String | No | The return departure airport or station. | Up to 250 characters, excluding surrounding spaces. Omit for no value. Applies to Flight (1), Train (2), Bus (3). | | return_checkin_date | String | No | The return departure, vehicle drop-off or lodging check-out date. | Use a calendar date in YYYY-MM-DD format. Omit for no value. | | return_checkin_time | String | No | The local return departure, vehicle drop-off or lodging check-out time. | Use local HH:mm, from 00:00 through 23:59, with no time zone conversion. See Dates and local times below. Omit for no value. | | return_reservation_details | String | No | Return layover or connection information. | Up to 750 characters, excluding surrounding spaces. Omit for no value. Applies to Flight (1). | | return_destination_location | String | No | The return arrival airport or station. | Up to 250 characters, excluding surrounding spaces. Omit for no value. Applies to Flight (1), Train (2), Bus (3). | | return_destination_date | String | No | The return arrival date. | Use a calendar date in YYYY-MM-DD format. Omit for no value. Applies to Flight (1), Train (2), Bus (3). | | return_destination_time | String | No | The local return arrival time. | Use local HH:mm, from 00:00 through 23:59, with no time zone conversion. See Dates and local times below. Omit for no value. Applies to Flight (1), Train (2), Bus (3). | | return_reservation_final_details | String | No | Return arrival information, drop-off notes or lodging check-out information. | Up to 750 characters, excluding surrounding spaces. Omit for no value. | | origin_vendor_address | String | No | The pickup or lodging address. | Up to 500 characters, excluding surrounding spaces. Omit for no value. Applies to Automobile (4), Other Transportation (5), Hotel (6), Other Lodging (7), Bed and Breakfast (8). | | notes | String | No | Notes about this Travel Reservation. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Both the saved text and the ExhibitDay editor's character count must fit within 30,000 characters; line breaks and characters such as & and < take extra space when saved. Omit for no value. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | payment_status_id | Number | No | The reservation's payment status. Omit for N/A. A status other than Partially Paid clears the next partial payment due date. | Allowed values: `0` (N/A) \| `1` (Paid in Full) \| `2` (Partially Paid) \| `3` (Not Paid Yet) | | payment_due_date | String | No | The reservation payment due date. | Use a calendar date in YYYY-MM-DD format. Omit for no value. | | next_payment_due_date | Date | No | The next partial payment due date. | Use a calendar date in YYYY-MM-DD format. Applies only to Partially Paid (2). Supplying it with another payment status clears the date; choosing another status also clears it. Omit for no value. | | payment_notes | String | No | Notes about the reservation payment. | Up to 200 characters, excluding surrounding spaces. Omit for no value. | | tagged_user_ids | JSON object/list | No | The people associated with this reservation. | A JSON array of unique, active workspace user or resource IDs, each 1 to 128 characters with no surrounding whitespace. A supplied array replaces the full tag list. Omit for no tagged people. Retained tags keep their notification state; only newly added tags can schedule notifications. | | notify_tagged_users | Boolean | No | Whether to notify newly tagged people. | Default: true when omitted or blank, subject to each person's preferences and recipient eligibility. False suppresses notifications only for tags added by this request. Existing tags are unchanged. JSON null is refused even when ignore-empty is true. Changing this option alone makes no reservation change or revision change. | | cost | Number or cost object | No | The full cost, as a number or an object with amount and/or cost_center_breakdown. [Record Costs and Split Them Across Cost Centers](/Help/V1?guide=entering-costs). | Optional; defaults to zero. | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` \| `object` | | Idempotency-Key | String | No | A unique key for safely retrying this add request. | Optional HTTP header: 1 to 255 visible ASCII characters without spaces or commas. Retry the identical request with the same key to replay its first saved response. Use a new key for a different request. | | $ignore_params_with_empty_values | Boolean | No | Whether supplied JSON null values should be omitted. | Default: false. With true, actual JSON null fields and tag lists are omitted. Nonempty text null still requests clearing where supported. This option does not bypass required values, strict notify_tagged_users input or revision checks. | | $request_principal_name | String | No | A display label for API-origin creation or newly added tags. | Optional; up to 122 characters. Omit or leave blank for ExhibitDay API. This is a display label, not a workspace user ID. | Declared schema for `tagged_user_ids` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "array", "items": { "type": "string" }, "maxItems": 2147483647, "nullable": true, "x-maximum-depth": 2, "x-empty-create-means-omitted": true, "example": [ "user-id" ] } ``` Declared schema for `cost` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "anyOf": [ { "type": "number", "minimum": 0, "description": "Shorthand for an object with amount. The amount is rounded to cents before the supported storage range is checked.", "nullable": true }, { "type": "object", "additionalProperties": false, "properties": { "amount": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 }, "cost_center_breakdown": { "type": "array", "items": { "type": "object", "additionalProperties": false, "properties": { "cost_center_id": { "type": "integer", "format": "int64", "nullable": true }, "charge": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 }, "cost_center": { "type": "string", "description": "Optional and read-only: the cost center name a read returns, so a cost can be sent back unchanged. It is ignored; the line is saved by cost_center_id, and a name that doesn't match that cost center is explained in a warning.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "required": [ "charge" ] }, "maxItems": 2147483647 } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "anyOf": [ { "required": [ "amount" ] }, { "required": [ "cost_center_breakdown" ] } ], "nullable": true } ], "x-numeric-shorthand": "A number is equivalent to {amount:number}.", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": { "amount": 125.50 } } ``` #### Choosing travel details The selected reservation type determines which fields are used. The origin fields describe the outbound journey, vehicle pickup or lodging check-in; return fields describe the return journey, drop-off or check-out. A supplied field that does not apply to the selected type is not kept; the table shows which types use each field. #### Dates and local times Enter each clock time in the local time at the relevant departure, arrival, pickup, drop-off or lodging location. The API does not convert timezones. Changing a date preserves an already recorded matching clock time. Clearing a date alone does not clear its clock time. To remove both, clear both fields. A clock time can also be supplied without a date. #### Tagging people and notifications A supplied tagged_user_ids array replaces the full tag list. Include any currently tagged people you want to keep. Users and Resources can both be tagged; notifications depend on actual recipient eligibility and preferences. notify_tagged_users defaults to true for newly added tags. False suppresses only those new notifications. Retained tags keep their existing notification state; changing the option alone saves no reservation change. #### After the add The response includes the new reservation and its id. The change is recorded in Event history. File Attachments and the Invoice Attachment are uploaded separately. Recording costs does not attach an invoice, mark a payment complete or change the Event's planned Travel budget. If a save outcome cannot be confirmed, retrieve the current reservation before deciding whether to retry. #### Access The Event's Travel Reservations tab must be available, visible and unlocked, and your current access must allow the change. #### Sending values Use JSON, query parameters or form fields for text containing commas and tag arrays. #### Sending text Send plain text for Notes and other rich-text fields. Characters such as `&`, `<` and quotes, along with line breaks, are encoded for storage. Notes and other rich-text values in the response contain the stored HTML, including encoded characters and line breaks such as `
`. #### Hidden or locked tab If the Event's Travel tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. An Event that is not in your workspace returns HTTP 404. #### Fields for each reservation type Each trip field applies only to some reservation types. A value for a field that doesn't apply to the reservation's type is not saved, and the response includes a warning that names the field and the type. - reservation_number: Flight, Train, Bus, Automobile, Other Transportation, Hotel, Other Lodging, Bed and Breakfast (B&B) - origin_vendor_name: Flight, Train, Bus, Automobile, Other Transportation, Hotel, Other Lodging, Bed and Breakfast (B&B) - origin_flight_number: Flight - origin_reservation_item_info: Flight, Train, Bus, Automobile, Hotel, Other Lodging, Bed and Breakfast (B&B) - origin_checkin_date: Flight, Train, Bus, Automobile, Other Transportation, Hotel, Other Lodging, Bed and Breakfast (B&B) - origin_checkin_time: Flight, Train, Bus, Automobile, Other Transportation, Hotel, Other Lodging, Bed and Breakfast (B&B) - origin_reservation_details: Flight - origin_destination_date: Flight, Train, Bus - origin_destination_time: Flight, Train, Bus - origin_reservation_final_details: Flight, Train, Bus, Automobile, Other Transportation, Hotel, Other Lodging, Bed and Breakfast (B&B) - return_vendor_name: Flight, Train, Bus - return_flight_number: Flight - return_reservation_item_info: Flight, Train, Bus - return_checkin_date: Flight, Train, Bus, Automobile, Other Transportation, Hotel, Other Lodging, Bed and Breakfast (B&B) - return_checkin_time: Flight, Train, Bus, Automobile, Other Transportation, Hotel, Other Lodging, Bed and Breakfast (B&B) - return_reservation_details: Flight - return_destination_date: Flight, Train, Bus - return_destination_time: Flight, Train, Bus - return_reservation_final_details: Flight, Train, Bus, Automobile, Other Transportation, Hotel, Other Lodging, Bed and Breakfast (B&B) - origin_vendor_address: Automobile, Other Transportation, Hotel, Other Lodging, Bed and Breakfast (B&B) #### Open in ExhibitDay The created record includes exhibitday_url, the record's page in ExhibitDay. It is the same link that GET /v1/events/travel_reservations/info returns for this record and opens the record in view mode on its Event's tab. Sign in with an account that can view the record; ExhibitDay checks access when the link is opened. Example — curl: ```bash curl -X POST "https://api.exhibitday.com/v1/events/travel_reservations" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"event_id\":23456,\"reservation_type_id\":1}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/travel_reservations", { method: "POST", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "event_id": 23456, "reservation_type_id": 1 }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.post( "https://api.exhibitday.com/v1/events/travel_reservations", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"event_id": 23456, "reservation_type_id": 1}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PostAsync("https://api.exhibitday.com/v1/events/travel_reservations", JsonContent.Create(new { event_id = 23456, reservation_type_id = 1 })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/travel_reservations")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("POST", HttpRequest.BodyPublishers.ofString("{\"event_id\":23456,\"reservation_type_id\":1}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"event_id":23456,"reservation_type_id":1}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/travel_reservations') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"event_id":23456,"reservation_type_id":1}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/events/travel_reservations", strings.NewReader("{\"event_id\":23456,\"reservation_type_id\":1}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): POST /v1/events/travel_reservations - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "id": 12345, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=23456&riType=9&riSub=0&riId=12345", "event_id": 23456, "event_name": "Sample Event", "reservation_type_id": 1, "booking_status_id": null, "book_by_date": null, "date_booked": null, "booking_url": null, "cancellation_instructions": null, "vehicle_drop_off_location": null, "reservation_number": null, "origin_vendor_name": null, "origin_flight_number": null, "origin_reservation_item_info": null, "origin_checkin_location": null, "origin_checkin_date": null, "origin_checkin_time": null, "origin_reservation_details": null, "origin_destination_location": null, "origin_destination_date": null, "origin_destination_time": null, "origin_reservation_final_details": null, "return_vendor_name": null, "return_flight_number": null, "return_reservation_item_info": null, "return_checkin_location": null, "return_checkin_date": null, "return_checkin_time": null, "return_reservation_details": null, "return_destination_location": null, "return_destination_date": null, "return_destination_time": null, "return_reservation_final_details": null, "origin_vendor_address": null, "notes": "", "payment_status_id": 0, "payment_due_date": null, "next_payment_due_date": null, "payment_notes": null, "invoice_attachment": null, "reservation_type": "Flight", "reservation_group": "Transportation", "booking_status": "Not Specified", "payment_status": { "id": 0, "name": "N/A" }, "cost": { "amount": 0.00, "cost_center_breakdown": [] }, "tagged_users": [], "created_by": { "id": null, "first_name": "ExhibitDay", "last_name": "API", "display_name": "ExhibitDay API", "email": null, "type": null, "workspace_role": null, "is_active": true } } ``` ### Update a Travel Reservation `PATCH https://api.exhibitday.com/v1/events/travel_reservations` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=travel-reservations#patch-v1-events-travel_reservations Updates a Travel Reservation's booking, travel, payment or tagged-person details. Send only the fields you want to change. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Travel Reservation. | Use its id from the list, single-record read or add response. | | reservation_type_id | Number | No | The transportation or lodging type. Choose a type currently returned by GET /v1/references/travel_reservation_types. Omit or leave blank to keep it; null cannot clear it. Changing type clears details not used by the new type. | Allowed values: `1` (Flight) \| `2` (Train) \| `3` (Bus) \| `4` (Automobile) \| `5` (Other Transportation) \| `6` (Hotel) \| `7` (Other Lodging) \| `8` (Bed and Breakfast) | | booking_status_id | Number | No | The reservation's booking status. Omit or leave blank to keep it; null means Not Specified. | Allowed values: `10` (Not Booked Yet) \| `20` (Booked) \| `30` (Canceled) | | book_by_date | String | No | The date by which you want to book the reservation. | Use a calendar date in YYYY-MM-DD format. Omit or leave blank to keep it; null clears it. | | date_booked | String | No | The date the reservation was booked. | Use a calendar date in YYYY-MM-DD format. Omit or leave blank to keep it; null clears it. | | booking_url | String | No | A link to book or manage the reservation. | Up to 2,000 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. | | cancellation_instructions | String | No | Instructions for canceling the reservation. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Both the saved text and the ExhibitDay editor's character count must fit within 30,000 characters; line breaks and characters such as & and < take extra space when saved. Omit or leave blank to keep it; null clears it. Existing over-limit content can stay unchanged or be shortened, but neither count may grow. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | vehicle_drop_off_location | String | No | The drop-off location for Automobile or Other Transportation. | Up to 1,000 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. Applies to Automobile (4), Other Transportation (5). | | reservation_number | String | No | The confirmation or reservation number. | Up to 125 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. | | origin_vendor_name | String | No | The outbound airline, transport operator, rental company or lodging name. | Up to 125 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. | | origin_flight_number | String | No | The outbound flight number. | Up to 100 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. Applies to Flight (1). | | origin_reservation_item_info | String | No | The outbound class or seat information, vehicle type or lodging room information. | Up to 125 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. Applies to Flight (1), Train (2), Bus (3), Automobile (4), Hotel (6), Other Lodging (7), Bed and Breakfast (8). | | origin_checkin_location | String | No | The outbound departure airport or station. | Up to 250 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. Applies to Flight (1), Train (2), Bus (3). | | origin_checkin_date | String | No | The outbound departure, vehicle pickup or lodging check-in date. | Use a calendar date in YYYY-MM-DD format. Omit or leave blank to keep it; null clears it. | | origin_checkin_time | String | No | The local outbound departure, vehicle pickup or lodging check-in time. | Use local HH:mm, from 00:00 through 23:59, with no time zone conversion. See Dates and local times below. Omit or leave blank to keep it; null clears it. | | origin_reservation_details | String | No | Outbound layover or connection information. | Up to 750 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. Applies to Flight (1). | | origin_destination_location | String | No | The outbound arrival airport or station. | Up to 250 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. Applies to Flight (1), Train (2), Bus (3). | | origin_destination_date | String | No | The outbound arrival date. | Use a calendar date in YYYY-MM-DD format. Omit or leave blank to keep it; null clears it. Applies to Flight (1), Train (2), Bus (3). | | origin_destination_time | String | No | The local outbound arrival time. | Use local HH:mm, from 00:00 through 23:59, with no time zone conversion. See Dates and local times below. Omit or leave blank to keep it; null clears it. Applies to Flight (1), Train (2), Bus (3). | | origin_reservation_final_details | String | No | Outbound arrival information, pickup notes or lodging check-in information. | Up to 750 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. | | return_vendor_name | String | No | The return airline or transport operator. | Up to 125 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. Applies to Flight (1), Train (2), Bus (3). | | return_flight_number | String | No | The return flight number. | Up to 100 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. Applies to Flight (1). | | return_reservation_item_info | String | No | The return class, cabin or seat information. | Up to 125 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. Applies to Flight (1), Train (2), Bus (3). | | return_checkin_location | String | No | The return departure airport or station. | Up to 250 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. Applies to Flight (1), Train (2), Bus (3). | | return_checkin_date | String | No | The return departure, vehicle drop-off or lodging check-out date. | Use a calendar date in YYYY-MM-DD format. Omit or leave blank to keep it; null clears it. | | return_checkin_time | String | No | The local return departure, vehicle drop-off or lodging check-out time. | Use local HH:mm, from 00:00 through 23:59, with no time zone conversion. See Dates and local times below. Omit or leave blank to keep it; null clears it. | | return_reservation_details | String | No | Return layover or connection information. | Up to 750 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. Applies to Flight (1). | | return_destination_location | String | No | The return arrival airport or station. | Up to 250 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. Applies to Flight (1), Train (2), Bus (3). | | return_destination_date | String | No | The return arrival date. | Use a calendar date in YYYY-MM-DD format. Omit or leave blank to keep it; null clears it. Applies to Flight (1), Train (2), Bus (3). | | return_destination_time | String | No | The local return arrival time. | Use local HH:mm, from 00:00 through 23:59, with no time zone conversion. See Dates and local times below. Omit or leave blank to keep it; null clears it. Applies to Flight (1), Train (2), Bus (3). | | return_reservation_final_details | String | No | Return arrival information, drop-off notes or lodging check-out information. | Up to 750 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. | | origin_vendor_address | String | No | The pickup or lodging address. | Up to 500 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. Applies to Automobile (4), Other Transportation (5), Hotel (6), Other Lodging (7), Bed and Breakfast (8). | | notes | String | No | Notes about this Travel Reservation. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Both the saved text and the ExhibitDay editor's character count must fit within 30,000 characters; line breaks and characters such as & and < take extra space when saved. Omit or leave blank to keep it; null clears it. Existing over-limit content can stay unchanged or be shortened, but neither count may grow. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | payment_status_id | Number | No | The reservation's payment status. Omit or leave blank to keep it; null resets it to N/A. A status other than Partially Paid clears the next partial payment due date. | Allowed values: `0` (N/A) \| `1` (Paid in Full) \| `2` (Partially Paid) \| `3` (Not Paid Yet) | | payment_due_date | String | No | The reservation payment due date. | Use a calendar date in YYYY-MM-DD format. Omit or leave blank to keep it; null clears it. | | next_payment_due_date | Date | No | The next partial payment due date. | Use a calendar date in YYYY-MM-DD format. Applies only to Partially Paid (2). Supplying it with another payment status clears the date; choosing another status also clears it. Omit or leave blank to keep it; null clears it. | | payment_notes | String | No | Notes about the reservation payment. | Up to 200 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. | | tagged_user_ids | JSON object/list | No | The people associated with this reservation. | A JSON array of unique, active workspace user or resource IDs, each 1 to 128 characters with no surrounding whitespace. A supplied array replaces the full tag list. Omit to keep existing tags; null or [] removes them. Actual JSON null is omitted when the ignore-empty option is true. Retained tags keep their notification state; only newly added tags can schedule notifications. | | notify_tagged_users | Boolean | No | Whether to notify newly tagged people. | Default: true when omitted or blank, subject to each person's preferences and recipient eligibility. False suppresses notifications only for tags added by this request. Existing tags are unchanged. JSON null is refused even when ignore-empty is true. Changing this option alone makes no reservation change or revision change. | | cost | Number or cost object | No | The full cost, as a number or an object with amount and/or cost_center_breakdown. [Record Costs and Split Them Across Cost Centers](/Help/V1?guide=entering-costs). | Omit to keep the saved cost. A supplied value replaces its full allocation. | | expected_revision | String | No | The record_revision from an earlier read of this Travel Reservation. | Optional. Obtain it from GET /v1/events/travel_reservations/info with $include_record_revision=true. A changed reservation returns HTTP 409 without saving this update. Omission skips the check; blank, null and malformed values are refused. | | $ignore_params_with_empty_values | Boolean | No | Whether supplied JSON null values should be omitted. | Default: false. With true, actual JSON null fields and tag lists are omitted. Nonempty text null still requests clearing where supported. This option does not bypass required values, strict notify_tagged_users input or revision checks. | | $request_principal_name | String | No | A display label for API-origin creation or newly added tags. | Optional; up to 122 characters. Omit or leave blank for ExhibitDay API. This is a display label, not a workspace user ID. | Declared schema for `tagged_user_ids` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "array", "items": { "type": "string" }, "maxItems": 2147483647, "nullable": true, "x-maximum-depth": 2, "x-empty-create-means-omitted": true, "example": [ "user-id" ] } ``` Declared schema for `cost` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "anyOf": [ { "type": "number", "minimum": 0, "description": "Shorthand for an object with amount. The amount is rounded to cents before the supported storage range is checked.", "nullable": true }, { "type": "object", "additionalProperties": false, "properties": { "amount": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 }, "cost_center_breakdown": { "type": "array", "items": { "type": "object", "additionalProperties": false, "properties": { "cost_center_id": { "type": "integer", "format": "int64", "nullable": true }, "charge": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 }, "cost_center": { "type": "string", "description": "Optional and read-only: the cost center name a read returns, so a cost can be sent back unchanged. It is ignored; the line is saved by cost_center_id, and a name that doesn't match that cost center is explained in a warning.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "required": [ "charge" ] }, "maxItems": 2147483647 } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "anyOf": [ { "required": [ "amount" ] }, { "required": [ "cost_center_breakdown" ] } ], "nullable": true } ], "x-numeric-shorthand": "A number is equivalent to {amount:number}.", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": { "amount": 125.50 } } ``` #### Choosing travel details The selected reservation type determines which fields are used. The origin fields describe the outbound journey, vehicle pickup or lodging check-in; return fields describe the return journey, drop-off or check-out. A supplied field that does not apply to the selected type is not kept; the table shows which types use each field. #### Dates and local times Enter each clock time in the local time at the relevant departure, arrival, pickup, drop-off or lodging location. The API does not convert timezones. Changing a date preserves an already recorded matching clock time. Clearing a date alone does not clear its clock time. To remove both, clear both fields. A clock time can also be supplied without a date. #### Tagging people and notifications A supplied tagged_user_ids array replaces the full tag list. Include any currently tagged people you want to keep. Users and Resources can both be tagged; notifications depend on actual recipient eligibility and preferences. notify_tagged_users defaults to true for newly added tags. False suppresses only those new notifications. Retained tags keep their existing notification state; changing the option alone saves no reservation change. #### Choosing what to change Omitted or blank fields keep their values. Null clears or resets supported fields; reservation_type_id cannot be cleared. Clearing payment_status_id resets it to N/A. With $ignore_params_with_empty_values=true, a JSON null is ignored instead. Changing reservation_type_id clears the details the new type does not use. An update that keeps the type keeps the details you leave out. An attached Invoice Attachment keeps its file; its label follows the new type. An unchanged request saves no business data or history and keeps its revision. File Attachments and the Invoice Attachment are managed separately. #### Using expected_revision 1. Retrieve this reservation with GET /v1/events/travel_reservations/info and $include_record_revision=true. 2. Send the returned record_revision unchanged as expected_revision with this update. 3. If the API reports a change, read the current reservation and decide what to update. #### After the update A real change is recorded in Event history. Supporting files and the Invoice Attachment use their separate file operations. Recording costs does not attach an invoice, mark a payment complete or change the Event's planned Travel budget. If a save outcome cannot be confirmed, retrieve the current reservation before deciding whether to retry. #### Access The Event's Travel Reservations tab must be available, visible and unlocked, and your current access must allow the change. #### Sending values Use JSON, query parameters or form fields for text containing commas and tag arrays. #### Sending text Send plain text for Notes and other rich-text fields. Characters such as `&`, `<` and quotes, along with line breaks, are encoded for storage. #### Hidden or locked tab If the Event's Travel tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. An Event that is not in your workspace returns HTTP 404. #### Fields for each reservation type Each trip field applies only to some reservation types. A value for a field that doesn't apply to the reservation's type is not saved, and the response includes a warning that names the field and the type. - reservation_number: Flight, Train, Bus, Automobile, Other Transportation, Hotel, Other Lodging, Bed and Breakfast (B&B) - origin_vendor_name: Flight, Train, Bus, Automobile, Other Transportation, Hotel, Other Lodging, Bed and Breakfast (B&B) - origin_flight_number: Flight - origin_reservation_item_info: Flight, Train, Bus, Automobile, Hotel, Other Lodging, Bed and Breakfast (B&B) - origin_checkin_date: Flight, Train, Bus, Automobile, Other Transportation, Hotel, Other Lodging, Bed and Breakfast (B&B) - origin_checkin_time: Flight, Train, Bus, Automobile, Other Transportation, Hotel, Other Lodging, Bed and Breakfast (B&B) - origin_reservation_details: Flight - origin_destination_date: Flight, Train, Bus - origin_destination_time: Flight, Train, Bus - origin_reservation_final_details: Flight, Train, Bus, Automobile, Other Transportation, Hotel, Other Lodging, Bed and Breakfast (B&B) - return_vendor_name: Flight, Train, Bus - return_flight_number: Flight - return_reservation_item_info: Flight, Train, Bus - return_checkin_date: Flight, Train, Bus, Automobile, Other Transportation, Hotel, Other Lodging, Bed and Breakfast (B&B) - return_checkin_time: Flight, Train, Bus, Automobile, Other Transportation, Hotel, Other Lodging, Bed and Breakfast (B&B) - return_reservation_details: Flight - return_destination_date: Flight, Train, Bus - return_destination_time: Flight, Train, Bus - return_reservation_final_details: Flight, Train, Bus, Automobile, Other Transportation, Hotel, Other Lodging, Bed and Breakfast (B&B) - origin_vendor_address: Automobile, Other Transportation, Hotel, Other Lodging, Bed and Breakfast (B&B) Example — curl: ```bash curl -X PATCH "https://api.exhibitday.com/v1/events/travel_reservations" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"id\":12345,\"notes\":\"Updated text\"}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/travel_reservations", { method: "PATCH", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "id": 12345, "notes": "Updated text" }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.patch( "https://api.exhibitday.com/v1/events/travel_reservations", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"id": 12345, "notes": "Updated text"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PatchAsync("https://api.exhibitday.com/v1/events/travel_reservations", JsonContent.Create(new { id = 12345, notes = "Updated text" })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/travel_reservations")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("PATCH", HttpRequest.BodyPublishers.ofString("{\"id\":12345,\"notes\":\"Updated text\"}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"id":12345,"notes":"Updated text"}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/travel_reservations') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"id":12345,"notes":"Updated text"}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/events/travel_reservations", strings.NewReader("{\"id\":12345,\"notes\":\"Updated text\"}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): PATCH /v1/events/travel_reservations - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Travel reservation updated.", "errors": [] } ``` ### Delete a Travel Reservation `DELETE https://api.exhibitday.com/v1/events/travel_reservations` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=travel-reservations#delete-v1-events-travel_reservations Deletes a Travel Reservation and its saved costs, taggings, related-item links, File Attachments and Invoice Attachment. Workspace members and linked Tasks or other records remain in place. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Travel Reservation. | Use its id from the list, single-record read or add response. | #### After the deletion The reservation, its taggings, costs, related-item links and attachment records are removed together. Only its files are scheduled for physical cleanup after the save. Tagged workspace members and linked records remain. The deletion is recorded in Event history. An unavailable reservation returns HTTP 404. If the save outcome cannot be confirmed, retrieve the current reservations before deciding whether to retry. #### Access The Event's Travel Reservations tab must be available, visible and unlocked, and your current access must allow the change. #### Hidden or locked tab If the Event's Travel tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. An Event that is not in your workspace returns HTTP 404. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/events/travel_reservations?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/travel_reservations?" + new URLSearchParams({ "id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/events/travel_reservations", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/events/travel_reservations?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/travel_reservations?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/travel_reservations?id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/events/travel_reservations?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/events/travel_reservations - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Travel reservation removed.", "errors": [] } ``` ### Download Travel Reservation Invoice Attachment `GET https://api.exhibitday.com/v1/events/travel_reservations/invoice_attachment/download` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=travel-reservations#get-v1-events-travel_reservations-invoice_attachment-download Downloads the original Invoice Attachment for this Travel Reservation. Use this method to retrieve the file itself. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | travel_reservation_id | Number | Yes | The ID of the Travel Reservation, from Retrieve Travel Reservations (GET /v1/events/travel_reservations) or its add response. | | #### Finding the file In the web app, this is the invoice control beside the Travel Reservation's cost and payment details. Each cost has one Invoice Attachment even when its amount is split among cost centers. For file metadata, retrieve the parent record with GET /v1/events/travel_reservations/info and read invoice_attachment. Use this download method for the contents. No attachment ID or invoice flag is needed. #### Download response A successful response contains the original uploaded file, with a safe download filename. API errors use the usual JSON response. If no invoice is attached, this method returns HTTP 404. Current record, financial and invoice permissions apply. A locked tab can still be read. Permitted downloads remain available on the Free plan. #### Files still being copied If this file is still being copied, the download returns HTTP 409 with file_copy_pending. Try the download again in a few minutes. #### Hidden tab If the Event's Travel tab is hidden, this request returns HTTP 400 (not_allowed), and the message says the tab is hidden. Show the tab in ExhibitDay first. A locked tab can still be read. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X GET "https://api.exhibitday.com/v1/events/travel_reservations/invoice_attachment/download?travel_reservation_id=12345" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi mv response-body.tmp 'invoice.pdf' ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const response = await fetch("https://api.exhibitday.com/v1/events/travel_reservations/invoice_attachment/download?travel_reservation_id=12345", { method: "GET", headers: { Authorization: 'Bearer YOUR_API_KEY' } }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); await writeFile("invoice.pdf", new Uint8Array(await response.arrayBuffer())); ``` Example — Python: ```python import requests import json response = requests.request("GET", "https://api.exhibitday.com/v1/events/travel_reservations/invoice_attachment/download?travel_reservation_id=12345", headers={'Authorization': 'Bearer YOUR_API_KEY'}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') with open("invoice.pdf", 'wb') as destination: destination.write(response.content) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.exhibitday.com/v1/events/travel_reservations/invoice_attachment/download?travel_reservation_id=12345"); using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); await File.WriteAllBytesAsync("invoice.pdf", await response.Content.ReadAsByteArrayAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/travel_reservations/invoice_attachment/download?travel_reservation_id=12345")).header("Authorization", "Bearer YOUR_API_KEY"); HttpResponse response = HttpClient.newHttpClient().send(request.method("GET", HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); Files.write(Path.of("invoice.pdf"), response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); file_put_contents('invoice.pdf', $response); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/travel_reservations/invoice_attachment/download?travel_reservation_id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' File.binwrite('invoice.pdf', response.body) ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/travel_reservations/invoice_attachment/download?travel_reservation_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } if err := os.WriteFile("invoice.pdf", data, 0600); err != nil { log.Fatal(err) } fmt.Println("File saved") } ``` HTTP 200: Returns the original uploaded file as a private download, using a safe filename. If the file cannot be downloaded, the response contains the usual JSON API error instead. Media: application/octet-stream. The body is the authorized file's real bytes, not JSON or base64. Errors are JSON status responses; check HTTP status before saving the file. ### Add Travel Reservation Invoice Attachment `POST https://api.exhibitday.com/v1/events/travel_reservations/invoice_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=travel-reservations#post-v1-events-travel_reservations-invoice_attachment Adds one Invoice Attachment to this Travel Reservation. You can attach an invoice, receipt or other payment document when no invoice file is currently attached. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | travel_reservation_id | Number | Yes | The ID of the Travel Reservation, from Retrieve Travel Reservations (GET /v1/events/travel_reservations) or its add response. | | | file | File (multipart) | Yes | The Invoice Attachment to upload. | Send exactly one complete, nonempty multipart/form-data file part named file. The supported extensions and current per-file limit are shown below; the complete request limit also includes multipart overhead. A missing or null file is invalid and does not remove an existing invoice. | | Idempotency-Key | String | No | A unique key for safely retrying this upload. | Optional HTTP header: 1 to 255 visible ASCII characters without spaces or commas. Retry the identical request with the same key to replay its first saved response. Use a new key for a different upload. | Declared schema for `file` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "string", "format": "binary", "x-maximum-bytes": 26214400, "x-allowed-extensions": [ "png", "jpg", "jpeg", "bmp", "gif", "pdf", "msg", "eml", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "rtf", "odp", "odt", "ods", "txt", "wks", "zip" ] } ``` #### Before you upload POST requires an empty invoice slot. If an invoice is already attached, the API returns HTTP 409; use PATCH to replace it. An Invoice Attachment is separate from the record's supporting File Attachments. Use the invoice control beside the Travel Reservation's cost and payment details in the web app. #### After the upload The response's invoice_attachment contains the attached file's id, filename and attachment_created_timestamp. The amount, payment fields, cost-center breakdown and other files are unchanged. The upload is recorded in Event history. Attaching an invoice does not mark the record as paid. #### Access and retries A current upload-enabled plan, record and financial permissions, and an editable applicable tab are required. Each uploaded file must fit its supported type and size limits. expected_revision is not supported by this file method. If the save outcome cannot be confirmed, retrieve the current parent record with GET /v1/events/travel_reservations/info and inspect invoice_attachment before deciding whether to retry. #### Hidden or locked tab If the Event's Travel tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X POST "https://api.exhibitday.com/v1/events/travel_reservations/invoice_attachment" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}" --form-string "travel_reservation_id=12345" --form "file=@invoice.pdf;type=application/octet-stream") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi cat response-body.tmp ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const form = new FormData(); form.append("travel_reservation_id", "12345"); form.append("file", new Blob([await readFile("invoice.pdf")], { type: "application/octet-stream" }), "invoice.pdf"); const response = await fetch("https://api.exhibitday.com/v1/events/travel_reservations/invoice_attachment", { method: "POST", headers: { Authorization: 'Bearer YOUR_API_KEY' }, body: form }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); console.log(await response.json()); ``` Example — Python: ```python import requests import json from contextlib import ExitStack with ExitStack() as stack: files = [ ("file", ("invoice.pdf", stack.enter_context(open("invoice.pdf", 'rb')), "application/octet-stream")), ] response = requests.request("POST", "https://api.exhibitday.com/v1/events/travel_reservations/invoice_attachment", headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data={"travel_reservation_id": "12345"}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') print(response.json()) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.exhibitday.com/v1/events/travel_reservations/invoice_attachment"); var form = new MultipartFormDataContent(); form.Add(new StringContent("12345"), "travel_reservation_id"); var file0 = new StreamContent(File.OpenRead("invoice.pdf")); file0.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(file0, "file", "invoice.pdf"); request.Content = form; using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/travel_reservations/invoice_attachment")).header("Authorization", "Bearer YOUR_API_KEY"); String boundary = "ExhibitDay-" + UUID.randomUUID(); ByteArrayOutputStream form = new ByteArrayOutputStream(); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"travel_reservation_id\"\r\n\r\n" + "12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"invoice.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8)); form.write(Files.readAllBytes(Path.of("invoice.pdf"))); form.write("\r\n".getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); request.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpResponse response = HttpClient.newHttpClient().send(request.method("POST", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); System.out.println(new String(response.body(), StandardCharsets.UTF_8)); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], CURLOPT_POSTFIELDS => [ 'travel_reservation_id' => '12345', 'file' => new CURLFile('invoice.pdf', 'application/octet-stream', 'invoice.pdf'), ], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); echo $response; ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/travel_reservations/invoice_attachment') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' files = [] begin parts = [ ['travel_reservation_id', '12345'], ['file', (files << File.open('invoice.pdf', 'rb')).last, {filename: 'invoice.pdf', content_type: 'application/octet-stream'}], ] request.set_form(parts, 'multipart/form-data') response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' puts response.body ensure files.each(&:close) end ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" "bytes" "mime/multipart" "net/textproto" ) func main() { var form bytes.Buffer writer := multipart.NewWriter(&form) if err := writer.WriteField("travel_reservation_id", "12345"); err != nil { log.Fatal(err) } header0 := textproto.MIMEHeader{} header0.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"invoice.pdf\"") header0.Set("Content-Type", "application/octet-stream") part0, err := writer.CreatePart(header0) if err != nil { log.Fatal(err) } file0, err := os.Open("invoice.pdf") if err != nil { log.Fatal(err) } if _, err = io.Copy(part0, file0); err != nil { log.Fatal(err) } file0.Close() if err := writer.Close(); err != nil { log.Fatal(err) } request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/events/travel_reservations/invoice_attachment", &form) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", writer.FormDataContentType()) response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } fmt.Printf("%s\n", data) } ``` Example HTTP response body (JSON): POST /v1/events/travel_reservations/invoice_attachment - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "invoice_attachment": { "id": 12345, "filename": "invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } } ``` ### Replace Travel Reservation Invoice Attachment `PATCH https://api.exhibitday.com/v1/events/travel_reservations/invoice_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=travel-reservations#patch-v1-events-travel_reservations-invoice_attachment Replaces this Travel Reservation's current Invoice Attachment with one uploaded file. Use this method when an invoice file is already attached. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | travel_reservation_id | Number | Yes | The ID of the Travel Reservation, from Retrieve Travel Reservations (GET /v1/events/travel_reservations) or its add response. | | | file | File (multipart) | Yes | The Invoice Attachment to upload. | Send exactly one complete, nonempty multipart/form-data file part named file. The supported extensions and current per-file limit are shown below; the complete request limit also includes multipart overhead. A missing or null file is invalid and does not remove an existing invoice. | Declared schema for `file` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "string", "format": "binary", "x-maximum-bytes": 26214400, "x-allowed-extensions": [ "png", "jpg", "jpeg", "bmp", "gif", "pdf", "msg", "eml", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "rtf", "odp", "odt", "ods", "txt", "wks", "zip" ] } ``` #### Replacing the current file PATCH requires a current invoice file. If none is attached, the API returns HTTP 404. Upload exactly one file; the previous attachment ID is not needed. If another request changes the current invoice during your upload, the API refuses this request instead of replacing a different file. Even identical replacement contents receive a new attachment ID. #### After the replacement The response's invoice_attachment contains the attached file's id, filename and attachment_created_timestamp. The amount, payment fields, cost-center breakdown and other files are unchanged. The previous file is scheduled for physical cleanup after a confirmed save; cleanup may finish later. The replacement is recorded in Event history. #### Access and retries A current upload-enabled plan, record and financial permissions, and an editable applicable tab are required. Each uploaded file must fit its supported type and size limits. expected_revision is not supported by this file method. PATCH does not use Idempotency-Key replay. If the save outcome cannot be confirmed, retrieve the current parent record with GET /v1/events/travel_reservations/info and inspect invoice_attachment before deciding whether to retry. #### Hidden or locked tab If the Event's Travel tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X PATCH "https://api.exhibitday.com/v1/events/travel_reservations/invoice_attachment" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}" --form-string "travel_reservation_id=12345" --form "file=@invoice.pdf;type=application/octet-stream") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi cat response-body.tmp ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const form = new FormData(); form.append("travel_reservation_id", "12345"); form.append("file", new Blob([await readFile("invoice.pdf")], { type: "application/octet-stream" }), "invoice.pdf"); const response = await fetch("https://api.exhibitday.com/v1/events/travel_reservations/invoice_attachment", { method: "PATCH", headers: { Authorization: 'Bearer YOUR_API_KEY' }, body: form }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); console.log(await response.json()); ``` Example — Python: ```python import requests import json from contextlib import ExitStack with ExitStack() as stack: files = [ ("file", ("invoice.pdf", stack.enter_context(open("invoice.pdf", 'rb')), "application/octet-stream")), ] response = requests.request("PATCH", "https://api.exhibitday.com/v1/events/travel_reservations/invoice_attachment", headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data={"travel_reservation_id": "12345"}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') print(response.json()) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("PATCH"), "https://api.exhibitday.com/v1/events/travel_reservations/invoice_attachment"); var form = new MultipartFormDataContent(); form.Add(new StringContent("12345"), "travel_reservation_id"); var file0 = new StreamContent(File.OpenRead("invoice.pdf")); file0.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(file0, "file", "invoice.pdf"); request.Content = form; using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/travel_reservations/invoice_attachment")).header("Authorization", "Bearer YOUR_API_KEY"); String boundary = "ExhibitDay-" + UUID.randomUUID(); ByteArrayOutputStream form = new ByteArrayOutputStream(); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"travel_reservation_id\"\r\n\r\n" + "12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"invoice.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8)); form.write(Files.readAllBytes(Path.of("invoice.pdf"))); form.write("\r\n".getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); request.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpResponse response = HttpClient.newHttpClient().send(request.method("PATCH", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); System.out.println(new String(response.body(), StandardCharsets.UTF_8)); } } ``` Example — PHP: ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], CURLOPT_POSTFIELDS => [ 'travel_reservation_id' => '12345', 'file' => new CURLFile('invoice.pdf', 'application/octet-stream', 'invoice.pdf'), ], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); echo $response; ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/travel_reservations/invoice_attachment') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' files = [] begin parts = [ ['travel_reservation_id', '12345'], ['file', (files << File.open('invoice.pdf', 'rb')).last, {filename: 'invoice.pdf', content_type: 'application/octet-stream'}], ] request.set_form(parts, 'multipart/form-data') response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' puts response.body ensure files.each(&:close) end ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" "bytes" "mime/multipart" "net/textproto" ) func main() { var form bytes.Buffer writer := multipart.NewWriter(&form) if err := writer.WriteField("travel_reservation_id", "12345"); err != nil { log.Fatal(err) } header0 := textproto.MIMEHeader{} header0.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"invoice.pdf\"") header0.Set("Content-Type", "application/octet-stream") part0, err := writer.CreatePart(header0) if err != nil { log.Fatal(err) } file0, err := os.Open("invoice.pdf") if err != nil { log.Fatal(err) } if _, err = io.Copy(part0, file0); err != nil { log.Fatal(err) } file0.Close() if err := writer.Close(); err != nil { log.Fatal(err) } request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/events/travel_reservations/invoice_attachment", &form) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", writer.FormDataContentType()) response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } fmt.Printf("%s\n", data) } ``` Example HTTP response body (JSON): PATCH /v1/events/travel_reservations/invoice_attachment - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "invoice_attachment": { "id": 12345, "filename": "invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } } ``` ### Remove Travel Reservation Invoice Attachment `DELETE https://api.exhibitday.com/v1/events/travel_reservations/invoice_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=travel-reservations#delete-v1-events-travel_reservations-invoice_attachment Removes this Travel Reservation's Invoice Attachment. The cost, payment details and other File Attachments stay in place. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | travel_reservation_id | Number | Yes | The ID of the Travel Reservation, from Retrieve Travel Reservations (GET /v1/events/travel_reservations) or its add response. | | #### After the removal The Invoice Attachment is cleared and the removal is recorded in Event history. Its physical file is scheduled for cleanup after a confirmed save; cleanup may finish later. Costs, payment fields, cost-center allocations and supporting files stay unchanged. If no invoice is attached, DELETE returns HTTP 404 Not Found with the message "This Travel Reservation has no invoice to remove." No saved data or history is changed. Current access and the record's binding are still checked. Do not send file parts with this request. #### Access and retries Current record, financial and invoice permissions and applicable tab-edit access are required. Permitted removals remain available on the Free plan. expected_revision is not supported, and DELETE does not use Idempotency-Key replay. If the save outcome cannot be confirmed, retrieve the current parent record with GET /v1/events/travel_reservations/info and inspect invoice_attachment before deciding whether to retry. #### Hidden or locked tab If the Event's Travel tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/events/travel_reservations/invoice_attachment?travel_reservation_id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/travel_reservations/invoice_attachment?" + new URLSearchParams({ "travel_reservation_id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/events/travel_reservations/invoice_attachment", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"travel_reservation_id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/events/travel_reservations/invoice_attachment?travel_reservation_id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/travel_reservations/invoice_attachment?travel_reservation_id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/travel_reservations/invoice_attachment?travel_reservation_id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/events/travel_reservations/invoice_attachment?travel_reservation_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/events/travel_reservations/invoice_attachment - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Attachment removed.", "errors": [] } ``` ### Retrieve Travel Reservation General File Attachments `GET https://api.exhibitday.com/v1/events/travel_reservations/attachments` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=travel-reservations#get-v1-events-travel_reservations-attachments Retrieves the General File Attachments on this Travel Reservation. Each result includes the file's ID, name and added time; use the download method for its contents. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | travel_reservation_id | Number | Yes | The ID of the Travel Reservation, from Retrieve Travel Reservations (GET /v1/events/travel_reservations) or its add response. | | | $limit | Number | No | The most File Attachments to return. | A positive whole number. Omit for all remaining matching files. | | $offset | Number | No | The number of matching File Attachments to skip. | A whole number of 0 or more. Default: 0. | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records. | Allowed values: `array` | | If-None-Match | String | No | An ETag from an earlier response to this GET. | Optional HTTP header. If the successful response is unchanged, the API returns HTTP 304 with no body. | #### Reading the file list Files are ordered by added time, then attachment ID, lowest first. Only files available under your current access are included. Paging totals and X-Total-Count count all matching files before $limit and $offset are applied. A record with no files you can view returns an empty list. This list does not return edit revisions or support changed-since filtering. #### Supporting files and invoices These are the record's General File Attachments. Its cost Invoice Attachment is separate and has its own download and upload methods. Use this list's id values for these supporting-file downloads and removals. #### Access The record's Event and tab must be available, and the tab must not be hidden. A locked tab can still be read. #### Hidden tab If the Event's Travel tab is hidden, this request returns HTTP 400 (not_allowed), and the message says the tab is hidden. Show the tab in ExhibitDay first. A locked tab can still be read. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/events/travel_reservations/attachments?travel_reservation_id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/travel_reservations/attachments?" + new URLSearchParams({ "travel_reservation_id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/events/travel_reservations/attachments", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"travel_reservation_id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/events/travel_reservations/attachments?travel_reservation_id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/travel_reservations/attachments?travel_reservation_id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/travel_reservations/attachments?travel_reservation_id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/travel_reservations/attachments?travel_reservation_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/events/travel_reservations/attachments - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "attachment", "list_data": [ { "id": 12345, "filename": "attachment.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } ] } ``` ### Add Travel Reservation General File Attachments `POST https://api.exhibitday.com/v1/events/travel_reservations/attachments` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=travel-reservations#post-v1-events-travel_reservations-attachments Adds one or more General File Attachments to this Travel Reservation. Send each file as a multipart upload part named file. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | travel_reservation_id | Number | Yes | The ID of the Travel Reservation, from Retrieve Travel Reservations (GET /v1/events/travel_reservations) or its add response. | | | file | File (multipart) | Yes | The File Attachments to upload. | Send one or more complete, nonempty multipart/form-data parts, each named file. Supported types and the current per-file limit are shown below. The complete request limit includes all files and multipart overhead; split larger batches. A missing or null upload is not a removal request. | | Idempotency-Key | String | No | A unique key for safely retrying this upload. | Optional HTTP header: 1 to 255 visible ASCII characters without spaces or commas. Retry the identical request with the same key to replay its first saved response. Use a new key for a different upload. | Declared schema for `file` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "array", "items": { "type": "string", "format": "binary", "x-maximum-bytes": 26214400, "x-allowed-extensions": [ "png", "jpg", "jpeg", "bmp", "gif", "pdf", "msg", "eml", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "rtf", "odp", "odt", "ods", "txt", "wks", "zip" ] } } ``` #### After the upload The response's list_data contains the newly attached files, including each id, filename and attachment_created_timestamp. Existing files are kept. Use each returned id to download or remove that file. Identical repeated files in one request are attached once when their cleaned filename, length and contents match. Files with different contents remain separate even when their names match. This does not remove or replace files already attached to the record. #### Choosing the right file method These uploads add General File Attachments. Use this record's Invoice Attachment methods for its cost invoice or receipt. Adding supporting files does not change amounts, payments or cost-center allocations. #### Access Current record and file-change permissions and applicable Event/tab locks must allow this upload. An upload-enabled paid plan is required. #### History and retries A confirmed file change is recorded in history. expected_revision is not supported by these file methods. If the save outcome cannot be confirmed, retrieve the current file list before deciding whether to retry; the API does not automatically repeat an uncertain change. Supporting File Attachments have no PATCH replacement. To replace one, add the new file and remove the old one using their separate requests; each request has its own outcome. #### Hidden or locked tab If the Event's Travel tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X POST "https://api.exhibitday.com/v1/events/travel_reservations/attachments" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}" --form-string "travel_reservation_id=12345" --form "file=@attachment.pdf;type=application/octet-stream") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi cat response-body.tmp ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const form = new FormData(); form.append("travel_reservation_id", "12345"); form.append("file", new Blob([await readFile("attachment.pdf")], { type: "application/octet-stream" }), "attachment.pdf"); const response = await fetch("https://api.exhibitday.com/v1/events/travel_reservations/attachments", { method: "POST", headers: { Authorization: 'Bearer YOUR_API_KEY' }, body: form }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); console.log(await response.json()); ``` Example — Python: ```python import requests import json from contextlib import ExitStack with ExitStack() as stack: files = [ ("file", ("attachment.pdf", stack.enter_context(open("attachment.pdf", 'rb')), "application/octet-stream")), ] response = requests.request("POST", "https://api.exhibitday.com/v1/events/travel_reservations/attachments", headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data={"travel_reservation_id": "12345"}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') print(response.json()) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.exhibitday.com/v1/events/travel_reservations/attachments"); var form = new MultipartFormDataContent(); form.Add(new StringContent("12345"), "travel_reservation_id"); var file0 = new StreamContent(File.OpenRead("attachment.pdf")); file0.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(file0, "file", "attachment.pdf"); request.Content = form; using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/travel_reservations/attachments")).header("Authorization", "Bearer YOUR_API_KEY"); String boundary = "ExhibitDay-" + UUID.randomUUID(); ByteArrayOutputStream form = new ByteArrayOutputStream(); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"travel_reservation_id\"\r\n\r\n" + "12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"attachment.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8)); form.write(Files.readAllBytes(Path.of("attachment.pdf"))); form.write("\r\n".getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); request.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpResponse response = HttpClient.newHttpClient().send(request.method("POST", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); System.out.println(new String(response.body(), StandardCharsets.UTF_8)); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], CURLOPT_POSTFIELDS => [ 'travel_reservation_id' => '12345', 'file' => new CURLFile('attachment.pdf', 'application/octet-stream', 'attachment.pdf'), ], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); echo $response; ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/travel_reservations/attachments') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' files = [] begin parts = [ ['travel_reservation_id', '12345'], ['file', (files << File.open('attachment.pdf', 'rb')).last, {filename: 'attachment.pdf', content_type: 'application/octet-stream'}], ] request.set_form(parts, 'multipart/form-data') response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' puts response.body ensure files.each(&:close) end ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" "bytes" "mime/multipart" "net/textproto" ) func main() { var form bytes.Buffer writer := multipart.NewWriter(&form) if err := writer.WriteField("travel_reservation_id", "12345"); err != nil { log.Fatal(err) } header0 := textproto.MIMEHeader{} header0.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"attachment.pdf\"") header0.Set("Content-Type", "application/octet-stream") part0, err := writer.CreatePart(header0) if err != nil { log.Fatal(err) } file0, err := os.Open("attachment.pdf") if err != nil { log.Fatal(err) } if _, err = io.Copy(part0, file0); err != nil { log.Fatal(err) } file0.Close() if err := writer.Close(); err != nil { log.Fatal(err) } request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/events/travel_reservations/attachments", &form) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", writer.FormDataContentType()) response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } fmt.Printf("%s\n", data) } ``` Example HTTP response body (JSON): POST /v1/events/travel_reservations/attachments - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "attachment", "list_data": [ { "id": 12345, "filename": "attachment.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } ] } ``` ### Remove a Travel Reservation General File Attachment `DELETE https://api.exhibitday.com/v1/events/travel_reservations/attachments` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=travel-reservations#delete-v1-events-travel_reservations-attachments Removes one General File Attachment from this Travel Reservation. Other attached files and the record's details stay in place. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the File Attachment. | Use the id from the attachment list. The API finds the record the file belongs to, so no record ID is sent. An Invoice Attachment is not selected by this method. | #### After the removal Only the selected file association is removed. Its physical file is scheduled for cleanup after a confirmed save; cleanup may finish later. Other attached files stay in place. Send only the file's id; the API finds the record it belongs to. A missing, already removed or unavailable attachment returns HTTP 404 Not Found. Do not send file parts with DELETE. #### Access Current record and file-removal permissions and applicable Event/tab locks must allow this change. Permitted removals remain available on the Free plan. #### History and retries A confirmed file change is recorded in history. expected_revision is not supported by these file methods. DELETE does not use Idempotency-Key replay. If the save outcome cannot be confirmed, retrieve the current file list before deciding whether to retry; the API does not automatically repeat an uncertain change. Supporting File Attachments have no PATCH replacement. To replace one, add the new file and remove the old one using their separate requests; each request has its own outcome. #### Hidden or locked tab If the Event's Travel tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/events/travel_reservations/attachments?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/travel_reservations/attachments?" + new URLSearchParams({ "id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/events/travel_reservations/attachments", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/events/travel_reservations/attachments?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/travel_reservations/attachments?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/travel_reservations/attachments?id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/events/travel_reservations/attachments?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/events/travel_reservations/attachments - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Attachment removed.", "errors": [] } ``` ### Download a Travel Reservation General File Attachment `GET https://api.exhibitday.com/v1/events/travel_reservations/attachments/download` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=travel-reservations#get-v1-events-travel_reservations-attachments-download Downloads one original General File Attachment from this Travel Reservation. Select the file using its ID from the attachment list. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the File Attachment. | Use the id from the attachment list. The API finds the record the file belongs to, so no record ID is sent. An Invoice Attachment is not selected by this method. | #### Download response A successful response contains the original uploaded file with a safe download filename. API errors use the usual JSON response. A missing or unavailable file returns HTTP 404. Send only the file's id from the attachment list to download that one file; the API finds the record it belongs to. The download leaves the record unchanged. #### Access The record's Event and tab must be available, and the tab must not be hidden. A locked tab can still be read. #### Files still being copied If this file is still being copied, the download returns HTTP 409 with file_copy_pending. Try the download again in a few minutes. #### Hidden tab If the Event's Travel tab is hidden, this request returns HTTP 400 (not_allowed), and the message says the tab is hidden. Show the tab in ExhibitDay first. A locked tab can still be read. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X GET "https://api.exhibitday.com/v1/events/travel_reservations/attachments/download?id=12345" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi mv response-body.tmp 'attachment.pdf' ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const response = await fetch("https://api.exhibitday.com/v1/events/travel_reservations/attachments/download?id=12345", { method: "GET", headers: { Authorization: 'Bearer YOUR_API_KEY' } }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); await writeFile("attachment.pdf", new Uint8Array(await response.arrayBuffer())); ``` Example — Python: ```python import requests import json response = requests.request("GET", "https://api.exhibitday.com/v1/events/travel_reservations/attachments/download?id=12345", headers={'Authorization': 'Bearer YOUR_API_KEY'}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') with open("attachment.pdf", 'wb') as destination: destination.write(response.content) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.exhibitday.com/v1/events/travel_reservations/attachments/download?id=12345"); using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); await File.WriteAllBytesAsync("attachment.pdf", await response.Content.ReadAsByteArrayAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/travel_reservations/attachments/download?id=12345")).header("Authorization", "Bearer YOUR_API_KEY"); HttpResponse response = HttpClient.newHttpClient().send(request.method("GET", HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); Files.write(Path.of("attachment.pdf"), response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); file_put_contents('attachment.pdf', $response); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/travel_reservations/attachments/download?id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' File.binwrite('attachment.pdf', response.body) ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/travel_reservations/attachments/download?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } if err := os.WriteFile("attachment.pdf", data, 0600); err != nil { log.Fatal(err) } fmt.Println("File saved") } ``` HTTP 200: Returns the original uploaded file as a private download, using a safe filename. If the file cannot be downloaded, the response contains the usual JSON API error instead. Media: application/octet-stream. The body is the authorized file's real bytes, not JSON or base64. Errors are JSON status responses; check HTTP status before saving the file. ## Events - Giveaways Giveaways on an Event: supplier and inventory sources, distribution details, costs, invoices, file attachments and exports. Documentation page: https://api.exhibitday.com/Help/V1?epf=1&topic=giveaways ### Retrieve a Single Giveaway by ID `GET https://api.exhibitday.com/v1/events/giveaways/info` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=giveaways#get-v1-events-giveaways-info Retrieves a Giveaway by its ID, including its item details, acquisition plans, distribution rules, costs and payment information. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Giveaway. | Use the id from Retrieve Giveaways (GET /v1/events/giveaways) or from the add response. You don't send the Event ID; the record's Event is found automatically. | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` \| `object` | | $include_record_revision | Boolean | No | Whether to include record_revision in the response. | Default: false. Send true to get record_revision, then send that value as expected_revision when you update this Giveaway. See What $include_record_revision covers below. | | $on_error_return_empty_result | Boolean | No | Whether an invalid or unavailable Giveaway should return an empty result. | Default: false. True returns HTTP 200 with {} (or [] for array format) for invalid IDs or an unavailable Giveaway. API key errors, conflicts with a change in progress, inconsistent invoice information and unexpected errors keep their normal status. | | If-None-Match | String | No | An ETag from an earlier response to this GET. | Optional HTTP header. If the successful response is unchanged, the API returns HTTP 304 with no body. | #### What $include_record_revision covers Setting $include_record_revision=true returns record_revision for use as expected_revision on a later update. record_revision covers saved Giveaway details, payment fields, cost allocations, related-item links and Event binding. File Attachment and Invoice Attachment metadata/contents are not included. #### Files and access Invoice Attachment metadata is included as invoice_attachment, or null if no invoice is attached. Supporting File Attachments have their own collection and download operation. The Event's Giveaways tab must be visible. A locked tab can still be read. Inconsistent invoice information returns HTTP 409 instead of exposing another record's file. #### Formatted text in the response Notes and other rich-text values in the response contain the stored HTML, including encoded characters and line breaks such as `
`. #### Open in ExhibitDay Each record includes exhibitday_url, the record's page in ExhibitDay. It opens the record in view mode on its Event's tab. Sign in with an account that can view the record; ExhibitDay checks access when the link is opened. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/events/giveaways/info?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/giveaways/info?" + new URLSearchParams({ "id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/events/giveaways/info", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/events/giveaways/info?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/giveaways/info?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/giveaways/info?id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/giveaways/info?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/events/giveaways/info - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "id": 12345, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=23456&riType=6&riSub=0&riId=12345", "event_id": 23456, "event_name": "Sample Event", "name": "Welcome kits", "item_source_id": 1, "acquisition_status_id": 10, "acquire_by_date": null, "supplier_source": null, "contact_name": null, "contact_email": null, "contact_phone": null, "product_order_url": null, "acquired_date": null, "order_reference_number": null, "planned_quantity": null, "entry_method_id": null, "entry_rules_url": null, "selection_distribution_method_id": null, "number_of_winners_recipients": null, "must_be_present_to_win": null, "payment_status_id": 0, "payment_due_date": null, "next_payment_due_date": null, "payment_notes": null, "invoice_attachment": { "id": 582345, "filename": "giveaway-invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" }, "notes": "", "item_package_details": "", "branding_customization": "", "preparation_requirements": "", "handling_storage_requirements": "", "intended_use_recipients": "", "eligibility_restrictions": "", "fulfillment_instructions": "", "results_follow_up": "", "item_source": "From a Supplier / Vendor", "acquisition_status": "Need to Acquire", "entry_method": "Not Specified", "selection_distribution_method": "Not Specified", "payment_status": { "id": 0, "name": "N/A" }, "cost": { "amount": 125.50, "cost_center_breakdown": [ { "cost_center_id": 34567, "cost_center": "Marketing", "charge": 75.50 }, { "cost_center_id": 34568, "cost_center": "Operations", "charge": 50.00 } ] }, "related_items": [ { "id": 5551, "related_item_id": 67890, "related_item_exhibitday_url": "https://www.exhibitday.com/Workspace/TaskView/98765?tid=67890", "related_item_type_id": 1, "related_item_type": "Task", "related_item_asset_type_id": null, "related_item_name": "Confirm booth graphics with the printer", "related_item_created_timestamp": "2030-01-10T14:03:00Z" }, { "id": 5552, "related_item_id": 45678, "related_item_exhibitday_url": "https://www.exhibitday.com/Workspace/RelatedItemView/98765?typeId=4&subTypeId=0&rid=45678", "related_item_type_id": 4, "related_item_type": "Shipment", "related_item_asset_type_id": null, "related_item_name": "Booth crates to convention center", "related_item_created_timestamp": "2030-01-10T14:03:00Z" } ] } ``` ### Retrieve Giveaways `GET https://api.exhibitday.com/v1/events/giveaways` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=giveaways#get-v1-events-giveaways Retrieves records across your workspace's readable Event tabs. Use filter_by_event_id to narrow the results to one Event, or omit it for the workspace list. Each record includes its event_id and Event name. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | filter_by_event_id | Number | No | Return records for this Event only. Omit for all readable Events in your workspace. | | | $limit | Number | No | The most Giveaways to return: a whole number of 1 or more. Omit it for all remaining matches; a blank value or null is refused, so leave the parameter out instead. | | | $offset | Number | No | How many matching Giveaways to skip: a whole number of 0 or more. Default: 0. A blank value or null is refused. | | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | | hydrate_related_items | Boolean | No | Set to true to include each record's related_items: the Tasks and items linked to it, with the key to use when adding or removing a link. Omit it or send false to leave related_items out of list results. Single-record GETs always include related_items. | Default: false. | #### Choosing Events Omit `filter_by_event_id` to retrieve records across readable Event tabs, or supply one Event ID to narrow the list. Each result retains its own `event_id` and Event name. Hidden or unavailable Event tabs are not included. A locked tab can still be read. If no records match, the response is an empty list. #### Reading pages The Event filter and any people filter are applied before the total count and paging. Results are ordered by Event start date ascending, Event ID ascending, then record ID ascending. Use `$limit` and `$offset` for successive pages. Omit `$limit` to return all remaining matches. `total_records` and `X-Total-Count` describe all matches; `records_found` counts this response. Omit `$result_format` for the normal list wrapper. `array` returns only the records; `wrapped_in_array` places the normal wrapper in a one-item array. #### Handling input and changes Unrecognized parameters are ignored and listed in the `X-API-Warnings` response header. Conflicting or malformed filter values return HTTP `400`; send arrays in JSON, query parameters or form fields rather than comma-bearing headers. Current API access is checked even when the list is empty. A concurrent change can return HTTP `409`; retrieve the list again. These filters retrieve records and do not change tags, assignments or notification settings. #### Related items Set `hydrate_related_items=true` to include each record's `related_items`: the Tasks and items linked to it. Add or remove links with POST and DELETE /v1/related_items. It is left out by default to keep lists fast. Retrieving one record always includes `related_items`. #### Formatted text in the response Notes and other rich-text values in the response contain the stored HTML, including encoded characters and line breaks such as `
`. #### Events with a hidden Giveaways tab Records on Events whose Giveaways tab is hidden are not listed. If filter_by_event_id names such an Event, the response is HTTP 200 with no records for it and a warning that names the tab and the Event. #### Open in ExhibitDay Each record includes exhibitday_url, the record's page in ExhibitDay. It opens the record in view mode on its Event's tab. Sign in with an account that can view the record; ExhibitDay checks access when the link is opened. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/events/giveaways" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/giveaways", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/events/giveaways", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/events/giveaways"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/giveaways")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/giveaways') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/giveaways", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/events/giveaways - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "list_type": "giveaway", "list_data": [ { "id": 12345, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=23456&riType=6&riSub=0&riId=12345", "event_id": 23456, "event_name": "Sample Event", "name": "Welcome kits", "item_source_id": 1, "acquisition_status_id": 10, "acquire_by_date": null, "supplier_source": null, "contact_name": null, "contact_email": null, "contact_phone": null, "product_order_url": null, "acquired_date": null, "order_reference_number": null, "planned_quantity": null, "entry_method_id": null, "entry_rules_url": null, "selection_distribution_method_id": null, "number_of_winners_recipients": null, "must_be_present_to_win": null, "payment_status_id": 0, "payment_due_date": null, "next_payment_due_date": null, "payment_notes": null, "invoice_attachment": { "id": 582345, "filename": "giveaway-invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" }, "notes": "", "item_package_details": "", "branding_customization": "", "preparation_requirements": "", "handling_storage_requirements": "", "intended_use_recipients": "", "eligibility_restrictions": "", "fulfillment_instructions": "", "results_follow_up": "", "item_source": "From a Supplier / Vendor", "acquisition_status": "Need to Acquire", "entry_method": "Not Specified", "selection_distribution_method": "Not Specified", "payment_status": { "id": 0, "name": "N/A" }, "cost": { "amount": 0.00, "cost_center_breakdown": [] } } ], "records_found": 1, "total_records": 1, "has_more": false } ``` ### Add a Giveaway `POST https://api.exhibitday.com/v1/events/giveaways` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=giveaways#post-v1-events-giveaways Adds a Giveaway to an Event. Name the items or package, choose where they will come from, and record how people can receive them. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | event_id | Number | Yes | The ID of the Event. | The Giveaway will be added to this Event. | | name | String | Yes | A name for the Giveaway, such as Welcome kits. | Up to 200 characters, excluding surrounding spaces. Required; enter a nonblank name. | | item_source_id | Number | No | Where the giveaway items will come from. Omit to use From a Supplier / Vendor. See Choosing a source below for supplier fields and linked inventory. | Allowed values: `1` (From a Supplier / Vendor) \| `2` (Existing Inventory) \| `3` (From a Supplier + Existing Inventory) | | acquisition_status_id | Number | No | Whether the supplier items have been acquired. This applies only when Source includes a supplier. Omit for Need to Acquire. Null resets supplier items to Need to Acquire. Existing Inventory clears this status. | Allowed values: `10` (Need to Acquire) \| `20` (Already Acquired) | | acquire_by_date | String | No | The deadline to purchase or secure the supplier items. | Use a calendar date in YYYY-MM-DD format. Omit for no value. Applies when the Source includes a supplier. | | supplier_source | String | No | The supplier or source of purchased items. | Up to 200 characters, excluding surrounding spaces. Omit for no value. Applies when the Source includes a supplier. | | contact_name | String | No | The supplier contact's name. | Up to 200 characters, excluding surrounding spaces. Omit for no value. Applies when the Source includes a supplier. | | contact_email | String | No | The supplier contact's email address. | Up to 200 characters, excluding surrounding spaces. Omit for no value. Applies when the Source includes a supplier. | | contact_phone | String | No | The supplier contact's phone number. | Up to 200 characters, excluding surrounding spaces. Omit for no value. Applies when the Source includes a supplier. | | product_order_url | String | No | A link to order the items or manage the purchase. | Up to 2,000 characters, excluding surrounding spaces. Omit for no value. Applies when the Source includes a supplier. | | acquired_date | String | No | The date the supplier purchase or arrangement was confirmed. | Use a calendar date in YYYY-MM-DD format. Omit for no value. Applies only to supplier items marked Already Acquired. Choosing another acquisition status clears this date and the order/reference number. | | order_reference_number | String | No | The supplier's order or reference number. | Up to 200 characters, excluding surrounding spaces. Omit for no value. Applies only to supplier items marked Already Acquired. | | planned_quantity | String | No | How many items or packages you plan to use. | Up to 150 characters, excluding surrounding spaces. Omit for no value. This is text, for example 200 pens, 50-75 kits, or One per team. | | entry_method_id | Number | No | What someone needs to do to enter or qualify. Omit or send null for Not Specified. | Allowed values: `9` (No Entry Required) \| `1` (Badge Scan) \| `2` (Business Card) \| `3` (Form Submission) \| `4` (Purchase) \| `5` (Event / Session Attendance) \| `6` (Game / Contest Participation) \| `8` (Social Media / Online Engagement) \| `7` (Other) | | entry_rules_url | String | No | A link to the giveaway's entry rules. | Up to 2,000 characters, excluding surrounding spaces. Omit for no value. | | selection_distribution_method_id | Number | No | How winners are chosen or the items are distributed. Omit or send null for Not Specified. See Distribution rules below. | Allowed values: `1` (Random Drawing) \| `2` (Judged Contest) \| `5` (Instant Win / Game Outcome) \| `3` (First Come / While Supplies Last) \| `6` (All Eligible Participants) \| `4` (Other) | | number_of_winners_recipients | String | No | How many people will win or receive the giveaway. | Up to 150 characters, excluding surrounding spaces. Omit for no value. This is text rather than a numeric-only count. | | must_be_present_to_win | Boolean | No | Whether a winner must be present when selected. | Use true or false. Send null to clear the answer. False remains an explicit No. Applies to Random Drawing (1), Judged Contest (2), Other (4), and Instant Win / Game Outcome (5). Choosing another method clears the answer. | | payment_status_id | Number | No | The Giveaway's payment status. Omit for N/A. Choosing a status other than Partially Paid clears the next partial payment due date. | Allowed values: `0` (N/A) \| `1` (Paid in Full) \| `2` (Partially Paid) \| `3` (Not Paid Yet) | | payment_due_date | String | No | The Giveaway payment due date. | Use a calendar date in YYYY-MM-DD format. Omit for no value. | | next_payment_due_date | Date | No | The next partial payment due date. | Use a calendar date in YYYY-MM-DD format. Applies only to Partially Paid (2). Supplying it with another payment status clears the date; choosing another status also clears it. Omit for no value. | | payment_notes | String | No | Notes about the giveaway payment. | Up to 200 characters, excluding surrounding spaces. Omit for no value. | | notes | String | No | General notes about this Giveaway. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Both the saved text and the ExhibitDay editor's character count must fit within 30,000 characters; line breaks and characters such as & and < take extra space when saved. Omit for no value. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | item_package_details | String | No | What is included in each item or package. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Both the saved text and the ExhibitDay editor's character count must fit within 30,000 characters; line breaks and characters such as & and < take extra space when saved. Omit for no value. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | branding_customization | String | No | How the items should be branded or customized. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Both the saved text and the ExhibitDay editor's character count must fit within 30,000 characters; line breaks and characters such as & and < take extra space when saved. Omit for no value. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | preparation_requirements | String | No | What needs to be prepared before the giveaway. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Both the saved text and the ExhibitDay editor's character count must fit within 30,000 characters; line breaks and characters such as & and < take extra space when saved. Omit for no value. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | handling_storage_requirements | String | No | How the items should be handled or stored. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Both the saved text and the ExhibitDay editor's character count must fit within 30,000 characters; line breaks and characters such as & and < take extra space when saved. Omit for no value. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | intended_use_recipients | String | No | Who the giveaway is intended for and how they will use it. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Both the saved text and the ExhibitDay editor's character count must fit within 30,000 characters; line breaks and characters such as & and < take extra space when saved. Omit for no value. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | eligibility_restrictions | String | No | Who is eligible to enter or receive the giveaway. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Both the saved text and the ExhibitDay editor's character count must fit within 30,000 characters; line breaks and characters such as & and < take extra space when saved. Omit for no value. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | fulfillment_instructions | String | No | How the items should be delivered or handed out. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Both the saved text and the ExhibitDay editor's character count must fit within 30,000 characters; line breaks and characters such as & and < take extra space when saved. Omit for no value. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | results_follow_up | String | No | Results to record and follow-up work after the giveaway. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Both the saved text and the ExhibitDay editor's character count must fit within 30,000 characters; line breaks and characters such as & and < take extra space when saved. Omit for no value. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | cost | Number or cost object | No | The full cost, as a number or an object with amount and/or cost_center_breakdown. [Record Costs and Split Them Across Cost Centers](/Help/V1?guide=entering-costs). | Optional; defaults to zero. | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` \| `object` | | Idempotency-Key | String | No | A unique key for safely retrying this add request. | Optional HTTP header: 1 to 255 visible ASCII characters without spaces or commas. Retry the identical request with the same key to replay its first saved response. Use a new key for a different request. | | $ignore_params_with_empty_values | Boolean | No | Whether supplied JSON null values should be omitted. | Default: false. With true, actual JSON null fields are omitted. Nonempty text null still requests clearing where supported. The required name, nonclearable fields and revision checks still apply. | Declared schema for `cost` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "anyOf": [ { "type": "number", "minimum": 0, "description": "Shorthand for an object with amount. The amount is rounded to cents before the supported storage range is checked.", "nullable": true }, { "type": "object", "additionalProperties": false, "properties": { "amount": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 }, "cost_center_breakdown": { "type": "array", "items": { "type": "object", "additionalProperties": false, "properties": { "cost_center_id": { "type": "integer", "format": "int64", "nullable": true }, "charge": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 }, "cost_center": { "type": "string", "description": "Optional and read-only: the cost center name a read returns, so a cost can be sent back unchanged. It is ignored; the line is saved by cost_center_id, and a name that doesn't match that cost center is explained in a warning.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "required": [ "charge" ] }, "maxItems": 2147483647 } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "anyOf": [ { "required": [ "amount" ] }, { "required": [ "cost_center_breakdown" ] } ], "nullable": true } ], "x-numeric-shorthand": "A number is equivalent to {amount:number}.", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": { "amount": 125.50 } } ``` #### Choosing a source Use From a Supplier / Vendor for items obtained for this Event, Existing Inventory for items represented by existing asset reservations, or From a Supplier + Existing Inventory for both. Existing Inventory clears supplier/acquisition details when that group is saved. Supplier items start at Need to Acquire; Already Acquired enables the date acquired and order/reference number. Choosing another acquisition status clears those two fields. Costs, payment fields, notes, files and inventory links remain independent. To use inventory, link existing asset reservations from this same Event with POST /v1/related_items; that call refuses inventory links while the Source is Supplier-only. Changing Source does not create a reservation or book stock. If linked inventory remains visible to this request, choosing Supplier-only is refused; use Source 2 or 3. #### Distribution rules Entry Method says how someone enters or qualifies. Selection / Distribution Method says how winners are chosen or items are handed out. No Entry Required is a valid choice for items anyone can take. Must Be Present to Win applies only when a winner is selected: Random Drawing, Judged Contest, Instant Win / Game Outcome or Other. First Come / While Supplies Last, All Eligible Participants or an unspecified method clears that answer. Planned Quantity and Number of Winners / Recipients accept text, including units or a range. #### After the add The response includes the new Giveaway and its id. The change is recorded in Event history. File Attachments and the Invoice Attachment are uploaded separately. Recording costs does not attach an invoice, mark a payment complete or change the Event's planned Giveaway budget. If a save outcome cannot be confirmed, retrieve the current Giveaway before deciding whether to retry. #### Access The Event's Giveaways tab must be available, visible and unlocked, and your current access must allow the change. #### Sending values Use JSON, query parameters or form fields for text containing commas. #### Sending text Send plain text for Notes and other rich-text fields. Characters such as `&`, `<` and quotes, along with line breaks, are encoded for storage. Notes and other rich-text values in the response contain the stored HTML, including encoded characters and line breaks such as `
`. #### Hidden or locked tab If the Event's Giveaways tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. An Event that is not in your workspace returns HTTP 404. #### Acquisition status When adding, acquisition_status_id is optional and defaults to Need to Acquire. The same statuses use different IDs in each family: Sponsorships use 1 for Need to Acquire and 2 for Already Acquired; Giveaways use 10 and 20. #### Open in ExhibitDay The created record includes exhibitday_url, the record's page in ExhibitDay. It is the same link that GET /v1/events/giveaways/info returns for this record and opens the record in view mode on its Event's tab. Sign in with an account that can view the record; ExhibitDay checks access when the link is opened. Example — curl: ```bash curl -X POST "https://api.exhibitday.com/v1/events/giveaways" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"event_id\":23456,\"name\":\"Welcome kits\"}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/giveaways", { method: "POST", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "event_id": 23456, "name": "Welcome kits" }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.post( "https://api.exhibitday.com/v1/events/giveaways", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"event_id": 23456, "name": "Welcome kits"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PostAsync("https://api.exhibitday.com/v1/events/giveaways", JsonContent.Create(new { event_id = 23456, name = "Welcome kits" })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/giveaways")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("POST", HttpRequest.BodyPublishers.ofString("{\"event_id\":23456,\"name\":\"Welcome kits\"}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"event_id":23456,"name":"Welcome kits"}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/giveaways') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"event_id":23456,"name":"Welcome kits"}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/events/giveaways", strings.NewReader("{\"event_id\":23456,\"name\":\"Welcome kits\"}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): POST /v1/events/giveaways - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "id": 12345, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=23456&riType=6&riSub=0&riId=12345", "event_id": 23456, "event_name": "Sample Event", "name": "Welcome kits", "item_source_id": 1, "acquisition_status_id": 10, "acquire_by_date": null, "supplier_source": null, "contact_name": null, "contact_email": null, "contact_phone": null, "product_order_url": null, "acquired_date": null, "order_reference_number": null, "planned_quantity": null, "entry_method_id": null, "entry_rules_url": null, "selection_distribution_method_id": null, "number_of_winners_recipients": null, "must_be_present_to_win": null, "payment_status_id": 0, "payment_due_date": null, "next_payment_due_date": null, "payment_notes": null, "invoice_attachment": null, "notes": "", "item_package_details": "", "branding_customization": "", "preparation_requirements": "", "handling_storage_requirements": "", "intended_use_recipients": "", "eligibility_restrictions": "", "fulfillment_instructions": "", "results_follow_up": "", "item_source": "From a Supplier / Vendor", "acquisition_status": "Need to Acquire", "entry_method": "Not Specified", "selection_distribution_method": "Not Specified", "payment_status": { "id": 0, "name": "N/A" }, "cost": { "amount": 0.00, "cost_center_breakdown": [] } } ``` ### Update a Giveaway `PATCH https://api.exhibitday.com/v1/events/giveaways` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=giveaways#patch-v1-events-giveaways Updates a Giveaway's item details, acquisition plans, distribution rules or payment information. Send only the fields you want to change. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Giveaway. | Use its id from the list, single-record read or add response. | | name | String | No | A name for the Giveaway, such as Welcome kits. | Up to 200 characters, excluding surrounding spaces. Omit or leave blank to keep it; null cannot clear it. Renaming also updates an existing valid Invoice Attachment's label. | | item_source_id | Number | No | Where the giveaway items will come from. Omit or leave blank to keep it; null cannot clear it. Older unspecified Sources can remain unchanged. See Choosing a source below for supplier fields and linked inventory. | Allowed values: `1` (From a Supplier / Vendor) \| `2` (Existing Inventory) \| `3` (From a Supplier + Existing Inventory) | | acquisition_status_id | Number | No | Whether the supplier items have been acquired. This applies only when Source includes a supplier. Omit or leave blank to keep it unless its source group changes. Null resets supplier items to Need to Acquire. Existing Inventory clears this status. | Allowed values: `10` (Need to Acquire) \| `20` (Already Acquired) | | acquire_by_date | String | No | The deadline to purchase or secure the supplier items. | Use a calendar date in YYYY-MM-DD format. Omit or leave blank to keep it; null clears it. Applies when the Source includes a supplier. | | supplier_source | String | No | The supplier or source of purchased items. | Up to 200 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. Applies when the Source includes a supplier. | | contact_name | String | No | The supplier contact's name. | Up to 200 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. Applies when the Source includes a supplier. | | contact_email | String | No | The supplier contact's email address. | Up to 200 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. Applies when the Source includes a supplier. | | contact_phone | String | No | The supplier contact's phone number. | Up to 200 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. Applies when the Source includes a supplier. | | product_order_url | String | No | A link to order the items or manage the purchase. | Up to 2,000 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. Applies when the Source includes a supplier. | | acquired_date | String | No | The date the supplier purchase or arrangement was confirmed. | Use a calendar date in YYYY-MM-DD format. Omit or leave blank to keep it; null clears it. Applies only to supplier items marked Already Acquired. Choosing another acquisition status clears this date and the order/reference number. | | order_reference_number | String | No | The supplier's order or reference number. | Up to 200 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. Applies only to supplier items marked Already Acquired. | | planned_quantity | String | No | How many items or packages you plan to use. | Up to 150 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. This is text, for example 200 pens, 50-75 kits, or One per team. | | entry_method_id | Number | No | What someone needs to do to enter or qualify. Null means Not Specified. Omit or leave blank to keep it. | Allowed values: `9` (No Entry Required) \| `1` (Badge Scan) \| `2` (Business Card) \| `3` (Form Submission) \| `4` (Purchase) \| `5` (Event / Session Attendance) \| `6` (Game / Contest Participation) \| `8` (Social Media / Online Engagement) \| `7` (Other) | | entry_rules_url | String | No | A link to the giveaway's entry rules. | Up to 2,000 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. | | selection_distribution_method_id | Number | No | How winners are chosen or the items are distributed. Null means Not Specified. Omit or leave blank to keep it. See Distribution rules below. | Allowed values: `1` (Random Drawing) \| `2` (Judged Contest) \| `5` (Instant Win / Game Outcome) \| `3` (First Come / While Supplies Last) \| `6` (All Eligible Participants) \| `4` (Other) | | number_of_winners_recipients | String | No | How many people will win or receive the giveaway. | Up to 150 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. This is text rather than a numeric-only count. | | must_be_present_to_win | Boolean | No | Whether a winner must be present when selected. | Use true or false. Send null to clear the answer. False remains an explicit No. Applies to Random Drawing (1), Judged Contest (2), Other (4), and Instant Win / Game Outcome (5). Choosing another method clears the answer. Omit or leave blank to keep it. | | payment_status_id | Number | No | The Giveaway's payment status. Omit or leave blank to keep it; null resets it to N/A. Choosing a status other than Partially Paid clears the next partial payment due date. | Allowed values: `0` (N/A) \| `1` (Paid in Full) \| `2` (Partially Paid) \| `3` (Not Paid Yet) | | payment_due_date | String | No | The Giveaway payment due date. | Use a calendar date in YYYY-MM-DD format. Omit or leave blank to keep it; null clears it. | | next_payment_due_date | Date | No | The next partial payment due date. | Use a calendar date in YYYY-MM-DD format. Applies only to Partially Paid (2). Supplying it with another payment status clears the date; choosing another status also clears it. Omit or leave blank to keep it; null clears it. | | payment_notes | String | No | Notes about the giveaway payment. | Up to 200 characters, excluding surrounding spaces. Omit or leave blank to keep it; null clears it. | | notes | String | No | General notes about this Giveaway. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Both the saved text and the ExhibitDay editor's character count must fit within 30,000 characters; line breaks and characters such as & and < take extra space when saved. Omit or leave blank to keep it; null clears it. Existing over-limit content can stay unchanged or be shortened, but neither count may grow. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | item_package_details | String | No | What is included in each item or package. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Both the saved text and the ExhibitDay editor's character count must fit within 30,000 characters; line breaks and characters such as & and < take extra space when saved. Omit or leave blank to keep it; null clears it. Existing over-limit content can stay unchanged or be shortened, but neither count may grow. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | branding_customization | String | No | How the items should be branded or customized. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Both the saved text and the ExhibitDay editor's character count must fit within 30,000 characters; line breaks and characters such as & and < take extra space when saved. Omit or leave blank to keep it; null clears it. Existing over-limit content can stay unchanged or be shortened, but neither count may grow. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | preparation_requirements | String | No | What needs to be prepared before the giveaway. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Both the saved text and the ExhibitDay editor's character count must fit within 30,000 characters; line breaks and characters such as & and < take extra space when saved. Omit or leave blank to keep it; null clears it. Existing over-limit content can stay unchanged or be shortened, but neither count may grow. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | handling_storage_requirements | String | No | How the items should be handled or stored. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Both the saved text and the ExhibitDay editor's character count must fit within 30,000 characters; line breaks and characters such as & and < take extra space when saved. Omit or leave blank to keep it; null clears it. Existing over-limit content can stay unchanged or be shortened, but neither count may grow. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | intended_use_recipients | String | No | Who the giveaway is intended for and how they will use it. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Both the saved text and the ExhibitDay editor's character count must fit within 30,000 characters; line breaks and characters such as & and < take extra space when saved. Omit or leave blank to keep it; null clears it. Existing over-limit content can stay unchanged or be shortened, but neither count may grow. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | eligibility_restrictions | String | No | Who is eligible to enter or receive the giveaway. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Both the saved text and the ExhibitDay editor's character count must fit within 30,000 characters; line breaks and characters such as & and < take extra space when saved. Omit or leave blank to keep it; null clears it. Existing over-limit content can stay unchanged or be shortened, but neither count may grow. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | fulfillment_instructions | String | No | How the items should be delivered or handed out. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Both the saved text and the ExhibitDay editor's character count must fit within 30,000 characters; line breaks and characters such as & and < take extra space when saved. Omit or leave blank to keep it; null clears it. Existing over-limit content can stay unchanged or be shortened, but neither count may grow. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | results_follow_up | String | No | Results to record and follow-up work after the giveaway. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Both the saved text and the ExhibitDay editor's character count must fit within 30,000 characters; line breaks and characters such as & and < take extra space when saved. Omit or leave blank to keep it; null clears it. Existing over-limit content can stay unchanged or be shortened, but neither count may grow. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | cost | Number or cost object | No | The full cost, as a number or an object with amount and/or cost_center_breakdown. [Record Costs and Split Them Across Cost Centers](/Help/V1?guide=entering-costs). | Omit to keep the saved cost. A supplied value replaces its full allocation. | | expected_revision | String | No | The record_revision from an earlier read of this Giveaway. | Optional. Obtain it from GET /v1/events/giveaways/info with $include_record_revision=true. A changed Giveaway returns HTTP 409 without saving this update. Omission skips the check; blank, null and malformed values are refused, even with $ignore_params_with_empty_values=true. | | $ignore_params_with_empty_values | Boolean | No | Whether supplied JSON null values should be omitted. | Default: false. With true, actual JSON null fields are omitted. Nonempty text null still requests clearing where supported. The required name, nonclearable fields and revision checks still apply. | Declared schema for `cost` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "anyOf": [ { "type": "number", "minimum": 0, "description": "Shorthand for an object with amount. The amount is rounded to cents before the supported storage range is checked.", "nullable": true }, { "type": "object", "additionalProperties": false, "properties": { "amount": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 }, "cost_center_breakdown": { "type": "array", "items": { "type": "object", "additionalProperties": false, "properties": { "cost_center_id": { "type": "integer", "format": "int64", "nullable": true }, "charge": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 }, "cost_center": { "type": "string", "description": "Optional and read-only: the cost center name a read returns, so a cost can be sent back unchanged. It is ignored; the line is saved by cost_center_id, and a name that doesn't match that cost center is explained in a warning.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "required": [ "charge" ] }, "maxItems": 2147483647 } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "anyOf": [ { "required": [ "amount" ] }, { "required": [ "cost_center_breakdown" ] } ], "nullable": true } ], "x-numeric-shorthand": "A number is equivalent to {amount:number}.", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": { "amount": 125.50 } } ``` #### Choosing a source Use From a Supplier / Vendor for items obtained for this Event, Existing Inventory for items represented by existing asset reservations, or From a Supplier + Existing Inventory for both. Existing Inventory clears supplier/acquisition details when that group is saved. Supplier items start at Need to Acquire; Already Acquired enables the date acquired and order/reference number. Choosing another acquisition status clears those two fields. Costs, payment fields, notes, files and inventory links remain independent. To use inventory, link existing asset reservations from this same Event with POST /v1/related_items; that call refuses inventory links while the Source is Supplier-only. Changing Source does not create a reservation or book stock. If linked inventory remains visible to this request, choosing Supplier-only is refused; use Source 2 or 3. #### Distribution rules Entry Method says how someone enters or qualifies. Selection / Distribution Method says how winners are chosen or items are handed out. No Entry Required is a valid choice for items anyone can take. Must Be Present to Win applies only when a winner is selected: Random Drawing, Judged Contest, Instant Win / Game Outcome or Other. First Come / While Supplies Last, All Eligible Participants or an unspecified method clears that answer. Planned Quantity and Number of Winners / Recipients accept text, including units or a range. #### Choosing what to change Omitted or blank fields keep their values. Null clears or resets supported fields; name and item_source_id cannot be cleared. Clearing payment_status_id resets it to N/A. With ignore-empty true, actual JSON null is omitted instead. A controlling field can clear dependent details as described above. An unrelated update preserves omitted older details. An unchanged request saves no business data or history and keeps its revision. File Attachments and the Invoice Attachment are managed separately. #### Using expected_revision 1. Retrieve this Giveaway with GET /v1/events/giveaways/info and $include_record_revision=true. 2. Send the returned record_revision unchanged as expected_revision with this update. 3. If the API reports a change, read the current Giveaway and decide what to update. #### After the update A real change is recorded in Event history. Renaming also updates an existing valid Invoice Attachment's label without replacing its contents. Recording costs does not attach an invoice, mark a payment complete or change the Event's planned Giveaway budget. If a save outcome cannot be confirmed, retrieve the current Giveaway before deciding whether to retry. #### Access The Event's Giveaways tab must be available, visible and unlocked, and your current access must allow the change. #### Sending values Use JSON, query parameters or form fields for text containing commas. #### Sending text Send plain text for Notes and other rich-text fields. Characters such as `&`, `<` and quotes, along with line breaks, are encoded for storage. #### Hidden or locked tab If the Event's Giveaways tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. An Event that is not in your workspace returns HTTP 404. Example — curl: ```bash curl -X PATCH "https://api.exhibitday.com/v1/events/giveaways" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"id\":12345,\"name\":\"Welcome kits\"}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/giveaways", { method: "PATCH", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "id": 12345, "name": "Welcome kits" }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.patch( "https://api.exhibitday.com/v1/events/giveaways", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"id": 12345, "name": "Welcome kits"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PatchAsync("https://api.exhibitday.com/v1/events/giveaways", JsonContent.Create(new { id = 12345, name = "Welcome kits" })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/giveaways")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("PATCH", HttpRequest.BodyPublishers.ofString("{\"id\":12345,\"name\":\"Welcome kits\"}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"id":12345,"name":"Welcome kits"}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/giveaways') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"id":12345,"name":"Welcome kits"}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/events/giveaways", strings.NewReader("{\"id\":12345,\"name\":\"Welcome kits\"}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): PATCH /v1/events/giveaways - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Giveaway updated.", "errors": [] } ``` ### Delete a Giveaway `DELETE https://api.exhibitday.com/v1/events/giveaways` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=giveaways#delete-v1-events-giveaways Deletes a Giveaway and its saved costs, related-item links, File Attachments and Invoice Attachment. Linked asset reservations, Tasks and other records remain in place. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Giveaway. | Use its id from the list, single-record read or add response. | #### After the deletion The Giveaway, its costs, related-item links and attachment records are removed together. Only its files are scheduled for physical cleanup after the save. Linked asset reservations, Tasks and other records remain. The deletion is recorded in Event history. An unavailable Giveaway returns HTTP 404. If the save outcome cannot be confirmed, retrieve the current Giveaways before deciding whether to retry. #### Access The Event's Giveaways tab must be available, visible and unlocked, and your current access must allow the change. #### Hidden or locked tab If the Event's Giveaways tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. An Event that is not in your workspace returns HTTP 404. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/events/giveaways?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/giveaways?" + new URLSearchParams({ "id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/events/giveaways", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/events/giveaways?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/giveaways?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/giveaways?id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/events/giveaways?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/events/giveaways - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Giveaway removed.", "errors": [] } ``` ### Download Giveaway Invoice Attachment `GET https://api.exhibitday.com/v1/events/giveaways/invoice_attachment/download` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=giveaways#get-v1-events-giveaways-invoice_attachment-download Downloads the original Invoice Attachment for this Giveaway. Use this method to retrieve the file itself. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | giveaway_id | Number | Yes | The ID of the Giveaway, from Retrieve Giveaways (GET /v1/events/giveaways) or its add response. | | #### Finding the file In the web app, this is the invoice control beside the Giveaway's cost and payment details. Each cost has one Invoice Attachment even when its amount is split among cost centers. For file metadata, retrieve the parent record with GET /v1/events/giveaways/info and read invoice_attachment. Use this download method for the contents. No attachment ID or invoice flag is needed. #### Download response A successful response contains the original uploaded file, with a safe download filename. API errors use the usual JSON response. If no invoice is attached, this method returns HTTP 404. Current record, financial and invoice permissions apply. A locked tab can still be read. Permitted downloads remain available on the Free plan. #### Files still being copied If this file is still being copied, the download returns HTTP 409 with file_copy_pending. Try the download again in a few minutes. #### Hidden tab If the Event's Giveaways tab is hidden, this request returns HTTP 400 (not_allowed), and the message says the tab is hidden. Show the tab in ExhibitDay first. A locked tab can still be read. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X GET "https://api.exhibitday.com/v1/events/giveaways/invoice_attachment/download?giveaway_id=12345" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi mv response-body.tmp 'invoice.pdf' ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const response = await fetch("https://api.exhibitday.com/v1/events/giveaways/invoice_attachment/download?giveaway_id=12345", { method: "GET", headers: { Authorization: 'Bearer YOUR_API_KEY' } }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); await writeFile("invoice.pdf", new Uint8Array(await response.arrayBuffer())); ``` Example — Python: ```python import requests import json response = requests.request("GET", "https://api.exhibitday.com/v1/events/giveaways/invoice_attachment/download?giveaway_id=12345", headers={'Authorization': 'Bearer YOUR_API_KEY'}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') with open("invoice.pdf", 'wb') as destination: destination.write(response.content) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.exhibitday.com/v1/events/giveaways/invoice_attachment/download?giveaway_id=12345"); using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); await File.WriteAllBytesAsync("invoice.pdf", await response.Content.ReadAsByteArrayAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/giveaways/invoice_attachment/download?giveaway_id=12345")).header("Authorization", "Bearer YOUR_API_KEY"); HttpResponse response = HttpClient.newHttpClient().send(request.method("GET", HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); Files.write(Path.of("invoice.pdf"), response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); file_put_contents('invoice.pdf', $response); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/giveaways/invoice_attachment/download?giveaway_id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' File.binwrite('invoice.pdf', response.body) ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/giveaways/invoice_attachment/download?giveaway_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } if err := os.WriteFile("invoice.pdf", data, 0600); err != nil { log.Fatal(err) } fmt.Println("File saved") } ``` HTTP 200: Returns the original uploaded file as a private download, using a safe filename. If the file cannot be downloaded, the response contains the usual JSON API error instead. Media: application/octet-stream. The body is the authorized file's real bytes, not JSON or base64. Errors are JSON status responses; check HTTP status before saving the file. ### Add Giveaway Invoice Attachment `POST https://api.exhibitday.com/v1/events/giveaways/invoice_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=giveaways#post-v1-events-giveaways-invoice_attachment Adds one Invoice Attachment to this Giveaway. You can attach an invoice, receipt or other payment document when no invoice file is currently attached. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | giveaway_id | Number | Yes | The ID of the Giveaway, from Retrieve Giveaways (GET /v1/events/giveaways) or its add response. | | | file | File (multipart) | Yes | The Invoice Attachment to upload. | Send exactly one complete, nonempty multipart/form-data file part named file. The supported extensions and current per-file limit are shown below; the complete request limit also includes multipart overhead. A missing or null file is invalid and does not remove an existing invoice. | | Idempotency-Key | String | No | A unique key for safely retrying this upload. | Optional HTTP header: 1 to 255 visible ASCII characters without spaces or commas. Retry the identical request with the same key to replay its first saved response. Use a new key for a different upload. | Declared schema for `file` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "string", "format": "binary", "x-maximum-bytes": 26214400, "x-allowed-extensions": [ "png", "jpg", "jpeg", "bmp", "gif", "pdf", "msg", "eml", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "rtf", "odp", "odt", "ods", "txt", "wks", "zip" ] } ``` #### Before you upload POST requires an empty invoice slot. If an invoice is already attached, the API returns HTTP 409; use PATCH to replace it. An Invoice Attachment is separate from the record's supporting File Attachments. Use the invoice control beside the Giveaway's cost and payment details in the web app. #### After the upload The response's invoice_attachment contains the attached file's id, filename and attachment_created_timestamp. The amount, payment fields, cost-center breakdown and other files are unchanged. The upload is recorded in Event history. Attaching an invoice does not mark the record as paid. #### Access and retries A current upload-enabled plan, record and financial permissions, and an editable applicable tab are required. Each uploaded file must fit its supported type and size limits. expected_revision is not supported by this file method. If the save outcome cannot be confirmed, retrieve the current parent record with GET /v1/events/giveaways/info and inspect invoice_attachment before deciding whether to retry. #### Hidden or locked tab If the Event's Giveaways tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X POST "https://api.exhibitday.com/v1/events/giveaways/invoice_attachment" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}" --form-string "giveaway_id=12345" --form "file=@invoice.pdf;type=application/octet-stream") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi cat response-body.tmp ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const form = new FormData(); form.append("giveaway_id", "12345"); form.append("file", new Blob([await readFile("invoice.pdf")], { type: "application/octet-stream" }), "invoice.pdf"); const response = await fetch("https://api.exhibitday.com/v1/events/giveaways/invoice_attachment", { method: "POST", headers: { Authorization: 'Bearer YOUR_API_KEY' }, body: form }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); console.log(await response.json()); ``` Example — Python: ```python import requests import json from contextlib import ExitStack with ExitStack() as stack: files = [ ("file", ("invoice.pdf", stack.enter_context(open("invoice.pdf", 'rb')), "application/octet-stream")), ] response = requests.request("POST", "https://api.exhibitday.com/v1/events/giveaways/invoice_attachment", headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data={"giveaway_id": "12345"}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') print(response.json()) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.exhibitday.com/v1/events/giveaways/invoice_attachment"); var form = new MultipartFormDataContent(); form.Add(new StringContent("12345"), "giveaway_id"); var file0 = new StreamContent(File.OpenRead("invoice.pdf")); file0.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(file0, "file", "invoice.pdf"); request.Content = form; using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/giveaways/invoice_attachment")).header("Authorization", "Bearer YOUR_API_KEY"); String boundary = "ExhibitDay-" + UUID.randomUUID(); ByteArrayOutputStream form = new ByteArrayOutputStream(); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"giveaway_id\"\r\n\r\n" + "12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"invoice.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8)); form.write(Files.readAllBytes(Path.of("invoice.pdf"))); form.write("\r\n".getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); request.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpResponse response = HttpClient.newHttpClient().send(request.method("POST", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); System.out.println(new String(response.body(), StandardCharsets.UTF_8)); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], CURLOPT_POSTFIELDS => [ 'giveaway_id' => '12345', 'file' => new CURLFile('invoice.pdf', 'application/octet-stream', 'invoice.pdf'), ], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); echo $response; ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/giveaways/invoice_attachment') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' files = [] begin parts = [ ['giveaway_id', '12345'], ['file', (files << File.open('invoice.pdf', 'rb')).last, {filename: 'invoice.pdf', content_type: 'application/octet-stream'}], ] request.set_form(parts, 'multipart/form-data') response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' puts response.body ensure files.each(&:close) end ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" "bytes" "mime/multipart" "net/textproto" ) func main() { var form bytes.Buffer writer := multipart.NewWriter(&form) if err := writer.WriteField("giveaway_id", "12345"); err != nil { log.Fatal(err) } header0 := textproto.MIMEHeader{} header0.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"invoice.pdf\"") header0.Set("Content-Type", "application/octet-stream") part0, err := writer.CreatePart(header0) if err != nil { log.Fatal(err) } file0, err := os.Open("invoice.pdf") if err != nil { log.Fatal(err) } if _, err = io.Copy(part0, file0); err != nil { log.Fatal(err) } file0.Close() if err := writer.Close(); err != nil { log.Fatal(err) } request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/events/giveaways/invoice_attachment", &form) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", writer.FormDataContentType()) response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } fmt.Printf("%s\n", data) } ``` Example HTTP response body (JSON): POST /v1/events/giveaways/invoice_attachment - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "invoice_attachment": { "id": 12345, "filename": "invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } } ``` ### Replace Giveaway Invoice Attachment `PATCH https://api.exhibitday.com/v1/events/giveaways/invoice_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=giveaways#patch-v1-events-giveaways-invoice_attachment Replaces this Giveaway's current Invoice Attachment with one uploaded file. Use this method when an invoice file is already attached. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | giveaway_id | Number | Yes | The ID of the Giveaway, from Retrieve Giveaways (GET /v1/events/giveaways) or its add response. | | | file | File (multipart) | Yes | The Invoice Attachment to upload. | Send exactly one complete, nonempty multipart/form-data file part named file. The supported extensions and current per-file limit are shown below; the complete request limit also includes multipart overhead. A missing or null file is invalid and does not remove an existing invoice. | Declared schema for `file` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "string", "format": "binary", "x-maximum-bytes": 26214400, "x-allowed-extensions": [ "png", "jpg", "jpeg", "bmp", "gif", "pdf", "msg", "eml", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "rtf", "odp", "odt", "ods", "txt", "wks", "zip" ] } ``` #### Replacing the current file PATCH requires a current invoice file. If none is attached, the API returns HTTP 404. Upload exactly one file; the previous attachment ID is not needed. If another request changes the current invoice during your upload, the API refuses this request instead of replacing a different file. Even identical replacement contents receive a new attachment ID. #### After the replacement The response's invoice_attachment contains the attached file's id, filename and attachment_created_timestamp. The amount, payment fields, cost-center breakdown and other files are unchanged. The previous file is scheduled for physical cleanup after a confirmed save; cleanup may finish later. The replacement is recorded in Event history. #### Access and retries A current upload-enabled plan, record and financial permissions, and an editable applicable tab are required. Each uploaded file must fit its supported type and size limits. expected_revision is not supported by this file method. PATCH does not use Idempotency-Key replay. If the save outcome cannot be confirmed, retrieve the current parent record with GET /v1/events/giveaways/info and inspect invoice_attachment before deciding whether to retry. #### Hidden or locked tab If the Event's Giveaways tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X PATCH "https://api.exhibitday.com/v1/events/giveaways/invoice_attachment" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}" --form-string "giveaway_id=12345" --form "file=@invoice.pdf;type=application/octet-stream") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi cat response-body.tmp ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const form = new FormData(); form.append("giveaway_id", "12345"); form.append("file", new Blob([await readFile("invoice.pdf")], { type: "application/octet-stream" }), "invoice.pdf"); const response = await fetch("https://api.exhibitday.com/v1/events/giveaways/invoice_attachment", { method: "PATCH", headers: { Authorization: 'Bearer YOUR_API_KEY' }, body: form }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); console.log(await response.json()); ``` Example — Python: ```python import requests import json from contextlib import ExitStack with ExitStack() as stack: files = [ ("file", ("invoice.pdf", stack.enter_context(open("invoice.pdf", 'rb')), "application/octet-stream")), ] response = requests.request("PATCH", "https://api.exhibitday.com/v1/events/giveaways/invoice_attachment", headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data={"giveaway_id": "12345"}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') print(response.json()) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("PATCH"), "https://api.exhibitday.com/v1/events/giveaways/invoice_attachment"); var form = new MultipartFormDataContent(); form.Add(new StringContent("12345"), "giveaway_id"); var file0 = new StreamContent(File.OpenRead("invoice.pdf")); file0.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(file0, "file", "invoice.pdf"); request.Content = form; using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/giveaways/invoice_attachment")).header("Authorization", "Bearer YOUR_API_KEY"); String boundary = "ExhibitDay-" + UUID.randomUUID(); ByteArrayOutputStream form = new ByteArrayOutputStream(); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"giveaway_id\"\r\n\r\n" + "12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"invoice.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8)); form.write(Files.readAllBytes(Path.of("invoice.pdf"))); form.write("\r\n".getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); request.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpResponse response = HttpClient.newHttpClient().send(request.method("PATCH", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); System.out.println(new String(response.body(), StandardCharsets.UTF_8)); } } ``` Example — PHP: ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], CURLOPT_POSTFIELDS => [ 'giveaway_id' => '12345', 'file' => new CURLFile('invoice.pdf', 'application/octet-stream', 'invoice.pdf'), ], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); echo $response; ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/giveaways/invoice_attachment') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' files = [] begin parts = [ ['giveaway_id', '12345'], ['file', (files << File.open('invoice.pdf', 'rb')).last, {filename: 'invoice.pdf', content_type: 'application/octet-stream'}], ] request.set_form(parts, 'multipart/form-data') response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' puts response.body ensure files.each(&:close) end ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" "bytes" "mime/multipart" "net/textproto" ) func main() { var form bytes.Buffer writer := multipart.NewWriter(&form) if err := writer.WriteField("giveaway_id", "12345"); err != nil { log.Fatal(err) } header0 := textproto.MIMEHeader{} header0.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"invoice.pdf\"") header0.Set("Content-Type", "application/octet-stream") part0, err := writer.CreatePart(header0) if err != nil { log.Fatal(err) } file0, err := os.Open("invoice.pdf") if err != nil { log.Fatal(err) } if _, err = io.Copy(part0, file0); err != nil { log.Fatal(err) } file0.Close() if err := writer.Close(); err != nil { log.Fatal(err) } request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/events/giveaways/invoice_attachment", &form) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", writer.FormDataContentType()) response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } fmt.Printf("%s\n", data) } ``` Example HTTP response body (JSON): PATCH /v1/events/giveaways/invoice_attachment - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "invoice_attachment": { "id": 12345, "filename": "invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } } ``` ### Remove Giveaway Invoice Attachment `DELETE https://api.exhibitday.com/v1/events/giveaways/invoice_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=giveaways#delete-v1-events-giveaways-invoice_attachment Removes this Giveaway's Invoice Attachment. The cost, payment details and other File Attachments stay in place. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | giveaway_id | Number | Yes | The ID of the Giveaway, from Retrieve Giveaways (GET /v1/events/giveaways) or its add response. | | #### After the removal The Invoice Attachment is cleared and the removal is recorded in Event history. Its physical file is scheduled for cleanup after a confirmed save; cleanup may finish later. Costs, payment fields, cost-center allocations and supporting files stay unchanged. If no invoice is attached, DELETE returns HTTP 404 Not Found with the message "This Giveaway has no invoice to remove." No saved data or history is changed. Current access and the record's binding are still checked. Do not send file parts with this request. #### Access and retries Current record, financial and invoice permissions and applicable tab-edit access are required. Permitted removals remain available on the Free plan. expected_revision is not supported, and DELETE does not use Idempotency-Key replay. If the save outcome cannot be confirmed, retrieve the current parent record with GET /v1/events/giveaways/info and inspect invoice_attachment before deciding whether to retry. #### Hidden or locked tab If the Event's Giveaways tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/events/giveaways/invoice_attachment?giveaway_id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/giveaways/invoice_attachment?" + new URLSearchParams({ "giveaway_id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/events/giveaways/invoice_attachment", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"giveaway_id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/events/giveaways/invoice_attachment?giveaway_id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/giveaways/invoice_attachment?giveaway_id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/giveaways/invoice_attachment?giveaway_id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/events/giveaways/invoice_attachment?giveaway_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/events/giveaways/invoice_attachment - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Attachment removed.", "errors": [] } ``` ### Retrieve Giveaway General File Attachments `GET https://api.exhibitday.com/v1/events/giveaways/attachments` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=giveaways#get-v1-events-giveaways-attachments Retrieves the General File Attachments on this Giveaway. Each result includes the file's ID, name and added time; use the download method for its contents. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | giveaway_id | Number | Yes | The ID of the Giveaway, from Retrieve Giveaways (GET /v1/events/giveaways) or its add response. | | | $limit | Number | No | The most File Attachments to return. | A positive whole number. Omit for all remaining matching files. | | $offset | Number | No | The number of matching File Attachments to skip. | A whole number of 0 or more. Default: 0. | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records. | Allowed values: `array` | | If-None-Match | String | No | An ETag from an earlier response to this GET. | Optional HTTP header. If the successful response is unchanged, the API returns HTTP 304 with no body. | #### Reading the file list Files are ordered by added time, then attachment ID, lowest first. Only files available under your current access are included. Paging totals and X-Total-Count count all matching files before $limit and $offset are applied. A record with no files you can view returns an empty list. This list does not return edit revisions or support changed-since filtering. #### Supporting files and invoices These are the record's General File Attachments. Its cost Invoice Attachment is separate and has its own download and upload methods. Use this list's id values for these supporting-file downloads and removals. #### Access The record's Event and tab must be available, and the tab must not be hidden. A locked tab can still be read. #### Hidden tab If the Event's Giveaways tab is hidden, this request returns HTTP 400 (not_allowed), and the message says the tab is hidden. Show the tab in ExhibitDay first. A locked tab can still be read. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/events/giveaways/attachments?giveaway_id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/giveaways/attachments?" + new URLSearchParams({ "giveaway_id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/events/giveaways/attachments", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"giveaway_id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/events/giveaways/attachments?giveaway_id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/giveaways/attachments?giveaway_id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/giveaways/attachments?giveaway_id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/giveaways/attachments?giveaway_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/events/giveaways/attachments - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "attachment", "list_data": [ { "id": 12345, "filename": "attachment.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } ] } ``` ### Add Giveaway General File Attachments `POST https://api.exhibitday.com/v1/events/giveaways/attachments` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=giveaways#post-v1-events-giveaways-attachments Adds one or more General File Attachments to this Giveaway. Send each file as a multipart upload part named file. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | giveaway_id | Number | Yes | The ID of the Giveaway, from Retrieve Giveaways (GET /v1/events/giveaways) or its add response. | | | file | File (multipart) | Yes | The File Attachments to upload. | Send one or more complete, nonempty multipart/form-data parts, each named file. Supported types and the current per-file limit are shown below. The complete request limit includes all files and multipart overhead; split larger batches. A missing or null upload is not a removal request. | | Idempotency-Key | String | No | A unique key for safely retrying this upload. | Optional HTTP header: 1 to 255 visible ASCII characters without spaces or commas. Retry the identical request with the same key to replay its first saved response. Use a new key for a different upload. | Declared schema for `file` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "array", "items": { "type": "string", "format": "binary", "x-maximum-bytes": 26214400, "x-allowed-extensions": [ "png", "jpg", "jpeg", "bmp", "gif", "pdf", "msg", "eml", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "rtf", "odp", "odt", "ods", "txt", "wks", "zip" ] } } ``` #### After the upload The response's list_data contains the newly attached files, including each id, filename and attachment_created_timestamp. Existing files are kept. Use each returned id to download or remove that file. Identical repeated files in one request are attached once when their cleaned filename, length and contents match. Files with different contents remain separate even when their names match. This does not remove or replace files already attached to the record. #### Choosing the right file method These uploads add General File Attachments. Use this record's Invoice Attachment methods for its cost invoice or receipt. Adding supporting files does not change amounts, payments or cost-center allocations. #### Access Current record and file-change permissions and applicable Event/tab locks must allow this upload. An upload-enabled paid plan is required. #### History and retries A confirmed file change is recorded in history. expected_revision is not supported by these file methods. If the save outcome cannot be confirmed, retrieve the current file list before deciding whether to retry; the API does not automatically repeat an uncertain change. Supporting File Attachments have no PATCH replacement. To replace one, add the new file and remove the old one using their separate requests; each request has its own outcome. #### Hidden or locked tab If the Event's Giveaways tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X POST "https://api.exhibitday.com/v1/events/giveaways/attachments" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}" --form-string "giveaway_id=12345" --form "file=@attachment.pdf;type=application/octet-stream") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi cat response-body.tmp ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const form = new FormData(); form.append("giveaway_id", "12345"); form.append("file", new Blob([await readFile("attachment.pdf")], { type: "application/octet-stream" }), "attachment.pdf"); const response = await fetch("https://api.exhibitday.com/v1/events/giveaways/attachments", { method: "POST", headers: { Authorization: 'Bearer YOUR_API_KEY' }, body: form }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); console.log(await response.json()); ``` Example — Python: ```python import requests import json from contextlib import ExitStack with ExitStack() as stack: files = [ ("file", ("attachment.pdf", stack.enter_context(open("attachment.pdf", 'rb')), "application/octet-stream")), ] response = requests.request("POST", "https://api.exhibitday.com/v1/events/giveaways/attachments", headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data={"giveaway_id": "12345"}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') print(response.json()) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.exhibitday.com/v1/events/giveaways/attachments"); var form = new MultipartFormDataContent(); form.Add(new StringContent("12345"), "giveaway_id"); var file0 = new StreamContent(File.OpenRead("attachment.pdf")); file0.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(file0, "file", "attachment.pdf"); request.Content = form; using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/giveaways/attachments")).header("Authorization", "Bearer YOUR_API_KEY"); String boundary = "ExhibitDay-" + UUID.randomUUID(); ByteArrayOutputStream form = new ByteArrayOutputStream(); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"giveaway_id\"\r\n\r\n" + "12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"attachment.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8)); form.write(Files.readAllBytes(Path.of("attachment.pdf"))); form.write("\r\n".getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); request.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpResponse response = HttpClient.newHttpClient().send(request.method("POST", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); System.out.println(new String(response.body(), StandardCharsets.UTF_8)); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], CURLOPT_POSTFIELDS => [ 'giveaway_id' => '12345', 'file' => new CURLFile('attachment.pdf', 'application/octet-stream', 'attachment.pdf'), ], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); echo $response; ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/giveaways/attachments') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' files = [] begin parts = [ ['giveaway_id', '12345'], ['file', (files << File.open('attachment.pdf', 'rb')).last, {filename: 'attachment.pdf', content_type: 'application/octet-stream'}], ] request.set_form(parts, 'multipart/form-data') response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' puts response.body ensure files.each(&:close) end ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" "bytes" "mime/multipart" "net/textproto" ) func main() { var form bytes.Buffer writer := multipart.NewWriter(&form) if err := writer.WriteField("giveaway_id", "12345"); err != nil { log.Fatal(err) } header0 := textproto.MIMEHeader{} header0.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"attachment.pdf\"") header0.Set("Content-Type", "application/octet-stream") part0, err := writer.CreatePart(header0) if err != nil { log.Fatal(err) } file0, err := os.Open("attachment.pdf") if err != nil { log.Fatal(err) } if _, err = io.Copy(part0, file0); err != nil { log.Fatal(err) } file0.Close() if err := writer.Close(); err != nil { log.Fatal(err) } request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/events/giveaways/attachments", &form) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", writer.FormDataContentType()) response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } fmt.Printf("%s\n", data) } ``` Example HTTP response body (JSON): POST /v1/events/giveaways/attachments - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "attachment", "list_data": [ { "id": 12345, "filename": "attachment.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } ] } ``` ### Remove a Giveaway General File Attachment `DELETE https://api.exhibitday.com/v1/events/giveaways/attachments` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=giveaways#delete-v1-events-giveaways-attachments Removes one General File Attachment from this Giveaway. Other attached files and the record's details stay in place. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the File Attachment. | Use the id from the attachment list. The API finds the record the file belongs to, so no record ID is sent. An Invoice Attachment is not selected by this method. | #### After the removal Only the selected file association is removed. Its physical file is scheduled for cleanup after a confirmed save; cleanup may finish later. Other attached files stay in place. Send only the file's id; the API finds the record it belongs to. A missing, already removed or unavailable attachment returns HTTP 404 Not Found. Do not send file parts with DELETE. #### Access Current record and file-removal permissions and applicable Event/tab locks must allow this change. Permitted removals remain available on the Free plan. #### History and retries A confirmed file change is recorded in history. expected_revision is not supported by these file methods. DELETE does not use Idempotency-Key replay. If the save outcome cannot be confirmed, retrieve the current file list before deciding whether to retry; the API does not automatically repeat an uncertain change. Supporting File Attachments have no PATCH replacement. To replace one, add the new file and remove the old one using their separate requests; each request has its own outcome. #### Hidden or locked tab If the Event's Giveaways tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/events/giveaways/attachments?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/giveaways/attachments?" + new URLSearchParams({ "id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/events/giveaways/attachments", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/events/giveaways/attachments?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/giveaways/attachments?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/giveaways/attachments?id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/events/giveaways/attachments?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/events/giveaways/attachments - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Attachment removed.", "errors": [] } ``` ### Download a Giveaway General File Attachment `GET https://api.exhibitday.com/v1/events/giveaways/attachments/download` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=giveaways#get-v1-events-giveaways-attachments-download Downloads one original General File Attachment from this Giveaway. Select the file using its ID from the attachment list. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the File Attachment. | Use the id from the attachment list. The API finds the record the file belongs to, so no record ID is sent. An Invoice Attachment is not selected by this method. | #### Download response A successful response contains the original uploaded file with a safe download filename. API errors use the usual JSON response. A missing or unavailable file returns HTTP 404. Send only the file's id from the attachment list to download that one file; the API finds the record it belongs to. The download leaves the record unchanged. #### Access The record's Event and tab must be available, and the tab must not be hidden. A locked tab can still be read. #### Files still being copied If this file is still being copied, the download returns HTTP 409 with file_copy_pending. Try the download again in a few minutes. #### Hidden tab If the Event's Giveaways tab is hidden, this request returns HTTP 400 (not_allowed), and the message says the tab is hidden. Show the tab in ExhibitDay first. A locked tab can still be read. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X GET "https://api.exhibitday.com/v1/events/giveaways/attachments/download?id=12345" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi mv response-body.tmp 'attachment.pdf' ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const response = await fetch("https://api.exhibitday.com/v1/events/giveaways/attachments/download?id=12345", { method: "GET", headers: { Authorization: 'Bearer YOUR_API_KEY' } }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); await writeFile("attachment.pdf", new Uint8Array(await response.arrayBuffer())); ``` Example — Python: ```python import requests import json response = requests.request("GET", "https://api.exhibitday.com/v1/events/giveaways/attachments/download?id=12345", headers={'Authorization': 'Bearer YOUR_API_KEY'}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') with open("attachment.pdf", 'wb') as destination: destination.write(response.content) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.exhibitday.com/v1/events/giveaways/attachments/download?id=12345"); using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); await File.WriteAllBytesAsync("attachment.pdf", await response.Content.ReadAsByteArrayAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/giveaways/attachments/download?id=12345")).header("Authorization", "Bearer YOUR_API_KEY"); HttpResponse response = HttpClient.newHttpClient().send(request.method("GET", HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); Files.write(Path.of("attachment.pdf"), response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); file_put_contents('attachment.pdf', $response); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/giveaways/attachments/download?id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' File.binwrite('attachment.pdf', response.body) ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/giveaways/attachments/download?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } if err := os.WriteFile("attachment.pdf", data, 0600); err != nil { log.Fatal(err) } fmt.Println("File saved") } ``` HTTP 200: Returns the original uploaded file as a private download, using a safe filename. If the file cannot be downloaded, the response contains the usual JSON API error instead. Media: application/octet-stream. The body is the authorized file's real bytes, not JSON or base64. Errors are JSON status responses; check HTTP status before saving the file. ## Events - Shipments Shipments on an Event: components, carrier and delivery details, costs, invoices, file attachments and exports. Documentation page: https://api.exhibitday.com/Help/V1?epf=1&topic=shipments ### Retrieve a Single Shipment by ID `GET https://api.exhibitday.com/v1/events/shipments/info` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=shipments#get-v1-events-shipments-info Retrieves a Shipment by its ID, including its carrier, pickup and delivery details, components, costs and payment information. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Shipment. | Use the id from Retrieve Shipments (GET /v1/events/shipments) or from the add response. You don't send the Event ID; the record's Event is found automatically. | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` \| `object` | | $include_record_revision | Boolean | No | Whether to include record_revision in the response. | Default: false. Send true to get record_revision, then send that value as expected_revision when you update this Shipment. See What $include_record_revision covers below. | | $on_error_return_empty_result | Boolean | No | Whether an invalid or unavailable Shipment should return an empty result. | Default: false. True returns HTTP 200 with {} (or [] for array format) for invalid IDs or an unavailable Shipment. API key errors, ambiguous headers, conflicts with a change in progress, inconsistent invoice information and unexpected errors keep their normal status. | | If-None-Match | String | No | An ETag from an earlier response to this GET. | Optional HTTP header. If the successful response is unchanged, the API returns HTTP 304 with no body. | #### What $include_record_revision covers Setting $include_record_revision=true returns record_revision for use as expected_revision on a later update. record_revision covers saved Shipment details, payment fields, component identities and values, cost allocations, related-item links and Event binding. File Attachment and Invoice Attachment metadata/contents are not included. #### Components, files and access Each Shipment includes its components and the workspace measurement units: dimensions_unit is in or cm, and weight_unit is lb or kg. Invoice Attachment metadata is included as invoice_attachment, or null if no invoice is attached. Supporting File Attachments use their own collection and download operation. The Event's Shipments tab must be visible. A locked tab can still be read. Inconsistent invoice information returns HTTP 409 instead of exposing another record's file. #### Formatted text in the response Notes and other rich-text values in the response contain the stored HTML, including encoded characters and line breaks such as `
`. #### Open in ExhibitDay Each record includes exhibitday_url, the record's page in ExhibitDay. It opens the record in view mode on its Event's tab. Sign in with an account that can view the record; ExhibitDay checks access when the link is opened. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/events/shipments/info?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/shipments/info?" + new URLSearchParams({ "id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/events/shipments/info", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/events/shipments/info?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/shipments/info?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/shipments/info?id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/shipments/info?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/events/shipments/info - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "id": 12345, "event_id": 23456, "event_name": "Sample Event", "carrier": null, "tracking_url": null, "shipment_status": "Not Specified", "payment_status": { "id": 0, "name": "N/A" }, "dimensions_unit": "in", "weight_unit": "lb", "components": [ { "id": 17346, "component_type_id": null, "component_type": "Not Specified", "description": "Display stand case", "tracking_number": "EXAMPLE-1001", "dimensions_length": 48.0, "dimensions_width": 24.0, "dimensions_height": 18.0, "weight": 65.0 }, { "id": 17347, "component_type_id": null, "component_type": "Not Specified", "description": "Brochure carton", "tracking_number": "EXAMPLE-1002", "dimensions_length": 20.0, "dimensions_width": 16.0, "dimensions_height": 12.0, "weight": 18.50 } ], "cost": { "amount": 125.50, "cost_center_breakdown": [ { "cost_center_id": 34567, "cost_center": "Marketing", "charge": 75.50 }, { "cost_center_id": 34568, "cost_center": "Operations", "charge": 50.00 } ] }, "name": "Exhibit freight", "tracking_number": null, "carrier_id": null, "other_carrier_name": null, "pickup_date": null, "delivery_date": null, "pickup_location": null, "delivery_location": null, "notes": "", "payment_status_id": 0, "payment_due_date": null, "next_payment_due_date": null, "payment_notes": null, "invoice_attachment": { "id": 482345, "filename": "shipment-invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" }, "shipment_status_id": null, "service_level": null, "shipment_reference_number": null, "pickup_contact_name": null, "pickup_contact_email": null, "pickup_contact_phone": null, "pickup_instructions": null, "delivery_contact_name": null, "delivery_contact_email": null, "delivery_contact_phone": null, "delivery_instructions": null, "packing_handling_requirements": null, "received_by": null, "delivery_exception_notes": null, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=23456&riType=4&riSub=0&riId=12345", "related_items": [ { "id": 5551, "related_item_id": 67890, "related_item_exhibitday_url": "https://www.exhibitday.com/Workspace/TaskView/98765?tid=67890", "related_item_type_id": 1, "related_item_type": "Task", "related_item_asset_type_id": null, "related_item_name": "Confirm booth graphics with the printer", "related_item_created_timestamp": "2030-01-10T14:03:00Z" }, { "id": 5552, "related_item_id": 45678, "related_item_exhibitday_url": "https://www.exhibitday.com/Workspace/RelatedItemView/98765?typeId=4&subTypeId=0&rid=45678", "related_item_type_id": 4, "related_item_type": "Shipment", "related_item_asset_type_id": null, "related_item_name": "Booth crates to convention center", "related_item_created_timestamp": "2030-01-10T14:03:00Z" } ] } ``` ### Retrieve Shipments `GET https://api.exhibitday.com/v1/events/shipments` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=shipments#get-v1-events-shipments Retrieves records across your workspace's readable Event tabs. Use filter_by_event_id to narrow the results to one Event, or omit it for the workspace list. Each record includes its event_id and Event name. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | filter_by_event_id | Number | No | Return records for this Event only. Omit for all readable Events in your workspace. | | | $limit | Number | No | The most Shipments to return, as a whole number of 1 or more. Omit it to return all remaining matching Shipments. | | | $offset | Number | No | How many Shipments to skip, as a whole number of 0 or more; 0 by default. | | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | | hydrate_related_items | Boolean | No | Set to true to include each record's related_items: the Tasks and items linked to it, with the key to use when adding or removing a link. Omit it or send false to leave related_items out of list results. Single-record GETs always include related_items. | Default: false. | #### Choosing Events Omit `filter_by_event_id` to retrieve records across readable Event tabs, or supply one Event ID to narrow the list. Each result retains its own `event_id` and Event name. Hidden or unavailable Event tabs are not included. A locked tab can still be read. If no records match, the response is an empty list. #### Reading pages The Event filter and any people filter are applied before the total count and paging. Results are ordered by Event start date ascending, Event ID ascending, then record ID ascending. Use `$limit` and `$offset` for successive pages. Omit `$limit` to return all remaining matches. `total_records` and `X-Total-Count` describe all matches; `records_found` counts this response. Omit `$result_format` for the normal list wrapper. `array` returns only the records; `wrapped_in_array` places the normal wrapper in a one-item array. #### Handling input and changes Unrecognized parameters are ignored and listed in the `X-API-Warnings` response header. Conflicting or malformed filter values return HTTP `400`; send arrays in JSON, query parameters or form fields rather than comma-bearing headers. Current API access is checked even when the list is empty. A concurrent change can return HTTP `409`; retrieve the list again. These filters retrieve records and do not change tags, assignments or notification settings. #### Related items Set `hydrate_related_items=true` to include each record's `related_items`: the Tasks and items linked to it. Add or remove links with POST and DELETE /v1/related_items. It is left out by default to keep lists fast. Retrieving one record always includes `related_items`. #### Formatted text in the response Notes and other rich-text values in the response contain the stored HTML, including encoded characters and line breaks such as `
`. #### Events with a hidden Shipments tab Records on Events whose Shipments tab is hidden are not listed. If filter_by_event_id names such an Event, the response is HTTP 200 with no records for it and a warning that names the tab and the Event. #### Open in ExhibitDay Each record includes exhibitday_url, the record's page in ExhibitDay. It opens the record in view mode on its Event's tab. Sign in with an account that can view the record; ExhibitDay checks access when the link is opened. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/events/shipments" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/shipments", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/events/shipments", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/events/shipments"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/shipments")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/shipments') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/shipments", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/events/shipments - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "shipment", "list_data": [ { "id": 12345, "event_id": 23456, "event_name": "Sample Event", "carrier": null, "tracking_url": null, "shipment_status": "Not Specified", "payment_status": { "id": 0, "name": "N/A" }, "dimensions_unit": "in", "weight_unit": "lb", "components": [], "cost": { "amount": 0.00, "cost_center_breakdown": [] }, "name": "Exhibit freight", "tracking_number": null, "carrier_id": null, "other_carrier_name": null, "pickup_date": null, "delivery_date": null, "pickup_location": null, "delivery_location": null, "notes": "", "payment_status_id": 0, "payment_due_date": null, "next_payment_due_date": null, "payment_notes": null, "invoice_attachment": { "id": 482345, "filename": "shipment-invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" }, "shipment_status_id": null, "service_level": null, "shipment_reference_number": null, "pickup_contact_name": null, "pickup_contact_email": null, "pickup_contact_phone": null, "pickup_instructions": null, "delivery_contact_name": null, "delivery_contact_email": null, "delivery_contact_phone": null, "delivery_instructions": null, "packing_handling_requirements": null, "received_by": null, "delivery_exception_notes": null, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=23456&riType=4&riSub=0&riId=12345" } ] } ``` ### Add a Shipment `POST https://api.exhibitday.com/v1/events/shipments` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=shipments#post-v1-events-shipments Adds a Shipment to an Event. Record what is being sent, its carrier and delivery plans, and any packages or other components. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | event_id | Number | Yes | The ID of the Event. | The Shipment will be added to this Event. | | name | String | Yes | A name describing what is being sent. | Up to 200 characters. Required; enter a nonblank name. | | tracking_number | String | No | The carrier's tracking number for the Shipment. | Up to 125 characters. Omit for no value. | | carrier_id | Number | No | The carrier handling the Shipment. | Use a current ID from GET /v1/references/shipment_carriers. Null means Not Specified. other_carrier_name applies only to Other (1); choosing another carrier clears that custom name. | | other_carrier_name | String | No | The carrier's name when carrier_id is Other (1). | Literal text, trimmed to the first 200 characters without splitting a Unicode surrogate pair. For any other carrier, the custom name is cleared. Omit for no value. | | pickup_date | String | No | The planned or recorded pickup date. | Use a calendar date in YYYY-MM-DD format, without a time or time zone. Omit for no value. This does not automatically change Shipment status. | | delivery_date | String | No | The planned or recorded delivery date. | Use a calendar date in YYYY-MM-DD format, without a time or time zone. Omit for no value. This does not automatically change Shipment status. | | pickup_location | String | No | Where the Shipment will be picked up. | Up to 400 characters. Omit for no value. | | delivery_location | String | No | Where the Shipment should be delivered. | Up to 400 characters. Omit for no value. | | notes | String | No | General notes about this Shipment. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Both the saved text and the ExhibitDay editor's character count must fit within 30,000 characters; line breaks and characters such as & and < take extra space when saved. Omit for no value. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | payment_status_id | Number | No | The Shipment's payment status. Omit for N/A. A status other than Partially Paid clears the next partial payment due date. | Allowed values: `0` (N/A) \| `1` (Paid in Full) \| `2` (Partially Paid) \| `3` (Not Paid Yet) | | payment_due_date | String | No | The Shipment payment due date. | Use a calendar date in YYYY-MM-DD format, without a time or time zone. Omit for no value. | | next_payment_due_date | Date | No | The next partial payment due date. | Use a calendar date in YYYY-MM-DD format, without a time or time zone. Applies only to Partially Paid (2). Supplying it with another payment status clears the date; choosing another status also clears it. Omit for no value. | | payment_notes | String | No | Notes about the Shipment payment. | Up to 200 characters. Omit for no value. | | shipment_status_id | Number | No | The Shipment's current status. Omit or send null for Not Specified. Pickup/delivery dates, costs and tracking do not automatically change this status. | Allowed values: `1` (Not Shipped Yet) \| `2` (Shipped) \| `3` (Delivered) \| `4` (Canceled) | | service_level | String | No | The carrier service or delivery speed, such as overnight. | Up to 200 characters. Omit for no value. | | shipment_reference_number | String | No | Your reference number for the Shipment. | Up to 200 characters. Omit for no value. | | pickup_contact_name | String | No | The name of the person arranging pickup. | Up to 200 characters. Omit for no value. | | pickup_contact_email | String | No | The pickup contact's email address. | Up to 200 characters. Omit for no value. | | pickup_contact_phone | String | No | The pickup contact's phone number. | Up to 200 characters. Omit for no value. | | pickup_instructions | String | No | Instructions for collecting the Shipment. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Both the saved text and the ExhibitDay editor's character count must fit within 30,000 characters; line breaks and characters such as & and < take extra space when saved. Omit for no value. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | delivery_contact_name | String | No | The name of the person receiving delivery. | Up to 200 characters. Omit for no value. | | delivery_contact_email | String | No | The delivery contact's email address. | Up to 200 characters. Omit for no value. | | delivery_contact_phone | String | No | The delivery contact's phone number. | Up to 200 characters. Omit for no value. | | delivery_instructions | String | No | Instructions for delivering the Shipment. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Both the saved text and the ExhibitDay editor's character count must fit within 30,000 characters; line breaks and characters such as & and < take extra space when saved. Omit for no value. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | packing_handling_requirements | String | No | Packing, handling, temperature, equipment or documentation requirements. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Both the saved text and the ExhibitDay editor's character count must fit within 30,000 characters; line breaks and characters such as & and < take extra space when saved. Omit for no value. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | received_by | String | No | The name of the person who received the Shipment. | Up to 200 characters. Omit for no value. | | delivery_exception_notes | String | No | Problems or exceptions to record about the delivery. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Both the saved text and the ExhibitDay editor's character count must fit within 30,000 characters; line breaks and characters such as & and < take extra space when saved. Omit for no value. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | components | JSON object/list | No | The complete list of packages or other items in this Shipment. | A JSON array of up to 500 objects. Each object may contain id, component_type_id (an ID from GET /v1/references/shipment_component_types), description (literal text, up to 100 characters), tracking_number (literal text, up to 125 characters), and dimensions_length, dimensions_width, dimensions_height and weight. Measurements must be nonnegative, at most 99999999999999999.99, with no more than two decimal places. Use the dimensions_unit and weight_unit returned by GET /v1/events/shipments/info. At least one component detail must be present. To keep or change an existing component, send its id; an id that is not one of this Shipment's components is refused with 400 (invalid_request, error_params components). Leave id out to add a new component. component_type_id is a Shipment Item Type ID, shown with its name as component_type in Shipment reads; null means Not Specified. Omit for no components. Existing component IDs are not accepted on add. | | cost | Number or cost object | No | The full cost, as a number or an object with amount and/or cost_center_breakdown. [Record Costs and Split Them Across Cost Centers](/Help/V1?guide=entering-costs). | Optional; defaults to zero. | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` \| `object` | | Idempotency-Key | String | No | A unique key for safely retrying this add request. | Optional HTTP header: 1 to 255 visible ASCII characters without spaces or commas. Retry the identical request with the same key to replay its first saved response. Use a new key for a different request. | | $ignore_params_with_empty_values | Boolean | No | Whether supplied JSON null values should be omitted. | Default: false. With true, actual JSON null fields and component lists are omitted. Ordinary null or blank add fields are already omitted; the required name must still be supplied. | Declared schema for `components` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "array", "items": { "type": "object", "additionalProperties": false, "properties": { "id": { "type": "integer", "format": "int64", "description": "The existing component id, only on PATCH. It must belong to this Shipment. Omit it for a new component, or to match an unchanged component by all its values.", "nullable": true }, "component_type_id": { "type": "integer", "format": "int32", "description": "An optional Shipment component type id (Shipment Item Type) from GET /v1/references/shipment_component_types. Null means Not Specified.", "nullable": true }, "description": { "type": "string", "description": "Optional literal text up to 100 characters. At least one component detail must be supplied.", "maxLength": 100, "minLength": 0, "nullable": true }, "tracking_number": { "type": "string", "description": "Optional literal tracking number up to 125 characters.", "maxLength": 125, "minLength": 0, "nullable": true }, "dimensions_length": { "type": "number", "description": "Optional nonnegative length with at most two decimal places, in the workspace measurement units returned with the Shipment.", "minimum": 0.0, "maximum": 99999999999999999.99, "nullable": true }, "dimensions_width": { "type": "number", "description": "Optional nonnegative width with at most two decimal places, in the workspace measurement units returned with the Shipment.", "minimum": 0.0, "maximum": 99999999999999999.99, "nullable": true }, "dimensions_height": { "type": "number", "description": "Optional nonnegative height with at most two decimal places, in the workspace measurement units returned with the Shipment.", "minimum": 0.0, "maximum": 99999999999999999.99, "nullable": true }, "weight": { "type": "number", "description": "Optional nonnegative weight with at most two decimal places, in the workspace measurement units returned with the Shipment.", "minimum": 0.0, "maximum": 99999999999999999.99, "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected" }, "maxItems": 500, "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": [ { "component_type_id": null, "description": "Exhibit crate", "weight": 125.5 } ] } ``` Declared schema for `cost` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "anyOf": [ { "type": "number", "minimum": 0, "description": "Shorthand for an object with amount. The amount is rounded to cents before the supported storage range is checked.", "nullable": true }, { "type": "object", "additionalProperties": false, "properties": { "amount": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 }, "cost_center_breakdown": { "type": "array", "items": { "type": "object", "additionalProperties": false, "properties": { "cost_center_id": { "type": "integer", "format": "int64", "nullable": true }, "charge": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 }, "cost_center": { "type": "string", "description": "Optional and read-only: the cost center name a read returns, so a cost can be sent back unchanged. It is ignored; the line is saved by cost_center_id, and a name that doesn't match that cost center is explained in a warning.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "required": [ "charge" ] }, "maxItems": 2147483647 } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "anyOf": [ { "required": [ "amount" ] }, { "required": [ "cost_center_breakdown" ] } ], "nullable": true } ], "x-numeric-shorthand": "A number is equivalent to {amount:number}.", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": { "amount": 125.50 } } ``` #### Carrier, status and dates Choose the carrier from the current reference list. Only Other (1) uses other_carrier_name. The optional custom name is literal text; only its first 200 characters are kept. Shipment status is a choice you make. Recording pickup/delivery dates, tracking numbers or costs does not change it or contact a carrier. Dates are calendar dates with no time or time zone conversion. Linking an asset reservation records the connection without reserving stock or changing inventory. #### Adding components Use components for the packages, crates or other items in this Shipment. Each object needs at least a type, description, tracking number or measurement. Omit id for new components; existing IDs are not accepted when adding a Shipment. Dimensions and weight use this workspace's units. Component descriptions and tracking numbers are literal text; commas can be supplied in JSON or form/query fields. #### After the add The response includes the new Shipment, its components and its id. The change is recorded in Event history. File Attachments and the Invoice Attachment are uploaded separately. Recording costs does not attach an invoice, mark a payment complete or change the Event's planned Shipments budget. If a save outcome cannot be confirmed, retrieve the current Shipment before deciding whether to retry. #### Access The Event's Shipments tab must be available, visible and unlocked, and your current access must allow the change. #### Sending values Use JSON, query parameters or form fields for text containing commas and components. #### Sending text Send plain text for Notes and other rich-text fields. Characters such as `&`, `<` and quotes, along with line breaks, are encoded for storage. Notes and other rich-text values in the response contain the stored HTML, including encoded characters and line breaks such as `
`. #### Hidden or locked tab If the Event's Shipments tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. An Event that is not in your workspace returns HTTP 404. #### Open in ExhibitDay The created record includes exhibitday_url, the record's page in ExhibitDay. It is the same link that GET /v1/events/shipments/info returns for this record and opens the record in view mode on its Event's tab. Sign in with an account that can view the record; ExhibitDay checks access when the link is opened. Example — curl: ```bash curl -X POST "https://api.exhibitday.com/v1/events/shipments" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"event_id\":12345,\"name\":\"Exhibit materials to Annual Expo\"}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/shipments", { method: "POST", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "event_id": 12345, "name": "Exhibit materials to Annual Expo" }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.post( "https://api.exhibitday.com/v1/events/shipments", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"event_id": 12345, "name": "Exhibit materials to Annual Expo"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PostAsync("https://api.exhibitday.com/v1/events/shipments", JsonContent.Create(new { event_id = 12345, name = "Exhibit materials to Annual Expo" })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/shipments")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("POST", HttpRequest.BodyPublishers.ofString("{\"event_id\":12345,\"name\":\"Exhibit materials to Annual Expo\"}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"event_id":12345,"name":"Exhibit materials to Annual Expo"}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/shipments') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"event_id":12345,"name":"Exhibit materials to Annual Expo"}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/events/shipments", strings.NewReader("{\"event_id\":12345,\"name\":\"Exhibit materials to Annual Expo\"}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): POST /v1/events/shipments - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "id": 12345, "event_id": 12345, "event_name": "Sample Event", "carrier": null, "tracking_url": null, "shipment_status": "Not Specified", "payment_status": { "id": 0, "name": "N/A" }, "dimensions_unit": "in", "weight_unit": "lb", "components": [], "cost": { "amount": 0.00, "cost_center_breakdown": [] }, "name": "Exhibit materials to Annual Expo", "tracking_number": null, "carrier_id": null, "other_carrier_name": null, "pickup_date": null, "delivery_date": null, "pickup_location": null, "delivery_location": null, "notes": "", "payment_status_id": 0, "payment_due_date": null, "next_payment_due_date": null, "payment_notes": null, "invoice_attachment": null, "shipment_status_id": null, "service_level": null, "shipment_reference_number": null, "pickup_contact_name": null, "pickup_contact_email": null, "pickup_contact_phone": null, "pickup_instructions": null, "delivery_contact_name": null, "delivery_contact_email": null, "delivery_contact_phone": null, "delivery_instructions": null, "packing_handling_requirements": null, "received_by": null, "delivery_exception_notes": null, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=12345&riType=4&riSub=0&riId=12345" } ``` ### Update a Shipment `PATCH https://api.exhibitday.com/v1/events/shipments` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=shipments#patch-v1-events-shipments Updates a Shipment's carrier, pickup and delivery plans, components or payment information. Send only the fields you want to change. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Shipment. | Use its id from the list, single-record read or add response. This identifies the Shipment, rather than a component or file. | | name | String | No | A name describing what is being sent. | Up to 200 characters. Omit or leave blank to keep it; null cannot clear it. Renaming also updates an existing valid Invoice Attachment's label. | | tracking_number | String | No | The carrier's tracking number for the Shipment. | Up to 125 characters. Omit or leave blank to keep it; null clears it. | | carrier_id | Number | No | The carrier handling the Shipment. | Use a current ID from GET /v1/references/shipment_carriers. Null means Not Specified. other_carrier_name applies only to Other (1); choosing another carrier clears that custom name. Omit or leave blank to keep it. | | other_carrier_name | String | No | The carrier's name when carrier_id is Other (1). | Literal text, trimmed to the first 200 characters without splitting a Unicode surrogate pair. For any other carrier, the custom name is cleared. Omit or leave blank to keep it; null clears it. | | pickup_date | String | No | The planned or recorded pickup date. | Use a calendar date in YYYY-MM-DD format, without a time or time zone. Omit or leave blank to keep it; null clears it. This does not automatically change Shipment status. | | delivery_date | String | No | The planned or recorded delivery date. | Use a calendar date in YYYY-MM-DD format, without a time or time zone. Omit or leave blank to keep it; null clears it. This does not automatically change Shipment status. | | pickup_location | String | No | Where the Shipment will be picked up. | Up to 400 characters. Omit or leave blank to keep it; null clears it. | | delivery_location | String | No | Where the Shipment should be delivered. | Up to 400 characters. Omit or leave blank to keep it; null clears it. | | notes | String | No | General notes about this Shipment. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Both the saved text and the ExhibitDay editor's character count must fit within 30,000 characters; line breaks and characters such as & and < take extra space when saved. Omit or leave blank to keep it; null clears it. Existing over-limit content can stay unchanged or be shortened, but neither count may grow. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | payment_status_id | Number | No | The Shipment's payment status. Omit or leave blank to keep it; null resets it to N/A. A status other than Partially Paid clears the next partial payment due date. | Allowed values: `0` (N/A) \| `1` (Paid in Full) \| `2` (Partially Paid) \| `3` (Not Paid Yet) | | payment_due_date | String | No | The Shipment payment due date. | Use a calendar date in YYYY-MM-DD format, without a time or time zone. Omit or leave blank to keep it; null clears it. | | next_payment_due_date | Date | No | The next partial payment due date. | Use a calendar date in YYYY-MM-DD format, without a time or time zone. Applies only to Partially Paid (2). Supplying it with another payment status clears the date; choosing another status also clears it. Omit or leave blank to keep it; null clears it. | | payment_notes | String | No | Notes about the Shipment payment. | Up to 200 characters. Omit or leave blank to keep it; null clears it. | | shipment_status_id | Number | No | The Shipment's current status. Omit or leave blank to keep it; null means Not Specified. Pickup/delivery dates, costs and tracking do not automatically change this status. | Allowed values: `1` (Not Shipped Yet) \| `2` (Shipped) \| `3` (Delivered) \| `4` (Canceled) | | service_level | String | No | The carrier service or delivery speed, such as overnight. | Up to 200 characters. Omit or leave blank to keep it; null clears it. | | shipment_reference_number | String | No | Your reference number for the Shipment. | Up to 200 characters. Omit or leave blank to keep it; null clears it. | | pickup_contact_name | String | No | The name of the person arranging pickup. | Up to 200 characters. Omit or leave blank to keep it; null clears it. | | pickup_contact_email | String | No | The pickup contact's email address. | Up to 200 characters. Omit or leave blank to keep it; null clears it. | | pickup_contact_phone | String | No | The pickup contact's phone number. | Up to 200 characters. Omit or leave blank to keep it; null clears it. | | pickup_instructions | String | No | Instructions for collecting the Shipment. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Both the saved text and the ExhibitDay editor's character count must fit within 30,000 characters; line breaks and characters such as & and < take extra space when saved. Omit or leave blank to keep it; null clears it. Existing over-limit content can stay unchanged or be shortened, but neither count may grow. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | delivery_contact_name | String | No | The name of the person receiving delivery. | Up to 200 characters. Omit or leave blank to keep it; null clears it. | | delivery_contact_email | String | No | The delivery contact's email address. | Up to 200 characters. Omit or leave blank to keep it; null clears it. | | delivery_contact_phone | String | No | The delivery contact's phone number. | Up to 200 characters. Omit or leave blank to keep it; null clears it. | | delivery_instructions | String | No | Instructions for delivering the Shipment. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Both the saved text and the ExhibitDay editor's character count must fit within 30,000 characters; line breaks and characters such as & and < take extra space when saved. Omit or leave blank to keep it; null clears it. Existing over-limit content can stay unchanged or be shortened, but neither count may grow. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | packing_handling_requirements | String | No | Packing, handling, temperature, equipment or documentation requirements. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Both the saved text and the ExhibitDay editor's character count must fit within 30,000 characters; line breaks and characters such as & and < take extra space when saved. Omit or leave blank to keep it; null clears it. Existing over-limit content can stay unchanged or be shortened, but neither count may grow. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | received_by | String | No | The name of the person who received the Shipment. | Up to 200 characters. Omit or leave blank to keep it; null clears it. | | delivery_exception_notes | String | No | Problems or exceptions to record about the delivery. | Send plain text; line breaks are kept. If you send HTML, only its text is saved. Both the saved text and the ExhibitDay editor's character count must fit within 30,000 characters; line breaks and characters such as & and < take extra space when saved. Omit or leave blank to keep it; null clears it. Existing over-limit content can stay unchanged or be shortened, but neither count may grow. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | components | JSON object/list | No | The complete list of packages or other items in this Shipment. | A JSON array of up to 500 objects. Each object may contain id, component_type_id (an ID from GET /v1/references/shipment_component_types), description (literal text, up to 100 characters), tracking_number (literal text, up to 125 characters), and dimensions_length, dimensions_width, dimensions_height and weight. Measurements must be nonnegative, at most 99999999999999999.99, with no more than two decimal places. Use the dimensions_unit and weight_unit returned by GET /v1/events/shipments/info. At least one component detail must be present. To keep or change an existing component, send its id; an id that is not one of this Shipment's components is refused with 400 (invalid_request, error_params components). Leave id out to add a new component. component_type_id is a Shipment Item Type ID, shown with its name as component_type in Shipment reads; null means Not Specified. Omit or leave blank to keep the list; null or [] clears it. With $ignore_params_with_empty_values=true, a JSON null is ignored instead. See Replacing components below. | | cost | Number or cost object | No | The full cost, as a number or an object with amount and/or cost_center_breakdown. [Record Costs and Split Them Across Cost Centers](/Help/V1?guide=entering-costs). | Omit to keep the saved cost. A supplied value replaces its full allocation. | | expected_revision | String | No | The record_revision from an earlier read of this Shipment. | Optional. Obtain it from GET /v1/events/shipments/info with $include_record_revision=true. A changed Shipment returns HTTP 409 without saving this update. Omission skips the check; blank, null and malformed values are refused, even with $ignore_params_with_empty_values=true. | | $ignore_params_with_empty_values | Boolean | No | Whether supplied JSON null values should be omitted. | Default: false. With true, actual JSON null fields and component lists are omitted. Nonempty top-level text null still requests clearing where supported. Nonclearable fields and expected_revision validation still apply. | Declared schema for `components` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "array", "items": { "type": "object", "additionalProperties": false, "properties": { "id": { "type": "integer", "format": "int64", "description": "The existing component id, only on PATCH. It must belong to this Shipment. Omit it for a new component, or to match an unchanged component by all its values.", "nullable": true }, "component_type_id": { "type": "integer", "format": "int32", "description": "An optional Shipment component type id (Shipment Item Type) from GET /v1/references/shipment_component_types. Null means Not Specified.", "nullable": true }, "description": { "type": "string", "description": "Optional literal text up to 100 characters. At least one component detail must be supplied.", "maxLength": 100, "minLength": 0, "nullable": true }, "tracking_number": { "type": "string", "description": "Optional literal tracking number up to 125 characters.", "maxLength": 125, "minLength": 0, "nullable": true }, "dimensions_length": { "type": "number", "description": "Optional nonnegative length with at most two decimal places, in the workspace measurement units returned with the Shipment.", "minimum": 0.0, "maximum": 99999999999999999.99, "nullable": true }, "dimensions_width": { "type": "number", "description": "Optional nonnegative width with at most two decimal places, in the workspace measurement units returned with the Shipment.", "minimum": 0.0, "maximum": 99999999999999999.99, "nullable": true }, "dimensions_height": { "type": "number", "description": "Optional nonnegative height with at most two decimal places, in the workspace measurement units returned with the Shipment.", "minimum": 0.0, "maximum": 99999999999999999.99, "nullable": true }, "weight": { "type": "number", "description": "Optional nonnegative weight with at most two decimal places, in the workspace measurement units returned with the Shipment.", "minimum": 0.0, "maximum": 99999999999999999.99, "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected" }, "maxItems": 500, "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": [ { "component_type_id": null, "description": "Exhibit crate", "weight": 125.5 } ] } ``` Declared schema for `cost` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "anyOf": [ { "type": "number", "minimum": 0, "description": "Shorthand for an object with amount. The amount is rounded to cents before the supported storage range is checked.", "nullable": true }, { "type": "object", "additionalProperties": false, "properties": { "amount": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 }, "cost_center_breakdown": { "type": "array", "items": { "type": "object", "additionalProperties": false, "properties": { "cost_center_id": { "type": "integer", "format": "int64", "nullable": true }, "charge": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 }, "cost_center": { "type": "string", "description": "Optional and read-only: the cost center name a read returns, so a cost can be sent back unchanged. It is ignored; the line is saved by cost_center_id, and a name that doesn't match that cost center is explained in a warning.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "required": [ "charge" ] }, "maxItems": 2147483647 } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "anyOf": [ { "required": [ "amount" ] }, { "required": [ "cost_center_breakdown" ] } ], "nullable": true } ], "x-numeric-shorthand": "A number is equivalent to {amount:number}.", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": { "amount": 125.50 } } ``` #### Carrier, status and dates Choose the carrier from the current reference list. Only Other (1) uses other_carrier_name. The optional custom name is literal text; only its first 200 characters are kept. Shipment status is a choice you make. Recording pickup/delivery dates, tracking numbers or costs does not change it or contact a carrier. Dates are calendar dates with no time or time zone conversion. Linking an asset reservation records the connection without reserving stock or changing inventory. #### Replacing components A supplied components array is the entire desired list. Include every component you want to keep; any current component omitted from that array is removed. Omit the whole parameter to leave the list alone. Null or [] clears it, except actual JSON null is omitted under true ignore-empty. Use an existing component's id to update that component in this Shipment. Omit id to add a component or match an unchanged component by all its values. Identical unchanged components keep their IDs and creation times even if the list order changes. Each supplied object is complete: omitted optional members become empty. #### Choosing what to change Omitted or blank top-level fields keep their values. Null clears or resets supported fields; name cannot be cleared. Clearing payment_status_id resets it to N/A. With ignore-empty true, actual JSON null is omitted instead. An unchanged request saves no business data or history and keeps its revision, component IDs, creation times and invoice label. File Attachments and the Invoice Attachment are managed separately. #### Using expected_revision 1. Retrieve this Shipment with GET /v1/events/shipments/info and $include_record_revision=true. 2. Send the returned record_revision unchanged as expected_revision with this update. 3. If the API reports a change, read the current Shipment and decide what to update. #### After the update A real change is recorded in Event history. Renaming also updates an existing valid Invoice Attachment's label without replacing its contents. Recording costs does not attach an invoice, mark a payment complete or change the Event's planned Shipments budget. If a save outcome cannot be confirmed, retrieve the current Shipment before deciding whether to retry. #### Access The Event's Shipments tab must be available, visible and unlocked, and your current access must allow the change. #### Sending values Use JSON, query parameters or form fields for text containing commas and components. #### Sending text Send plain text for Notes and other rich-text fields. Characters such as `&`, `<` and quotes, along with line breaks, are encoded for storage. #### Hidden or locked tab If the Event's Shipments tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. An Event that is not in your workspace returns HTTP 404. Example — curl: ```bash curl -X PATCH "https://api.exhibitday.com/v1/events/shipments" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"id\":12345,\"name\":\"Exhibit materials to Annual Expo\"}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/shipments", { method: "PATCH", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "id": 12345, "name": "Exhibit materials to Annual Expo" }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.patch( "https://api.exhibitday.com/v1/events/shipments", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"id": 12345, "name": "Exhibit materials to Annual Expo"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PatchAsync("https://api.exhibitday.com/v1/events/shipments", JsonContent.Create(new { id = 12345, name = "Exhibit materials to Annual Expo" })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/shipments")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("PATCH", HttpRequest.BodyPublishers.ofString("{\"id\":12345,\"name\":\"Exhibit materials to Annual Expo\"}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"id":12345,"name":"Exhibit materials to Annual Expo"}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/shipments') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"id":12345,"name":"Exhibit materials to Annual Expo"}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/events/shipments", strings.NewReader("{\"id\":12345,\"name\":\"Exhibit materials to Annual Expo\"}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): PATCH /v1/events/shipments - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Shipment updated.", "errors": [] } ``` ### Delete a Shipment `DELETE https://api.exhibitday.com/v1/events/shipments` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=shipments#delete-v1-events-shipments Deletes a Shipment and its components, saved costs, related-item links, File Attachments and Invoice Attachment. Linked Tasks, asset reservations and other records remain in place. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Shipment. | Use its id from the list, single-record read or add response. This identifies the Shipment, rather than a component or file. | #### After the deletion The Shipment, its components, costs, related-item links and attachment records are removed together. Only its files are scheduled for physical cleanup after the save. Linked Tasks, asset reservations and other records remain. The deletion is recorded in Event history. An unavailable Shipment returns HTTP 404. If the save outcome cannot be confirmed, retrieve the current Shipments before deciding whether to retry. #### Access The Event's Shipments tab must be available, visible and unlocked, and your current access must allow the change. #### Hidden or locked tab If the Event's Shipments tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. An Event that is not in your workspace returns HTTP 404. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/events/shipments?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/shipments?" + new URLSearchParams({ "id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/events/shipments", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/events/shipments?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/shipments?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/shipments?id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/events/shipments?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/events/shipments - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Shipment removed.", "errors": [] } ``` ### Download Shipment Invoice Attachment `GET https://api.exhibitday.com/v1/events/shipments/invoice_attachment/download` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=shipments#get-v1-events-shipments-invoice_attachment-download Downloads the original Invoice Attachment for this Shipment. Use this method to retrieve the file itself. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | shipment_id | Number | Yes | The ID of the Shipment, from Retrieve Shipments (GET /v1/events/shipments) or its add response. | | #### Finding the file In the web app, this is the invoice control beside the Shipment's cost and payment details. Each cost has one Invoice Attachment even when its amount is split among cost centers. For file metadata, retrieve the parent record with GET /v1/events/shipments/info and read invoice_attachment. Use this download method for the contents. No attachment ID or invoice flag is needed. #### Download response A successful response contains the original uploaded file, with a safe download filename. API errors use the usual JSON response. If no invoice is attached, this method returns HTTP 404. Current record, financial and invoice permissions apply. A locked tab can still be read. Permitted downloads remain available on the Free plan. #### Files still being copied If this file is still being copied, the download returns HTTP 409 with file_copy_pending. Try the download again in a few minutes. #### Hidden tab If the Event's Shipments tab is hidden, this request returns HTTP 400 (not_allowed), and the message says the tab is hidden. Show the tab in ExhibitDay first. A locked tab can still be read. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X GET "https://api.exhibitday.com/v1/events/shipments/invoice_attachment/download?shipment_id=12345" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi mv response-body.tmp 'invoice.pdf' ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const response = await fetch("https://api.exhibitday.com/v1/events/shipments/invoice_attachment/download?shipment_id=12345", { method: "GET", headers: { Authorization: 'Bearer YOUR_API_KEY' } }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); await writeFile("invoice.pdf", new Uint8Array(await response.arrayBuffer())); ``` Example — Python: ```python import requests import json response = requests.request("GET", "https://api.exhibitday.com/v1/events/shipments/invoice_attachment/download?shipment_id=12345", headers={'Authorization': 'Bearer YOUR_API_KEY'}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') with open("invoice.pdf", 'wb') as destination: destination.write(response.content) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.exhibitday.com/v1/events/shipments/invoice_attachment/download?shipment_id=12345"); using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); await File.WriteAllBytesAsync("invoice.pdf", await response.Content.ReadAsByteArrayAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/shipments/invoice_attachment/download?shipment_id=12345")).header("Authorization", "Bearer YOUR_API_KEY"); HttpResponse response = HttpClient.newHttpClient().send(request.method("GET", HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); Files.write(Path.of("invoice.pdf"), response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); file_put_contents('invoice.pdf', $response); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/shipments/invoice_attachment/download?shipment_id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' File.binwrite('invoice.pdf', response.body) ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/shipments/invoice_attachment/download?shipment_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } if err := os.WriteFile("invoice.pdf", data, 0600); err != nil { log.Fatal(err) } fmt.Println("File saved") } ``` HTTP 200: Returns the original uploaded file as a private download, using a safe filename. If the file cannot be downloaded, the response contains the usual JSON API error instead. Media: application/octet-stream. The body is the authorized file's real bytes, not JSON or base64. Errors are JSON status responses; check HTTP status before saving the file. ### Add Shipment Invoice Attachment `POST https://api.exhibitday.com/v1/events/shipments/invoice_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=shipments#post-v1-events-shipments-invoice_attachment Adds one Invoice Attachment to this Shipment. You can attach an invoice, receipt or other payment document when no invoice file is currently attached. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | shipment_id | Number | Yes | The ID of the Shipment, from Retrieve Shipments (GET /v1/events/shipments) or its add response. | | | file | File (multipart) | Yes | The Invoice Attachment to upload. | Send exactly one complete, nonempty multipart/form-data file part named file. The supported extensions and current per-file limit are shown below; the complete request limit also includes multipart overhead. A missing or null file is invalid and does not remove an existing invoice. | | Idempotency-Key | String | No | A unique key for safely retrying this upload. | Optional HTTP header: 1 to 255 visible ASCII characters without spaces or commas. Retry the identical request with the same key to replay its first saved response. Use a new key for a different upload. | Declared schema for `file` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "string", "format": "binary", "x-maximum-bytes": 26214400, "x-allowed-extensions": [ "png", "jpg", "jpeg", "bmp", "gif", "pdf", "msg", "eml", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "rtf", "odp", "odt", "ods", "txt", "wks", "zip" ] } ``` #### Before you upload POST requires an empty invoice slot. If an invoice is already attached, the API returns HTTP 409; use PATCH to replace it. An Invoice Attachment is separate from the record's supporting File Attachments. Use the invoice control beside the Shipment's cost and payment details in the web app. #### After the upload The response's invoice_attachment contains the attached file's id, filename and attachment_created_timestamp. The amount, payment fields, cost-center breakdown and other files are unchanged. The upload is recorded in Event history. Attaching an invoice does not mark the record as paid. #### Access and retries A current upload-enabled plan, record and financial permissions, and an editable applicable tab are required. Each uploaded file must fit its supported type and size limits. expected_revision is not supported by this file method. If the save outcome cannot be confirmed, retrieve the current parent record with GET /v1/events/shipments/info and inspect invoice_attachment before deciding whether to retry. #### Hidden or locked tab If the Event's Shipments tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X POST "https://api.exhibitday.com/v1/events/shipments/invoice_attachment" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}" --form-string "shipment_id=12345" --form "file=@invoice.pdf;type=application/octet-stream") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi cat response-body.tmp ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const form = new FormData(); form.append("shipment_id", "12345"); form.append("file", new Blob([await readFile("invoice.pdf")], { type: "application/octet-stream" }), "invoice.pdf"); const response = await fetch("https://api.exhibitday.com/v1/events/shipments/invoice_attachment", { method: "POST", headers: { Authorization: 'Bearer YOUR_API_KEY' }, body: form }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); console.log(await response.json()); ``` Example — Python: ```python import requests import json from contextlib import ExitStack with ExitStack() as stack: files = [ ("file", ("invoice.pdf", stack.enter_context(open("invoice.pdf", 'rb')), "application/octet-stream")), ] response = requests.request("POST", "https://api.exhibitday.com/v1/events/shipments/invoice_attachment", headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data={"shipment_id": "12345"}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') print(response.json()) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.exhibitday.com/v1/events/shipments/invoice_attachment"); var form = new MultipartFormDataContent(); form.Add(new StringContent("12345"), "shipment_id"); var file0 = new StreamContent(File.OpenRead("invoice.pdf")); file0.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(file0, "file", "invoice.pdf"); request.Content = form; using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/shipments/invoice_attachment")).header("Authorization", "Bearer YOUR_API_KEY"); String boundary = "ExhibitDay-" + UUID.randomUUID(); ByteArrayOutputStream form = new ByteArrayOutputStream(); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"shipment_id\"\r\n\r\n" + "12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"invoice.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8)); form.write(Files.readAllBytes(Path.of("invoice.pdf"))); form.write("\r\n".getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); request.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpResponse response = HttpClient.newHttpClient().send(request.method("POST", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); System.out.println(new String(response.body(), StandardCharsets.UTF_8)); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], CURLOPT_POSTFIELDS => [ 'shipment_id' => '12345', 'file' => new CURLFile('invoice.pdf', 'application/octet-stream', 'invoice.pdf'), ], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); echo $response; ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/shipments/invoice_attachment') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' files = [] begin parts = [ ['shipment_id', '12345'], ['file', (files << File.open('invoice.pdf', 'rb')).last, {filename: 'invoice.pdf', content_type: 'application/octet-stream'}], ] request.set_form(parts, 'multipart/form-data') response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' puts response.body ensure files.each(&:close) end ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" "bytes" "mime/multipart" "net/textproto" ) func main() { var form bytes.Buffer writer := multipart.NewWriter(&form) if err := writer.WriteField("shipment_id", "12345"); err != nil { log.Fatal(err) } header0 := textproto.MIMEHeader{} header0.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"invoice.pdf\"") header0.Set("Content-Type", "application/octet-stream") part0, err := writer.CreatePart(header0) if err != nil { log.Fatal(err) } file0, err := os.Open("invoice.pdf") if err != nil { log.Fatal(err) } if _, err = io.Copy(part0, file0); err != nil { log.Fatal(err) } file0.Close() if err := writer.Close(); err != nil { log.Fatal(err) } request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/events/shipments/invoice_attachment", &form) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", writer.FormDataContentType()) response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } fmt.Printf("%s\n", data) } ``` Example HTTP response body (JSON): POST /v1/events/shipments/invoice_attachment - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "invoice_attachment": { "id": 12345, "filename": "invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } } ``` ### Replace Shipment Invoice Attachment `PATCH https://api.exhibitday.com/v1/events/shipments/invoice_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=shipments#patch-v1-events-shipments-invoice_attachment Replaces this Shipment's current Invoice Attachment with one uploaded file. Use this method when an invoice file is already attached. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | shipment_id | Number | Yes | The ID of the Shipment, from Retrieve Shipments (GET /v1/events/shipments) or its add response. | | | file | File (multipart) | Yes | The Invoice Attachment to upload. | Send exactly one complete, nonempty multipart/form-data file part named file. The supported extensions and current per-file limit are shown below; the complete request limit also includes multipart overhead. A missing or null file is invalid and does not remove an existing invoice. | Declared schema for `file` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "string", "format": "binary", "x-maximum-bytes": 26214400, "x-allowed-extensions": [ "png", "jpg", "jpeg", "bmp", "gif", "pdf", "msg", "eml", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "rtf", "odp", "odt", "ods", "txt", "wks", "zip" ] } ``` #### Replacing the current file PATCH requires a current invoice file. If none is attached, the API returns HTTP 404. Upload exactly one file; the previous attachment ID is not needed. If another request changes the current invoice during your upload, the API refuses this request instead of replacing a different file. Even identical replacement contents receive a new attachment ID. #### After the replacement The response's invoice_attachment contains the attached file's id, filename and attachment_created_timestamp. The amount, payment fields, cost-center breakdown and other files are unchanged. The previous file is scheduled for physical cleanup after a confirmed save; cleanup may finish later. The replacement is recorded in Event history. #### Access and retries A current upload-enabled plan, record and financial permissions, and an editable applicable tab are required. Each uploaded file must fit its supported type and size limits. expected_revision is not supported by this file method. PATCH does not use Idempotency-Key replay. If the save outcome cannot be confirmed, retrieve the current parent record with GET /v1/events/shipments/info and inspect invoice_attachment before deciding whether to retry. #### Hidden or locked tab If the Event's Shipments tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X PATCH "https://api.exhibitday.com/v1/events/shipments/invoice_attachment" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}" --form-string "shipment_id=12345" --form "file=@invoice.pdf;type=application/octet-stream") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi cat response-body.tmp ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const form = new FormData(); form.append("shipment_id", "12345"); form.append("file", new Blob([await readFile("invoice.pdf")], { type: "application/octet-stream" }), "invoice.pdf"); const response = await fetch("https://api.exhibitday.com/v1/events/shipments/invoice_attachment", { method: "PATCH", headers: { Authorization: 'Bearer YOUR_API_KEY' }, body: form }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); console.log(await response.json()); ``` Example — Python: ```python import requests import json from contextlib import ExitStack with ExitStack() as stack: files = [ ("file", ("invoice.pdf", stack.enter_context(open("invoice.pdf", 'rb')), "application/octet-stream")), ] response = requests.request("PATCH", "https://api.exhibitday.com/v1/events/shipments/invoice_attachment", headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data={"shipment_id": "12345"}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') print(response.json()) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("PATCH"), "https://api.exhibitday.com/v1/events/shipments/invoice_attachment"); var form = new MultipartFormDataContent(); form.Add(new StringContent("12345"), "shipment_id"); var file0 = new StreamContent(File.OpenRead("invoice.pdf")); file0.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(file0, "file", "invoice.pdf"); request.Content = form; using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/shipments/invoice_attachment")).header("Authorization", "Bearer YOUR_API_KEY"); String boundary = "ExhibitDay-" + UUID.randomUUID(); ByteArrayOutputStream form = new ByteArrayOutputStream(); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"shipment_id\"\r\n\r\n" + "12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"invoice.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8)); form.write(Files.readAllBytes(Path.of("invoice.pdf"))); form.write("\r\n".getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); request.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpResponse response = HttpClient.newHttpClient().send(request.method("PATCH", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); System.out.println(new String(response.body(), StandardCharsets.UTF_8)); } } ``` Example — PHP: ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], CURLOPT_POSTFIELDS => [ 'shipment_id' => '12345', 'file' => new CURLFile('invoice.pdf', 'application/octet-stream', 'invoice.pdf'), ], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); echo $response; ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/shipments/invoice_attachment') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' files = [] begin parts = [ ['shipment_id', '12345'], ['file', (files << File.open('invoice.pdf', 'rb')).last, {filename: 'invoice.pdf', content_type: 'application/octet-stream'}], ] request.set_form(parts, 'multipart/form-data') response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' puts response.body ensure files.each(&:close) end ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" "bytes" "mime/multipart" "net/textproto" ) func main() { var form bytes.Buffer writer := multipart.NewWriter(&form) if err := writer.WriteField("shipment_id", "12345"); err != nil { log.Fatal(err) } header0 := textproto.MIMEHeader{} header0.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"invoice.pdf\"") header0.Set("Content-Type", "application/octet-stream") part0, err := writer.CreatePart(header0) if err != nil { log.Fatal(err) } file0, err := os.Open("invoice.pdf") if err != nil { log.Fatal(err) } if _, err = io.Copy(part0, file0); err != nil { log.Fatal(err) } file0.Close() if err := writer.Close(); err != nil { log.Fatal(err) } request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/events/shipments/invoice_attachment", &form) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", writer.FormDataContentType()) response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } fmt.Printf("%s\n", data) } ``` Example HTTP response body (JSON): PATCH /v1/events/shipments/invoice_attachment - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "invoice_attachment": { "id": 12345, "filename": "invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } } ``` ### Remove Shipment Invoice Attachment `DELETE https://api.exhibitday.com/v1/events/shipments/invoice_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=shipments#delete-v1-events-shipments-invoice_attachment Removes this Shipment's Invoice Attachment. The cost, payment details and other File Attachments stay in place. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | shipment_id | Number | Yes | The ID of the Shipment, from Retrieve Shipments (GET /v1/events/shipments) or its add response. | | #### After the removal The Invoice Attachment is cleared and the removal is recorded in Event history. Its physical file is scheduled for cleanup after a confirmed save; cleanup may finish later. Costs, payment fields, cost-center allocations and supporting files stay unchanged. If no invoice is attached, DELETE returns HTTP 404 Not Found with the message "This Shipment has no invoice to remove." No saved data or history is changed. Current access and the record's binding are still checked. Do not send file parts with this request. #### Access and retries Current record, financial and invoice permissions and applicable tab-edit access are required. Permitted removals remain available on the Free plan. expected_revision is not supported, and DELETE does not use Idempotency-Key replay. If the save outcome cannot be confirmed, retrieve the current parent record with GET /v1/events/shipments/info and inspect invoice_attachment before deciding whether to retry. #### Hidden or locked tab If the Event's Shipments tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/events/shipments/invoice_attachment?shipment_id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/shipments/invoice_attachment?" + new URLSearchParams({ "shipment_id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/events/shipments/invoice_attachment", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"shipment_id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/events/shipments/invoice_attachment?shipment_id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/shipments/invoice_attachment?shipment_id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/shipments/invoice_attachment?shipment_id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/events/shipments/invoice_attachment?shipment_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/events/shipments/invoice_attachment - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Attachment removed.", "errors": [] } ``` ### Retrieve Shipment General File Attachments `GET https://api.exhibitday.com/v1/events/shipments/attachments` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=shipments#get-v1-events-shipments-attachments Retrieves the General File Attachments on this Shipment. Each result includes the file's ID, name and added time; use the download method for its contents. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | shipment_id | Number | Yes | The ID of the Shipment, from Retrieve Shipments (GET /v1/events/shipments) or its add response. | | | $limit | Number | No | The most File Attachments to return. | A positive whole number. Omit for all remaining matching files. | | $offset | Number | No | The number of matching File Attachments to skip. | A whole number of 0 or more. Default: 0. | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records. | Allowed values: `array` | | If-None-Match | String | No | An ETag from an earlier response to this GET. | Optional HTTP header. If the successful response is unchanged, the API returns HTTP 304 with no body. | #### Reading the file list Files are ordered by added time, then attachment ID, lowest first. Only files available under your current access are included. Paging totals and X-Total-Count count all matching files before $limit and $offset are applied. A record with no files you can view returns an empty list. This list does not return edit revisions or support changed-since filtering. #### Supporting files and invoices These are the record's General File Attachments. Its cost Invoice Attachment is separate and has its own download and upload methods. Use this list's id values for these supporting-file downloads and removals. #### Access The record's Event and tab must be available, and the tab must not be hidden. A locked tab can still be read. #### Hidden tab If the Event's Shipments tab is hidden, this request returns HTTP 400 (not_allowed), and the message says the tab is hidden. Show the tab in ExhibitDay first. A locked tab can still be read. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/events/shipments/attachments?shipment_id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/shipments/attachments?" + new URLSearchParams({ "shipment_id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/events/shipments/attachments", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"shipment_id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/events/shipments/attachments?shipment_id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/shipments/attachments?shipment_id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/shipments/attachments?shipment_id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/shipments/attachments?shipment_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/events/shipments/attachments - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "attachment", "list_data": [ { "id": 12345, "filename": "attachment.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } ] } ``` ### Add Shipment General File Attachments `POST https://api.exhibitday.com/v1/events/shipments/attachments` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=shipments#post-v1-events-shipments-attachments Adds one or more General File Attachments to this Shipment. Send each file as a multipart upload part named file. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | shipment_id | Number | Yes | The ID of the Shipment, from Retrieve Shipments (GET /v1/events/shipments) or its add response. | | | file | File (multipart) | Yes | The File Attachments to upload. | Send one or more complete, nonempty multipart/form-data parts, each named file. Supported types and the current per-file limit are shown below. The complete request limit includes all files and multipart overhead; split larger batches. A missing or null upload is not a removal request. | | Idempotency-Key | String | No | A unique key for safely retrying this upload. | Optional HTTP header: 1 to 255 visible ASCII characters without spaces or commas. Retry the identical request with the same key to replay its first saved response. Use a new key for a different upload. | Declared schema for `file` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "array", "items": { "type": "string", "format": "binary", "x-maximum-bytes": 26214400, "x-allowed-extensions": [ "png", "jpg", "jpeg", "bmp", "gif", "pdf", "msg", "eml", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "rtf", "odp", "odt", "ods", "txt", "wks", "zip" ] } } ``` #### After the upload The response's list_data contains the newly attached files, including each id, filename and attachment_created_timestamp. Existing files are kept. Use each returned id to download or remove that file. Identical repeated files in one request are attached once when their cleaned filename, length and contents match. Files with different contents remain separate even when their names match. This does not remove or replace files already attached to the record. #### Choosing the right file method These uploads add General File Attachments. Use this record's Invoice Attachment methods for its cost invoice or receipt. Adding supporting files does not change amounts, payments or cost-center allocations. #### Access Current record and file-change permissions and applicable Event/tab locks must allow this upload. An upload-enabled paid plan is required. #### History and retries A confirmed file change is recorded in history. expected_revision is not supported by these file methods. If the save outcome cannot be confirmed, retrieve the current file list before deciding whether to retry; the API does not automatically repeat an uncertain change. Supporting File Attachments have no PATCH replacement. To replace one, add the new file and remove the old one using their separate requests; each request has its own outcome. #### Hidden or locked tab If the Event's Shipments tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X POST "https://api.exhibitday.com/v1/events/shipments/attachments" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}" --form-string "shipment_id=12345" --form "file=@attachment.pdf;type=application/octet-stream") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi cat response-body.tmp ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const form = new FormData(); form.append("shipment_id", "12345"); form.append("file", new Blob([await readFile("attachment.pdf")], { type: "application/octet-stream" }), "attachment.pdf"); const response = await fetch("https://api.exhibitday.com/v1/events/shipments/attachments", { method: "POST", headers: { Authorization: 'Bearer YOUR_API_KEY' }, body: form }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); console.log(await response.json()); ``` Example — Python: ```python import requests import json from contextlib import ExitStack with ExitStack() as stack: files = [ ("file", ("attachment.pdf", stack.enter_context(open("attachment.pdf", 'rb')), "application/octet-stream")), ] response = requests.request("POST", "https://api.exhibitday.com/v1/events/shipments/attachments", headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data={"shipment_id": "12345"}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') print(response.json()) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.exhibitday.com/v1/events/shipments/attachments"); var form = new MultipartFormDataContent(); form.Add(new StringContent("12345"), "shipment_id"); var file0 = new StreamContent(File.OpenRead("attachment.pdf")); file0.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(file0, "file", "attachment.pdf"); request.Content = form; using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/shipments/attachments")).header("Authorization", "Bearer YOUR_API_KEY"); String boundary = "ExhibitDay-" + UUID.randomUUID(); ByteArrayOutputStream form = new ByteArrayOutputStream(); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"shipment_id\"\r\n\r\n" + "12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"attachment.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8)); form.write(Files.readAllBytes(Path.of("attachment.pdf"))); form.write("\r\n".getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); request.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpResponse response = HttpClient.newHttpClient().send(request.method("POST", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); System.out.println(new String(response.body(), StandardCharsets.UTF_8)); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], CURLOPT_POSTFIELDS => [ 'shipment_id' => '12345', 'file' => new CURLFile('attachment.pdf', 'application/octet-stream', 'attachment.pdf'), ], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); echo $response; ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/shipments/attachments') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' files = [] begin parts = [ ['shipment_id', '12345'], ['file', (files << File.open('attachment.pdf', 'rb')).last, {filename: 'attachment.pdf', content_type: 'application/octet-stream'}], ] request.set_form(parts, 'multipart/form-data') response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' puts response.body ensure files.each(&:close) end ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" "bytes" "mime/multipart" "net/textproto" ) func main() { var form bytes.Buffer writer := multipart.NewWriter(&form) if err := writer.WriteField("shipment_id", "12345"); err != nil { log.Fatal(err) } header0 := textproto.MIMEHeader{} header0.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"attachment.pdf\"") header0.Set("Content-Type", "application/octet-stream") part0, err := writer.CreatePart(header0) if err != nil { log.Fatal(err) } file0, err := os.Open("attachment.pdf") if err != nil { log.Fatal(err) } if _, err = io.Copy(part0, file0); err != nil { log.Fatal(err) } file0.Close() if err := writer.Close(); err != nil { log.Fatal(err) } request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/events/shipments/attachments", &form) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", writer.FormDataContentType()) response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } fmt.Printf("%s\n", data) } ``` Example HTTP response body (JSON): POST /v1/events/shipments/attachments - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "attachment", "list_data": [ { "id": 12345, "filename": "attachment.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } ] } ``` ### Remove a Shipment General File Attachment `DELETE https://api.exhibitday.com/v1/events/shipments/attachments` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=shipments#delete-v1-events-shipments-attachments Removes one General File Attachment from this Shipment. Other attached files and the record's details stay in place. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the File Attachment. | Use the id from the attachment list. The API finds the record the file belongs to, so no record ID is sent. An Invoice Attachment is not selected by this method. | #### After the removal Only the selected file association is removed. Its physical file is scheduled for cleanup after a confirmed save; cleanup may finish later. Other attached files stay in place. Send only the file's id; the API finds the record it belongs to. A missing, already removed or unavailable attachment returns HTTP 404 Not Found. Do not send file parts with DELETE. #### Access Current record and file-removal permissions and applicable Event/tab locks must allow this change. Permitted removals remain available on the Free plan. #### History and retries A confirmed file change is recorded in history. expected_revision is not supported by these file methods. DELETE does not use Idempotency-Key replay. If the save outcome cannot be confirmed, retrieve the current file list before deciding whether to retry; the API does not automatically repeat an uncertain change. Supporting File Attachments have no PATCH replacement. To replace one, add the new file and remove the old one using their separate requests; each request has its own outcome. #### Hidden or locked tab If the Event's Shipments tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/events/shipments/attachments?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/shipments/attachments?" + new URLSearchParams({ "id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/events/shipments/attachments", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/events/shipments/attachments?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/shipments/attachments?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/shipments/attachments?id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/events/shipments/attachments?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/events/shipments/attachments - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Attachment removed.", "errors": [] } ``` ### Download a Shipment General File Attachment `GET https://api.exhibitday.com/v1/events/shipments/attachments/download` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=shipments#get-v1-events-shipments-attachments-download Downloads one original General File Attachment from this Shipment. Select the file using its ID from the attachment list. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the File Attachment. | Use the id from the attachment list. The API finds the record the file belongs to, so no record ID is sent. An Invoice Attachment is not selected by this method. | #### Download response A successful response contains the original uploaded file with a safe download filename. API errors use the usual JSON response. A missing or unavailable file returns HTTP 404. Send only the file's id from the attachment list to download that one file; the API finds the record it belongs to. The download leaves the record unchanged. #### Access The record's Event and tab must be available, and the tab must not be hidden. A locked tab can still be read. #### Files still being copied If this file is still being copied, the download returns HTTP 409 with file_copy_pending. Try the download again in a few minutes. #### Hidden tab If the Event's Shipments tab is hidden, this request returns HTTP 400 (not_allowed), and the message says the tab is hidden. Show the tab in ExhibitDay first. A locked tab can still be read. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X GET "https://api.exhibitday.com/v1/events/shipments/attachments/download?id=12345" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi mv response-body.tmp 'attachment.pdf' ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const response = await fetch("https://api.exhibitday.com/v1/events/shipments/attachments/download?id=12345", { method: "GET", headers: { Authorization: 'Bearer YOUR_API_KEY' } }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); await writeFile("attachment.pdf", new Uint8Array(await response.arrayBuffer())); ``` Example — Python: ```python import requests import json response = requests.request("GET", "https://api.exhibitday.com/v1/events/shipments/attachments/download?id=12345", headers={'Authorization': 'Bearer YOUR_API_KEY'}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') with open("attachment.pdf", 'wb') as destination: destination.write(response.content) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.exhibitday.com/v1/events/shipments/attachments/download?id=12345"); using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); await File.WriteAllBytesAsync("attachment.pdf", await response.Content.ReadAsByteArrayAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/shipments/attachments/download?id=12345")).header("Authorization", "Bearer YOUR_API_KEY"); HttpResponse response = HttpClient.newHttpClient().send(request.method("GET", HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); Files.write(Path.of("attachment.pdf"), response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); file_put_contents('attachment.pdf', $response); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/shipments/attachments/download?id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' File.binwrite('attachment.pdf', response.body) ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/shipments/attachments/download?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } if err := os.WriteFile("attachment.pdf", data, 0600); err != nil { log.Fatal(err) } fmt.Println("File saved") } ``` HTTP 200: Returns the original uploaded file as a private download, using a safe filename. If the file cannot be downloaded, the response contains the usual JSON API error instead. Media: application/octet-stream. The body is the authorized file's real bytes, not JSON or base64. Errors are JSON status responses; check HTTP status before saving the file. ## Events - Sponsorships Sponsorships on an Event: their details and costs, invoices, file attachments and exports. Documentation page: https://api.exhibitday.com/Help/V1?epf=1&topic=sponsorships ### Retrieve a Single Sponsorship by ID `GET https://api.exhibitday.com/v1/events/sponsorships/info` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=sponsorships#get-v1-events-sponsorships-info Retrieves a Sponsorship by its ID, including its details, notes, costs and payment information. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Sponsorship. Use the id from Retrieve Sponsorships (GET /v1/events/sponsorships) or from the add response; you don't send the Event ID. | | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` \| `object` | | $include_record_revision | Boolean | No | Set to true to include record_revision in the response. Send that value as expected_revision when updating to check for conflicting changes. | Default: false. | | $on_error_return_empty_result | Boolean | No | For missing or invalid ids, or a Sponsorship not available in this Event, return HTTP 200 with {} (or [] in array format). API key errors, conflicts with a change in progress and unexpected errors keep their normal error status. | | #### Current Event and access The Sponsorship's current Event is determined automatically. The request must have access to that Event and its Sponsorships tab. #### Record revision Set $include_record_revision=true to get record_revision, which covers this Sponsorship's editable fields, costs, related-item links and Event binding. Send it as expected_revision with a later update. File Attachment and Invoice Attachment metadata and contents are not covered. #### File Attachments The response includes the Invoice Attachment metadata as invoice_attachment, or null when no invoice is attached. Use the separate File Attachment collection to retrieve ordinary attachment metadata. #### Formatted text in the response Notes and other rich-text values in the response contain the stored HTML, including encoded characters and line breaks such as `
`. #### Open in ExhibitDay Each record includes exhibitday_url, the record's page in ExhibitDay. It opens the record in view mode on its Event's tab. Sign in with an account that can view the record; ExhibitDay checks access when the link is opened. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/events/sponsorships/info?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/sponsorships/info?" + new URLSearchParams({ "id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/events/sponsorships/info", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/events/sponsorships/info?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/sponsorships/info?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/sponsorships/info?id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/sponsorships/info?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/events/sponsorships/info - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "id": 12345, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=12345&riType=7&riSub=0&riId=12345", "event_id": 12345, "event_name": "Sample Event", "name": "Welcome reception", "acquisition_status_id": 1, "acquisition_status": "Need to Acquire", "acquire_by_date": null, "acquired_date": null, "agreement_confirmation_number": null, "organizer_provider": null, "contact_name": null, "contact_email": null, "contact_phone": null, "portal_url": null, "benefits_inclusions": "", "coverage_placement_details": "", "conditions_restrictions": "", "materials_contributions_required": "", "submission_delivery_instructions": "", "key_dates_deadlines": "", "benefits_received_outstanding": "", "notes": "", "payment_status_id": 0, "payment_status": { "id": 0, "name": "N/A" }, "payment_due_date": null, "next_payment_due_date": null, "payment_notes": null, "invoice_attachment": { "id": 382345, "filename": "sponsorship-invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" }, "cost": { "amount": 125.50, "cost_center_breakdown": [ { "cost_center_id": 34567, "cost_center": "Marketing", "charge": 75.50 }, { "cost_center_id": 34568, "cost_center": "Operations", "charge": 50.00 } ] }, "related_items": [ { "id": 5551, "related_item_id": 67890, "related_item_exhibitday_url": "https://www.exhibitday.com/Workspace/TaskView/98765?tid=67890", "related_item_type_id": 1, "related_item_type": "Task", "related_item_asset_type_id": null, "related_item_name": "Confirm booth graphics with the printer", "related_item_created_timestamp": "2030-01-10T14:03:00Z" }, { "id": 5552, "related_item_id": 45678, "related_item_exhibitday_url": "https://www.exhibitday.com/Workspace/RelatedItemView/98765?typeId=4&subTypeId=0&rid=45678", "related_item_type_id": 4, "related_item_type": "Shipment", "related_item_asset_type_id": null, "related_item_name": "Booth crates to convention center", "related_item_created_timestamp": "2030-01-10T14:03:00Z" } ] } ``` ### Retrieve Sponsorships `GET https://api.exhibitday.com/v1/events/sponsorships` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=sponsorships#get-v1-events-sponsorships Retrieves records across your workspace's readable Event tabs. Use filter_by_event_id to narrow the results to one Event, or omit it for the workspace list. Each record includes its event_id and Event name. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | filter_by_event_id | Number | No | Return records for this Event only. Omit for all readable Events in your workspace. | | | $limit | Number | No | The most Sponsorships to return (a whole number of 1 or more). Leave it out to return all remaining matching records. | | | $offset | Number | No | How many matching Sponsorships to skip (a whole number of 0 or more; 0 by default). Use this with $limit to read the next page. | | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | | hydrate_related_items | Boolean | No | Set to true to include each record's related_items: the Tasks and items linked to it, with the key to use when adding or removing a link. Omit it or send false to leave related_items out of list results. Single-record GETs always include related_items. | Default: false. | #### Choosing Events Omit `filter_by_event_id` to retrieve records across readable Event tabs, or supply one Event ID to narrow the list. Each result retains its own `event_id` and Event name. Hidden or unavailable Event tabs are not included. A locked tab can still be read. If no records match, the response is an empty list. #### Reading pages The Event filter and any people filter are applied before the total count and paging. Results are ordered by Event start date ascending, Event ID ascending, then record ID ascending. Use `$limit` and `$offset` for successive pages. Omit `$limit` to return all remaining matches. `total_records` and `X-Total-Count` describe all matches; `records_found` counts this response. Omit `$result_format` for the normal list wrapper. `array` returns only the records; `wrapped_in_array` places the normal wrapper in a one-item array. #### Handling input and changes Unrecognized parameters are ignored and listed in the `X-API-Warnings` response header. Conflicting or malformed filter values return HTTP `400`; send arrays in JSON, query parameters or form fields rather than comma-bearing headers. Current API access is checked even when the list is empty. A concurrent change can return HTTP `409`; retrieve the list again. These filters retrieve records and do not change tags, assignments or notification settings. #### Related items Set `hydrate_related_items=true` to include each record's `related_items`: the Tasks and items linked to it. Add or remove links with POST and DELETE /v1/related_items. It is left out by default to keep lists fast. Retrieving one record always includes `related_items`. #### Events with a hidden Sponsorships tab Records on Events whose Sponsorships tab is hidden are not listed. If filter_by_event_id names such an Event, the response is HTTP 200 with no records for it and a warning that names the tab and the Event. #### Open in ExhibitDay Each record includes exhibitday_url, the record's page in ExhibitDay. It opens the record in view mode on its Event's tab. Sign in with an account that can view the record; ExhibitDay checks access when the link is opened. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/events/sponsorships" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/sponsorships", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/events/sponsorships", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/events/sponsorships"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/sponsorships")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/sponsorships') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/sponsorships", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/events/sponsorships - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "sponsorship", "list_data": [ { "id": 12345, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=12345&riType=7&riSub=0&riId=12345", "event_id": 12345, "event_name": "Sample Event", "name": "Welcome reception", "acquisition_status_id": 1, "acquisition_status": "Need to Acquire", "acquire_by_date": null, "acquired_date": null, "agreement_confirmation_number": null, "organizer_provider": null, "contact_name": null, "contact_email": null, "contact_phone": null, "portal_url": null, "benefits_inclusions": "", "coverage_placement_details": "", "conditions_restrictions": "", "materials_contributions_required": "", "submission_delivery_instructions": "", "key_dates_deadlines": "", "benefits_received_outstanding": "", "notes": "", "payment_status_id": 0, "payment_status": { "id": 0, "name": "N/A" }, "payment_due_date": null, "next_payment_due_date": null, "payment_notes": null, "invoice_attachment": { "id": 382345, "filename": "sponsorship-invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" }, "cost": { "amount": 0.00, "cost_center_breakdown": [] } } ] } ``` ### Add a Sponsorship `POST https://api.exhibitday.com/v1/events/sponsorships` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=sponsorships#post-v1-events-sponsorships These methods manage Sponsorships for an existing Event in your workspace. Supply the Event id and, for an existing Sponsorship, its id; a Sponsorship cannot be moved to another Event. Your current permissions and the Event's hidden or locked tab settings apply. A Sponsorship records what you plan to acquire and whether it has been acquired. Its costs, payment details and Cost Invoice / Receipt are separate: recording a cost does not attach an invoice or mark a payment complete. Deleting a Sponsorship removes its own costs, related-item links and attachment records together, then schedules only its files for physical cleanup. No contact or assignee email is sent. A POST Idempotency-Key must be one value without commas. Send text containing commas and cost lists through JSON, the query string or form fields. A URL may retain its own %2C encoding; other text is not percent-decoded. Optional Idempotency-Key replay applies to POST; PATCH and DELETE retain their existing behavior of ignoring that header. A confirmed change is then added to history; failure to write history does not undo the saved change. An unchanged PATCH writes no data, timestamp or history. Creating this record does not attach an invoice; its invoice attachment metadata is null. Add an invoice using the separate invoice attachment method. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | event_id | Number | Yes | The id of the Event in your workspace to add the Sponsorship to. | | | name | String | Yes | The Sponsorship name, up to 300 characters. It can't be blank. | Max length: 300. | | acquisition_status_id | Number | No | Whether the Sponsorship still needs to be acquired. Optional when adding a Sponsorship: omitted, blank or null means Need to Acquire. Choosing Need to Acquire clears the acquisition date and agreement or confirmation number, while keeping financial details. | Allowed values: `1` (Need to Acquire) \| `2` (Already Acquired) | | notes | String | No | Send plain text for notes; line breaks are kept. If you send HTML, only its text is saved. The text must fit within 30,000 characters both when saved and when counted by the Sponsorship editor in ExhibitDay; formatting and encoded characters count toward those limits. Existing text over a limit can be kept or shortened, but cannot grow under either count. On PATCH, an omitted or blank value keeps it; null clears it. This applies to either acquisition status. | Max length: 30000. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | acquire_by_date | String | No | A calendar date in YYYY-MM-DD format, without a time or time zone. On PATCH, an omitted or blank value keeps the current date, and `null` clears it. This date applies regardless of acquisition or payment status. | | | payment_status_id | Number | No | The Sponsorship's payment status. Omit for N/A; null resets it to N/A. A status other than Partially Paid clears the next partial payment due date. Payment status can be recorded for either acquisition status. | Allowed values: `0` (N/A) \| `1` (Paid in Full) \| `2` (Partially Paid) \| `3` (Not Paid Yet) | | payment_due_date | String | No | A calendar date in YYYY-MM-DD format, without a time or time zone. On PATCH, an omitted or blank value keeps the current date, and `null` clears it. This date applies regardless of acquisition or payment status. | | | next_payment_due_date | Date | No | A calendar date in YYYY-MM-DD format, without a time or time zone. On PATCH, an omitted or blank value keeps the current date, and `null` clears it. Applies only when the payment status is Partially Paid (`payment_status_id=2`). With any other status, supplying either this date or the payment status clears the date. | | | payment_notes | String | No | Up to 200 characters. On PATCH, an omitted or blank value keeps it; null clears it. This applies to either acquisition status. | Max length: 200. | | acquired_date | String | No | A calendar date in YYYY-MM-DD format, without a time or time zone. On PATCH, an omitted or blank value keeps the current date, and `null` clears it. Applies only when the acquisition status is Already Acquired (`acquisition_status_id=2`). With any other status, supplying this date, the acquisition status or the agreement or confirmation number clears the date. | | | agreement_confirmation_number | String | No | The agreement or confirmation number, up to 200 characters. This applies only to Already Acquired (acquisition_status_id=2); otherwise it is cleared when the acquisition status, date or agreement information is supplied. On PATCH, an omitted or blank value keeps it; null clears it. | Max length: 200. | | organizer_provider | String | No | Up to 200 characters. On PATCH, an omitted or blank value keeps it; null clears it. This applies to either acquisition status. | Max length: 200. | | contact_name | String | No | Up to 200 characters. On PATCH, an omitted or blank value keeps it; null clears it. This applies to either acquisition status. | Max length: 200. | | contact_email | String | No | Up to 200 characters. On PATCH, an omitted or blank value keeps it; null clears it. This applies to either acquisition status. | Max length: 200. | | contact_phone | String | No | Up to 200 characters. On PATCH, an omitted or blank value keeps it; null clears it. This applies to either acquisition status. | Max length: 200. | | portal_url | String | No | Up to 2000 characters. On PATCH, an omitted or blank value keeps it; null clears it. This applies to either acquisition status. | Max length: 2000. | | benefits_inclusions | String | No | Send plain text for benefits inclusions; line breaks are kept. If you send HTML, only its text is saved. The text must fit within 30,000 characters both when saved and when counted by the Sponsorship editor in ExhibitDay; formatting and encoded characters count toward those limits. Existing text over a limit can be kept or shortened, but cannot grow under either count. On PATCH, an omitted or blank value keeps it; null clears it. This applies to either acquisition status. | Max length: 30000. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | coverage_placement_details | String | No | Send plain text for coverage placement details; line breaks are kept. If you send HTML, only its text is saved. The text must fit within 30,000 characters both when saved and when counted by the Sponsorship editor in ExhibitDay; formatting and encoded characters count toward those limits. Existing text over a limit can be kept or shortened, but cannot grow under either count. On PATCH, an omitted or blank value keeps it; null clears it. This applies to either acquisition status. | Max length: 30000. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | conditions_restrictions | String | No | Send plain text for conditions restrictions; line breaks are kept. If you send HTML, only its text is saved. The text must fit within 30,000 characters both when saved and when counted by the Sponsorship editor in ExhibitDay; formatting and encoded characters count toward those limits. Existing text over a limit can be kept or shortened, but cannot grow under either count. On PATCH, an omitted or blank value keeps it; null clears it. This applies to either acquisition status. | Max length: 30000. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | materials_contributions_required | String | No | Send plain text for materials contributions required; line breaks are kept. If you send HTML, only its text is saved. The text must fit within 30,000 characters both when saved and when counted by the Sponsorship editor in ExhibitDay; formatting and encoded characters count toward those limits. Existing text over a limit can be kept or shortened, but cannot grow under either count. On PATCH, an omitted or blank value keeps it; null clears it. This applies to either acquisition status. | Max length: 30000. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | submission_delivery_instructions | String | No | Send plain text for submission delivery instructions; line breaks are kept. If you send HTML, only its text is saved. The text must fit within 30,000 characters both when saved and when counted by the Sponsorship editor in ExhibitDay; formatting and encoded characters count toward those limits. Existing text over a limit can be kept or shortened, but cannot grow under either count. On PATCH, an omitted or blank value keeps it; null clears it. This applies to either acquisition status. | Max length: 30000. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | key_dates_deadlines | String | No | Send plain text for key dates deadlines; line breaks are kept. If you send HTML, only its text is saved. The text must fit within 30,000 characters both when saved and when counted by the Sponsorship editor in ExhibitDay; formatting and encoded characters count toward those limits. Existing text over a limit can be kept or shortened, but cannot grow under either count. On PATCH, an omitted or blank value keeps it; null clears it. This applies to either acquisition status. | Max length: 30000. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | benefits_received_outstanding | String | No | Send plain text for benefits received outstanding; line breaks are kept. If you send HTML, only its text is saved. The text must fit within 30,000 characters both when saved and when counted by the Sponsorship editor in ExhibitDay; formatting and encoded characters count toward those limits. Existing text over a limit can be kept or shortened, but cannot grow under either count. On PATCH, an omitted or blank value keeps it; null clears it. This applies to either acquisition status. | Max length: 30000. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | cost | Number or cost object | No | The full cost, as a number or an object with amount and/or cost_center_breakdown. [Record Costs and Split Them Across Cost Centers](/Help/V1?guide=entering-costs). | Optional; defaults to zero. | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` \| `object` | Declared schema for `cost` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "anyOf": [ { "type": "number", "minimum": 0, "description": "Shorthand for an object with amount. The amount is rounded to cents before the supported storage range is checked.", "nullable": true }, { "type": "object", "additionalProperties": false, "properties": { "amount": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 }, "cost_center_breakdown": { "type": "array", "items": { "type": "object", "additionalProperties": false, "properties": { "cost_center_id": { "type": "integer", "format": "int64", "nullable": true }, "charge": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 }, "cost_center": { "type": "string", "description": "Optional and read-only: the cost center name a read returns, so a cost can be sent back unchanged. It is ignored; the line is saved by cost_center_id, and a name that doesn't match that cost center is explained in a warning.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "required": [ "charge" ] }, "maxItems": 2147483647 } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "anyOf": [ { "required": [ "amount" ] }, { "required": [ "cost_center_breakdown" ] } ], "nullable": true } ], "x-numeric-shorthand": "A number is equivalent to {amount:number}.", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": { "amount": 125.50 } } ``` #### Sending text Send plain text for Notes and other rich-text fields. Characters such as `&`, `<` and quotes, along with line breaks, are encoded for storage. Notes and other rich-text values in the response contain the stored HTML, including encoded characters and line breaks such as `
`. #### Hidden or locked tab If the Event's Sponsorships tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. An Event that is not in your workspace returns HTTP 404. #### Acquisition status When adding, acquisition_status_id is optional and defaults to Need to Acquire. The same statuses use different IDs in each family: Sponsorships use 1 for Need to Acquire and 2 for Already Acquired; Giveaways use 10 and 20. #### Open in ExhibitDay The created record includes exhibitday_url, the record's page in ExhibitDay. It is the same link that GET /v1/events/sponsorships/info returns for this record and opens the record in view mode on its Event's tab. Sign in with an account that can view the record; ExhibitDay checks access when the link is opened. Example — curl: ```bash curl -X POST "https://api.exhibitday.com/v1/events/sponsorships" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"event_id\":12345,\"name\":\"Welcome reception\",\"acquisition_status_id\":1}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/sponsorships", { method: "POST", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "event_id": 12345, "name": "Welcome reception", "acquisition_status_id": 1 }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.post( "https://api.exhibitday.com/v1/events/sponsorships", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"event_id": 12345, "name": "Welcome reception", "acquisition_status_id": 1}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PostAsync("https://api.exhibitday.com/v1/events/sponsorships", JsonContent.Create(new { event_id = 12345, name = "Welcome reception", acquisition_status_id = 1 })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/sponsorships")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("POST", HttpRequest.BodyPublishers.ofString("{\"event_id\":12345,\"name\":\"Welcome reception\",\"acquisition_status_id\":1}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"event_id":12345,"name":"Welcome reception","acquisition_status_id":1}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/sponsorships') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"event_id":12345,"name":"Welcome reception","acquisition_status_id":1}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/events/sponsorships", strings.NewReader("{\"event_id\":12345,\"name\":\"Welcome reception\",\"acquisition_status_id\":1}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): POST /v1/events/sponsorships - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "id": 23456, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=12345&riType=7&riSub=0&riId=23456", "event_id": 12345, "event_name": "Sample Event", "name": "Welcome reception", "acquisition_status_id": 1, "acquisition_status": "Need to Acquire", "acquire_by_date": null, "acquired_date": null, "agreement_confirmation_number": null, "organizer_provider": null, "contact_name": null, "contact_email": null, "contact_phone": null, "portal_url": null, "benefits_inclusions": "", "coverage_placement_details": "", "conditions_restrictions": "", "materials_contributions_required": "", "submission_delivery_instructions": "", "key_dates_deadlines": "", "benefits_received_outstanding": "", "notes": "", "payment_status_id": 0, "payment_status": { "id": 0, "name": "N/A" }, "payment_due_date": null, "next_payment_due_date": null, "payment_notes": null, "invoice_attachment": null, "cost": { "amount": 0.00, "cost_center_breakdown": [] } } ``` ### Update a Sponsorship `PATCH https://api.exhibitday.com/v1/events/sponsorships` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=sponsorships#patch-v1-events-sponsorships These methods manage Sponsorships for an existing Event in your workspace. Supply the Event id and, for an existing Sponsorship, its id; a Sponsorship cannot be moved to another Event. Your current permissions and the Event's hidden or locked tab settings apply. A Sponsorship records what you plan to acquire and whether it has been acquired. Its costs, payment details and Cost Invoice / Receipt are separate: recording a cost does not attach an invoice or mark a payment complete. Deleting a Sponsorship removes its own costs, related-item links and attachment records together, then schedules only its files for physical cleanup. No contact or assignee email is sent. On PATCH, send only fields you want to change; omitted or blank values keep their current values. null clears a field only when that field supports clearing. If you use $ignore_params_with_empty_values=true, JSON null is ignored, while the text "null" still requests clearing. A POST Idempotency-Key must be one value without commas. Send text containing commas and cost lists through JSON, the query string or form fields. A URL may retain its own %2C encoding; other text is not percent-decoded. Optional Idempotency-Key replay applies to POST; PATCH and DELETE retain their existing behavior of ignoring that header. A confirmed change is then added to history; failure to write history does not undo the saved change. An unchanged PATCH writes no data, timestamp or history. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Sponsorship to update. Use the id from Retrieve Sponsorships (GET /v1/events/sponsorships) or from the add response. | | | name | String | No | The Sponsorship name, up to 300 characters. Omit or leave blank to keep the current name. The name can't be cleared. | Max length: 300. | | acquisition_status_id | Number | No | Whether the Sponsorship still needs to be acquired. Omit or leave blank to keep it; null is refused. Choosing Need to Acquire clears the acquisition date and agreement or confirmation number, while keeping financial details. | Allowed values: `1` (Need to Acquire) \| `2` (Already Acquired) | | notes | String | No | Send plain text for notes; line breaks are kept. If you send HTML, only its text is saved. The text must fit within 30,000 characters both when saved and when counted by the Sponsorship editor in ExhibitDay; formatting and encoded characters count toward those limits. Existing text over a limit can be kept or shortened, but cannot grow under either count. On PATCH, an omitted or blank value keeps it; null clears it. This applies to either acquisition status. | Max length: 30000. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | acquire_by_date | String | No | A calendar date in YYYY-MM-DD format, without a time or time zone. On PATCH, an omitted or blank value keeps the current date, and `null` clears it. This date applies regardless of acquisition or payment status. | | | payment_status_id | Number | No | The Sponsorship's payment status. Omit or leave blank to keep it; null resets it to N/A. A status other than Partially Paid clears the next partial payment due date. Payment status can be recorded for either acquisition status. | Allowed values: `0` (N/A) \| `1` (Paid in Full) \| `2` (Partially Paid) \| `3` (Not Paid Yet) | | payment_due_date | String | No | A calendar date in YYYY-MM-DD format, without a time or time zone. On PATCH, an omitted or blank value keeps the current date, and `null` clears it. This date applies regardless of acquisition or payment status. | | | next_payment_due_date | Date | No | A calendar date in YYYY-MM-DD format, without a time or time zone. On PATCH, an omitted or blank value keeps the current date, and `null` clears it. Applies only when the payment status is Partially Paid (`payment_status_id=2`). With any other status, supplying either this date or the payment status clears the date. | | | payment_notes | String | No | Up to 200 characters. On PATCH, an omitted or blank value keeps it; null clears it. This applies to either acquisition status. | Max length: 200. | | acquired_date | String | No | A calendar date in YYYY-MM-DD format, without a time or time zone. On PATCH, an omitted or blank value keeps the current date, and `null` clears it. Applies only when the acquisition status is Already Acquired (`acquisition_status_id=2`). With any other status, supplying this date, the acquisition status or the agreement or confirmation number clears the date. | | | agreement_confirmation_number | String | No | The agreement or confirmation number, up to 200 characters. This applies only to Already Acquired (acquisition_status_id=2); otherwise it is cleared when the acquisition status, date or agreement information is supplied. On PATCH, an omitted or blank value keeps it; null clears it. | Max length: 200. | | organizer_provider | String | No | Up to 200 characters. On PATCH, an omitted or blank value keeps it; null clears it. This applies to either acquisition status. | Max length: 200. | | contact_name | String | No | Up to 200 characters. On PATCH, an omitted or blank value keeps it; null clears it. This applies to either acquisition status. | Max length: 200. | | contact_email | String | No | Up to 200 characters. On PATCH, an omitted or blank value keeps it; null clears it. This applies to either acquisition status. | Max length: 200. | | contact_phone | String | No | Up to 200 characters. On PATCH, an omitted or blank value keeps it; null clears it. This applies to either acquisition status. | Max length: 200. | | portal_url | String | No | Up to 2000 characters. On PATCH, an omitted or blank value keeps it; null clears it. This applies to either acquisition status. | Max length: 2000. | | benefits_inclusions | String | No | Send plain text for benefits inclusions; line breaks are kept. If you send HTML, only its text is saved. The text must fit within 30,000 characters both when saved and when counted by the Sponsorship editor in ExhibitDay; formatting and encoded characters count toward those limits. Existing text over a limit can be kept or shortened, but cannot grow under either count. On PATCH, an omitted or blank value keeps it; null clears it. This applies to either acquisition status. | Max length: 30000. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | coverage_placement_details | String | No | Send plain text for coverage placement details; line breaks are kept. If you send HTML, only its text is saved. The text must fit within 30,000 characters both when saved and when counted by the Sponsorship editor in ExhibitDay; formatting and encoded characters count toward those limits. Existing text over a limit can be kept or shortened, but cannot grow under either count. On PATCH, an omitted or blank value keeps it; null clears it. This applies to either acquisition status. | Max length: 30000. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | conditions_restrictions | String | No | Send plain text for conditions restrictions; line breaks are kept. If you send HTML, only its text is saved. The text must fit within 30,000 characters both when saved and when counted by the Sponsorship editor in ExhibitDay; formatting and encoded characters count toward those limits. Existing text over a limit can be kept or shortened, but cannot grow under either count. On PATCH, an omitted or blank value keeps it; null clears it. This applies to either acquisition status. | Max length: 30000. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | materials_contributions_required | String | No | Send plain text for materials contributions required; line breaks are kept. If you send HTML, only its text is saved. The text must fit within 30,000 characters both when saved and when counted by the Sponsorship editor in ExhibitDay; formatting and encoded characters count toward those limits. Existing text over a limit can be kept or shortened, but cannot grow under either count. On PATCH, an omitted or blank value keeps it; null clears it. This applies to either acquisition status. | Max length: 30000. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | submission_delivery_instructions | String | No | Send plain text for submission delivery instructions; line breaks are kept. If you send HTML, only its text is saved. The text must fit within 30,000 characters both when saved and when counted by the Sponsorship editor in ExhibitDay; formatting and encoded characters count toward those limits. Existing text over a limit can be kept or shortened, but cannot grow under either count. On PATCH, an omitted or blank value keeps it; null clears it. This applies to either acquisition status. | Max length: 30000. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | key_dates_deadlines | String | No | Send plain text for key dates deadlines; line breaks are kept. If you send HTML, only its text is saved. The text must fit within 30,000 characters both when saved and when counted by the Sponsorship editor in ExhibitDay; formatting and encoded characters count toward those limits. Existing text over a limit can be kept or shortened, but cannot grow under either count. On PATCH, an omitted or blank value keeps it; null clears it. This applies to either acquisition status. | Max length: 30000. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | benefits_received_outstanding | String | No | Send plain text for benefits received outstanding; line breaks are kept. If you send HTML, only its text is saved. The text must fit within 30,000 characters both when saved and when counted by the Sponsorship editor in ExhibitDay; formatting and encoded characters count toward those limits. Existing text over a limit can be kept or shortened, but cannot grow under either count. On PATCH, an omitted or blank value keeps it; null clears it. This applies to either acquisition status. | Max length: 30000. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | cost | Number or cost object | No | The full cost, as a number or an object with amount and/or cost_center_breakdown. [Record Costs and Split Them Across Cost Centers](/Help/V1?guide=entering-costs). | Omit to keep the saved cost. A supplied value replaces its full allocation. | | expected_revision | String | No | The record_revision returned when you retrieved this record. Include it to avoid overwriting someone else's changes. Omit it to skip this check. | | Declared schema for `cost` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "anyOf": [ { "type": "number", "minimum": 0, "description": "Shorthand for an object with amount. The amount is rounded to cents before the supported storage range is checked.", "nullable": true }, { "type": "object", "additionalProperties": false, "properties": { "amount": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 }, "cost_center_breakdown": { "type": "array", "items": { "type": "object", "additionalProperties": false, "properties": { "cost_center_id": { "type": "integer", "format": "int64", "nullable": true }, "charge": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 }, "cost_center": { "type": "string", "description": "Optional and read-only: the cost center name a read returns, so a cost can be sent back unchanged. It is ignored; the line is saved by cost_center_id, and a name that doesn't match that cost center is explained in a warning.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "required": [ "charge" ] }, "maxItems": 2147483647 } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "anyOf": [ { "required": [ "amount" ] }, { "required": [ "cost_center_breakdown" ] } ], "nullable": true } ], "x-numeric-shorthand": "A number is equivalent to {amount:number}.", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": { "amount": 125.50 } } ``` #### Sending text Send plain text for Notes and other rich-text fields. Characters such as `&`, `<` and quotes, along with line breaks, are encoded for storage. #### Hidden or locked tab If the Event's Sponsorships tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. An Event that is not in your workspace returns HTTP 404. Example — curl: ```bash curl -X PATCH "https://api.exhibitday.com/v1/events/sponsorships" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"id\":12345,\"name\":\"Welcome reception\"}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/sponsorships", { method: "PATCH", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "id": 12345, "name": "Welcome reception" }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.patch( "https://api.exhibitday.com/v1/events/sponsorships", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"id": 12345, "name": "Welcome reception"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PatchAsync("https://api.exhibitday.com/v1/events/sponsorships", JsonContent.Create(new { id = 12345, name = "Welcome reception" })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/sponsorships")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("PATCH", HttpRequest.BodyPublishers.ofString("{\"id\":12345,\"name\":\"Welcome reception\"}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"id":12345,"name":"Welcome reception"}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/sponsorships') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"id":12345,"name":"Welcome reception"}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/events/sponsorships", strings.NewReader("{\"id\":12345,\"name\":\"Welcome reception\"}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): PATCH /v1/events/sponsorships - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Sponsorship updated.", "errors": [] } ``` ### Delete a Sponsorship `DELETE https://api.exhibitday.com/v1/events/sponsorships` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=sponsorships#delete-v1-events-sponsorships These methods manage Sponsorships for an existing Event in your workspace. Supply the Event id and, for an existing Sponsorship, its id; a Sponsorship cannot be moved to another Event. Your current permissions and the Event's hidden or locked tab settings apply. A Sponsorship records what you plan to acquire and whether it has been acquired. Its costs, payment details and Cost Invoice / Receipt are separate: recording a cost does not attach an invoice or mark a payment complete. Deleting a Sponsorship removes its own costs, related-item links and attachment records together, then schedules only its files for physical cleanup. No contact or assignee email is sent. A POST Idempotency-Key must be one value without commas. Send text containing commas and cost lists through JSON, the query string or form fields. A URL may retain its own %2C encoding; other text is not percent-decoded. Optional Idempotency-Key replay applies to POST; PATCH and DELETE retain their existing behavior of ignoring that header. A confirmed change is then added to history; failure to write history does not undo the saved change. An unchanged PATCH writes no data, timestamp or history. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Sponsorship to delete. Use the id from Retrieve Sponsorships (GET /v1/events/sponsorships) or from the add response. | | #### Hidden or locked tab If the Event's Sponsorships tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. An Event that is not in your workspace returns HTTP 404. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/events/sponsorships?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/sponsorships?" + new URLSearchParams({ "id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/events/sponsorships", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/events/sponsorships?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/sponsorships?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/sponsorships?id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/events/sponsorships?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/events/sponsorships - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Sponsorship removed.", "errors": [] } ``` ### Download Sponsorship Invoice Attachment `GET https://api.exhibitday.com/v1/events/sponsorships/invoice_attachment/download` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=sponsorships#get-v1-events-sponsorships-invoice_attachment-download Downloads the original Invoice Attachment for this Sponsorship. Use this method to retrieve the file itself. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | sponsorship_id | Number | Yes | The ID of the Sponsorship, from Retrieve Sponsorships (GET /v1/events/sponsorships) or its add response. | | #### Finding the file In the web app, this is the invoice control beside the Sponsorship's cost and payment details. Each cost has one Invoice Attachment even when its amount is split among cost centers. For file metadata, retrieve the parent record with GET /v1/events/sponsorships/info and read invoice_attachment. Use this download method for the contents. No attachment ID or invoice flag is needed. #### Download response A successful response contains the original uploaded file, with a safe download filename. API errors use the usual JSON response. If no invoice is attached, this method returns HTTP 404. Current record, financial and invoice permissions apply. A locked tab can still be read. Permitted downloads remain available on the Free plan. #### Files still being copied If this file is still being copied, the download returns HTTP 409 with file_copy_pending. Try the download again in a few minutes. #### Hidden tab If the Event's Sponsorships tab is hidden, this request returns HTTP 400 (not_allowed), and the message says the tab is hidden. Show the tab in ExhibitDay first. A locked tab can still be read. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X GET "https://api.exhibitday.com/v1/events/sponsorships/invoice_attachment/download?sponsorship_id=12345" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi mv response-body.tmp 'invoice.pdf' ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const response = await fetch("https://api.exhibitday.com/v1/events/sponsorships/invoice_attachment/download?sponsorship_id=12345", { method: "GET", headers: { Authorization: 'Bearer YOUR_API_KEY' } }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); await writeFile("invoice.pdf", new Uint8Array(await response.arrayBuffer())); ``` Example — Python: ```python import requests import json response = requests.request("GET", "https://api.exhibitday.com/v1/events/sponsorships/invoice_attachment/download?sponsorship_id=12345", headers={'Authorization': 'Bearer YOUR_API_KEY'}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') with open("invoice.pdf", 'wb') as destination: destination.write(response.content) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.exhibitday.com/v1/events/sponsorships/invoice_attachment/download?sponsorship_id=12345"); using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); await File.WriteAllBytesAsync("invoice.pdf", await response.Content.ReadAsByteArrayAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/sponsorships/invoice_attachment/download?sponsorship_id=12345")).header("Authorization", "Bearer YOUR_API_KEY"); HttpResponse response = HttpClient.newHttpClient().send(request.method("GET", HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); Files.write(Path.of("invoice.pdf"), response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); file_put_contents('invoice.pdf', $response); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/sponsorships/invoice_attachment/download?sponsorship_id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' File.binwrite('invoice.pdf', response.body) ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/sponsorships/invoice_attachment/download?sponsorship_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } if err := os.WriteFile("invoice.pdf", data, 0600); err != nil { log.Fatal(err) } fmt.Println("File saved") } ``` HTTP 200: Returns the original uploaded file as a private download, using a safe filename. If the file cannot be downloaded, the response contains the usual JSON API error instead. Media: application/octet-stream. The body is the authorized file's real bytes, not JSON or base64. Errors are JSON status responses; check HTTP status before saving the file. ### Add Sponsorship Invoice Attachment `POST https://api.exhibitday.com/v1/events/sponsorships/invoice_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=sponsorships#post-v1-events-sponsorships-invoice_attachment Adds one Invoice Attachment to this Sponsorship. You can attach an invoice, receipt or other payment document when no invoice file is currently attached. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | sponsorship_id | Number | Yes | The ID of the Sponsorship, from Retrieve Sponsorships (GET /v1/events/sponsorships) or its add response. | | | file | File (multipart) | Yes | The Invoice Attachment to upload. | Send exactly one complete, nonempty multipart/form-data file part named file. The supported extensions and current per-file limit are shown below; the complete request limit also includes multipart overhead. A missing or null file is invalid and does not remove an existing invoice. | | Idempotency-Key | String | No | A unique key for safely retrying this upload. | Optional HTTP header: 1 to 255 visible ASCII characters without spaces or commas. Retry the identical request with the same key to replay its first saved response. Use a new key for a different upload. | Declared schema for `file` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "string", "format": "binary", "x-maximum-bytes": 26214400, "x-allowed-extensions": [ "png", "jpg", "jpeg", "bmp", "gif", "pdf", "msg", "eml", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "rtf", "odp", "odt", "ods", "txt", "wks", "zip" ] } ``` #### Before you upload POST requires an empty invoice slot. If an invoice is already attached, the API returns HTTP 409; use PATCH to replace it. An Invoice Attachment is separate from the record's supporting File Attachments. Use the invoice control beside the Sponsorship's cost and payment details in the web app. #### After the upload The response's invoice_attachment contains the attached file's id, filename and attachment_created_timestamp. The amount, payment fields, cost-center breakdown and other files are unchanged. The upload is recorded in Event history. Attaching an invoice does not mark the record as paid. #### Access and retries A current upload-enabled plan, record and financial permissions, and an editable applicable tab are required. Each uploaded file must fit its supported type and size limits. expected_revision is not supported by this file method. If the save outcome cannot be confirmed, retrieve the current parent record with GET /v1/events/sponsorships/info and inspect invoice_attachment before deciding whether to retry. #### Hidden or locked tab If the Event's Sponsorships tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X POST "https://api.exhibitday.com/v1/events/sponsorships/invoice_attachment" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}" --form-string "sponsorship_id=12345" --form "file=@invoice.pdf;type=application/octet-stream") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi cat response-body.tmp ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const form = new FormData(); form.append("sponsorship_id", "12345"); form.append("file", new Blob([await readFile("invoice.pdf")], { type: "application/octet-stream" }), "invoice.pdf"); const response = await fetch("https://api.exhibitday.com/v1/events/sponsorships/invoice_attachment", { method: "POST", headers: { Authorization: 'Bearer YOUR_API_KEY' }, body: form }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); console.log(await response.json()); ``` Example — Python: ```python import requests import json from contextlib import ExitStack with ExitStack() as stack: files = [ ("file", ("invoice.pdf", stack.enter_context(open("invoice.pdf", 'rb')), "application/octet-stream")), ] response = requests.request("POST", "https://api.exhibitday.com/v1/events/sponsorships/invoice_attachment", headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data={"sponsorship_id": "12345"}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') print(response.json()) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.exhibitday.com/v1/events/sponsorships/invoice_attachment"); var form = new MultipartFormDataContent(); form.Add(new StringContent("12345"), "sponsorship_id"); var file0 = new StreamContent(File.OpenRead("invoice.pdf")); file0.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(file0, "file", "invoice.pdf"); request.Content = form; using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/sponsorships/invoice_attachment")).header("Authorization", "Bearer YOUR_API_KEY"); String boundary = "ExhibitDay-" + UUID.randomUUID(); ByteArrayOutputStream form = new ByteArrayOutputStream(); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"sponsorship_id\"\r\n\r\n" + "12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"invoice.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8)); form.write(Files.readAllBytes(Path.of("invoice.pdf"))); form.write("\r\n".getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); request.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpResponse response = HttpClient.newHttpClient().send(request.method("POST", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); System.out.println(new String(response.body(), StandardCharsets.UTF_8)); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], CURLOPT_POSTFIELDS => [ 'sponsorship_id' => '12345', 'file' => new CURLFile('invoice.pdf', 'application/octet-stream', 'invoice.pdf'), ], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); echo $response; ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/sponsorships/invoice_attachment') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' files = [] begin parts = [ ['sponsorship_id', '12345'], ['file', (files << File.open('invoice.pdf', 'rb')).last, {filename: 'invoice.pdf', content_type: 'application/octet-stream'}], ] request.set_form(parts, 'multipart/form-data') response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' puts response.body ensure files.each(&:close) end ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" "bytes" "mime/multipart" "net/textproto" ) func main() { var form bytes.Buffer writer := multipart.NewWriter(&form) if err := writer.WriteField("sponsorship_id", "12345"); err != nil { log.Fatal(err) } header0 := textproto.MIMEHeader{} header0.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"invoice.pdf\"") header0.Set("Content-Type", "application/octet-stream") part0, err := writer.CreatePart(header0) if err != nil { log.Fatal(err) } file0, err := os.Open("invoice.pdf") if err != nil { log.Fatal(err) } if _, err = io.Copy(part0, file0); err != nil { log.Fatal(err) } file0.Close() if err := writer.Close(); err != nil { log.Fatal(err) } request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/events/sponsorships/invoice_attachment", &form) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", writer.FormDataContentType()) response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } fmt.Printf("%s\n", data) } ``` Example HTTP response body (JSON): POST /v1/events/sponsorships/invoice_attachment - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "invoice_attachment": { "id": 12345, "filename": "invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } } ``` ### Replace Sponsorship Invoice Attachment `PATCH https://api.exhibitday.com/v1/events/sponsorships/invoice_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=sponsorships#patch-v1-events-sponsorships-invoice_attachment Replaces this Sponsorship's current Invoice Attachment with one uploaded file. Use this method when an invoice file is already attached. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | sponsorship_id | Number | Yes | The ID of the Sponsorship, from Retrieve Sponsorships (GET /v1/events/sponsorships) or its add response. | | | file | File (multipart) | Yes | The Invoice Attachment to upload. | Send exactly one complete, nonempty multipart/form-data file part named file. The supported extensions and current per-file limit are shown below; the complete request limit also includes multipart overhead. A missing or null file is invalid and does not remove an existing invoice. | Declared schema for `file` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "string", "format": "binary", "x-maximum-bytes": 26214400, "x-allowed-extensions": [ "png", "jpg", "jpeg", "bmp", "gif", "pdf", "msg", "eml", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "rtf", "odp", "odt", "ods", "txt", "wks", "zip" ] } ``` #### Replacing the current file PATCH requires a current invoice file. If none is attached, the API returns HTTP 404. Upload exactly one file; the previous attachment ID is not needed. If another request changes the current invoice during your upload, the API refuses this request instead of replacing a different file. Even identical replacement contents receive a new attachment ID. #### After the replacement The response's invoice_attachment contains the attached file's id, filename and attachment_created_timestamp. The amount, payment fields, cost-center breakdown and other files are unchanged. The previous file is scheduled for physical cleanup after a confirmed save; cleanup may finish later. The replacement is recorded in Event history. #### Access and retries A current upload-enabled plan, record and financial permissions, and an editable applicable tab are required. Each uploaded file must fit its supported type and size limits. expected_revision is not supported by this file method. PATCH does not use Idempotency-Key replay. If the save outcome cannot be confirmed, retrieve the current parent record with GET /v1/events/sponsorships/info and inspect invoice_attachment before deciding whether to retry. #### Hidden or locked tab If the Event's Sponsorships tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X PATCH "https://api.exhibitday.com/v1/events/sponsorships/invoice_attachment" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}" --form-string "sponsorship_id=12345" --form "file=@invoice.pdf;type=application/octet-stream") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi cat response-body.tmp ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const form = new FormData(); form.append("sponsorship_id", "12345"); form.append("file", new Blob([await readFile("invoice.pdf")], { type: "application/octet-stream" }), "invoice.pdf"); const response = await fetch("https://api.exhibitday.com/v1/events/sponsorships/invoice_attachment", { method: "PATCH", headers: { Authorization: 'Bearer YOUR_API_KEY' }, body: form }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); console.log(await response.json()); ``` Example — Python: ```python import requests import json from contextlib import ExitStack with ExitStack() as stack: files = [ ("file", ("invoice.pdf", stack.enter_context(open("invoice.pdf", 'rb')), "application/octet-stream")), ] response = requests.request("PATCH", "https://api.exhibitday.com/v1/events/sponsorships/invoice_attachment", headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data={"sponsorship_id": "12345"}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') print(response.json()) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("PATCH"), "https://api.exhibitday.com/v1/events/sponsorships/invoice_attachment"); var form = new MultipartFormDataContent(); form.Add(new StringContent("12345"), "sponsorship_id"); var file0 = new StreamContent(File.OpenRead("invoice.pdf")); file0.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(file0, "file", "invoice.pdf"); request.Content = form; using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/sponsorships/invoice_attachment")).header("Authorization", "Bearer YOUR_API_KEY"); String boundary = "ExhibitDay-" + UUID.randomUUID(); ByteArrayOutputStream form = new ByteArrayOutputStream(); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"sponsorship_id\"\r\n\r\n" + "12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"invoice.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8)); form.write(Files.readAllBytes(Path.of("invoice.pdf"))); form.write("\r\n".getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); request.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpResponse response = HttpClient.newHttpClient().send(request.method("PATCH", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); System.out.println(new String(response.body(), StandardCharsets.UTF_8)); } } ``` Example — PHP: ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], CURLOPT_POSTFIELDS => [ 'sponsorship_id' => '12345', 'file' => new CURLFile('invoice.pdf', 'application/octet-stream', 'invoice.pdf'), ], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); echo $response; ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/sponsorships/invoice_attachment') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' files = [] begin parts = [ ['sponsorship_id', '12345'], ['file', (files << File.open('invoice.pdf', 'rb')).last, {filename: 'invoice.pdf', content_type: 'application/octet-stream'}], ] request.set_form(parts, 'multipart/form-data') response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' puts response.body ensure files.each(&:close) end ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" "bytes" "mime/multipart" "net/textproto" ) func main() { var form bytes.Buffer writer := multipart.NewWriter(&form) if err := writer.WriteField("sponsorship_id", "12345"); err != nil { log.Fatal(err) } header0 := textproto.MIMEHeader{} header0.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"invoice.pdf\"") header0.Set("Content-Type", "application/octet-stream") part0, err := writer.CreatePart(header0) if err != nil { log.Fatal(err) } file0, err := os.Open("invoice.pdf") if err != nil { log.Fatal(err) } if _, err = io.Copy(part0, file0); err != nil { log.Fatal(err) } file0.Close() if err := writer.Close(); err != nil { log.Fatal(err) } request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/events/sponsorships/invoice_attachment", &form) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", writer.FormDataContentType()) response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } fmt.Printf("%s\n", data) } ``` Example HTTP response body (JSON): PATCH /v1/events/sponsorships/invoice_attachment - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "invoice_attachment": { "id": 12345, "filename": "invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } } ``` ### Remove Sponsorship Invoice Attachment `DELETE https://api.exhibitday.com/v1/events/sponsorships/invoice_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=sponsorships#delete-v1-events-sponsorships-invoice_attachment Removes this Sponsorship's Invoice Attachment. The cost, payment details and other File Attachments stay in place. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | sponsorship_id | Number | Yes | The ID of the Sponsorship, from Retrieve Sponsorships (GET /v1/events/sponsorships) or its add response. | | #### After the removal The Invoice Attachment is cleared and the removal is recorded in Event history. Its physical file is scheduled for cleanup after a confirmed save; cleanup may finish later. Costs, payment fields, cost-center allocations and supporting files stay unchanged. If no invoice is attached, DELETE returns HTTP 404 Not Found with the message "This Sponsorship has no invoice to remove." No saved data or history is changed. Current access and the record's binding are still checked. Do not send file parts with this request. #### Access and retries Current record, financial and invoice permissions and applicable tab-edit access are required. Permitted removals remain available on the Free plan. expected_revision is not supported, and DELETE does not use Idempotency-Key replay. If the save outcome cannot be confirmed, retrieve the current parent record with GET /v1/events/sponsorships/info and inspect invoice_attachment before deciding whether to retry. #### Hidden or locked tab If the Event's Sponsorships tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/events/sponsorships/invoice_attachment?sponsorship_id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/sponsorships/invoice_attachment?" + new URLSearchParams({ "sponsorship_id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/events/sponsorships/invoice_attachment", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"sponsorship_id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/events/sponsorships/invoice_attachment?sponsorship_id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/sponsorships/invoice_attachment?sponsorship_id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/sponsorships/invoice_attachment?sponsorship_id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/events/sponsorships/invoice_attachment?sponsorship_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/events/sponsorships/invoice_attachment - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Attachment removed.", "errors": [] } ``` ### Retrieve Sponsorship General File Attachments `GET https://api.exhibitday.com/v1/events/sponsorships/attachments` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=sponsorships#get-v1-events-sponsorships-attachments Retrieves the General File Attachments on this Sponsorship. Each result includes the file's ID, name and added time; use the download method for its contents. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | sponsorship_id | Number | Yes | The ID of the Sponsorship, from Retrieve Sponsorships (GET /v1/events/sponsorships) or its add response. | | | $limit | Number | No | The most File Attachments to return. | A positive whole number. Omit for all remaining matching files. | | $offset | Number | No | The number of matching File Attachments to skip. | A whole number of 0 or more. Default: 0. | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records. | Allowed values: `array` | | If-None-Match | String | No | An ETag from an earlier response to this GET. | Optional HTTP header. If the successful response is unchanged, the API returns HTTP 304 with no body. | #### Reading the file list Files are ordered by added time, then attachment ID, lowest first. Only files available under your current access are included. Paging totals and X-Total-Count count all matching files before $limit and $offset are applied. A record with no files you can view returns an empty list. This list does not return edit revisions or support changed-since filtering. #### Supporting files and invoices These are the record's General File Attachments. Its cost Invoice Attachment is separate and has its own download and upload methods. Use this list's id values for these supporting-file downloads and removals. #### Access The record's Event and tab must be available, and the tab must not be hidden. A locked tab can still be read. #### Hidden tab If the Event's Sponsorships tab is hidden, this request returns HTTP 400 (not_allowed), and the message says the tab is hidden. Show the tab in ExhibitDay first. A locked tab can still be read. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/events/sponsorships/attachments?sponsorship_id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/sponsorships/attachments?" + new URLSearchParams({ "sponsorship_id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/events/sponsorships/attachments", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"sponsorship_id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/events/sponsorships/attachments?sponsorship_id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/sponsorships/attachments?sponsorship_id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/sponsorships/attachments?sponsorship_id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/sponsorships/attachments?sponsorship_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/events/sponsorships/attachments - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "attachment", "list_data": [ { "id": 12345, "filename": "attachment.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } ] } ``` ### Add Sponsorship General File Attachments `POST https://api.exhibitday.com/v1/events/sponsorships/attachments` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=sponsorships#post-v1-events-sponsorships-attachments Adds one or more General File Attachments to this Sponsorship. Send each file as a multipart upload part named file. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | sponsorship_id | Number | Yes | The ID of the Sponsorship, from Retrieve Sponsorships (GET /v1/events/sponsorships) or its add response. | | | file | File (multipart) | Yes | The File Attachments to upload. | Send one or more complete, nonempty multipart/form-data parts, each named file. Supported types and the current per-file limit are shown below. The complete request limit includes all files and multipart overhead; split larger batches. A missing or null upload is not a removal request. | | Idempotency-Key | String | No | A unique key for safely retrying this upload. | Optional HTTP header: 1 to 255 visible ASCII characters without spaces or commas. Retry the identical request with the same key to replay its first saved response. Use a new key for a different upload. | Declared schema for `file` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "array", "items": { "type": "string", "format": "binary", "x-maximum-bytes": 26214400, "x-allowed-extensions": [ "png", "jpg", "jpeg", "bmp", "gif", "pdf", "msg", "eml", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "rtf", "odp", "odt", "ods", "txt", "wks", "zip" ] } } ``` #### After the upload The response's list_data contains the newly attached files, including each id, filename and attachment_created_timestamp. Existing files are kept. Use each returned id to download or remove that file. Identical repeated files in one request are attached once when their cleaned filename, length and contents match. Files with different contents remain separate even when their names match. This does not remove or replace files already attached to the record. #### Choosing the right file method These uploads add General File Attachments. Use this record's Invoice Attachment methods for its cost invoice or receipt. Adding supporting files does not change amounts, payments or cost-center allocations. #### Access Current record and file-change permissions and applicable Event/tab locks must allow this upload. An upload-enabled paid plan is required. #### History and retries A confirmed file change is recorded in history. expected_revision is not supported by these file methods. If the save outcome cannot be confirmed, retrieve the current file list before deciding whether to retry; the API does not automatically repeat an uncertain change. Supporting File Attachments have no PATCH replacement. To replace one, add the new file and remove the old one using their separate requests; each request has its own outcome. #### Hidden or locked tab If the Event's Sponsorships tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X POST "https://api.exhibitday.com/v1/events/sponsorships/attachments" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}" --form-string "sponsorship_id=12345" --form "file=@attachment.pdf;type=application/octet-stream") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi cat response-body.tmp ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const form = new FormData(); form.append("sponsorship_id", "12345"); form.append("file", new Blob([await readFile("attachment.pdf")], { type: "application/octet-stream" }), "attachment.pdf"); const response = await fetch("https://api.exhibitday.com/v1/events/sponsorships/attachments", { method: "POST", headers: { Authorization: 'Bearer YOUR_API_KEY' }, body: form }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); console.log(await response.json()); ``` Example — Python: ```python import requests import json from contextlib import ExitStack with ExitStack() as stack: files = [ ("file", ("attachment.pdf", stack.enter_context(open("attachment.pdf", 'rb')), "application/octet-stream")), ] response = requests.request("POST", "https://api.exhibitday.com/v1/events/sponsorships/attachments", headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data={"sponsorship_id": "12345"}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') print(response.json()) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.exhibitday.com/v1/events/sponsorships/attachments"); var form = new MultipartFormDataContent(); form.Add(new StringContent("12345"), "sponsorship_id"); var file0 = new StreamContent(File.OpenRead("attachment.pdf")); file0.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(file0, "file", "attachment.pdf"); request.Content = form; using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/sponsorships/attachments")).header("Authorization", "Bearer YOUR_API_KEY"); String boundary = "ExhibitDay-" + UUID.randomUUID(); ByteArrayOutputStream form = new ByteArrayOutputStream(); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"sponsorship_id\"\r\n\r\n" + "12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"attachment.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8)); form.write(Files.readAllBytes(Path.of("attachment.pdf"))); form.write("\r\n".getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); request.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpResponse response = HttpClient.newHttpClient().send(request.method("POST", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); System.out.println(new String(response.body(), StandardCharsets.UTF_8)); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], CURLOPT_POSTFIELDS => [ 'sponsorship_id' => '12345', 'file' => new CURLFile('attachment.pdf', 'application/octet-stream', 'attachment.pdf'), ], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); echo $response; ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/sponsorships/attachments') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' files = [] begin parts = [ ['sponsorship_id', '12345'], ['file', (files << File.open('attachment.pdf', 'rb')).last, {filename: 'attachment.pdf', content_type: 'application/octet-stream'}], ] request.set_form(parts, 'multipart/form-data') response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' puts response.body ensure files.each(&:close) end ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" "bytes" "mime/multipart" "net/textproto" ) func main() { var form bytes.Buffer writer := multipart.NewWriter(&form) if err := writer.WriteField("sponsorship_id", "12345"); err != nil { log.Fatal(err) } header0 := textproto.MIMEHeader{} header0.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"attachment.pdf\"") header0.Set("Content-Type", "application/octet-stream") part0, err := writer.CreatePart(header0) if err != nil { log.Fatal(err) } file0, err := os.Open("attachment.pdf") if err != nil { log.Fatal(err) } if _, err = io.Copy(part0, file0); err != nil { log.Fatal(err) } file0.Close() if err := writer.Close(); err != nil { log.Fatal(err) } request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/events/sponsorships/attachments", &form) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", writer.FormDataContentType()) response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } fmt.Printf("%s\n", data) } ``` Example HTTP response body (JSON): POST /v1/events/sponsorships/attachments - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "attachment", "list_data": [ { "id": 12345, "filename": "attachment.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } ] } ``` ### Remove a Sponsorship General File Attachment `DELETE https://api.exhibitday.com/v1/events/sponsorships/attachments` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=sponsorships#delete-v1-events-sponsorships-attachments Removes one General File Attachment from this Sponsorship. Other attached files and the record's details stay in place. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the File Attachment. | Use the id from the attachment list. The API finds the record the file belongs to, so no record ID is sent. An Invoice Attachment is not selected by this method. | #### After the removal Only the selected file association is removed. Its physical file is scheduled for cleanup after a confirmed save; cleanup may finish later. Other attached files stay in place. Send only the file's id; the API finds the record it belongs to. A missing, already removed or unavailable attachment returns HTTP 404 Not Found. Do not send file parts with DELETE. #### Access Current record and file-removal permissions and applicable Event/tab locks must allow this change. Permitted removals remain available on the Free plan. #### History and retries A confirmed file change is recorded in history. expected_revision is not supported by these file methods. DELETE does not use Idempotency-Key replay. If the save outcome cannot be confirmed, retrieve the current file list before deciding whether to retry; the API does not automatically repeat an uncertain change. Supporting File Attachments have no PATCH replacement. To replace one, add the new file and remove the old one using their separate requests; each request has its own outcome. #### Hidden or locked tab If the Event's Sponsorships tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/events/sponsorships/attachments?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/sponsorships/attachments?" + new URLSearchParams({ "id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/events/sponsorships/attachments", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/events/sponsorships/attachments?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/sponsorships/attachments?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/sponsorships/attachments?id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/events/sponsorships/attachments?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/events/sponsorships/attachments - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Attachment removed.", "errors": [] } ``` ### Download a Sponsorship General File Attachment `GET https://api.exhibitday.com/v1/events/sponsorships/attachments/download` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=sponsorships#get-v1-events-sponsorships-attachments-download Downloads one original General File Attachment from this Sponsorship. Select the file using its ID from the attachment list. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the File Attachment. | Use the id from the attachment list. The API finds the record the file belongs to, so no record ID is sent. An Invoice Attachment is not selected by this method. | #### Download response A successful response contains the original uploaded file with a safe download filename. API errors use the usual JSON response. A missing or unavailable file returns HTTP 404. Send only the file's id from the attachment list to download that one file; the API finds the record it belongs to. The download leaves the record unchanged. #### Access The record's Event and tab must be available, and the tab must not be hidden. A locked tab can still be read. #### Files still being copied If this file is still being copied, the download returns HTTP 409 with file_copy_pending. Try the download again in a few minutes. #### Hidden tab If the Event's Sponsorships tab is hidden, this request returns HTTP 400 (not_allowed), and the message says the tab is hidden. Show the tab in ExhibitDay first. A locked tab can still be read. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X GET "https://api.exhibitday.com/v1/events/sponsorships/attachments/download?id=12345" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi mv response-body.tmp 'attachment.pdf' ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const response = await fetch("https://api.exhibitday.com/v1/events/sponsorships/attachments/download?id=12345", { method: "GET", headers: { Authorization: 'Bearer YOUR_API_KEY' } }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); await writeFile("attachment.pdf", new Uint8Array(await response.arrayBuffer())); ``` Example — Python: ```python import requests import json response = requests.request("GET", "https://api.exhibitday.com/v1/events/sponsorships/attachments/download?id=12345", headers={'Authorization': 'Bearer YOUR_API_KEY'}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') with open("attachment.pdf", 'wb') as destination: destination.write(response.content) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.exhibitday.com/v1/events/sponsorships/attachments/download?id=12345"); using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); await File.WriteAllBytesAsync("attachment.pdf", await response.Content.ReadAsByteArrayAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/sponsorships/attachments/download?id=12345")).header("Authorization", "Bearer YOUR_API_KEY"); HttpResponse response = HttpClient.newHttpClient().send(request.method("GET", HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); Files.write(Path.of("attachment.pdf"), response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); file_put_contents('attachment.pdf', $response); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/sponsorships/attachments/download?id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' File.binwrite('attachment.pdf', response.body) ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/sponsorships/attachments/download?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } if err := os.WriteFile("attachment.pdf", data, 0600); err != nil { log.Fatal(err) } fmt.Println("File saved") } ``` HTTP 200: Returns the original uploaded file as a private download, using a safe filename. If the file cannot be downloaded, the response contains the usual JSON API error instead. Media: application/octet-stream. The body is the authorized file's real bytes, not JSON or base64. Errors are JSON status responses; check HTTP status before saving the file. ## Events - Playbook The Event Playbook: scheduled activities, activity costs, invoices, file attachments and exports. Documentation page: https://api.exhibitday.com/Help/V1?epf=1&topic=playbook ### Retrieve a Single Playbook Activity by ID `GET https://api.exhibitday.com/v1/events/playbook_activities/info` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=playbook#get-v1-events-playbook_activities-info Retrieves one Playbook activity, including its schedule, details and tagged people. Costs and invoices use their separate methods. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Playbook activity. | | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` \| `object` | | $include_record_revision | Boolean | No | Set to true to include record_revision in the response. Send that value as expected_revision when updating to check for conflicting changes. | Default: false. | | $on_error_return_empty_result | Boolean | No | For missing or invalid IDs, or a record unavailable in this event, return HTTP 200 with {} (or [] in array format). Current-key failures, a record that changes while it is read and unexpected errors keep their normal error status. | | #### Formatted text in the response Notes and other rich-text values in the response contain the stored HTML, including encoded characters and line breaks such as `
`. #### Open in ExhibitDay Each record includes exhibitday_url, the record's page in ExhibitDay. It opens the record in view mode on its Event's tab. Sign in with an account that can view the record; ExhibitDay checks access when the link is opened. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/events/playbook_activities/info?id=34567" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/playbook_activities/info?" + new URLSearchParams({ "id": "34567" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/events/playbook_activities/info", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 34567}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/events/playbook_activities/info?id=34567"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/playbook_activities/info?id=34567")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/playbook_activities/info?id=34567') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/playbook_activities/info?id=34567", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/events/playbook_activities/info - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "id": 34567, "event_id": 23456, "event_name": "Sample Event", "title": "Team briefing", "description": null, "activity_type_id": 1, "activity_status_id": 1, "our_role_id": null, "day_type_id": 1, "day_number": 1, "is_all_day": true, "start_time": null, "end_time": null, "timezone": "", "location": null, "tagged_users": [ { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, { "id": "66666666-7777-4888-8999-aaaaaaaaaaaa", "first_name": "Alex", "last_name": "Morgan", "display_name": "Alex Morgan", "email": "alex@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true } ], "created_by": { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, "booth_operations": null, "meeting": null, "presentation": null, "networking": null, "meal_break": null, "registration": null, "special_event": null, "planning": null, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=23456&riType=2&riSub=0&riId=34567", "related_items": [ { "id": 5551, "related_item_id": 67890, "related_item_exhibitday_url": "https://www.exhibitday.com/Workspace/TaskView/98765?tid=67890", "related_item_type_id": 1, "related_item_type": "Task", "related_item_asset_type_id": null, "related_item_name": "Confirm booth graphics with the printer", "related_item_created_timestamp": "2030-01-10T14:03:00Z" }, { "id": 5552, "related_item_id": 45678, "related_item_exhibitday_url": "https://www.exhibitday.com/Workspace/RelatedItemView/98765?typeId=4&subTypeId=0&rid=45678", "related_item_type_id": 4, "related_item_type": "Shipment", "related_item_asset_type_id": null, "related_item_name": "Booth crates to convention center", "related_item_created_timestamp": "2030-01-10T14:03:00Z" } ] } ``` ### Retrieve Playbook Activities `GET https://api.exhibitday.com/v1/events/playbook_activities` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=playbook#get-v1-events-playbook_activities Lists Playbook activities in the Events you can read. Use Event and tagged-user filters to narrow the results. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | filter_by_event_id | Number | No | Return records for this Event only. Omit for all readable Events in your workspace. | | | filter_by_tagged_user_ids | String or JSON array | No | Return records tagged with these users or resources. Send one user ID or an array of user IDs, for example "user-id" or ["user-id","other-user-id"]. Omit, leave blank or send [] for no tagged-user filter. Duplicate IDs collapse. Inactive and deactivated people, and people no longer in this workspace, still match the records they are tagged on; IDs never tagged in this workspace match nothing. Use filter_by_tagged_user_ids_match_type to require at least one or every selected person. This filter combines with the other filters before counting and paging. | | | filter_by_tagged_user_ids_match_type | String | No | How to match the selected tagged people. Omit or leave blank to return records tagged with at least one selected person (the default), or require every selected person; records can have other tags too. This combines with the other filters before counting and paging. If filter_by_tagged_user_ids has no IDs, this option is ignored and the response includes a warning. Values are case-insensitive. | Allowed values: `any` \| `all` | | $limit | Number | No | The most records to return, as a positive whole number. Omit for all remaining records. | | | $offset | Number | No | How many records to skip: a whole number of 0 or more; 0 by default. | | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | Declared schema for `filter_by_tagged_user_ids` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "oneOf": [ { "type": "string", "minLength": 1, "maxLength": 128, "pattern": "\\S" }, { "type": "array", "items": { "type": "string", "minLength": 1, "maxLength": 128, "pattern": "\\S" } } ], "x-normalization": "one string becomes a one-item array; trimmed distinct IDs; no record-count cap", "nullable": false, "x-maximum-depth": 1, "x-empty-create-means-omitted": false, "example": [ "user-id" ] } ``` #### Filtering and paging Omit filter_by_event_id for all readable Events in your workspace. A supplied Event that is missing or unavailable returns an empty list with a warning. A readable Event with no matching activities returns an empty list without that warning. Event and tagged-user filters combine with AND before counts and paging. any matches at least one selected person; all requires every selected person and permits extra tags. Inactive and deactivated people, and people no longer in this workspace, still match the activities they are tagged on; IDs never tagged match nothing. Sending filter_by_tagged_user_ids_match_type without IDs is ignored with a warning. The list is ordered by activity ID. Omit $limit for all remaining matching activities; $offset defaults to 0. Each returned activity carries its own event_id and Event name. Costs are managed through the separate activity-cost methods. #### Formatted text in the response Notes and other rich-text values in the response contain the stored HTML, including encoded characters and line breaks such as `
`. #### Events with a hidden Playbook tab Records on Events whose Playbook tab is hidden are not listed. If filter_by_event_id names such an Event, the response is HTTP 200 with no records for it and a warning that names the tab and the Event. #### Open in ExhibitDay Each record includes exhibitday_url, the record's page in ExhibitDay. It opens the record in view mode on its Event's tab. Sign in with an account that can view the record; ExhibitDay checks access when the link is opened. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/events/playbook_activities" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/playbook_activities", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/events/playbook_activities", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/events/playbook_activities"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/playbook_activities")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/playbook_activities') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/playbook_activities", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/events/playbook_activities - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "list_type": "playbook_activity", "list_data": [ { "id": 12345, "event_id": 23456, "event_name": "Sample Event", "title": "Team briefing", "description": null, "activity_type_id": 1, "activity_status_id": 1, "our_role_id": null, "day_type_id": 1, "day_number": 1, "is_all_day": true, "start_time": null, "end_time": null, "timezone": "", "location": null, "tagged_users": [ { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, { "id": "66666666-7777-4888-8999-aaaaaaaaaaaa", "first_name": "Alex", "last_name": "Morgan", "display_name": "Alex Morgan", "email": "alex@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true } ], "created_by": { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, "booth_operations": null, "meeting": null, "presentation": null, "networking": null, "meal_break": null, "registration": null, "special_event": null, "planning": null, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=23456&riType=2&riSub=0&riId=12345" } ], "records_found": 1, "total_records": 1, "has_more": false } ``` ### Add a Playbook Activity `POST https://api.exhibitday.com/v1/events/playbook_activities` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=playbook#post-v1-events-playbook_activities Adds a scheduled activity to an Event's Playbook. The response includes the new activity and its ID. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | event_id | Number | Yes | The ID of the Event in your workspace. | | | title | String | Yes | A short title for the scheduled activity, up to 500 characters. This is required on create and cannot be cleared. | Max length: 500. | | day_type_id | Number | Yes | Where the scheduled day falls relative to the Event. Required when adding an activity; combine it with day_number and choose a day currently available in the Event's Playbook. All Pages is a display choice and cannot be saved. | Allowed values: `1` (Event Day) \| `2` (Days Before the Event) \| `3` (Days After the Event) | | day_number | Number | Yes | The positive day number within the selected day type. New activities and day changes must use a day available in this event's Playbook. An existing activity may keep its own older unresolved day while you edit other fields. | | | description | String | No | Accepts plain text; line breaks are retained. The saved text and its representation in the ExhibitDay editor must each fit within 30,000 characters, including formatting and encoded characters. Older text over the limit may be kept or shortened, but cannot grow. On PATCH, an omitted or blank whole parameter keeps its value; null clears it. | Max length: 30000. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | location | String | No | The activity location, up to 200 characters. | Max length: 200. | | timezone | String | No | The time-zone label displayed beside the activity's times, up to 20 characters. This does not convert the clock readings. All-day activities clear this label. | Max length: 20. | | activity_type_id | Number | No | Use an id from GET /v1/references/playbook_activity_types. The default on create is General — Other (1). | | | activity_status_id | Number | No | Whether the activity is Confirmed (1), Tentative (2) or Canceled (3). The default on create is Confirmed. This is independent of proposal, registration and payment statuses. | | | our_role_id | Number | No | Your team's role in the activity. The available choices depend on the activity type. Omit to use that type's default. A supplied role that does not apply, including null, becomes the type's default; types with no role store no role. | Allowed values: `1` (Attending; Attending / Participating for Special Event activities) \| `2` (Hosting / Organizing) \| `3` (Presenting / Participating) | | is_all_day | Boolean | No | Use true for an all-day activity, or false for a specific start and end time. The default on create is true. All-day activities have no start time, end time or time zone. | Default: true. | | start_time | String | No | A time of day, such as 09:30 or 2:30 PM, without a date or UTC offset. A specific-time activity needs both times. An end before the start is swapped with the start; it does not create an overnight activity. | | | end_time | String | No | A time of day, such as 09:30 or 2:30 PM, without a date or UTC offset. A specific-time activity needs both times. An end before the start is swapped with the start; it does not create an overnight activity. | | | booth_operations | JSON object/list | No | The Booth Operations fields shown for this activity type. Send an object using the fields listed below. On PATCH, omitted members keep their current values; JSON null clears a member, and an empty text member clears its text. Within the object, the text "null" remains literal text. The current type, role and related choices decide which fields apply; values that no longer apply are cleared. A filled member that this type or role does not use is not saved, and the response warns about that member by name. Changing category removes the other category's details. A blank whole parameter keeps the section; null clears its fields. The ignore-empty option applies to a whole JSON-null parameter, not to members of a supplied object. Rich-text fields accept plain text; line breaks are retained. The saved text and its representation in the ExhibitDay editor must each fit within 30,000 characters, including formatting and encoded characters. Older text over the limit may be kept or shortened, but cannot grow. On PATCH, an omitted or blank whole parameter keeps its value; null clears it. | | | booth_operations.inspection_result_id | integer or null | No | Inspection Result. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `1` (Pending) \| `2` (Passed) \| `3` (Corrections Required) \| `4` (Failed) | | booth_operations.execution_status_id | integer or null | No | Execution Status. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `1` (Not Started) \| `2` (In Progress) \| `3` (Completed) \| `4` (Blocked) | | booth_operations.staffing_status_id | integer or null | No | Staffing Status. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `1` (Not Started) \| `2` (In Progress) \| `3` (Fully Staffed) \| `4` (Issue / Blocked) | | meeting | JSON object/list | No | The Meeting fields shown for this activity type. Send an object using the fields listed below. On PATCH, omitted members keep their current values; JSON null clears a member, and an empty text member clears its text. Within the object, the text "null" remains literal text. The current type, role and related choices decide which fields apply; values that no longer apply are cleared. A filled member that this type or role does not use is not saved, and the response warns about that member by name. Changing category removes the other category's details. A blank whole parameter keeps the section; null clears its fields. The ignore-empty option applies to a whole JSON-null parameter, not to members of a supplied object. Rich-text fields accept plain text; line breaks are retained. The saved text and its representation in the ExhibitDay editor must each fit within 30,000 characters, including formatting and encoded characters. Older text over the limit may be kept or shortened, but cannot grow. On PATCH, an omitted or blank whole parameter keeps its value; null clears it. | | | meeting.meeting_format_id | integer or null | No | Meeting Format. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `1` (In-Person) \| `2` (Virtual) \| `3` (Phone) \| `4` (Hybrid) | | presentation | JSON object/list | No | The Presentation fields shown for this activity type. Send an object using the fields listed below. On PATCH, omitted members keep their current values; JSON null clears a member, and an empty text member clears its text. Within the object, the text "null" remains literal text. The current type, role and related choices decide which fields apply; values that no longer apply are cleared. A filled member that this type or role does not use is not saved, and the response warns about that member by name. Changing category removes the other category's details. A blank whole parameter keeps the section; null clears its fields. The ignore-empty option applies to a whole JSON-null parameter, not to members of a supplied object. Rich-text fields accept plain text; line breaks are retained. The saved text and its representation in the ExhibitDay editor must each fit within 30,000 characters, including formatting and encoded characters. Older text over the limit may be kept or shortened, but cannot grow. On PATCH, an omitted or blank whole parameter keeps its value; null clears it. | | | presentation.room_setup_id | integer or null | No | Room Setup. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `1` (Theater) \| `2` (Classroom) \| `3` (Boardroom) \| `4` (Panel Table) \| `5` (U-Shape) \| `6` (Demo Area) \| `7` (Other) \| `8` (Rounds / Banquet) \| `9` (Poster Boards / Stations) | | presentation.submission_status_id | integer or null | No | Submission Status. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `1` (Draft) \| `2` (Not Submitted) \| `3` (Submitted) \| `4` (Under Review) \| `5` (Accepted) \| `6` (Rejected) \| `7` (Withdrawn) | | presentation.rehearsal_status_id | integer or null | No | Rehearsal Status. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `1` (Not Scheduled) \| `2` (Scheduled) \| `3` (Completed) \| `4` (Canceled) | | presentation.session_format_id | integer or null | No | Session Format. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `1` (In-Person) \| `2` (Virtual) \| `3` (Hybrid) | | networking | JSON object/list | No | The Networking fields shown for this activity type. Send an object using the fields listed below. On PATCH, omitted members keep their current values; JSON null clears a member, and an empty text member clears its text. Within the object, the text "null" remains literal text. The current type, role and related choices decide which fields apply; values that no longer apply are cleared. A filled member that this type or role does not use is not saved, and the response warns about that member by name. Changing category removes the other category's details. A blank whole parameter keeps the section; null clears its fields. The ignore-empty option applies to a whole JSON-null parameter, not to members of a supplied object. Rich-text fields accept plain text; line breaks are retained. The saved text and its representation in the ExhibitDay editor must each fit within 30,000 characters, including formatting and encoded characters. Older text over the limit may be kept or shortened, but cannot grow. On PATCH, an omitted or blank whole parameter keeps its value; null clears it. | | | networking.rsvp_status_id | integer or null | No | RSVP Status. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `8` (Not Started) \| `9` (In Progress) \| `10` (Completed) \| `11` (Issue / Blocked) | | networking.access_level_id | integer or null | No | Access Level. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `1` (General Admission) \| `2` (Exhibitor) \| `3` (Speaker) \| `4` (Sponsor) \| `5` (VIP) \| `7` (Other) \| `8` (Staff) \| `9` (Press / Media) | | networking.attendance_priority_id | integer or null | No | Attendance Priority. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `1` (Optional) \| `2` (Recommended) \| `3` (Required) | | networking.dress_code_id | integer or null | No | Dress Code. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `1` (Casual) \| `2` (Business Casual) \| `3` (Business Formal) \| `4` (Cocktail) \| `5` (Black Tie) \| `6` (Company-Branded Apparel) \| `7` (Other) | | meal_break | JSON object/list | No | The Meal Break fields shown for this activity type. Send an object using the fields listed below. On PATCH, omitted members keep their current values; JSON null clears a member, and an empty text member clears its text. Within the object, the text "null" remains literal text. The current type, role and related choices decide which fields apply; values that no longer apply are cleared. A filled member that this type or role does not use is not saved, and the response warns about that member by name. Changing category removes the other category's details. A blank whole parameter keeps the section; null clears its fields. The ignore-empty option applies to a whole JSON-null parameter, not to members of a supplied object. Rich-text fields accept plain text; line breaks are retained. The saved text and its representation in the ExhibitDay editor must each fit within 30,000 characters, including formatting and encoded characters. Older text over the limit may be kept or shortened, but cannot grow. On PATCH, an omitted or blank whole parameter keeps its value; null clears it. | | | meal_break.purpose_id | integer or null | No | Purpose. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `1` (Personal / Routine) \| `2` (Team / Internal) \| `3` (Customer / Prospect Engagement) \| `4` (Partner / Vendor Engagement) \| `6` (Other) \| `7` (Networking / Relationship Building) \| `8` (Working / Planning) \| `9` (Hospitality / VIP) \| `10` (Celebration / Recognition) | | meal_break.reservation_status_id | integer or null | No | Reservation Status. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `1` (Not Required) \| `2` (Requested / Pending) \| `3` (Confirmed) \| `4` (Waitlisted) \| `5` (Canceled) \| `6` (Not Yet Reserved) | | meal_break.seating_arrangement_id | integer or null | No | Seating Arrangement. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `1` (Private Room) \| `2` (Reserved Table) \| `3` (Assigned Seating) \| `4` (Open Seating) \| `5` (Other) | | registration | JSON object/list | No | The Registration fields shown for this activity type. Send an object using the fields listed below. On PATCH, omitted members keep their current values; JSON null clears a member, and an empty text member clears its text. Within the object, the text "null" remains literal text. The current type, role and related choices decide which fields apply; values that no longer apply are cleared. A filled member that this type or role does not use is not saved, and the response warns about that member by name. Changing category removes the other category's details. A blank whole parameter keeps the section; null clears its fields. The ignore-empty option applies to a whole JSON-null parameter, not to members of a supplied object. Rich-text fields accept plain text; line breaks are retained. The saved text and its representation in the ExhibitDay editor must each fit within 30,000 characters, including formatting and encoded characters. Older text over the limit may be kept or shortened, but cannot grow. On PATCH, an omitted or blank whole parameter keeps its value; null clears it. | | | registration.status_id | integer or null | No | Status. Check-in / Registration offers 6 Not Checked In, 7 Checked In and 12 Issue / Blocked. Other offers 1 Not Started, 2 In Progress, 11 Completed and 12 Issue / Blocked. Send a JSON integer from the current activity type's choices, or JSON null for no choice. Changing the activity type can clear a status that no longer applies. | Allowed values: `1` (Not Started) \| `2` (In Progress) \| `6` (Not Checked In) \| `7` (Checked In) \| `11` (Completed) \| `12` (Issue / Blocked) | | special_event | JSON object/list | No | The Special Event fields shown for this activity type. Send an object using the fields listed below. On PATCH, omitted members keep their current values; JSON null clears a member, and an empty text member clears its text. Within the object, the text "null" remains literal text. The current type, role and related choices decide which fields apply; values that no longer apply are cleared. A filled member that this type or role does not use is not saved, and the response warns about that member by name. Changing category removes the other category's details. A blank whole parameter keeps the section; null clears its fields. The ignore-empty option applies to a whole JSON-null parameter, not to members of a supplied object. Rich-text fields accept plain text; line breaks are retained. The saved text and its representation in the ExhibitDay editor must each fit within 30,000 characters, including formatting and encoded characters. Older text over the limit may be kept or shortened, but cannot grow. On PATCH, an omitted or blank whole parameter keeps its value; null clears it. | | | special_event.staffing_status_id | integer or null | No | Staffing Status. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `1` (Not Started) \| `2` (In Progress) \| `3` (Fully Staffed) \| `4` (Issue / Blocked) | | special_event.participant_registration_status_id | integer or null | No | Participant Registration Status. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `1` (Not Started) \| `2` (In Progress) \| `11` (Completed) \| `12` (Issue / Blocked) | | special_event.participant_waiver_status_id | integer or null | No | Participant Waiver Status. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `2` (In Progress) \| `3` (Completed) \| `4` (Not Started) \| `5` (Issue / Blocked) | | special_event.waiver_status_id | integer or null | No | Waiver Status. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `2` (In Progress) \| `3` (Completed) \| `4` (Not Started) \| `5` (Issue / Blocked) | | special_event.registration_status_id | integer or null | No | Registration Status. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `1` (Not Started) \| `2` (In Progress) \| `11` (Completed) \| `12` (Issue / Blocked) | | planning | JSON object/list | No | The Planning fields shown for this activity type. Send an object using the fields listed below. On PATCH, omitted members keep their current values; JSON null clears a member, and an empty text member clears its text. Within the object, the text "null" remains literal text. The current type, role and related choices decide which fields apply; values that no longer apply are cleared. A filled member that this type or role does not use is not saved, and the response warns about that member by name. Changing category removes the other category's details. Planning contacts are free text; they do not tag users or send notifications. A blank whole parameter keeps the section; null clears its fields. The ignore-empty option applies to a whole JSON-null parameter, not to members of a supplied object. Rich-text fields accept plain text; line breaks are retained. The saved text and its representation in the ExhibitDay editor must each fit within 30,000 characters, including formatting and encoded characters. Older text over the limit may be kept or shortened, but cannot grow. On PATCH, an omitted or blank whole parameter keeps its value; null clears it. | | | tagged_user_ids | JSON object/list | No | The full list of people tagged in this activity, as an array of unique user IDs from your workspace's active users and resources. Omit it to keep the current people; null or [] removes all tags. Existing tags keep their notification state. Newly tagged people receive the usual assignment notification only when notify_tagged_users is true and their account and email settings allow it. Existing tags keep their notification state. | | | notify_tagged_users | Boolean | No | Whether newly tagged people may receive the usual assignment email. Omit this option or leave it blank for true. Send false to suppress the new notifications from this request. Existing tags keep their notification state; this option does not resend or cancel earlier notifications. JSON null is refused, even with the ignore-empty option. Delivery still depends on each person's current account, access and email settings. | Default: true. | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` \| `object` | Declared schema for `booth_operations` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "area_or_station": { "type": "string", "description": "Area Or Station. Optional text, up to 200 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "required_headcount": { "type": "string", "description": "Required Headcount. Optional text, up to 150 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "team_staffing_requirements": { "type": "string", "description": "Team Staffing Requirements. Optional text, up to 150 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "on_site_contact_name": { "type": "string", "description": "On Site Contact Name. Optional text, up to 200 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "on_site_contact_phone": { "type": "string", "description": "On Site Contact Phone. Optional text, up to 50 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "on_site_contact_email": { "type": "string", "description": "On Site Contact Email. Optional text, up to 320 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "materials_equipment": { "type": "string", "description": "Materials Equipment. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "handoff_instructions": { "type": "string", "description": "Handoff Instructions. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "blocking_issue": { "type": "string", "description": "Blocking Issue. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "inspection_result_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4 ], "description": "Inspection Result. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `1` (Pending) | `2` (Passed) | `3` (Corrections Required) | `4` (Failed)", "nullable": true }, "inspection_scope_type": { "type": "string", "description": "Inspection Scope Type. Optional text, up to 200 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "issues_deficiencies": { "type": "string", "description": "Issues Deficiencies. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "corrective_action_follow_up": { "type": "string", "description": "Corrective Action Followup. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "execution_status_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4 ], "description": "Execution Status. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `1` (Not Started) | `2` (In Progress) | `3` (Completed) | `4` (Blocked)", "nullable": true }, "staffing_status_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4 ], "description": "Staffing Status. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `1` (Not Started) | `2` (In Progress) | `3` (Fully Staffed) | `4` (Issue / Blocked)", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 2, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `meeting` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "meeting_format_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4 ], "description": "Meeting Format. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `1` (In-Person) | `2` (Virtual) | `3` (Phone) | `4` (Hybrid)", "nullable": true }, "organization": { "type": "string", "description": "Organization. Optional text, up to 300 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "virtual_meeting_url": { "type": "string", "description": "Virtual Meeting URL. Optional text, up to 1000 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "purpose": { "type": "string", "description": "Purpose. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "agenda": { "type": "string", "description": "Agenda. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "preparation_requirements": { "type": "string", "description": "Preparation Requirements. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "desired_outcome": { "type": "string", "description": "Desired Outcome. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "actual_outcome": { "type": "string", "description": "Actual Outcome. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "next_steps": { "type": "string", "description": "Next Steps. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "follow_up_date": { "type": "string", "description": "Follow Up Date. Use YYYY-MM-DD, without a time or time zone. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "format": "date", "nullable": true }, "external_attendees": { "type": "string", "description": "External Attendees. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 2, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `presentation` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "session_number": { "type": "string", "description": "Session Number. Optional text, up to 100 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "track": { "type": "string", "description": "Track. Optional text, up to 200 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "organizer": { "type": "string", "description": "Organizer. Optional text, up to 300 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "report_time": { "type": "string", "description": "Report Time. Use a time of day, such as 09:30 or 2:30 PM, without a date or UTC offset. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "room_access_time": { "type": "string", "description": "Room Access Time. Use a time of day, such as 09:30 or 2:30 PM, without a date or UTC offset. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "audience": { "type": "string", "description": "Audience. Optional text, up to 1000 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "expected_attendance": { "type": "string", "description": "Expected Attendance. Optional text, up to 150 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "room_setup_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ], "description": "Room Setup. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `1` (Theater) | `2` (Classroom) | `3` (Boardroom) | `4` (Panel Table) | `5` (U-Shape) | `6` (Demo Area) | `7` (Other) | `8` (Rounds / Banquet) | `9` (Poster Boards / Stations)", "nullable": true }, "session_abstract": { "type": "string", "description": "Session Abstract. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "learning_objectives": { "type": "string", "description": "Learning Objectives. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "av_requirements": { "type": "string", "description": "A/V Requirements. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "material_requirements": { "type": "string", "description": "Material Requirements. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "submission_deadline": { "type": "string", "description": "Submission Deadline. Use YYYY-MM-DD, without a time or time zone. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "format": "date", "nullable": true }, "rehearsal_required": { "type": "boolean", "description": "Rehearsal Required. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "speaker_preparation_notes": { "type": "string", "description": "Speaker Preparation Notes. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "speakers_participants": { "type": "string", "description": "Speakers Participants. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "submission_portal_url": { "type": "string", "description": "Submission Portal Link. Optional text, up to 500 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "report_location": { "type": "string", "description": "Report Location. Optional text, up to 200 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "recording_audio": { "type": "boolean", "description": "Recording Audio. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "recording_video": { "type": "boolean", "description": "Recording Video. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "recording_livestream": { "type": "boolean", "description": "Recording Livestream. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "recording_photography": { "type": "boolean", "description": "Recording Photography. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "qa_live_audience_questions": { "type": "boolean", "description": "Q&A Live Audience Questions. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "qa_moderated": { "type": "boolean", "description": "Q&A Moderated. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "qa_pre_submitted": { "type": "boolean", "description": "Q&A Pre Submitted. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "submission_status_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4, 5, 6, 7 ], "description": "Submission Status. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `1` (Draft) | `2` (Not Submitted) | `3` (Submitted) | `4` (Under Review) | `5` (Accepted) | `6` (Rejected) | `7` (Withdrawn)", "nullable": true }, "rehearsal_status_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4 ], "description": "Rehearsal Status. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `1` (Not Scheduled) | `2` (Scheduled) | `3` (Completed) | `4` (Canceled)", "nullable": true }, "materials_due_date": { "type": "string", "description": "Materials Due Date. Use YYYY-MM-DD, without a time or time zone. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "format": "date", "nullable": true }, "session_format_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3 ], "description": "Session Format. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `1` (In-Person) | `2` (Virtual) | `3` (Hybrid)", "nullable": true }, "session_join_url": { "type": "string", "description": "Session Join Link. Optional text, up to 1000 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 2, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `networking` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "host_or_sponsor": { "type": "string", "description": "Host Or Sponsor. Optional text, up to 300 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "preparation_requirements": { "type": "string", "description": "Preparation Requirements. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "rsvp_status_id": { "type": "integer", "format": "int64", "enum": [ 8, 9, 10, 11 ], "description": "RSVP Status. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `8` (Not Started) | `9` (In Progress) | `10` (Completed) | `11` (Issue / Blocked)", "nullable": true }, "access_level_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4, 5, 7, 8, 9 ], "description": "Access Level. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `1` (General Admission) | `2` (Exhibitor) | `3` (Speaker) | `4` (Sponsor) | `5` (VIP) | `7` (Other) | `8` (Staff) | `9` (Press / Media)", "nullable": true }, "attendance_priority_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3 ], "description": "Attendance Priority. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `1` (Optional) | `2` (Recommended) | `3` (Required)", "nullable": true }, "internal_objective": { "type": "string", "description": "Internal Objective. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "invited_audience": { "type": "string", "description": "Invited Audience. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "dress_code_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4, 5, 6, 7 ], "description": "Dress Code. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `1` (Casual) | `2` (Business Casual) | `3` (Business Formal) | `4` (Cocktail) | `5` (Black Tie) | `6` (Company-Branded Apparel) | `7` (Other)", "nullable": true }, "confirmation_number": { "type": "string", "description": "Confirmation Number. Optional text, up to 200 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "guest_allowance": { "type": "string", "description": "Guest Allowance. Optional text, up to 150 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "meeting_point": { "type": "string", "description": "Meeting Point. Optional text, up to 500 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "rsvp_registration_url": { "type": "string", "description": "RSVP Registration URL. Optional text, up to 1000 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "expected_attendance": { "type": "string", "description": "Expected Attendance. Optional text, up to 150 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "team_meet_up_time": { "type": "string", "description": "Team Meet Up Time. Use a time of day, such as 09:30 or 2:30 PM, without a date or UTC offset. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "admission_registration_required": { "type": "boolean", "description": "Admission Registration Required. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "admission_ticket_required": { "type": "boolean", "description": "Admission Ticket Required. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "admission_invitation_required": { "type": "boolean", "description": "Admission Invitation Required. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "admission_credential_required": { "type": "boolean", "description": "Admission Credential Required. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "rsvp_registration_deadline": { "type": "string", "description": "Rsvp Registration Deadline. Use YYYY-MM-DD, without a time or time zone. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "format": "date", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 2, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `meal_break` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "purpose_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4, 6, 7, 8, 9, 10 ], "description": "Purpose. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `1` (Personal / Routine) | `2` (Team / Internal) | `3` (Customer / Prospect Engagement) | `4` (Partner / Vendor Engagement) | `6` (Other) | `7` (Networking / Relationship Building) | `8` (Working / Planning) | `9` (Hospitality / VIP) | `10` (Celebration / Recognition)", "nullable": true }, "host_or_sponsor": { "type": "string", "description": "Host Or Sponsor. Optional text, up to 300 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "reservation_status_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4, 5, 6 ], "description": "Reservation Status. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `1` (Not Required) | `2` (Requested / Pending) | `3` (Confirmed) | `4` (Waitlisted) | `5` (Canceled) | `6` (Not Yet Reserved)", "nullable": true }, "reservation_name": { "type": "string", "description": "Reservation Name. Optional text, up to 200 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "reservation_number": { "type": "string", "description": "Reservation Number. Optional text, up to 200 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "party_size": { "type": "string", "description": "Party Size. Optional text, up to 150 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "dietary_requirements": { "type": "string", "description": "Dietary Requirements. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "restaurant_contact_name": { "type": "string", "description": "Restaurant Contact Name. Optional text, up to 200 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "restaurant_contact_phone": { "type": "string", "description": "Restaurant Contact Phone. Optional text, up to 50 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "seating_arrangement_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4, 5 ], "description": "Seating Arrangement. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `1` (Private Room) | `2` (Reserved Table) | `3` (Assigned Seating) | `4` (Open Seating) | `5` (Other)", "nullable": true }, "guests_attendees": { "type": "string", "description": "Guests Attendees. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "reservation_deadline": { "type": "string", "description": "Reservation Deadline. Use YYYY-MM-DD, without a time or time zone. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "format": "date", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 2, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `registration` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "credential_details": { "type": "string", "description": "Credential Details. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "confirmation_number": { "type": "string", "description": "Confirmation Number. Optional text, up to 200 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "required_documents_items": { "type": "string", "description": "Required Documents Items. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "escalation_contact_name": { "type": "string", "description": "Escalation Contact Name. Optional text, up to 200 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "escalation_contact_phone": { "type": "string", "description": "Escalation Contact Phone. Optional text, up to 50 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "escalation_contact_email": { "type": "string", "description": "Escalation Contact Email. Optional text, up to 320 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "issue_notes": { "type": "string", "description": "Issue Notes. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "status_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 6, 7, 11, 12 ], "description": "Status. Check-in / Registration offers 6 Not Checked In, 7 Checked In and 12 Issue / Blocked. Other offers 1 Not Started, 2 In Progress, 11 Completed and 12 Issue / Blocked. Send a JSON integer from the current activity type's choices, or JSON null for no choice. Changing the activity type can clear a status that no longer applies.\n\nAllowed values: `1` (Not Started) | `2` (In Progress) | `6` (Not Checked In) | `7` (Checked In) | `11` (Completed) | `12` (Issue / Blocked)", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 2, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `special_event` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "required_headcount": { "type": "string", "description": "Required Headcount. Optional text, up to 150 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "staffing_status_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4 ], "description": "Staffing Status. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `1` (Not Started) | `2` (In Progress) | `3` (Fully Staffed) | `4` (Issue / Blocked)", "nullable": true }, "participant_registration_status_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 11, 12 ], "description": "Participant Registration Status. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `1` (Not Started) | `2` (In Progress) | `11` (Completed) | `12` (Issue / Blocked)", "nullable": true }, "participant_waiver_status_id": { "type": "integer", "format": "int64", "enum": [ 2, 3, 4, 5 ], "description": "Participant Waiver Status. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `2` (In Progress) | `3` (Completed) | `4` (Not Started) | `5` (Issue / Blocked)", "nullable": true }, "organizer": { "type": "string", "description": "Organizer. Optional text, up to 300 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "ticket_confirmation_number": { "type": "string", "description": "Ticket Confirmation Number. Optional text, up to 200 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "participation_instructions": { "type": "string", "description": "Participation Instructions. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "attire_requirements": { "type": "string", "description": "Attire Requirements. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "capacity_group_size": { "type": "string", "description": "Capacity Group Size. Optional text, up to 150 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "waiver_required": { "type": "boolean", "description": "Waiver Required. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "waiver_status_id": { "type": "integer", "format": "int64", "enum": [ 2, 3, 4, 5 ], "description": "Waiver Status. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `2` (In Progress) | `3` (Completed) | `4` (Not Started) | `5` (Issue / Blocked)", "nullable": true }, "eligibility_restrictions": { "type": "string", "description": "Eligibility Restrictions. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "weather_dependent": { "type": "boolean", "description": "Weather Dependent. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "contingency_plan": { "type": "string", "description": "Contingency Plan. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "safety_instructions": { "type": "string", "description": "Safety Instructions. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "emergency_contact_name": { "type": "string", "description": "Emergency Contact Name. Optional text, up to 200 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "emergency_contact_phone": { "type": "string", "description": "Emergency Contact Phone. Optional text, up to 50 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "on_site_contact_name": { "type": "string", "description": "On Site Contact Name. Optional text, up to 200 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "on_site_contact_phone": { "type": "string", "description": "On Site Contact Phone. Optional text, up to 50 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "on_site_contact_email": { "type": "string", "description": "On Site Contact Email. Optional text, up to 200 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "report_checkin_time": { "type": "string", "description": "Report Checkin Time. Use a time of day, such as 09:30 or 2:30 PM, without a date or UTC offset. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "meeting_checkin_point": { "type": "string", "description": "Meeting Checkin Point. Optional text, up to 300 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "participants_guests": { "type": "string", "description": "Participants Guests. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "admission_registration_required": { "type": "boolean", "description": "Admission Registration Required. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "admission_ticket_required": { "type": "boolean", "description": "Admission Ticket Required. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "admission_invitation_required": { "type": "boolean", "description": "Admission Invitation Required. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "admission_credential_required": { "type": "boolean", "description": "Admission Credential Required. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "registration_status_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 11, 12 ], "description": "Registration Status. Send a JSON integer, or JSON null for no choice. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `1` (Not Started) | `2` (In Progress) | `11` (Completed) | `12` (Issue / Blocked)", "nullable": true }, "registration_deadline": { "type": "string", "description": "Registration Deadline. Use YYYY-MM-DD, without a time or time zone. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "format": "date", "nullable": true }, "registration_url": { "type": "string", "description": "Registration URL. Optional text, up to 500 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "waiver_deadline": { "type": "string", "description": "Waiver Deadline. Use YYYY-MM-DD, without a time or time zone. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "format": "date", "nullable": true }, "preparation_requirements": { "type": "string", "description": "Preparation Requirements. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "floor_walk_exhibitors_areas": { "type": "string", "description": "Floor Walk Exhibitors Areas. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "floor_walk_visit_focus": { "type": "string", "description": "Floor Walk Visit Focus. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 2, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `planning` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "notes": { "type": "string", "description": "Planning Notes. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "contacts": { "type": "string", "description": "Planning Contacts. Optional text, up to 500 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 2, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `tagged_user_ids` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "array", "items": { "type": "string" }, "maxItems": 2147483647, "nullable": true, "x-maximum-depth": 2, "x-empty-create-means-omitted": true, "example": [ "user-id" ] } ``` #### Creating the activity Send event_id, title, day_type_id and day_number. The field descriptions below explain the available days, default choices and optional times. Add costs and invoices with the Playbook Cost methods after the activity exists. #### Access and locks Your current API access and the Event's Playbook visibility and lock settings apply. #### Sending the request Use JSON, the query string or form data for values containing commas. Send comma-containing text, related-item lists and detail objects in JSON, query parameters or form fields. To make a retry safe, send an Idempotency-Key. Resending the same request with the same key returns the saved response instead of adding a second activity. #### After the add Newly tagged people may receive the usual assignment email unless you send notify_tagged_users=false; delivery still depends on their account and email settings. Confirmed changes appear in activity history; a history-writing failure does not undo the change. If you can't confirm the result and didn't send an Idempotency-Key, check the Event's Playbook before trying again; the API does not repeat the action automatically. #### Sending text Send plain text for Notes and other rich-text fields. Characters such as `&`, `<` and quotes, along with line breaks, are encoded for storage. Notes and other rich-text values in the response contain the stored HTML, including encoded characters and line breaks such as `
`. #### Hidden or locked tab If the Event's Playbook tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. An Event that is not in your workspace returns HTTP 404. #### Open in ExhibitDay The created record includes exhibitday_url, the record's page in ExhibitDay. It is the same link that GET /v1/events/playbook_activities/info returns for this record and opens the record in view mode on its Event's tab. Sign in with an account that can view the record; ExhibitDay checks access when the link is opened. Example — curl: ```bash curl -X POST "https://api.exhibitday.com/v1/events/playbook_activities" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"event_id\":23456,\"title\":\"Team briefing\",\"day_type_id\":1,\"day_number\":1}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/playbook_activities", { method: "POST", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "event_id": 23456, "title": "Team briefing", "day_type_id": 1, "day_number": 1 }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.post( "https://api.exhibitday.com/v1/events/playbook_activities", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"event_id": 23456, "title": "Team briefing", "day_type_id": 1, "day_number": 1}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PostAsync("https://api.exhibitday.com/v1/events/playbook_activities", JsonContent.Create(new { event_id = 23456, title = "Team briefing", day_type_id = 1, day_number = 1 })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/playbook_activities")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("POST", HttpRequest.BodyPublishers.ofString("{\"event_id\":23456,\"title\":\"Team briefing\",\"day_type_id\":1,\"day_number\":1}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"event_id":23456,"title":"Team briefing","day_type_id":1,"day_number":1}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/playbook_activities') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"event_id":23456,"title":"Team briefing","day_type_id":1,"day_number":1}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/events/playbook_activities", strings.NewReader("{\"event_id\":23456,\"title\":\"Team briefing\",\"day_type_id\":1,\"day_number\":1}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): POST /v1/events/playbook_activities - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "id": 12345, "event_id": 23456, "event_name": "Sample Event", "title": "Team briefing", "description": null, "activity_type_id": 1, "activity_status_id": 1, "our_role_id": null, "day_type_id": 1, "day_number": 1, "is_all_day": true, "start_time": null, "end_time": null, "timezone": "", "location": null, "tagged_users": [], "created_by": { "id": null, "first_name": "ExhibitDay", "last_name": "API", "display_name": "ExhibitDay API", "email": null, "type": null, "workspace_role": null, "is_active": true }, "booth_operations": null, "meeting": null, "presentation": null, "networking": null, "meal_break": null, "registration": null, "special_event": null, "planning": null, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=23456&riType=2&riSub=0&riId=12345" } ``` ### Update a Playbook Activity `PATCH https://api.exhibitday.com/v1/events/playbook_activities` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=playbook#patch-v1-events-playbook_activities Updates the fields you choose on an existing Playbook activity. Omitted fields keep their current values. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Playbook activity in that event. Use its ID from the activity list, Info or Create response. | | | title | String | No | A short title for the scheduled activity, up to 500 characters. This is required on create and cannot be cleared. | Max length: 500. | | description | String | No | Accepts plain text; line breaks are retained. The saved text and its representation in the ExhibitDay editor must each fit within 30,000 characters, including formatting and encoded characters. Older text over the limit may be kept or shortened, but cannot grow. On PATCH, an omitted or blank whole parameter keeps its value; null clears it. | Max length: 30000. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | location | String | No | The activity location, up to 200 characters. | Max length: 200. | | timezone | String | No | The time-zone label displayed beside the activity's times, up to 20 characters. This does not convert the clock readings. All-day activities clear this label. | Max length: 20. | | activity_type_id | Number | No | Use an id from GET /v1/references/playbook_activity_types. The default on create is General — Other (1). | | | activity_status_id | Number | No | Whether the activity is Confirmed (1), Tentative (2) or Canceled (3). The default on create is Confirmed. This is independent of proposal, registration and payment statuses. | | | our_role_id | Number | No | Your team's role in the activity. The available choices depend on the activity type. Omit or leave blank to keep it unless the activity type changes. A supplied role that does not apply, including null, becomes the type's default; types with no role store no role. | Allowed values: `1` (Attending; Attending / Participating for Special Event activities) \| `2` (Hosting / Organizing) \| `3` (Presenting / Participating) | | day_type_id | Number | No | Where the scheduled day falls relative to the Event. Combine it with day_number and choose a day currently available in the Event's Playbook. Omit or leave blank to keep it; null cannot clear it. An unchanged older unresolved day may remain while editing other fields. All Pages is a display choice and cannot be saved. | Allowed values: `1` (Event Day) \| `2` (Days Before the Event) \| `3` (Days After the Event) | | day_number | Number | No | The positive day number within the selected day type. New activities and day changes must use a day available in this event's Playbook. An existing activity may keep its own older unresolved day while you edit other fields. | | | is_all_day | Boolean | No | Use true for an all-day activity, or false for a specific start and end time. The default on create is true. All-day activities have no start time, end time or time zone. | Default: true. | | start_time | String | No | A time of day, such as 09:30 or 2:30 PM, without a date or UTC offset. A specific-time activity needs both times. An end before the start is swapped with the start; it does not create an overnight activity. | | | end_time | String | No | A time of day, such as 09:30 or 2:30 PM, without a date or UTC offset. A specific-time activity needs both times. An end before the start is swapped with the start; it does not create an overnight activity. | | | booth_operations | JSON object/list | No | The Booth Operations fields shown for this activity type. Send an object using the fields listed below. On PATCH, omitted members keep their current values; JSON null clears a member, and an empty text member clears its text. Within the object, the text "null" remains literal text. The current type, role and related choices decide which fields apply; values that no longer apply are cleared. A filled member that this type or role does not use is not saved, and the response warns about that member by name. Changing category removes the other category's details. A blank whole parameter keeps the section; null clears its fields. The ignore-empty option applies to a whole JSON-null parameter, not to members of a supplied object. Rich-text fields accept plain text; line breaks are retained. The saved text and its representation in the ExhibitDay editor must each fit within 30,000 characters, including formatting and encoded characters. Older text over the limit may be kept or shortened, but cannot grow. On PATCH, an omitted or blank whole parameter keeps its value; null clears it. | | | booth_operations.inspection_result_id | integer or null | No | Inspection Result. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `1` (Pending) \| `2` (Passed) \| `3` (Corrections Required) \| `4` (Failed) | | booth_operations.execution_status_id | integer or null | No | Execution Status. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `1` (Not Started) \| `2` (In Progress) \| `3` (Completed) \| `4` (Blocked) | | booth_operations.staffing_status_id | integer or null | No | Staffing Status. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `1` (Not Started) \| `2` (In Progress) \| `3` (Fully Staffed) \| `4` (Issue / Blocked) | | meeting | JSON object/list | No | The Meeting fields shown for this activity type. Send an object using the fields listed below. On PATCH, omitted members keep their current values; JSON null clears a member, and an empty text member clears its text. Within the object, the text "null" remains literal text. The current type, role and related choices decide which fields apply; values that no longer apply are cleared. A filled member that this type or role does not use is not saved, and the response warns about that member by name. Changing category removes the other category's details. A blank whole parameter keeps the section; null clears its fields. The ignore-empty option applies to a whole JSON-null parameter, not to members of a supplied object. Rich-text fields accept plain text; line breaks are retained. The saved text and its representation in the ExhibitDay editor must each fit within 30,000 characters, including formatting and encoded characters. Older text over the limit may be kept or shortened, but cannot grow. On PATCH, an omitted or blank whole parameter keeps its value; null clears it. | | | meeting.meeting_format_id | integer or null | No | Meeting Format. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `1` (In-Person) \| `2` (Virtual) \| `3` (Phone) \| `4` (Hybrid) | | presentation | JSON object/list | No | The Presentation fields shown for this activity type. Send an object using the fields listed below. On PATCH, omitted members keep their current values; JSON null clears a member, and an empty text member clears its text. Within the object, the text "null" remains literal text. The current type, role and related choices decide which fields apply; values that no longer apply are cleared. A filled member that this type or role does not use is not saved, and the response warns about that member by name. Changing category removes the other category's details. A blank whole parameter keeps the section; null clears its fields. The ignore-empty option applies to a whole JSON-null parameter, not to members of a supplied object. Rich-text fields accept plain text; line breaks are retained. The saved text and its representation in the ExhibitDay editor must each fit within 30,000 characters, including formatting and encoded characters. Older text over the limit may be kept or shortened, but cannot grow. On PATCH, an omitted or blank whole parameter keeps its value; null clears it. | | | presentation.room_setup_id | integer or null | No | Room Setup. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `1` (Theater) \| `2` (Classroom) \| `3` (Boardroom) \| `4` (Panel Table) \| `5` (U-Shape) \| `6` (Demo Area) \| `7` (Other) \| `8` (Rounds / Banquet) \| `9` (Poster Boards / Stations) | | presentation.submission_status_id | integer or null | No | Submission Status. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `1` (Draft) \| `2` (Not Submitted) \| `3` (Submitted) \| `4` (Under Review) \| `5` (Accepted) \| `6` (Rejected) \| `7` (Withdrawn) | | presentation.rehearsal_status_id | integer or null | No | Rehearsal Status. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `1` (Not Scheduled) \| `2` (Scheduled) \| `3` (Completed) \| `4` (Canceled) | | presentation.session_format_id | integer or null | No | Session Format. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `1` (In-Person) \| `2` (Virtual) \| `3` (Hybrid) | | networking | JSON object/list | No | The Networking fields shown for this activity type. Send an object using the fields listed below. On PATCH, omitted members keep their current values; JSON null clears a member, and an empty text member clears its text. Within the object, the text "null" remains literal text. The current type, role and related choices decide which fields apply; values that no longer apply are cleared. A filled member that this type or role does not use is not saved, and the response warns about that member by name. Changing category removes the other category's details. A blank whole parameter keeps the section; null clears its fields. The ignore-empty option applies to a whole JSON-null parameter, not to members of a supplied object. Rich-text fields accept plain text; line breaks are retained. The saved text and its representation in the ExhibitDay editor must each fit within 30,000 characters, including formatting and encoded characters. Older text over the limit may be kept or shortened, but cannot grow. On PATCH, an omitted or blank whole parameter keeps its value; null clears it. | | | networking.rsvp_status_id | integer or null | No | RSVP Status. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `8` (Not Started) \| `9` (In Progress) \| `10` (Completed) \| `11` (Issue / Blocked) | | networking.access_level_id | integer or null | No | Access Level. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `1` (General Admission) \| `2` (Exhibitor) \| `3` (Speaker) \| `4` (Sponsor) \| `5` (VIP) \| `7` (Other) \| `8` (Staff) \| `9` (Press / Media) | | networking.attendance_priority_id | integer or null | No | Attendance Priority. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `1` (Optional) \| `2` (Recommended) \| `3` (Required) | | networking.dress_code_id | integer or null | No | Dress Code. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `1` (Casual) \| `2` (Business Casual) \| `3` (Business Formal) \| `4` (Cocktail) \| `5` (Black Tie) \| `6` (Company-Branded Apparel) \| `7` (Other) | | meal_break | JSON object/list | No | The Meal Break fields shown for this activity type. Send an object using the fields listed below. On PATCH, omitted members keep their current values; JSON null clears a member, and an empty text member clears its text. Within the object, the text "null" remains literal text. The current type, role and related choices decide which fields apply; values that no longer apply are cleared. A filled member that this type or role does not use is not saved, and the response warns about that member by name. Changing category removes the other category's details. A blank whole parameter keeps the section; null clears its fields. The ignore-empty option applies to a whole JSON-null parameter, not to members of a supplied object. Rich-text fields accept plain text; line breaks are retained. The saved text and its representation in the ExhibitDay editor must each fit within 30,000 characters, including formatting and encoded characters. Older text over the limit may be kept or shortened, but cannot grow. On PATCH, an omitted or blank whole parameter keeps its value; null clears it. | | | meal_break.purpose_id | integer or null | No | Purpose. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `1` (Personal / Routine) \| `2` (Team / Internal) \| `3` (Customer / Prospect Engagement) \| `4` (Partner / Vendor Engagement) \| `6` (Other) \| `7` (Networking / Relationship Building) \| `8` (Working / Planning) \| `9` (Hospitality / VIP) \| `10` (Celebration / Recognition) | | meal_break.reservation_status_id | integer or null | No | Reservation Status. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `1` (Not Required) \| `2` (Requested / Pending) \| `3` (Confirmed) \| `4` (Waitlisted) \| `5` (Canceled) \| `6` (Not Yet Reserved) | | meal_break.seating_arrangement_id | integer or null | No | Seating Arrangement. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `1` (Private Room) \| `2` (Reserved Table) \| `3` (Assigned Seating) \| `4` (Open Seating) \| `5` (Other) | | registration | JSON object/list | No | The Registration fields shown for this activity type. Send an object using the fields listed below. On PATCH, omitted members keep their current values; JSON null clears a member, and an empty text member clears its text. Within the object, the text "null" remains literal text. The current type, role and related choices decide which fields apply; values that no longer apply are cleared. A filled member that this type or role does not use is not saved, and the response warns about that member by name. Changing category removes the other category's details. A blank whole parameter keeps the section; null clears its fields. The ignore-empty option applies to a whole JSON-null parameter, not to members of a supplied object. Rich-text fields accept plain text; line breaks are retained. The saved text and its representation in the ExhibitDay editor must each fit within 30,000 characters, including formatting and encoded characters. Older text over the limit may be kept or shortened, but cannot grow. On PATCH, an omitted or blank whole parameter keeps its value; null clears it. | | | registration.status_id | integer or null | No | Status. Check-in / Registration offers 6 Not Checked In, 7 Checked In and 12 Issue / Blocked. Other offers 1 Not Started, 2 In Progress, 11 Completed and 12 Issue / Blocked. Send a JSON integer from the current activity type's choices, or JSON null for no choice. Omit this member on PATCH to keep its value. Changing the activity type can clear a status that no longer applies. | Allowed values: `1` (Not Started) \| `2` (In Progress) \| `6` (Not Checked In) \| `7` (Checked In) \| `11` (Completed) \| `12` (Issue / Blocked) | | special_event | JSON object/list | No | The Special Event fields shown for this activity type. Send an object using the fields listed below. On PATCH, omitted members keep their current values; JSON null clears a member, and an empty text member clears its text. Within the object, the text "null" remains literal text. The current type, role and related choices decide which fields apply; values that no longer apply are cleared. A filled member that this type or role does not use is not saved, and the response warns about that member by name. Changing category removes the other category's details. A blank whole parameter keeps the section; null clears its fields. The ignore-empty option applies to a whole JSON-null parameter, not to members of a supplied object. Rich-text fields accept plain text; line breaks are retained. The saved text and its representation in the ExhibitDay editor must each fit within 30,000 characters, including formatting and encoded characters. Older text over the limit may be kept or shortened, but cannot grow. On PATCH, an omitted or blank whole parameter keeps its value; null clears it. | | | special_event.staffing_status_id | integer or null | No | Staffing Status. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `1` (Not Started) \| `2` (In Progress) \| `3` (Fully Staffed) \| `4` (Issue / Blocked) | | special_event.participant_registration_status_id | integer or null | No | Participant Registration Status. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `1` (Not Started) \| `2` (In Progress) \| `11` (Completed) \| `12` (Issue / Blocked) | | special_event.participant_waiver_status_id | integer or null | No | Participant Waiver Status. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `2` (In Progress) \| `3` (Completed) \| `4` (Not Started) \| `5` (Issue / Blocked) | | special_event.waiver_status_id | integer or null | No | Waiver Status. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `2` (In Progress) \| `3` (Completed) \| `4` (Not Started) \| `5` (Issue / Blocked) | | special_event.registration_status_id | integer or null | No | Registration Status. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset. | Allowed values: `1` (Not Started) \| `2` (In Progress) \| `11` (Completed) \| `12` (Issue / Blocked) | | planning | JSON object/list | No | The Planning fields shown for this activity type. Send an object using the fields listed below. On PATCH, omitted members keep their current values; JSON null clears a member, and an empty text member clears its text. Within the object, the text "null" remains literal text. The current type, role and related choices decide which fields apply; values that no longer apply are cleared. A filled member that this type or role does not use is not saved, and the response warns about that member by name. Changing category removes the other category's details. Planning contacts are free text; they do not tag users or send notifications. A blank whole parameter keeps the section; null clears its fields. The ignore-empty option applies to a whole JSON-null parameter, not to members of a supplied object. Rich-text fields accept plain text; line breaks are retained. The saved text and its representation in the ExhibitDay editor must each fit within 30,000 characters, including formatting and encoded characters. Older text over the limit may be kept or shortened, but cannot grow. On PATCH, an omitted or blank whole parameter keeps its value; null clears it. | | | tagged_user_ids | JSON object/list | No | The full list of people tagged in this activity, as an array of unique user IDs from your workspace's active users and resources. Omit it to keep the current people; null or [] removes all tags. Existing tags keep their notification state. Newly tagged people receive the usual assignment notification only when notify_tagged_users is true and their account and email settings allow it. Existing tags keep their notification state. | | | notify_tagged_users | Boolean | No | Whether newly tagged people may receive the usual assignment email. Omit this option or leave it blank for true. Send false to suppress the new notifications from this request. Existing tags keep their notification state; this option does not resend or cancel earlier notifications. JSON null is refused, even with the ignore-empty option. Delivery still depends on each person's current account, access and email settings. | Default: true. | | expected_revision | String | No | The record_revision returned when you retrieved this record. Include it to avoid overwriting someone else's changes. Omit it to skip this check. | | Declared schema for `booth_operations` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "area_or_station": { "type": "string", "description": "Area Or Station. Optional text, up to 200 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "required_headcount": { "type": "string", "description": "Required Headcount. Optional text, up to 150 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "team_staffing_requirements": { "type": "string", "description": "Team Staffing Requirements. Optional text, up to 150 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "on_site_contact_name": { "type": "string", "description": "On Site Contact Name. Optional text, up to 200 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "on_site_contact_phone": { "type": "string", "description": "On Site Contact Phone. Optional text, up to 50 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "on_site_contact_email": { "type": "string", "description": "On Site Contact Email. Optional text, up to 320 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "materials_equipment": { "type": "string", "description": "Materials Equipment. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "handoff_instructions": { "type": "string", "description": "Handoff Instructions. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "blocking_issue": { "type": "string", "description": "Blocking Issue. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "inspection_result_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4 ], "description": "Inspection Result. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `1` (Pending) | `2` (Passed) | `3` (Corrections Required) | `4` (Failed)", "nullable": true }, "inspection_scope_type": { "type": "string", "description": "Inspection Scope Type. Optional text, up to 200 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "issues_deficiencies": { "type": "string", "description": "Issues Deficiencies. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "corrective_action_follow_up": { "type": "string", "description": "Corrective Action Followup. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "execution_status_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4 ], "description": "Execution Status. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `1` (Not Started) | `2` (In Progress) | `3` (Completed) | `4` (Blocked)", "nullable": true }, "staffing_status_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4 ], "description": "Staffing Status. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `1` (Not Started) | `2` (In Progress) | `3` (Fully Staffed) | `4` (Issue / Blocked)", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 2, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `meeting` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "meeting_format_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4 ], "description": "Meeting Format. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `1` (In-Person) | `2` (Virtual) | `3` (Phone) | `4` (Hybrid)", "nullable": true }, "organization": { "type": "string", "description": "Organization. Optional text, up to 300 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "virtual_meeting_url": { "type": "string", "description": "Virtual Meeting URL. Optional text, up to 1000 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "purpose": { "type": "string", "description": "Purpose. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "agenda": { "type": "string", "description": "Agenda. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "preparation_requirements": { "type": "string", "description": "Preparation Requirements. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "desired_outcome": { "type": "string", "description": "Desired Outcome. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "actual_outcome": { "type": "string", "description": "Actual Outcome. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "next_steps": { "type": "string", "description": "Next Steps. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "follow_up_date": { "type": "string", "description": "Follow Up Date. Use YYYY-MM-DD, without a time or time zone. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "format": "date", "nullable": true }, "external_attendees": { "type": "string", "description": "External Attendees. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 2, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `presentation` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "session_number": { "type": "string", "description": "Session Number. Optional text, up to 100 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "track": { "type": "string", "description": "Track. Optional text, up to 200 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "organizer": { "type": "string", "description": "Organizer. Optional text, up to 300 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "report_time": { "type": "string", "description": "Report Time. Use a time of day, such as 09:30 or 2:30 PM, without a date or UTC offset. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "room_access_time": { "type": "string", "description": "Room Access Time. Use a time of day, such as 09:30 or 2:30 PM, without a date or UTC offset. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "audience": { "type": "string", "description": "Audience. Optional text, up to 1000 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "expected_attendance": { "type": "string", "description": "Expected Attendance. Optional text, up to 150 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "room_setup_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ], "description": "Room Setup. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `1` (Theater) | `2` (Classroom) | `3` (Boardroom) | `4` (Panel Table) | `5` (U-Shape) | `6` (Demo Area) | `7` (Other) | `8` (Rounds / Banquet) | `9` (Poster Boards / Stations)", "nullable": true }, "session_abstract": { "type": "string", "description": "Session Abstract. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "learning_objectives": { "type": "string", "description": "Learning Objectives. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "av_requirements": { "type": "string", "description": "A/V Requirements. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "material_requirements": { "type": "string", "description": "Material Requirements. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "submission_deadline": { "type": "string", "description": "Submission Deadline. Use YYYY-MM-DD, without a time or time zone. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "format": "date", "nullable": true }, "rehearsal_required": { "type": "boolean", "description": "Rehearsal Required. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "speaker_preparation_notes": { "type": "string", "description": "Speaker Preparation Notes. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "speakers_participants": { "type": "string", "description": "Speakers Participants. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "submission_portal_url": { "type": "string", "description": "Submission Portal Link. Optional text, up to 500 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "report_location": { "type": "string", "description": "Report Location. Optional text, up to 200 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "recording_audio": { "type": "boolean", "description": "Recording Audio. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "recording_video": { "type": "boolean", "description": "Recording Video. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "recording_livestream": { "type": "boolean", "description": "Recording Livestream. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "recording_photography": { "type": "boolean", "description": "Recording Photography. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "qa_live_audience_questions": { "type": "boolean", "description": "Q&A Live Audience Questions. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "qa_moderated": { "type": "boolean", "description": "Q&A Moderated. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "qa_pre_submitted": { "type": "boolean", "description": "Q&A Pre Submitted. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "submission_status_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4, 5, 6, 7 ], "description": "Submission Status. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `1` (Draft) | `2` (Not Submitted) | `3` (Submitted) | `4` (Under Review) | `5` (Accepted) | `6` (Rejected) | `7` (Withdrawn)", "nullable": true }, "rehearsal_status_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4 ], "description": "Rehearsal Status. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `1` (Not Scheduled) | `2` (Scheduled) | `3` (Completed) | `4` (Canceled)", "nullable": true }, "materials_due_date": { "type": "string", "description": "Materials Due Date. Use YYYY-MM-DD, without a time or time zone. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "format": "date", "nullable": true }, "session_format_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3 ], "description": "Session Format. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `1` (In-Person) | `2` (Virtual) | `3` (Hybrid)", "nullable": true }, "session_join_url": { "type": "string", "description": "Session Join Link. Optional text, up to 1000 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 2, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `networking` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "host_or_sponsor": { "type": "string", "description": "Host Or Sponsor. Optional text, up to 300 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "preparation_requirements": { "type": "string", "description": "Preparation Requirements. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "rsvp_status_id": { "type": "integer", "format": "int64", "enum": [ 8, 9, 10, 11 ], "description": "RSVP Status. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `8` (Not Started) | `9` (In Progress) | `10` (Completed) | `11` (Issue / Blocked)", "nullable": true }, "access_level_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4, 5, 7, 8, 9 ], "description": "Access Level. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `1` (General Admission) | `2` (Exhibitor) | `3` (Speaker) | `4` (Sponsor) | `5` (VIP) | `7` (Other) | `8` (Staff) | `9` (Press / Media)", "nullable": true }, "attendance_priority_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3 ], "description": "Attendance Priority. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `1` (Optional) | `2` (Recommended) | `3` (Required)", "nullable": true }, "internal_objective": { "type": "string", "description": "Internal Objective. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "invited_audience": { "type": "string", "description": "Invited Audience. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "dress_code_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4, 5, 6, 7 ], "description": "Dress Code. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `1` (Casual) | `2` (Business Casual) | `3` (Business Formal) | `4` (Cocktail) | `5` (Black Tie) | `6` (Company-Branded Apparel) | `7` (Other)", "nullable": true }, "confirmation_number": { "type": "string", "description": "Confirmation Number. Optional text, up to 200 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "guest_allowance": { "type": "string", "description": "Guest Allowance. Optional text, up to 150 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "meeting_point": { "type": "string", "description": "Meeting Point. Optional text, up to 500 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "rsvp_registration_url": { "type": "string", "description": "RSVP Registration URL. Optional text, up to 1000 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "expected_attendance": { "type": "string", "description": "Expected Attendance. Optional text, up to 150 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "team_meet_up_time": { "type": "string", "description": "Team Meet Up Time. Use a time of day, such as 09:30 or 2:30 PM, without a date or UTC offset. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "admission_registration_required": { "type": "boolean", "description": "Admission Registration Required. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "admission_ticket_required": { "type": "boolean", "description": "Admission Ticket Required. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "admission_invitation_required": { "type": "boolean", "description": "Admission Invitation Required. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "admission_credential_required": { "type": "boolean", "description": "Admission Credential Required. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "rsvp_registration_deadline": { "type": "string", "description": "Rsvp Registration Deadline. Use YYYY-MM-DD, without a time or time zone. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "format": "date", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 2, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `meal_break` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "purpose_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4, 6, 7, 8, 9, 10 ], "description": "Purpose. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `1` (Personal / Routine) | `2` (Team / Internal) | `3` (Customer / Prospect Engagement) | `4` (Partner / Vendor Engagement) | `6` (Other) | `7` (Networking / Relationship Building) | `8` (Working / Planning) | `9` (Hospitality / VIP) | `10` (Celebration / Recognition)", "nullable": true }, "host_or_sponsor": { "type": "string", "description": "Host Or Sponsor. Optional text, up to 300 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "reservation_status_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4, 5, 6 ], "description": "Reservation Status. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `1` (Not Required) | `2` (Requested / Pending) | `3` (Confirmed) | `4` (Waitlisted) | `5` (Canceled) | `6` (Not Yet Reserved)", "nullable": true }, "reservation_name": { "type": "string", "description": "Reservation Name. Optional text, up to 200 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "reservation_number": { "type": "string", "description": "Reservation Number. Optional text, up to 200 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "party_size": { "type": "string", "description": "Party Size. Optional text, up to 150 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "dietary_requirements": { "type": "string", "description": "Dietary Requirements. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "restaurant_contact_name": { "type": "string", "description": "Restaurant Contact Name. Optional text, up to 200 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "restaurant_contact_phone": { "type": "string", "description": "Restaurant Contact Phone. Optional text, up to 50 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "seating_arrangement_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4, 5 ], "description": "Seating Arrangement. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `1` (Private Room) | `2` (Reserved Table) | `3` (Assigned Seating) | `4` (Open Seating) | `5` (Other)", "nullable": true }, "guests_attendees": { "type": "string", "description": "Guests Attendees. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "reservation_deadline": { "type": "string", "description": "Reservation Deadline. Use YYYY-MM-DD, without a time or time zone. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "format": "date", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 2, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `registration` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "credential_details": { "type": "string", "description": "Credential Details. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "confirmation_number": { "type": "string", "description": "Confirmation Number. Optional text, up to 200 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "required_documents_items": { "type": "string", "description": "Required Documents Items. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "escalation_contact_name": { "type": "string", "description": "Escalation Contact Name. Optional text, up to 200 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "escalation_contact_phone": { "type": "string", "description": "Escalation Contact Phone. Optional text, up to 50 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "escalation_contact_email": { "type": "string", "description": "Escalation Contact Email. Optional text, up to 320 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "issue_notes": { "type": "string", "description": "Issue Notes. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "status_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 6, 7, 11, 12 ], "description": "Status. Check-in / Registration offers 6 Not Checked In, 7 Checked In and 12 Issue / Blocked. Other offers 1 Not Started, 2 In Progress, 11 Completed and 12 Issue / Blocked. Send a JSON integer from the current activity type's choices, or JSON null for no choice. Omit this member on PATCH to keep its value. Changing the activity type can clear a status that no longer applies.\n\nAllowed values: `1` (Not Started) | `2` (In Progress) | `6` (Not Checked In) | `7` (Checked In) | `11` (Completed) | `12` (Issue / Blocked)", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 2, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `special_event` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "required_headcount": { "type": "string", "description": "Required Headcount. Optional text, up to 150 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "staffing_status_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 3, 4 ], "description": "Staffing Status. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `1` (Not Started) | `2` (In Progress) | `3` (Fully Staffed) | `4` (Issue / Blocked)", "nullable": true }, "participant_registration_status_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 11, 12 ], "description": "Participant Registration Status. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `1` (Not Started) | `2` (In Progress) | `11` (Completed) | `12` (Issue / Blocked)", "nullable": true }, "participant_waiver_status_id": { "type": "integer", "format": "int64", "enum": [ 2, 3, 4, 5 ], "description": "Participant Waiver Status. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `2` (In Progress) | `3` (Completed) | `4` (Not Started) | `5` (Issue / Blocked)", "nullable": true }, "organizer": { "type": "string", "description": "Organizer. Optional text, up to 300 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "ticket_confirmation_number": { "type": "string", "description": "Ticket Confirmation Number. Optional text, up to 200 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "participation_instructions": { "type": "string", "description": "Participation Instructions. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "attire_requirements": { "type": "string", "description": "Attire Requirements. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "capacity_group_size": { "type": "string", "description": "Capacity Group Size. Optional text, up to 150 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "waiver_required": { "type": "boolean", "description": "Waiver Required. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "waiver_status_id": { "type": "integer", "format": "int64", "enum": [ 2, 3, 4, 5 ], "description": "Waiver Status. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `2` (In Progress) | `3` (Completed) | `4` (Not Started) | `5` (Issue / Blocked)", "nullable": true }, "eligibility_restrictions": { "type": "string", "description": "Eligibility Restrictions. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "weather_dependent": { "type": "boolean", "description": "Weather Dependent. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "contingency_plan": { "type": "string", "description": "Contingency Plan. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "safety_instructions": { "type": "string", "description": "Safety Instructions. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "emergency_contact_name": { "type": "string", "description": "Emergency Contact Name. Optional text, up to 200 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "emergency_contact_phone": { "type": "string", "description": "Emergency Contact Phone. Optional text, up to 50 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "on_site_contact_name": { "type": "string", "description": "On Site Contact Name. Optional text, up to 200 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "on_site_contact_phone": { "type": "string", "description": "On Site Contact Phone. Optional text, up to 50 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "on_site_contact_email": { "type": "string", "description": "On Site Contact Email. Optional text, up to 200 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "report_checkin_time": { "type": "string", "description": "Report Checkin Time. Use a time of day, such as 09:30 or 2:30 PM, without a date or UTC offset. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "meeting_checkin_point": { "type": "string", "description": "Meeting Checkin Point. Optional text, up to 300 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "participants_guests": { "type": "string", "description": "Participants Guests. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "admission_registration_required": { "type": "boolean", "description": "Admission Registration Required. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "admission_ticket_required": { "type": "boolean", "description": "Admission Ticket Required. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "admission_invitation_required": { "type": "boolean", "description": "Admission Invitation Required. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "admission_credential_required": { "type": "boolean", "description": "Admission Credential Required. Use true for Yes, false for No, or JSON null for unanswered. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "registration_status_id": { "type": "integer", "format": "int64", "enum": [ 1, 2, 11, 12 ], "description": "Registration Status. Send a JSON integer, or JSON null for no choice. Omit this member on PATCH to keep its value. The activity type, your role and related choices determine whether it applies; a choice that no longer applies can be cleared or reset.\n\nAllowed values: `1` (Not Started) | `2` (In Progress) | `11` (Completed) | `12` (Issue / Blocked)", "nullable": true }, "registration_deadline": { "type": "string", "description": "Registration Deadline. Use YYYY-MM-DD, without a time or time zone. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "format": "date", "nullable": true }, "registration_url": { "type": "string", "description": "Registration URL. Optional text, up to 500 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "waiver_deadline": { "type": "string", "description": "Waiver Deadline. Use YYYY-MM-DD, without a time or time zone. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "format": "date", "nullable": true }, "preparation_requirements": { "type": "string", "description": "Preparation Requirements. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "floor_walk_exhibitors_areas": { "type": "string", "description": "Floor Walk Exhibitors Areas. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "floor_walk_visit_focus": { "type": "string", "description": "Floor Walk Visit Focus. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 2, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `planning` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "notes": { "type": "string", "description": "Planning Notes. Optional plain text with line breaks. Saved text and the editor count must each fit 30,000 characters, including formatting. Older over-limit text may be kept or shortened, but cannot grow. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true }, "contacts": { "type": "string", "description": "Planning Contacts. Optional text, up to 500 characters, excluding surrounding spaces. The activity type, role and other choices decide whether this field applies. Omit it to keep its value on PATCH; JSON null clears it.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": true, "x-maximum-depth": 2, "x-empty-create-means-omitted": true, "example": {} } ``` Declared schema for `tagged_user_ids` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "array", "items": { "type": "string" }, "maxItems": 2147483647, "nullable": true, "x-maximum-depth": 2, "x-empty-create-means-omitted": true, "example": [ "user-id" ] } ``` #### Choosing what to change Send only what you want to change. Omitted or blank whole parameters keep their values; null clears only fields that allow it. With $ignore_params_with_empty_values=true, a whole JSON-null parameter is ignored, while the text "null" still requests clearing. An activity cannot move to another Event. Its type and your team's role decide which details apply; see each field below for its rules. #### Access and locks Your current API access and the Event's Playbook visibility and lock settings apply. #### Sending the request Use JSON, the query string or form data for values containing commas. Send comma-containing text, related-item lists and detail objects in JSON, query parameters or form fields. This method ignores Idempotency-Key. #### After the update An unchanged PATCH writes no data, timestamp or history. Newly tagged people may receive the usual assignment email unless you send notify_tagged_users=false; delivery still depends on their account and email settings. Confirmed changes appear in activity history; a history-writing failure does not undo the change. If a save result cannot be confirmed, review the record before trying again; the API does not repeat the action automatically. #### Sending text Send plain text for Notes and other rich-text fields. Characters such as `&`, `<` and quotes, along with line breaks, are encoded for storage. #### Hidden or locked tab If the Event's Playbook tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. An Event that is not in your workspace returns HTTP 404. Example — curl: ```bash curl -X PATCH "https://api.exhibitday.com/v1/events/playbook_activities" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"id\":34567,\"description\":\"Updated description\"}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/playbook_activities", { method: "PATCH", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "id": 34567, "description": "Updated description" }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.patch( "https://api.exhibitday.com/v1/events/playbook_activities", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"id": 34567, "description": "Updated description"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PatchAsync("https://api.exhibitday.com/v1/events/playbook_activities", JsonContent.Create(new { id = 34567, description = "Updated description" })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/playbook_activities")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("PATCH", HttpRequest.BodyPublishers.ofString("{\"id\":34567,\"description\":\"Updated description\"}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"id":34567,"description":"Updated description"}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/playbook_activities') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"id":34567,"description":"Updated description"}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/events/playbook_activities", strings.NewReader("{\"id\":34567,\"description\":\"Updated description\"}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): PATCH /v1/events/playbook_activities - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Playbook activity updated.", "errors": [] } ``` ### Delete a Playbook Activity `DELETE https://api.exhibitday.com/v1/events/playbook_activities` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=playbook#delete-v1-events-playbook_activities Permanently deletes one Playbook activity and its associated details and costs. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Playbook activity in that event. Use its ID from the activity list, Info or Create response. | | #### What is removed Deleting the activity also removes its details, tagged people, costs, related-item links and attachment records. Only this activity's own files are scheduled for cleanup. #### Access and locks Your current API access and the Event's Playbook visibility and lock settings apply. #### Sending the request Use JSON, the query string or form data for values containing commas. This method ignores Idempotency-Key. #### After the deletion The deletion appears in the Event's Playbook history; a history-writing failure does not undo it. If you can't confirm the deletion, retrieve the activity before trying again; the API does not repeat the action automatically. #### Hidden or locked tab If the Event's Playbook tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. An Event that is not in your workspace returns HTTP 404. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/events/playbook_activities?id=34567" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/playbook_activities?" + new URLSearchParams({ "id": "34567" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/events/playbook_activities", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 34567}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/events/playbook_activities?id=34567"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/playbook_activities?id=34567")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/playbook_activities?id=34567') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/events/playbook_activities?id=34567", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/events/playbook_activities - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Playbook activity removed.", "errors": [] } ``` ### Retrieve a Single Playbook Cost by ID `GET https://api.exhibitday.com/v1/events/playbook_activity_costs/info` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=playbook#get-v1-events-playbook_activity_costs-info Retrieves one cost recorded on a Playbook activity, including its amounts, payment details and invoice. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Playbook cost. | | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` \| `object` | | $include_record_revision | Boolean | No | Set to true to include record_revision in the response. Send that value as expected_revision when updating to check for conflicting changes. | Default: false. | | $on_error_return_empty_result | Boolean | No | For missing or invalid IDs, or a record unavailable in this event, return HTTP 200 with {} (or [] in array format). Current-key failures, a record that changes while it is read and unexpected errors keep their normal error status. | | #### Invoice attachment The response includes invoice_attachment immediately after payment_notes, without a hydration option. It contains the invoice attachment ID, original file name and added time, or null when no invoice is attached. Use the invoice download method for its contents. An inconsistent saved invoice reference returns HTTP409 rather than being shown as an empty slot. Invoice attachments are separate from the parent record's edit revision. #### Formatted text in the response Notes and other rich-text values in the response contain the stored HTML, including encoded characters and line breaks such as `
`. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/events/playbook_activity_costs/info?id=34567" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/playbook_activity_costs/info?" + new URLSearchParams({ "id": "34567" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/events/playbook_activity_costs/info", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 34567}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/events/playbook_activity_costs/info?id=34567"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/playbook_activity_costs/info?id=34567")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/playbook_activity_costs/info?id=34567') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/playbook_activity_costs/info?id=34567", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/events/playbook_activity_costs/info - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "id": 34567, "event_id": 23456, "event_name": "Sample Event", "playbook_activity_id": 12345, "description": "Meeting room booking", "vendor_payee": null, "reference_number": null, "expense_date": null, "notes": null, "payment_status_id": 0, "payment_status": { "id": 0, "name": "N/A" }, "payment_due_date": null, "next_payment_due_date": null, "payment_notes": null, "invoice_attachment": { "id": 1004567, "filename": "activity-cost-invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" }, "cost": { "amount": 125.50, "cost_center_breakdown": [ { "cost_center_id": 34567, "cost_center": "Marketing", "charge": 75.50 }, { "cost_center_id": 34568, "cost_center": "Operations", "charge": 50.00 } ] } } ``` ### Retrieve Playbook Costs `GET https://api.exhibitday.com/v1/events/playbook_activity_costs` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=playbook#get-v1-events-playbook_activity_costs Lists the Playbook costs of one Event (filter_by_event_id), or of one of its activities with filter_by_playbook_activity_id, including their amounts, payment details and invoice. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | filter_by_event_id | Number | Yes | The ID of the Event whose Playbook costs to list. Every cost of every activity in that Event is returned unless filter_by_playbook_activity_id is also sent. | | | filter_by_playbook_activity_id | Number | No | Optional: only list the costs of this Playbook activity in that Event. | | | $limit | Number | No | The most records to return, as a positive whole number. Omit for all remaining records. | | | $offset | Number | No | How many records to skip: a whole number of 0 or more; 0 by default. | | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | #### Invoice attachment The response includes invoice_attachment immediately after payment_notes, without a hydration option. It contains the invoice attachment ID, original file name and added time, or null when no invoice is attached. Use the invoice download method for its contents. An inconsistent saved invoice reference returns HTTP409 rather than being shown as an empty slot. Invoice attachments are separate from the parent record's edit revision. #### Formatted text in the response Notes and other rich-text values in the response contain the stored HTML, including encoded characters and line breaks such as `
`. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/events/playbook_activity_costs?filter_by_event_id=23456" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/playbook_activity_costs?" + new URLSearchParams({ "filter_by_event_id": "23456" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/events/playbook_activity_costs", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"filter_by_event_id": 23456}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/events/playbook_activity_costs?filter_by_event_id=23456"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/playbook_activity_costs?filter_by_event_id=23456")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/playbook_activity_costs?filter_by_event_id=23456') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/playbook_activity_costs?filter_by_event_id=23456", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/events/playbook_activity_costs - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "list_type": "playbook_activity_cost", "list_data": [ { "id": 34567, "event_id": 23456, "event_name": "Sample Event", "playbook_activity_id": 12345, "description": "Meeting room booking", "vendor_payee": null, "reference_number": null, "expense_date": null, "notes": null, "payment_status_id": 0, "payment_status": { "id": 0, "name": "N/A" }, "payment_due_date": null, "next_payment_due_date": null, "payment_notes": null, "invoice_attachment": { "id": 1004567, "filename": "activity-cost-invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" }, "cost": { "amount": 0.00, "cost_center_breakdown": [] } } ], "records_found": 1, "total_records": 1, "has_more": false } ``` ### Add a Playbook Cost `POST https://api.exhibitday.com/v1/events/playbook_activity_costs` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=playbook#post-v1-events-playbook_activity_costs Adds a cost to a Playbook activity. The response includes the new cost and its ID. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | playbook_activity_id | Number | Yes | The ID of the Playbook activity in that event. Use its ID from the activity list, Info or Create response. | | | description | String | Yes | A description for this cost, up to 400 characters. This is required on create and cannot be cleared. | Max length: 400. | | vendor_payee | String | No | Vendor Payee, up to 200 characters. | Max length: 200. | | reference_number | String | No | Reference Number, up to 200 characters. | Max length: 200. | | expense_date | String | No | A calendar date in YYYY-MM-DD format, without a time or time zone. | | | notes | String | No | Plain-text Notes, up to 80,000 characters as saved, including formatting and encoded characters. Line breaks are retained. An over-limit value is refused, never shortened. On PATCH, an omitted or blank value keeps the current Notes; null clears them. | Max length: 80000. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | payment_status_id | Number | No | The cost's payment status. Omit or send null for N/A. This does not change the recorded amount or attach an invoice. | Allowed values: `0` (N/A) \| `1` (Paid in Full) \| `2` (Partially Paid) \| `3` (Not Paid Yet) | | payment_due_date | String | No | A calendar date in YYYY-MM-DD format, without a time or time zone. | | | next_payment_due_date | Date | No | A calendar date in YYYY-MM-DD format, without a time or time zone. Applies only when the payment status is Partially Paid. With any other status, supplying either this date or the payment status clears the date. | | | payment_notes | String | No | Payment Notes, up to 200 characters. | Max length: 200. | | cost | Number or cost object | No | The full cost, as a number or an object with amount and/or cost_center_breakdown. [Record Costs and Split Them Across Cost Centers](/Help/V1?guide=entering-costs). | Optional; defaults to zero. | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` \| `object` | Declared schema for `cost` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "anyOf": [ { "type": "number", "minimum": 0, "description": "Shorthand for an object with amount. The amount is rounded to cents before the supported storage range is checked.", "nullable": true }, { "type": "object", "additionalProperties": false, "properties": { "amount": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 }, "cost_center_breakdown": { "type": "array", "items": { "type": "object", "additionalProperties": false, "properties": { "cost_center_id": { "type": "integer", "format": "int64", "nullable": true }, "charge": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 }, "cost_center": { "type": "string", "description": "Optional and read-only: the cost center name a read returns, so a cost can be sent back unchanged. It is ignored; the line is saved by cost_center_id, and a name that doesn't match that cost center is explained in a warning.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "required": [ "charge" ] }, "maxItems": 2147483647 } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "anyOf": [ { "required": [ "amount" ] }, { "required": [ "cost_center_breakdown" ] } ], "nullable": true } ], "x-numeric-shorthand": "A number is equivalent to {amount:number}.", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": { "amount": 125.50 } } ``` #### Creating the cost Send playbook_activity_id and description. An activity can contain up to 500 costs. Costs cannot move between activities. Creating this record does not attach an invoice; its invoice attachment metadata is null. Add an invoice using the separate invoice attachment method. #### Access and locks Your current API access and the Event's Playbook visibility and lock settings apply, along with access to activity costs. #### Sending the request Use JSON, the query string or form data for values containing commas. Send comma-containing text and cost-center breakdowns in JSON, query parameters or form fields. To make a retry safe, send an Idempotency-Key. Resending the same request with the same key returns the saved response instead of adding a second cost. #### After the add This action sends no business email. Confirmed changes appear in activity history; a history-writing failure does not undo the change. If you can't confirm the result and didn't send an Idempotency-Key, retrieve the activity's costs before trying again; the API does not repeat the action automatically. #### Sending text Send plain text for Notes and other rich-text fields. Characters such as `&`, `<` and quotes, along with line breaks, are encoded for storage. Notes and other rich-text values in the response contain the stored HTML, including encoded characters and line breaks such as `
`. #### Hidden or locked tab If the Event's Playbook tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. An Event that is not in your workspace returns HTTP 404. Example — curl: ```bash curl -X POST "https://api.exhibitday.com/v1/events/playbook_activity_costs" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"playbook_activity_id\":12345,\"description\":\"Meeting room booking\"}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/playbook_activity_costs", { method: "POST", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "playbook_activity_id": 12345, "description": "Meeting room booking" }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.post( "https://api.exhibitday.com/v1/events/playbook_activity_costs", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"playbook_activity_id": 12345, "description": "Meeting room booking"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PostAsync("https://api.exhibitday.com/v1/events/playbook_activity_costs", JsonContent.Create(new { playbook_activity_id = 12345, description = "Meeting room booking" })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/playbook_activity_costs")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("POST", HttpRequest.BodyPublishers.ofString("{\"playbook_activity_id\":12345,\"description\":\"Meeting room booking\"}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"playbook_activity_id":12345,"description":"Meeting room booking"}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/playbook_activity_costs') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"playbook_activity_id":12345,"description":"Meeting room booking"}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/events/playbook_activity_costs", strings.NewReader("{\"playbook_activity_id\":12345,\"description\":\"Meeting room booking\"}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): POST /v1/events/playbook_activity_costs - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "id": 34567, "event_id": 23456, "event_name": "Sample Event", "playbook_activity_id": 12345, "description": "Meeting room booking", "vendor_payee": null, "reference_number": null, "expense_date": null, "notes": null, "payment_status_id": 0, "payment_status": { "id": 0, "name": "N/A" }, "payment_due_date": null, "next_payment_due_date": null, "payment_notes": null, "invoice_attachment": null, "cost": { "amount": 0.00, "cost_center_breakdown": [] } } ``` ### Update a Playbook Cost `PATCH https://api.exhibitday.com/v1/events/playbook_activity_costs` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=playbook#patch-v1-events-playbook_activity_costs Updates the fields you choose on an existing Playbook cost. Omitted fields keep their current values. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the cost in that activity. Use its ID from the cost list, Info or Create response; this is not an invoice or cost-allocation ID. | | | description | String | No | A description for this cost, up to 400 characters. This is required on create and cannot be cleared. | Max length: 400. | | vendor_payee | String | No | Vendor Payee, up to 200 characters. | Max length: 200. | | reference_number | String | No | Reference Number, up to 200 characters. | Max length: 200. | | expense_date | String | No | A calendar date in YYYY-MM-DD format, without a time or time zone. | | | notes | String | No | Plain-text Notes, up to 80,000 characters as saved, including formatting and encoded characters. Line breaks are retained. An over-limit value is refused, never shortened. On PATCH, an omitted or blank value keeps the current Notes; null clears them. | Max length: 80000. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | payment_status_id | Number | No | The cost's payment status. Omit or leave blank to keep it; null cannot clear it. This does not change the recorded amount or attach an invoice. | Allowed values: `0` (N/A) \| `1` (Paid in Full) \| `2` (Partially Paid) \| `3` (Not Paid Yet) | | payment_due_date | String | No | A calendar date in YYYY-MM-DD format, without a time or time zone. | | | next_payment_due_date | Date | No | A calendar date in YYYY-MM-DD format, without a time or time zone. Applies only when the payment status is Partially Paid. With any other status, supplying either this date or the payment status clears the date. | | | payment_notes | String | No | Payment Notes, up to 200 characters. | Max length: 200. | | cost | Number or cost object | No | The full cost, as a number or an object with amount and/or cost_center_breakdown. [Record Costs and Split Them Across Cost Centers](/Help/V1?guide=entering-costs). | Omit to keep the saved cost. A supplied value replaces its full allocation. | | expected_revision | String | No | The record_revision returned when you retrieved this record. Include it to avoid overwriting someone else's changes. Omit it to skip this check. | | Declared schema for `cost` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "anyOf": [ { "type": "number", "minimum": 0, "description": "Shorthand for an object with amount. The amount is rounded to cents before the supported storage range is checked.", "nullable": true }, { "type": "object", "additionalProperties": false, "properties": { "amount": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 }, "cost_center_breakdown": { "type": "array", "items": { "type": "object", "additionalProperties": false, "properties": { "cost_center_id": { "type": "integer", "format": "int64", "nullable": true }, "charge": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 }, "cost_center": { "type": "string", "description": "Optional and read-only: the cost center name a read returns, so a cost can be sent back unchanged. It is ignored; the line is saved by cost_center_id, and a name that doesn't match that cost center is explained in a warning.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "required": [ "charge" ] }, "maxItems": 2147483647 } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "anyOf": [ { "required": [ "amount" ] }, { "required": [ "cost_center_breakdown" ] } ], "nullable": true } ], "x-numeric-shorthand": "A number is equivalent to {amount:number}.", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": { "amount": 125.50 } } ``` #### Choosing what to change Send only what you want to change. Omitted or blank whole parameters keep their values; null clears only fields that allow it. With $ignore_params_with_empty_values=true, a whole JSON-null parameter is ignored, while the text "null" still requests clearing. A cost cannot move to another activity. Use the cost fields below to change its description, payment details or amounts. #### Access and locks Your current API access and the Event's Playbook visibility and lock settings apply, along with access to activity costs. #### Sending the request Use JSON, the query string or form data for values containing commas. Send comma-containing text and cost-center breakdowns in JSON, query parameters or form fields. This method ignores Idempotency-Key. #### After the update This action sends no business email. An unchanged PATCH writes no data, timestamp or history. Confirmed changes appear in activity history; a history-writing failure does not undo the change. If a save result cannot be confirmed, review the cost before trying again; the API does not repeat the action automatically. #### Sending text Send plain text for Notes and other rich-text fields. Characters such as `&`, `<` and quotes, along with line breaks, are encoded for storage. #### Hidden or locked tab If the Event's Playbook tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. An Event that is not in your workspace returns HTTP 404. Example — curl: ```bash curl -X PATCH "https://api.exhibitday.com/v1/events/playbook_activity_costs" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"id\":34567,\"description\":\"Meeting room booking\"}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/playbook_activity_costs", { method: "PATCH", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "id": 34567, "description": "Meeting room booking" }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.patch( "https://api.exhibitday.com/v1/events/playbook_activity_costs", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"id": 34567, "description": "Meeting room booking"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PatchAsync("https://api.exhibitday.com/v1/events/playbook_activity_costs", JsonContent.Create(new { id = 34567, description = "Meeting room booking" })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/playbook_activity_costs")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("PATCH", HttpRequest.BodyPublishers.ofString("{\"id\":34567,\"description\":\"Meeting room booking\"}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"id":34567,"description":"Meeting room booking"}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/playbook_activity_costs') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"id":34567,"description":"Meeting room booking"}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/events/playbook_activity_costs", strings.NewReader("{\"id\":34567,\"description\":\"Meeting room booking\"}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): PATCH /v1/events/playbook_activity_costs - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Playbook cost updated.", "errors": [] } ``` ### Delete a Playbook Cost `DELETE https://api.exhibitday.com/v1/events/playbook_activity_costs` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=playbook#delete-v1-events-playbook_activity_costs Permanently deletes one Playbook cost, its cost-center breakdown and its invoice. Other costs on the activity stay as they are. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the cost in that activity. Use its ID from the cost list, Info or Create response; this is not an invoice or cost-allocation ID. | | #### Access and locks Your current API access and the Event's Playbook visibility and lock settings apply, along with access to activity costs. #### Sending the request Use JSON, the query string or form data for values containing commas. This method ignores Idempotency-Key. #### After the deletion This action sends no business email. The deletion appears in activity history; a history-writing failure does not undo it. If you can't confirm the deletion, retrieve the activity's costs before trying again; the API does not repeat the action automatically. #### Hidden or locked tab If the Event's Playbook tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. An Event that is not in your workspace returns HTTP 404. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/events/playbook_activity_costs?id=34567" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/playbook_activity_costs?" + new URLSearchParams({ "id": "34567" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/events/playbook_activity_costs", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 34567}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/events/playbook_activity_costs?id=34567"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/playbook_activity_costs?id=34567")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/playbook_activity_costs?id=34567') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/events/playbook_activity_costs?id=34567", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/events/playbook_activity_costs - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Playbook cost removed.", "errors": [] } ``` ### Download Playbook Cost Invoice Attachment `GET https://api.exhibitday.com/v1/events/playbook_activity_costs/invoice_attachment/download` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=playbook#get-v1-events-playbook_activity_costs-invoice_attachment-download Downloads the original Invoice Attachment for this Playbook Cost. Use this method to retrieve the file itself. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | playbook_activity_cost_id | Number | Yes | The ID of the Playbook cost entry. | Use the cost entry's id from Retrieve Playbook Costs (GET /v1/events/playbook_activity_costs), rather than a cost-center allocation ID. Each cost entry has its own Invoice Attachment. The API finds the cost's Playbook activity, so playbook_activity_id is not sent. | #### Finding the file In the web app, this is the invoice control beside the selected Playbook activity's cost entry. Each cost has one Invoice Attachment even when its amount is split among cost centers. For file metadata, retrieve the parent record with GET /v1/events/playbook_activity_costs/info and read invoice_attachment. Use this download method for the contents. No attachment ID or invoice flag is needed. #### Download response A successful response contains the original uploaded file, with a safe download filename. API errors use the usual JSON response. If no invoice is attached, this method returns HTTP 404. Current record, financial and invoice permissions apply. A locked tab can still be read. Permitted downloads remain available on the Free plan. #### Files still being copied If this file is still being copied, the download returns HTTP 409 with file_copy_pending. Try the download again in a few minutes. #### Hidden tab If the Event's Playbook tab is hidden, this request returns HTTP 400 (not_allowed), and the message says the tab is hidden. Show the tab in ExhibitDay first. A locked tab can still be read. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X GET "https://api.exhibitday.com/v1/events/playbook_activity_costs/invoice_attachment/download?playbook_activity_cost_id=12345" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi mv response-body.tmp 'invoice.pdf' ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const response = await fetch("https://api.exhibitday.com/v1/events/playbook_activity_costs/invoice_attachment/download?playbook_activity_cost_id=12345", { method: "GET", headers: { Authorization: 'Bearer YOUR_API_KEY' } }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); await writeFile("invoice.pdf", new Uint8Array(await response.arrayBuffer())); ``` Example — Python: ```python import requests import json response = requests.request("GET", "https://api.exhibitday.com/v1/events/playbook_activity_costs/invoice_attachment/download?playbook_activity_cost_id=12345", headers={'Authorization': 'Bearer YOUR_API_KEY'}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') with open("invoice.pdf", 'wb') as destination: destination.write(response.content) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.exhibitday.com/v1/events/playbook_activity_costs/invoice_attachment/download?playbook_activity_cost_id=12345"); using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); await File.WriteAllBytesAsync("invoice.pdf", await response.Content.ReadAsByteArrayAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/playbook_activity_costs/invoice_attachment/download?playbook_activity_cost_id=12345")).header("Authorization", "Bearer YOUR_API_KEY"); HttpResponse response = HttpClient.newHttpClient().send(request.method("GET", HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); Files.write(Path.of("invoice.pdf"), response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); file_put_contents('invoice.pdf', $response); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/playbook_activity_costs/invoice_attachment/download?playbook_activity_cost_id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' File.binwrite('invoice.pdf', response.body) ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/playbook_activity_costs/invoice_attachment/download?playbook_activity_cost_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } if err := os.WriteFile("invoice.pdf", data, 0600); err != nil { log.Fatal(err) } fmt.Println("File saved") } ``` HTTP 200: Returns the original uploaded file as a private download, using a safe filename. If the file cannot be downloaded, the response contains the usual JSON API error instead. Media: application/octet-stream. The body is the authorized file's real bytes, not JSON or base64. Errors are JSON status responses; check HTTP status before saving the file. ### Add Playbook Cost Invoice Attachment `POST https://api.exhibitday.com/v1/events/playbook_activity_costs/invoice_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=playbook#post-v1-events-playbook_activity_costs-invoice_attachment Adds one Invoice Attachment to this Playbook Cost. You can attach an invoice, receipt or other payment document when no invoice file is currently attached. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | playbook_activity_cost_id | Number | Yes | The ID of the Playbook cost entry. | Use the cost entry's id from Retrieve Playbook Costs (GET /v1/events/playbook_activity_costs), rather than a cost-center allocation ID. Each cost entry has its own Invoice Attachment. The API finds the cost's Playbook activity, so playbook_activity_id is not sent. | | file | File (multipart) | Yes | The Invoice Attachment to upload. | Send exactly one complete, nonempty multipart/form-data file part named file. The supported extensions and current per-file limit are shown below; the complete request limit also includes multipart overhead. A missing or null file is invalid and does not remove an existing invoice. | | Idempotency-Key | String | No | A unique key for safely retrying this upload. | Optional HTTP header: 1 to 255 visible ASCII characters without spaces or commas. Retry the identical request with the same key to replay its first saved response. Use a new key for a different upload. | Declared schema for `file` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "string", "format": "binary", "x-maximum-bytes": 26214400, "x-allowed-extensions": [ "png", "jpg", "jpeg", "bmp", "gif", "pdf", "msg", "eml", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "rtf", "odp", "odt", "ods", "txt", "wks", "zip" ] } ``` #### Before you upload POST requires an empty invoice slot. If an invoice is already attached, the API returns HTTP 409; use PATCH to replace it. An Invoice Attachment is separate from the record's supporting File Attachments. Use the invoice control beside the selected Playbook activity's cost entry in the web app. #### After the upload The response's invoice_attachment contains the attached file's id, filename and attachment_created_timestamp. The amount, payment fields, cost-center breakdown and other files are unchanged. The upload is recorded in Event history. Attaching an invoice does not mark the record as paid. #### Access and retries A current upload-enabled plan, record and financial permissions, and an editable applicable tab are required. Each uploaded file must fit its supported type and size limits. expected_revision is not supported by this file method. If the save outcome cannot be confirmed, retrieve the current parent record with GET /v1/events/playbook_activity_costs/info and inspect invoice_attachment before deciding whether to retry. #### Hidden or locked tab If the Event's Playbook tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X POST "https://api.exhibitday.com/v1/events/playbook_activity_costs/invoice_attachment" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}" --form-string "playbook_activity_cost_id=12345" --form "file=@invoice.pdf;type=application/octet-stream") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi cat response-body.tmp ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const form = new FormData(); form.append("playbook_activity_cost_id", "12345"); form.append("file", new Blob([await readFile("invoice.pdf")], { type: "application/octet-stream" }), "invoice.pdf"); const response = await fetch("https://api.exhibitday.com/v1/events/playbook_activity_costs/invoice_attachment", { method: "POST", headers: { Authorization: 'Bearer YOUR_API_KEY' }, body: form }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); console.log(await response.json()); ``` Example — Python: ```python import requests import json from contextlib import ExitStack with ExitStack() as stack: files = [ ("file", ("invoice.pdf", stack.enter_context(open("invoice.pdf", 'rb')), "application/octet-stream")), ] response = requests.request("POST", "https://api.exhibitday.com/v1/events/playbook_activity_costs/invoice_attachment", headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data={"playbook_activity_cost_id": "12345"}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') print(response.json()) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.exhibitday.com/v1/events/playbook_activity_costs/invoice_attachment"); var form = new MultipartFormDataContent(); form.Add(new StringContent("12345"), "playbook_activity_cost_id"); var file0 = new StreamContent(File.OpenRead("invoice.pdf")); file0.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(file0, "file", "invoice.pdf"); request.Content = form; using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/playbook_activity_costs/invoice_attachment")).header("Authorization", "Bearer YOUR_API_KEY"); String boundary = "ExhibitDay-" + UUID.randomUUID(); ByteArrayOutputStream form = new ByteArrayOutputStream(); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"playbook_activity_cost_id\"\r\n\r\n" + "12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"invoice.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8)); form.write(Files.readAllBytes(Path.of("invoice.pdf"))); form.write("\r\n".getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); request.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpResponse response = HttpClient.newHttpClient().send(request.method("POST", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); System.out.println(new String(response.body(), StandardCharsets.UTF_8)); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], CURLOPT_POSTFIELDS => [ 'playbook_activity_cost_id' => '12345', 'file' => new CURLFile('invoice.pdf', 'application/octet-stream', 'invoice.pdf'), ], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); echo $response; ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/playbook_activity_costs/invoice_attachment') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' files = [] begin parts = [ ['playbook_activity_cost_id', '12345'], ['file', (files << File.open('invoice.pdf', 'rb')).last, {filename: 'invoice.pdf', content_type: 'application/octet-stream'}], ] request.set_form(parts, 'multipart/form-data') response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' puts response.body ensure files.each(&:close) end ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" "bytes" "mime/multipart" "net/textproto" ) func main() { var form bytes.Buffer writer := multipart.NewWriter(&form) if err := writer.WriteField("playbook_activity_cost_id", "12345"); err != nil { log.Fatal(err) } header0 := textproto.MIMEHeader{} header0.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"invoice.pdf\"") header0.Set("Content-Type", "application/octet-stream") part0, err := writer.CreatePart(header0) if err != nil { log.Fatal(err) } file0, err := os.Open("invoice.pdf") if err != nil { log.Fatal(err) } if _, err = io.Copy(part0, file0); err != nil { log.Fatal(err) } file0.Close() if err := writer.Close(); err != nil { log.Fatal(err) } request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/events/playbook_activity_costs/invoice_attachment", &form) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", writer.FormDataContentType()) response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } fmt.Printf("%s\n", data) } ``` Example HTTP response body (JSON): POST /v1/events/playbook_activity_costs/invoice_attachment - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "invoice_attachment": { "id": 12345, "filename": "invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } } ``` ### Replace Playbook Cost Invoice Attachment `PATCH https://api.exhibitday.com/v1/events/playbook_activity_costs/invoice_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=playbook#patch-v1-events-playbook_activity_costs-invoice_attachment Replaces this Playbook Cost's current Invoice Attachment with one uploaded file. Use this method when an invoice file is already attached. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | playbook_activity_cost_id | Number | Yes | The ID of the Playbook cost entry. | Use the cost entry's id from Retrieve Playbook Costs (GET /v1/events/playbook_activity_costs), rather than a cost-center allocation ID. Each cost entry has its own Invoice Attachment. The API finds the cost's Playbook activity, so playbook_activity_id is not sent. | | file | File (multipart) | Yes | The Invoice Attachment to upload. | Send exactly one complete, nonempty multipart/form-data file part named file. The supported extensions and current per-file limit are shown below; the complete request limit also includes multipart overhead. A missing or null file is invalid and does not remove an existing invoice. | Declared schema for `file` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "string", "format": "binary", "x-maximum-bytes": 26214400, "x-allowed-extensions": [ "png", "jpg", "jpeg", "bmp", "gif", "pdf", "msg", "eml", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "rtf", "odp", "odt", "ods", "txt", "wks", "zip" ] } ``` #### Replacing the current file PATCH requires a current invoice file. If none is attached, the API returns HTTP 404. Upload exactly one file; the previous attachment ID is not needed. If another request changes the current invoice during your upload, the API refuses this request instead of replacing a different file. Even identical replacement contents receive a new attachment ID. #### After the replacement The response's invoice_attachment contains the attached file's id, filename and attachment_created_timestamp. The amount, payment fields, cost-center breakdown and other files are unchanged. The previous file is scheduled for physical cleanup after a confirmed save; cleanup may finish later. The replacement is recorded in Event history. #### Access and retries A current upload-enabled plan, record and financial permissions, and an editable applicable tab are required. Each uploaded file must fit its supported type and size limits. expected_revision is not supported by this file method. PATCH does not use Idempotency-Key replay. If the save outcome cannot be confirmed, retrieve the current parent record with GET /v1/events/playbook_activity_costs/info and inspect invoice_attachment before deciding whether to retry. #### Hidden or locked tab If the Event's Playbook tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X PATCH "https://api.exhibitday.com/v1/events/playbook_activity_costs/invoice_attachment" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}" --form-string "playbook_activity_cost_id=12345" --form "file=@invoice.pdf;type=application/octet-stream") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi cat response-body.tmp ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const form = new FormData(); form.append("playbook_activity_cost_id", "12345"); form.append("file", new Blob([await readFile("invoice.pdf")], { type: "application/octet-stream" }), "invoice.pdf"); const response = await fetch("https://api.exhibitday.com/v1/events/playbook_activity_costs/invoice_attachment", { method: "PATCH", headers: { Authorization: 'Bearer YOUR_API_KEY' }, body: form }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); console.log(await response.json()); ``` Example — Python: ```python import requests import json from contextlib import ExitStack with ExitStack() as stack: files = [ ("file", ("invoice.pdf", stack.enter_context(open("invoice.pdf", 'rb')), "application/octet-stream")), ] response = requests.request("PATCH", "https://api.exhibitday.com/v1/events/playbook_activity_costs/invoice_attachment", headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data={"playbook_activity_cost_id": "12345"}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') print(response.json()) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("PATCH"), "https://api.exhibitday.com/v1/events/playbook_activity_costs/invoice_attachment"); var form = new MultipartFormDataContent(); form.Add(new StringContent("12345"), "playbook_activity_cost_id"); var file0 = new StreamContent(File.OpenRead("invoice.pdf")); file0.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(file0, "file", "invoice.pdf"); request.Content = form; using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/playbook_activity_costs/invoice_attachment")).header("Authorization", "Bearer YOUR_API_KEY"); String boundary = "ExhibitDay-" + UUID.randomUUID(); ByteArrayOutputStream form = new ByteArrayOutputStream(); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"playbook_activity_cost_id\"\r\n\r\n" + "12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"invoice.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8)); form.write(Files.readAllBytes(Path.of("invoice.pdf"))); form.write("\r\n".getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); request.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpResponse response = HttpClient.newHttpClient().send(request.method("PATCH", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); System.out.println(new String(response.body(), StandardCharsets.UTF_8)); } } ``` Example — PHP: ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], CURLOPT_POSTFIELDS => [ 'playbook_activity_cost_id' => '12345', 'file' => new CURLFile('invoice.pdf', 'application/octet-stream', 'invoice.pdf'), ], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); echo $response; ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/playbook_activity_costs/invoice_attachment') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' files = [] begin parts = [ ['playbook_activity_cost_id', '12345'], ['file', (files << File.open('invoice.pdf', 'rb')).last, {filename: 'invoice.pdf', content_type: 'application/octet-stream'}], ] request.set_form(parts, 'multipart/form-data') response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' puts response.body ensure files.each(&:close) end ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" "bytes" "mime/multipart" "net/textproto" ) func main() { var form bytes.Buffer writer := multipart.NewWriter(&form) if err := writer.WriteField("playbook_activity_cost_id", "12345"); err != nil { log.Fatal(err) } header0 := textproto.MIMEHeader{} header0.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"invoice.pdf\"") header0.Set("Content-Type", "application/octet-stream") part0, err := writer.CreatePart(header0) if err != nil { log.Fatal(err) } file0, err := os.Open("invoice.pdf") if err != nil { log.Fatal(err) } if _, err = io.Copy(part0, file0); err != nil { log.Fatal(err) } file0.Close() if err := writer.Close(); err != nil { log.Fatal(err) } request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/events/playbook_activity_costs/invoice_attachment", &form) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", writer.FormDataContentType()) response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } fmt.Printf("%s\n", data) } ``` Example HTTP response body (JSON): PATCH /v1/events/playbook_activity_costs/invoice_attachment - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "invoice_attachment": { "id": 12345, "filename": "invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } } ``` ### Remove Playbook Cost Invoice Attachment `DELETE https://api.exhibitday.com/v1/events/playbook_activity_costs/invoice_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=playbook#delete-v1-events-playbook_activity_costs-invoice_attachment Removes this Playbook Cost's Invoice Attachment. The cost, payment details and other File Attachments stay in place. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | playbook_activity_cost_id | Number | Yes | The ID of the Playbook cost entry. | Use the cost entry's id from Retrieve Playbook Costs (GET /v1/events/playbook_activity_costs), rather than a cost-center allocation ID. Each cost entry has its own Invoice Attachment. The API finds the cost's Playbook activity, so playbook_activity_id is not sent. | #### After the removal The Invoice Attachment is cleared and the removal is recorded in Event history. Its physical file is scheduled for cleanup after a confirmed save; cleanup may finish later. Costs, payment fields, cost-center allocations and supporting files stay unchanged. If no invoice is attached, DELETE returns HTTP 404 Not Found with the message "This Playbook Cost has no invoice to remove." No saved data or history is changed. Current access and the record's binding are still checked. Do not send file parts with this request. #### Access and retries Current record, financial and invoice permissions and applicable tab-edit access are required. Permitted removals remain available on the Free plan. expected_revision is not supported, and DELETE does not use Idempotency-Key replay. If the save outcome cannot be confirmed, retrieve the current parent record with GET /v1/events/playbook_activity_costs/info and inspect invoice_attachment before deciding whether to retry. #### Hidden or locked tab If the Event's Playbook tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/events/playbook_activity_costs/invoice_attachment?playbook_activity_cost_id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/playbook_activity_costs/invoice_attachment?" + new URLSearchParams({ "playbook_activity_cost_id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/events/playbook_activity_costs/invoice_attachment", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"playbook_activity_cost_id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/events/playbook_activity_costs/invoice_attachment?playbook_activity_cost_id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/playbook_activity_costs/invoice_attachment?playbook_activity_cost_id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/playbook_activity_costs/invoice_attachment?playbook_activity_cost_id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/events/playbook_activity_costs/invoice_attachment?playbook_activity_cost_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/events/playbook_activity_costs/invoice_attachment - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Attachment removed.", "errors": [] } ``` ### Retrieve Playbook Activity General File Attachments `GET https://api.exhibitday.com/v1/events/playbook_activities/attachments` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=playbook#get-v1-events-playbook_activities-attachments Retrieves the General File Attachments on this Playbook Activity. Each result includes the file's ID, name and added time; use the download method for its contents. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | playbook_activity_id | Number | Yes | The ID of the Playbook activity, from Retrieve Playbook Activities (GET /v1/events/playbook_activities) or its add response. | | | $limit | Number | No | The most File Attachments to return. | A positive whole number. Omit for all remaining matching files. | | $offset | Number | No | The number of matching File Attachments to skip. | A whole number of 0 or more. Default: 0. | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records. | Allowed values: `array` | | If-None-Match | String | No | An ETag from an earlier response to this GET. | Optional HTTP header. If the successful response is unchanged, the API returns HTTP 304 with no body. | #### Reading the file list Files are ordered by added time, then attachment ID, lowest first. Only files available under your current access are included. Paging totals and X-Total-Count count all matching files before $limit and $offset are applied. A record with no files you can view returns an empty list. This list does not return edit revisions or support changed-since filtering. #### Supporting files and invoices A Playbook activity can have several cost entries, each with its own Invoice Attachment. Those files use the cost-invoice methods; this list contains the activity's General File Attachments. #### Access The record's Event and tab must be available, and the tab must not be hidden. A locked tab can still be read. #### Hidden tab If the Event's Playbook tab is hidden, this request returns HTTP 400 (not_allowed), and the message says the tab is hidden. Show the tab in ExhibitDay first. A locked tab can still be read. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/events/playbook_activities/attachments?playbook_activity_id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/playbook_activities/attachments?" + new URLSearchParams({ "playbook_activity_id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/events/playbook_activities/attachments", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"playbook_activity_id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/events/playbook_activities/attachments?playbook_activity_id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/playbook_activities/attachments?playbook_activity_id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/playbook_activities/attachments?playbook_activity_id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/playbook_activities/attachments?playbook_activity_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/events/playbook_activities/attachments - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "attachment", "list_data": [ { "id": 12345, "filename": "attachment.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } ] } ``` ### Add Playbook Activity General File Attachments `POST https://api.exhibitday.com/v1/events/playbook_activities/attachments` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=playbook#post-v1-events-playbook_activities-attachments Adds one or more General File Attachments to this Playbook Activity. Send each file as a multipart upload part named file. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | playbook_activity_id | Number | Yes | The ID of the Playbook activity, from Retrieve Playbook Activities (GET /v1/events/playbook_activities) or its add response. | | | file | File (multipart) | Yes | The File Attachments to upload. | Send one or more complete, nonempty multipart/form-data parts, each named file. Supported types and the current per-file limit are shown below. The complete request limit includes all files and multipart overhead; split larger batches. A missing or null upload is not a removal request. | | Idempotency-Key | String | No | A unique key for safely retrying this upload. | Optional HTTP header: 1 to 255 visible ASCII characters without spaces or commas. Retry the identical request with the same key to replay its first saved response. Use a new key for a different upload. | Declared schema for `file` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "array", "items": { "type": "string", "format": "binary", "x-maximum-bytes": 26214400, "x-allowed-extensions": [ "png", "jpg", "jpeg", "bmp", "gif", "pdf", "msg", "eml", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "rtf", "odp", "odt", "ods", "txt", "wks", "zip" ] } } ``` #### After the upload The response's list_data contains the newly attached files, including each id, filename and attachment_created_timestamp. Existing files are kept. Use each returned id to download or remove that file. Identical repeated files in one request are attached once when their cleaned filename, length and contents match. Files with different contents remain separate even when their names match. This does not remove or replace files already attached to the record. #### Choosing the right file method These uploads add supporting files to the activity. Use the Playbook Cost Invoice Attachment methods with the cost entry's ID to attach an invoice or receipt to a specific cost. Adding supporting files does not change the activity's costs or payments. #### Access Current record and file-change permissions and applicable Event/tab locks must allow this upload. An upload-enabled paid plan is required. #### History and retries A confirmed file change is recorded in history. expected_revision is not supported by these file methods. If the save outcome cannot be confirmed, retrieve the current file list before deciding whether to retry; the API does not automatically repeat an uncertain change. Supporting File Attachments have no PATCH replacement. To replace one, add the new file and remove the old one using their separate requests; each request has its own outcome. #### Hidden or locked tab If the Event's Playbook tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X POST "https://api.exhibitday.com/v1/events/playbook_activities/attachments" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}" --form-string "playbook_activity_id=12345" --form "file=@attachment.pdf;type=application/octet-stream") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi cat response-body.tmp ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const form = new FormData(); form.append("playbook_activity_id", "12345"); form.append("file", new Blob([await readFile("attachment.pdf")], { type: "application/octet-stream" }), "attachment.pdf"); const response = await fetch("https://api.exhibitday.com/v1/events/playbook_activities/attachments", { method: "POST", headers: { Authorization: 'Bearer YOUR_API_KEY' }, body: form }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); console.log(await response.json()); ``` Example — Python: ```python import requests import json from contextlib import ExitStack with ExitStack() as stack: files = [ ("file", ("attachment.pdf", stack.enter_context(open("attachment.pdf", 'rb')), "application/octet-stream")), ] response = requests.request("POST", "https://api.exhibitday.com/v1/events/playbook_activities/attachments", headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data={"playbook_activity_id": "12345"}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') print(response.json()) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.exhibitday.com/v1/events/playbook_activities/attachments"); var form = new MultipartFormDataContent(); form.Add(new StringContent("12345"), "playbook_activity_id"); var file0 = new StreamContent(File.OpenRead("attachment.pdf")); file0.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(file0, "file", "attachment.pdf"); request.Content = form; using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/playbook_activities/attachments")).header("Authorization", "Bearer YOUR_API_KEY"); String boundary = "ExhibitDay-" + UUID.randomUUID(); ByteArrayOutputStream form = new ByteArrayOutputStream(); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"playbook_activity_id\"\r\n\r\n" + "12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"attachment.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8)); form.write(Files.readAllBytes(Path.of("attachment.pdf"))); form.write("\r\n".getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); request.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpResponse response = HttpClient.newHttpClient().send(request.method("POST", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); System.out.println(new String(response.body(), StandardCharsets.UTF_8)); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], CURLOPT_POSTFIELDS => [ 'playbook_activity_id' => '12345', 'file' => new CURLFile('attachment.pdf', 'application/octet-stream', 'attachment.pdf'), ], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); echo $response; ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/playbook_activities/attachments') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' files = [] begin parts = [ ['playbook_activity_id', '12345'], ['file', (files << File.open('attachment.pdf', 'rb')).last, {filename: 'attachment.pdf', content_type: 'application/octet-stream'}], ] request.set_form(parts, 'multipart/form-data') response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' puts response.body ensure files.each(&:close) end ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" "bytes" "mime/multipart" "net/textproto" ) func main() { var form bytes.Buffer writer := multipart.NewWriter(&form) if err := writer.WriteField("playbook_activity_id", "12345"); err != nil { log.Fatal(err) } header0 := textproto.MIMEHeader{} header0.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"attachment.pdf\"") header0.Set("Content-Type", "application/octet-stream") part0, err := writer.CreatePart(header0) if err != nil { log.Fatal(err) } file0, err := os.Open("attachment.pdf") if err != nil { log.Fatal(err) } if _, err = io.Copy(part0, file0); err != nil { log.Fatal(err) } file0.Close() if err := writer.Close(); err != nil { log.Fatal(err) } request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/events/playbook_activities/attachments", &form) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", writer.FormDataContentType()) response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } fmt.Printf("%s\n", data) } ``` Example HTTP response body (JSON): POST /v1/events/playbook_activities/attachments - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "attachment", "list_data": [ { "id": 12345, "filename": "attachment.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } ] } ``` ### Remove a Playbook Activity General File Attachment `DELETE https://api.exhibitday.com/v1/events/playbook_activities/attachments` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=playbook#delete-v1-events-playbook_activities-attachments Removes one General File Attachment from this Playbook Activity. Other attached files and the record's details stay in place. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the File Attachment. | Use the id from the attachment list. The API finds the record the file belongs to, so no record ID is sent. An Invoice Attachment is not selected by this method. | #### After the removal Only the selected file association is removed. Its physical file is scheduled for cleanup after a confirmed save; cleanup may finish later. Other attached files stay in place. Send only the file's id; the API finds the record it belongs to. A missing, already removed or unavailable attachment returns HTTP 404 Not Found. Do not send file parts with DELETE. #### Access Current record and file-removal permissions and applicable Event/tab locks must allow this change. Permitted removals remain available on the Free plan. #### History and retries A confirmed file change is recorded in history. expected_revision is not supported by these file methods. DELETE does not use Idempotency-Key replay. If the save outcome cannot be confirmed, retrieve the current file list before deciding whether to retry; the API does not automatically repeat an uncertain change. Supporting File Attachments have no PATCH replacement. To replace one, add the new file and remove the old one using their separate requests; each request has its own outcome. #### Hidden or locked tab If the Event's Playbook tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/events/playbook_activities/attachments?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/playbook_activities/attachments?" + new URLSearchParams({ "id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/events/playbook_activities/attachments", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/events/playbook_activities/attachments?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/playbook_activities/attachments?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/playbook_activities/attachments?id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/events/playbook_activities/attachments?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/events/playbook_activities/attachments - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Attachment removed.", "errors": [] } ``` ### Download a Playbook Activity General File Attachment `GET https://api.exhibitday.com/v1/events/playbook_activities/attachments/download` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=playbook#get-v1-events-playbook_activities-attachments-download Downloads one original General File Attachment from this Playbook Activity. Select the file using its ID from the attachment list. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the File Attachment. | Use the id from the attachment list. The API finds the record the file belongs to, so no record ID is sent. An Invoice Attachment is not selected by this method. | #### Download response A successful response contains the original uploaded file with a safe download filename. API errors use the usual JSON response. A missing or unavailable file returns HTTP 404. Send only the file's id from the attachment list to download that one file; the API finds the record it belongs to. The download leaves the record unchanged. #### Access The record's Event and tab must be available, and the tab must not be hidden. A locked tab can still be read. #### Files still being copied If this file is still being copied, the download returns HTTP 409 with file_copy_pending. Try the download again in a few minutes. #### Hidden tab If the Event's Playbook tab is hidden, this request returns HTTP 400 (not_allowed), and the message says the tab is hidden. Show the tab in ExhibitDay first. A locked tab can still be read. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X GET "https://api.exhibitday.com/v1/events/playbook_activities/attachments/download?id=12345" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi mv response-body.tmp 'attachment.pdf' ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const response = await fetch("https://api.exhibitday.com/v1/events/playbook_activities/attachments/download?id=12345", { method: "GET", headers: { Authorization: 'Bearer YOUR_API_KEY' } }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); await writeFile("attachment.pdf", new Uint8Array(await response.arrayBuffer())); ``` Example — Python: ```python import requests import json response = requests.request("GET", "https://api.exhibitday.com/v1/events/playbook_activities/attachments/download?id=12345", headers={'Authorization': 'Bearer YOUR_API_KEY'}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') with open("attachment.pdf", 'wb') as destination: destination.write(response.content) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.exhibitday.com/v1/events/playbook_activities/attachments/download?id=12345"); using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); await File.WriteAllBytesAsync("attachment.pdf", await response.Content.ReadAsByteArrayAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/playbook_activities/attachments/download?id=12345")).header("Authorization", "Bearer YOUR_API_KEY"); HttpResponse response = HttpClient.newHttpClient().send(request.method("GET", HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); Files.write(Path.of("attachment.pdf"), response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); file_put_contents('attachment.pdf', $response); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/playbook_activities/attachments/download?id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' File.binwrite('attachment.pdf', response.body) ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/playbook_activities/attachments/download?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } if err := os.WriteFile("attachment.pdf", data, 0600); err != nil { log.Fatal(err) } fmt.Println("File saved") } ``` HTTP 200: Returns the original uploaded file as a private download, using a safe filename. If the file cannot be downloaded, the response contains the usual JSON API error instead. Media: application/octet-stream. The body is the authorized file's real bytes, not JSON or base64. Errors are JSON status responses; check HTTP status before saving the file. ## Events - Misc. Expenses & Credits Miscellaneous expenses and credits on an Event: amounts, invoices, file attachments and exports. Documentation page: https://api.exhibitday.com/Help/V1?epf=100 ### Retrieve a Single Misc. Expense / Credit by ID `GET https://api.exhibitday.com/v1/events/misc_expenses_credits/info` Documentation: https://api.exhibitday.com/Help/V1?epf=100#get-v1-events-misc_expenses_credits-info Retrieves information about a specific event miscellaneous expense/credit (using the "id" parameter). The response includes invoice_attachment immediately after payment_notes, without a hydration option. It contains the invoice attachment ID, original file name and added time, or null when no invoice is attached. Use the invoice download method for its contents. Existing record and amount visibility is preserved; inaccessible invoice metadata is null. An inconsistent saved invoice reference returns HTTP409 rather than being shown as an empty slot. Invoice attachments are separate from the parent record's edit revision. Older path, still accepted: /v1/events/miscexpensecredit. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | Id of the specific event miscellaneous expense/credit that you would like to retrieve. | | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` | | $on_error_return_empty_result | Boolean | No | For a missing or invalid expense/credit id, or a record not found, return HTTP 200 with null (or [null] when $result_format=array). Authentication, rate-limit and unexpected server errors keep their normal HTTP status. | Default: false. | | $include_record_revision | Boolean | No | Set to true to include record_revision in the response. Send that value as expected_revision when updating to check for conflicting changes. | Default: false. | Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/events/misc_expenses_credits/info?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/misc_expenses_credits/info?" + new URLSearchParams({ "id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/events/misc_expenses_credits/info", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/events/misc_expenses_credits/info?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/misc_expenses_credits/info?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/misc_expenses_credits/info?id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/misc_expenses_credits/info?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/events/misc_expenses_credits/info - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "id": 12345, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=12345&riType=8&riSub=0&riId=12345", "description": "Sample description", "is_credit": false, "expense_date": "2026-03-14", "vendor_payee": "Acme Printing", "reference_number": "INV-20431", "cost": { "amount": 125.50, "cost_center_breakdown": [ { "cost_center_id": 34567, "cost_center": "Marketing", "charge": 75.50 }, { "cost_center_id": 34568, "cost_center": "Operations", "charge": 50.00 } ] }, "notes": "", "payment_due_date": null, "payment_status": { "id": 0, "name": "Not Specified" }, "next_payment_due_date": null, "payment_notes": null, "expected_credit_date": null, "credit_status": null, "credit_notes": null, "invoice_attachment": { "id": 682345, "filename": "expense-invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" }, "tagged_users": [ { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, { "id": "66666666-7777-4888-8999-aaaaaaaaaaaa", "first_name": "Alex", "last_name": "Morgan", "display_name": "Alex Morgan", "email": "alex@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true } ], "event_id": 12345, "event": { "id": 12345, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=12345", "name": "Sample Event", "start_date": "2026-12-21", "end_date": "2026-12-23", "participation_type_id": 1, "participation_type": "Committed", "format_id": 1, "format": "In-Person", "event_created_timestamp": "2026-11-21T17:00:00Z", "event_last_update_timestamp": "2026-11-21T17:00:00Z" }, "event_misc_expense_credit_created_timestamp": "2026-11-21T17:00:00Z", "event_misc_expense_credit_last_update_timestamp": "2026-11-21T17:00:00Z", "integration_metadata_field_1": "", "integration_metadata_field_2": "", "integration_metadata_field_3": "", "integration_metadata_field_4": "", "integration_metadata_field_5": "", "related_items": [ { "id": 5551, "related_item_id": 67890, "related_item_exhibitday_url": "https://www.exhibitday.com/Workspace/TaskView/98765?tid=67890", "related_item_type_id": 1, "related_item_type": "Task", "related_item_asset_type_id": null, "related_item_name": "Confirm booth graphics with the printer", "related_item_created_timestamp": "2030-01-10T14:03:00Z" }, { "id": 5552, "related_item_id": 45678, "related_item_exhibitday_url": "https://www.exhibitday.com/Workspace/RelatedItemView/98765?typeId=4&subTypeId=0&rid=45678", "related_item_type_id": 4, "related_item_type": "Shipment", "related_item_asset_type_id": null, "related_item_name": "Booth crates to convention center", "related_item_created_timestamp": "2030-01-10T14:03:00Z" } ] } ``` ### Retrieve Misc. Expenses / Credits `GET https://api.exhibitday.com/v1/events/misc_expenses_credits` Documentation: https://api.exhibitday.com/Help/V1?epf=100#get-v1-events-misc_expenses_credits Retrieves Misc Expenses and Credits across readable Events in your workspace. Optionally filter by Event, tagged people, integration metadata or the last update time. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | filter_by_event_id | Number | No | Only include miscellaneous expenses/credits for a given event. | | | filter_by_integration_metadata_field_1 | String | No | Only include event miscellaneous expenses/credits that have their integration_metadata_field_1 property equal to the value you pass in for this parameter. Note: The integration_metadata_field_1 property is an integration-specific text field only accessible via the ExhibitDay API. This field is typically used to store metadata or information about a particular miscellaneous expense/credit (e.g., the "external id" of the expense from another system you're integrating with). | Max length: 3000. | | filter_by_integration_metadata_field_2 | String | No | Only include event miscellaneous expenses/credits that have their integration_metadata_field_2 property equal to the value you pass in for this parameter. Note: The integration_metadata_field_2 property is an integration-specific text field only accessible via the ExhibitDay API. This field is typically used to store metadata or information about a particular miscellaneous expense/credit (e.g., the "external id" of the expense from another system you're integrating with). | Max length: 3000. | | filter_by_integration_metadata_field_3 | String | No | Only include event miscellaneous expenses/credits that have their integration_metadata_field_3 property equal to the value you pass in for this parameter. Note: The integration_metadata_field_3 property is an integration-specific text field only accessible via the ExhibitDay API. This field is typically used to store metadata or information about a particular miscellaneous expense/credit (e.g., the "external id" of the expense from another system you're integrating with). | Max length: 3000. | | filter_by_integration_metadata_field_4 | String | No | Only include event miscellaneous expenses/credits that have their integration_metadata_field_4 property equal to the value you pass in for this parameter. Note: The integration_metadata_field_4 property is an integration-specific text field only accessible via the ExhibitDay API. This field is typically used to store metadata or information about a particular miscellaneous expense/credit (e.g., the "external id" of the expense from another system you're integrating with). | Max length: 3000. | | filter_by_integration_metadata_field_5 | String | No | Only include event miscellaneous expenses/credits that have their integration_metadata_field_5 property equal to the value you pass in for this parameter. Note: The integration_metadata_field_5 property is an integration-specific text field only accessible via the ExhibitDay API. This field is typically used to store metadata or information about a particular miscellaneous expense/credit (e.g., the "external id" of the expense from another system you're integrating with). | Max length: 3000. | | filter_by_last_update_timestamp_greater_than_or_equal_to | String | No | Only include miscellaneous expenses/credits that were added or changed on or after this date and time, for example 2026-10-14T18:30:00 (a date alone, such as 2026-10-14, means midnight). Responses give event_misc_expense_credit_last_update_timestamp in UTC (it ends in Z), and that value can be passed back unchanged; a value without an offset is read as US Eastern time, and any other offset (e.g., 2026-10-14T18:30:00-04:00) is converted. To sync changes, process and save every page before advancing the cursor. Save the latest event_misc_expense_credit_last_update_timestamp you receive and pass it in next time (miscellaneous expenses/credits changed at exactly that time come back again, upsert every returned record by id, including boundary records). Deleted miscellaneous expenses/credits are not returned. Any other value is rejected with an error. | | | $limit | Number | No | The most miscellaneous expenses/credits to return (a whole number of 1 or more). Use it with $offset to read a long list in pages: total_records in the response counts every matching miscellaneous expense/credit and has_more is true while more pages follow (the X-Total-Count header carries the total too). Without $limit, every matching miscellaneous expense/credit is returned. | | | $offset | Number | No | How many miscellaneous expenses/credits to skip before the first one returned (a whole number; 0 by default). For the next page, add the number of miscellaneous expenses/credits you received to $offset. | | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | | $on_error_return_empty_result | Boolean | No | For an invalid Event, integration metadata, timestamp or paging filter, return HTTP 200 with an empty list instead of a validation error. Invalid new tag filters or conflicting copies remain errors. Authentication, rate-limit and unexpected server errors keep their normal status. | Default: false. | | filter_by_tagged_user_ids | String or JSON array | No | Return records tagged with these users or resources. Send one user ID or an array of user IDs, for example "user-id" or ["user-id","other-user-id"]. Omit, leave blank or send [] for no tagged-user filter. Duplicate IDs collapse. Inactive and deactivated people, and people no longer in this workspace, still match the records they are tagged on; IDs never tagged in this workspace match nothing. Use filter_by_tagged_user_ids_match_type to require at least one or every selected person. This filter combines with the other filters before counting and paging. | | | filter_by_tagged_user_ids_match_type | String | No | How to match the selected tagged people. Omit or leave blank to return records tagged with at least one selected person (the default), or require every selected person; records can have other tags too. This combines with the other filters before counting and paging. If filter_by_tagged_user_ids has no IDs, this option is ignored and the response includes a warning. Values are case-insensitive. | Allowed values: `any` \| `all` | | hydrate_related_items | Boolean | No | Set to true to include each record's related_items: the Tasks and items linked to it, with the key to use when adding or removing a link. Omit it or send false to leave related_items out of list results. Single-record GETs always include related_items. | Default: false. | Declared schema for `filter_by_tagged_user_ids` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "oneOf": [ { "type": "string", "minLength": 1, "maxLength": 128, "pattern": "\\S" }, { "type": "array", "items": { "type": "string", "minLength": 1, "maxLength": 128, "pattern": "\\S" } } ], "x-normalization": "one string becomes a one-item array; trimmed distinct IDs; no record-count cap", "nullable": false, "x-maximum-depth": 1, "x-empty-create-means-omitted": false, "example": [ "user-id" ] } ``` #### Filter the list Omit `filter_by_event_id` to search all readable Events. When provided, only that Event is searched. Event, tag, integration metadata and update-time filters are combined. For tagged people, pass one user ID or an array of IDs from Workspace Users. `any` matches at least one selected person; `all` requires every selected person and allows additional tags. Inactive and deactivated people, and people no longer in this workspace, still match the records they are tagged on; IDs never tagged match nothing, and this is not an error. Sending `filter_by_tagged_user_ids_match_type` without IDs is ignored with a warning. #### Read changes in pages Use `$limit` and `$offset` to page through matching records. Without `$limit`, all remaining matching records are returned. Filters are applied before the count and page are selected. The update-time filter includes records at exactly the supplied time. Process every page before advancing a saved cursor; deleted records are not returned. #### Events with a hidden Misc. Expenses & Credits tab Records on Events whose Misc. Expenses & Credits tab is hidden are not listed. If filter_by_event_id names such an Event, the response is HTTP 200 with no records for it and a warning that names the tab and the Event. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/events/misc_expenses_credits?filter_by_event_id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/misc_expenses_credits?" + new URLSearchParams({ "filter_by_event_id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/events/misc_expenses_credits", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"filter_by_event_id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/events/misc_expenses_credits?filter_by_event_id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/misc_expenses_credits?filter_by_event_id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/misc_expenses_credits?filter_by_event_id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/misc_expenses_credits?filter_by_event_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/events/misc_expenses_credits - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "event_misc_expense_credit", "list_data": [ { "id": 12345, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=12345&riType=8&riSub=0&riId=12345", "description": "Sample description", "is_credit": false, "expense_date": "2026-03-14", "vendor_payee": "Acme Printing", "reference_number": "INV-20431", "cost": { "amount": 0.00, "cost_center_breakdown": [] }, "notes": "", "payment_due_date": null, "payment_status": { "id": 0, "name": "Not Specified" }, "next_payment_due_date": null, "payment_notes": null, "expected_credit_date": null, "credit_status": null, "credit_notes": null, "invoice_attachment": { "id": 682345, "filename": "expense-invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" }, "tagged_users": [ { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, { "id": "66666666-7777-4888-8999-aaaaaaaaaaaa", "first_name": "Alex", "last_name": "Morgan", "display_name": "Alex Morgan", "email": "alex@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true } ], "event_id": 12345, "event": { "id": 12345, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=12345", "name": "Sample Event", "start_date": "2026-12-21", "end_date": "2026-12-23", "participation_type_id": 1, "participation_type": "Committed", "format_id": 1, "format": "In-Person", "event_created_timestamp": "2026-11-21T17:00:00Z", "event_last_update_timestamp": "2026-11-21T17:00:00Z" }, "event_misc_expense_credit_created_timestamp": "2026-11-21T17:00:00Z", "event_misc_expense_credit_last_update_timestamp": "2026-11-21T17:00:00Z", "integration_metadata_field_1": "", "integration_metadata_field_2": "", "integration_metadata_field_3": "", "integration_metadata_field_4": "", "integration_metadata_field_5": "" } ] } ``` ### Add a Misc. Expense / Credit `POST https://api.exhibitday.com/v1/events/misc_expenses_credits` Documentation: https://api.exhibitday.com/Help/V1?epf=100#post-v1-events-misc_expenses_credits Creating this record does not attach an invoice; its invoice attachment metadata is null. Add an invoice using the separate invoice attachment method. Older path, still accepted: /v1/events/miscexpensecredit. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | event_id | Number | Yes | The id of the event you would like to add the miscellaneous expense/credit to. | | | description | String | Yes | A short description of the miscellaneous expense or credit, up to 400 characters. A longer description is refused, and the entry isn't added. | Max length: 400. | | is_credit | Boolean | No | The is_credit flag indicates whether or not the miscellaneous expense/credit you’re adding is a credit. For example, if you’re adding a partial credit the event organizer issued for a booth service, set the is_credit flag to true. Use true or false. If omitted or blank, the default is false. | Default: false. | | cost | Number or cost object | No | The full cost, as a number or an object with amount and/or cost_center_breakdown. [Record Costs and Split Them Across Cost Centers](/Help/V1?guide=entering-costs). | Optional; defaults to zero. A credit reads back with a negative amount and charges. For a credit you may send those negative values back unchanged: -200 and 200 both record a 200 credit. An expense refuses negative values. | | payment_status_id | Number | No | The Payment Status Id for the miscellaneous expense/credit. Note: Payment status only applies to miscellaneous expenses. If you pass in a payment_status_id for a miscellaneous credit (i.e., when the is_credit flag is set to true), it will be ignored, and the response includes a warning saying so. You can use the following endpoint to retrieve a list of available payment_status_id's: /v1/references/payment_statuses. Any other value is rejected with an error. | Default: 0. | | payment_due_date | Date | No | Payment due date in YYYY-MM-DD format. Note: Payment Due Date only applies to miscellaneous expenses. If you pass in a payment_due_date for a miscellaneous credit (i.e., when the is_credit flag is set to true), it will be ignored, and the response includes a warning saying so. A value that is not a valid date is rejected with an error. | | | next_payment_due_date | Date | No | The next payment due date in YYYY-MM-DD format. This field only applies to expenses with payment_status_id 2 (Partially Paid). It is ignored for credits and other payment statuses, and the response includes a warning saying so. A value that is not a valid date is rejected with an error. | | | payment_notes | String | No | Notes about the payment for the expense. Note: Payment notes only apply to miscellaneous expenses. If you pass in a payment_notes for a miscellaneous credit (i.e., when the is_credit flag is set to true), it will be ignored, and the response includes a warning saying so. | Max length: 200. | | notes | String | No | Notes about the miscellaneous expense/credit. Only accepts plain text. Any html tags in the value you pass in will be stripped. New line characters will get replaced with a
tag, and the text is stored HTML-encoded, so it is returned as HTML (a < b comes back as a < b). Accepts up to 30,000 characters as stored, including formatting. Some characters take more space when stored: each line break counts as the 5 characters of
, the characters & < > " ' count as their HTML codes (for example, & is stored as &), and accented letters, symbols and non-breaking spaces such as é, ü, © and ° count as 6 characters each (é is stored as é). The notes must also fit the notes editor in ExhibitDay, which counts up to 30,000 characters of its own HTML: it adds 7 characters of formatting and counts letters and symbols such as é ’ “ — € as their HTML codes (for example, ’ counts as the 7 characters of ’). Longer notes are rejected with an error, and the miscellaneous expense/credit is not added. | Max length: 30000. | | expense_date | Date | No | The date of the expense, in YYYY-MM-DD format. On a credit this is the credit date (the website shows it as Credit Date). | | | vendor_payee | String | No | Who was paid, up to 200 characters. On a credit this is who the credit is from (the website shows it as Credit From). Line breaks become spaces. A longer value is refused. | Max length: 200. | | reference_number | String | No | A reference such as an invoice, order or receipt number, up to 200 characters. A longer value is refused. | Max length: 200. | | tagged_user_ids | JSON object/list | No | The full list of people tagged on this expense or credit, as a JSON array of unique user or Resource IDs from your workspace's active users and Resources. Omit it to tag nobody. Existing tags keep their notification state. Newly tagged people receive the usual tagging email only when notify_tagged_users is true and their account and email settings allow it. | | | notify_tagged_users | Boolean | No | Whether people newly tagged by this request receive the usual tagging email, subject to their email settings. True when omitted or blank. False suppresses the email only for tags added by this request; existing tags are unchanged. This option is not stored on the record. JSON null is refused. | Default: true. | | expected_credit_date | Date | No | Credits only: the date the credit is expected, in YYYY-MM-DD format. Sent for an expense, it is ignored with a warning. | | | credit_status_id | Number | No | Credits only: the credit status. One of 1 (Not Credited Yet), 2 (Partially Credited), 3 (Credited in Full). Sent for an expense, it is ignored with a warning. | | | credit_notes | String | No | Credits only: notes about the credit, up to 200 characters. Line breaks become spaces. A longer value is refused. Sent for an expense, it is ignored with a warning. | Max length: 200. | | integration_metadata_field_1 | String | No | The integration_metadata_field_1 property is an integration-specific text field only accessible via the ExhibitDay API. This field is typically used to store metadata or information about a particular miscellaneous expense/credit (e.g., the "external id" of the expense from another system you're integrating with). | Max length: 3000. | | integration_metadata_field_2 | String | No | The integration_metadata_field_2 property is an integration-specific text field only accessible via the ExhibitDay API. This field is typically used to store metadata or information about a particular miscellaneous expense/credit (e.g., the "external id" of the expense from another system you're integrating with). | Max length: 3000. | | integration_metadata_field_3 | String | No | The integration_metadata_field_3 property is an integration-specific text field only accessible via the ExhibitDay API. This field is typically used to store metadata or information about a particular miscellaneous expense/credit (e.g., the "external id" of the expense from another system you're integrating with). | Max length: 3000. | | integration_metadata_field_4 | String | No | The integration_metadata_field_4 property is an integration-specific text field only accessible via the ExhibitDay API. This field is typically used to store metadata or information about a particular miscellaneous expense/credit (e.g., the "external id" of the expense from another system you're integrating with). | Max length: 3000. | | integration_metadata_field_5 | String | No | The integration_metadata_field_5 property is an integration-specific text field only accessible via the ExhibitDay API. This field is typically used to store metadata or information about a particular miscellaneous expense/credit (e.g., the "external id" of the expense from another system you're integrating with). | Max length: 3000. | Declared schema for `cost` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "anyOf": [ { "type": "number", "description": "Shorthand for an object with amount. The amount is rounded to cents before the supported storage range is checked. A credit may send the negative amount it reads back; an expense must be zero or positive.", "nullable": true }, { "type": "object", "additionalProperties": false, "properties": { "amount": { "type": "number", "minimum": -79228162514264337593543950335.0, "maximum": 79228162514264337593543950335.0 }, "cost_center_breakdown": { "type": "array", "items": { "type": "object", "additionalProperties": false, "properties": { "cost_center_id": { "type": "integer", "format": "int64", "nullable": true }, "charge": { "type": "number", "minimum": -79228162514264337593543950335.0, "maximum": 79228162514264337593543950335.0 }, "cost_center": { "type": "string", "description": "Optional and read-only: the cost center name a read returns, so a cost can be sent back unchanged. It is ignored; the line is saved by cost_center_id, and a name that doesn't match that cost center is explained in a warning.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "required": [ "charge" ] }, "maxItems": 2147483647 } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "anyOf": [ { "required": [ "amount" ] }, { "required": [ "cost_center_breakdown" ] } ], "nullable": true } ], "x-numeric-shorthand": "A number is equivalent to {amount:number}.", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": { "amount": 125.50 } } ``` Declared schema for `tagged_user_ids` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "array", "items": { "type": "string" }, "maxItems": 2147483647, "nullable": true, "x-maximum-depth": 2, "x-empty-create-means-omitted": true, "example": [ "user-id" ] } ``` #### Hidden Misc. Expenses & Credits tab If the Event's Misc. Expenses & Credits tab is hidden, adding, changing or deleting its expenses and credits returns HTTP 400 (not_allowed). Show the tab in ExhibitDay first. Example — curl: ```bash curl -X POST "https://api.exhibitday.com/v1/events/misc_expenses_credits" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"event_id\":12345,\"description\":\"Sample description\"}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/misc_expenses_credits", { method: "POST", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "event_id": 12345, "description": "Sample description" }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.post( "https://api.exhibitday.com/v1/events/misc_expenses_credits", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"event_id": 12345, "description": "Sample description"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PostAsync("https://api.exhibitday.com/v1/events/misc_expenses_credits", JsonContent.Create(new { event_id = 12345, description = "Sample description" })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/misc_expenses_credits")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("POST", HttpRequest.BodyPublishers.ofString("{\"event_id\":12345,\"description\":\"Sample description\"}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"event_id":12345,"description":"Sample description"}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/misc_expenses_credits') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"event_id":12345,"description":"Sample description"}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/events/misc_expenses_credits", strings.NewReader("{\"event_id\":12345,\"description\":\"Sample description\"}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): POST /v1/events/misc_expenses_credits - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "id": 23456, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=12345&riType=8&riSub=0&riId=23456", "description": "Sample description", "is_credit": false, "expense_date": null, "vendor_payee": null, "reference_number": null, "cost": { "amount": 0.00, "cost_center_breakdown": [] }, "notes": "", "payment_due_date": null, "payment_status": { "id": 0, "name": "Not Specified" }, "next_payment_due_date": null, "payment_notes": null, "expected_credit_date": null, "credit_status": null, "credit_notes": null, "invoice_attachment": null, "tagged_users": [ { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, { "id": "66666666-7777-4888-8999-aaaaaaaaaaaa", "first_name": "Alex", "last_name": "Morgan", "display_name": "Alex Morgan", "email": "alex@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true } ], "event_id": 12345, "event": { "id": 12345, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=12345", "name": "Sample Event", "start_date": "2026-12-21", "end_date": "2026-12-23", "participation_type_id": 1, "participation_type": "Committed", "format_id": 1, "format": "In-Person", "event_created_timestamp": "2026-11-21T17:00:00Z", "event_last_update_timestamp": "2026-11-21T17:00:00Z" }, "event_misc_expense_credit_created_timestamp": "2026-11-21T17:00:00Z", "event_misc_expense_credit_last_update_timestamp": "2026-11-21T17:00:00Z", "integration_metadata_field_1": "", "integration_metadata_field_2": "", "integration_metadata_field_3": "", "integration_metadata_field_4": "", "integration_metadata_field_5": "" } ``` ### Update a Misc. Expense / Credit `PATCH https://api.exhibitday.com/v1/events/misc_expenses_credits` Documentation: https://api.exhibitday.com/Help/V1?epf=100#patch-v1-events-misc_expenses_credits To update an event miscellaneous expense/credit, only pass in the properties that you want to update. A miscellaneous expense/credit cannot be moved to another event. To clear a property that supports clearing, pass in null; an empty value leaves the property unchanged (the warnings property in the response names any such parameters). If the update is successful, the message property in the response will contain a list of event miscellaneous expense/credit properties that were actually changed. Older path, still accepted: /v1/events/miscexpensecredit. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The id of the event miscellaneous expense/credit you would like to update. | | | description | String | No | A short description of the miscellaneous expense or credit, up to 400 characters. A longer description is refused, and nothing is changed. If a saved description is already over the limit, an update can keep or shorten it but can't make it longer. | Max length: 400. | | is_credit | Boolean | No | Whether this record is a credit. Use true or false. Blank leaves the current type unchanged. An actual expense/credit conversion clears financial details belonging to the previous type while preserving amount, allocations, description and other applicable fields. Valid expense payment fields supplied when converting to an expense apply afterward. Omitted payment fields remain unchanged when type is unchanged, subject to normal next-payment-date normalization. Credit fields (expected_credit_date, credit_status_id, credit_notes) apply to credits and payment fields to expenses. Existing records are not changed until a conversion request; no additional confirmation step is required. | | | cost | Number or cost object | No | The full cost, as a number or an object with amount and/or cost_center_breakdown. [Record Costs and Split Them Across Cost Centers](/Help/V1?guide=entering-costs). | Omit to keep the saved cost. A supplied value replaces its full allocation. A credit reads back with a negative amount and charges. For a credit you may send those negative values back unchanged: -200 and 200 both record a 200 credit. An expense refuses negative values. | | payment_status_id | Number | No | The Payment Status Id for the miscellaneous expense/credit. Note: Payment status only applies to miscellaneous expenses. If you pass in a payment_status_id for a miscellaneous credit (i.e., when the is_credit flag is set to true), it will be ignored, and the response includes a warning saying so. You can use the following endpoint to retrieve a list of available payment_status_id's: /v1/references/payment_statuses. Any other value is rejected with an error. To reset the payment status to 0 (N/A), pass in null. | | | payment_due_date | Date | No | Payment due date in YYYY-MM-DD format. Note: Payment Due Date only applies to miscellaneous expenses. If you pass in a payment_due_date for a miscellaneous credit (i.e., when the is_credit flag is set to true), it will be ignored, and the response includes a warning saying so. A value that is not a valid date is rejected with an error. | | | next_payment_due_date | Date | No | The next payment due date in YYYY-MM-DD format. This field only applies to expenses with payment_status_id 2 (Partially Paid). It is ignored for credits and other payment statuses, and the response includes a warning saying so. A value that is not a valid date is rejected with an error. | | | payment_notes | String | No | Notes about the payment for the expense. Note: Payment notes only apply to miscellaneous expenses. If you pass in a payment_notes for a miscellaneous credit (i.e., when the is_credit flag is set to true), it will be ignored, and the response includes a warning saying so. | Max length: 200. | | notes | String | No | Notes about the miscellaneous expense/credit. Only accepts plain text. Any html tags in the value you pass in will be stripped. New line characters will get replaced with a
tag, and the text is stored HTML-encoded, so it is returned as HTML (a < b comes back as a < b). Accepts up to 30,000 characters as stored, including formatting. Some characters take more space when stored: each line break counts as the 5 characters of
, the characters & < > " ' count as their HTML codes (for example, & is stored as &), and accented letters, symbols and non-breaking spaces such as é, ü, © and ° count as 6 characters each (é is stored as é). The notes must also fit the notes editor in ExhibitDay, which counts up to 30,000 characters of its own HTML: it adds 7 characters of formatting and counts letters and symbols such as é ’ “ — € as their HTML codes (for example, ’ counts as the 7 characters of ’). Longer notes are rejected with an error, and nothing is changed. Notes that are already stored longer than this can be kept as they are or shortened, but not made longer. | Max length: 30000. | | expense_date | Date | No | The date of the expense, in YYYY-MM-DD format. On a credit this is the credit date (the website shows it as Credit Date). An empty value leaves it unchanged; null clears it. | | | vendor_payee | String | No | Who was paid, up to 200 characters. On a credit this is who the credit is from (the website shows it as Credit From). Line breaks become spaces. A longer value is refused. An empty value leaves it unchanged; null clears it. | Max length: 200. | | reference_number | String | No | A reference such as an invoice, order or receipt number, up to 200 characters. A longer value is refused. An empty value leaves it unchanged; null clears it. | Max length: 200. | | tagged_user_ids | JSON object/list | No | The full list of people tagged on this expense or credit, as a JSON array of unique user or Resource IDs from your workspace's active users and Resources. Omit it (or send an empty value) to keep the current people; null or [] removes all tags. Existing tags keep their notification state. Newly tagged people receive the usual tagging email only when notify_tagged_users is true and their account and email settings allow it. | | | notify_tagged_users | Boolean | No | Whether people newly tagged by this request receive the usual tagging email, subject to their email settings. True when omitted or blank. False suppresses the email only for tags added by this request; existing tags are unchanged. This option is not stored on the record. JSON null is refused. | Default: true. | | expected_credit_date | Date | No | Credits only: the date the credit is expected, in YYYY-MM-DD format. Sent for an expense, it is ignored with a warning. An empty value leaves it unchanged; null clears it. | | | credit_status_id | Number | No | Credits only: the credit status. One of 1 (Not Credited Yet), 2 (Partially Credited), 3 (Credited in Full). Sent for an expense, it is ignored with a warning. An empty value leaves it unchanged; null clears it. | | | credit_notes | String | No | Credits only: notes about the credit, up to 200 characters. Line breaks become spaces. A longer value is refused. Sent for an expense, it is ignored with a warning. An empty value leaves it unchanged; null clears it. | Max length: 200. | | integration_metadata_field_1 | String | No | The integration_metadata_field_1 property is an integration-specific text field only accessible via the ExhibitDay API. This field is typically used to store metadata or information about a particular miscellaneous expense/credit (e.g., the "external id" of the expense from another system you're integrating with). | Max length: 3000. | | integration_metadata_field_2 | String | No | The integration_metadata_field_2 property is an integration-specific text field only accessible via the ExhibitDay API. This field is typically used to store metadata or information about a particular miscellaneous expense/credit (e.g., the "external id" of the expense from another system you're integrating with). | Max length: 3000. | | integration_metadata_field_3 | String | No | The integration_metadata_field_3 property is an integration-specific text field only accessible via the ExhibitDay API. This field is typically used to store metadata or information about a particular miscellaneous expense/credit (e.g., the "external id" of the expense from another system you're integrating with). | Max length: 3000. | | integration_metadata_field_4 | String | No | The integration_metadata_field_4 property is an integration-specific text field only accessible via the ExhibitDay API. This field is typically used to store metadata or information about a particular miscellaneous expense/credit (e.g., the "external id" of the expense from another system you're integrating with). | Max length: 3000. | | integration_metadata_field_5 | String | No | The integration_metadata_field_5 property is an integration-specific text field only accessible via the ExhibitDay API. This field is typically used to store metadata or information about a particular miscellaneous expense/credit (e.g., the "external id" of the expense from another system you're integrating with). | Max length: 3000. | | expected_revision | String | No | The record_revision returned when you retrieved this record. Include it to avoid overwriting someone else's changes. Omit it to skip this check. | | Declared schema for `cost` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "anyOf": [ { "type": "number", "description": "Shorthand for an object with amount. The amount is rounded to cents before the supported storage range is checked. A credit may send the negative amount it reads back; an expense must be zero or positive.", "nullable": true }, { "type": "object", "additionalProperties": false, "properties": { "amount": { "type": "number", "minimum": -79228162514264337593543950335.0, "maximum": 79228162514264337593543950335.0 }, "cost_center_breakdown": { "type": "array", "items": { "type": "object", "additionalProperties": false, "properties": { "cost_center_id": { "type": "integer", "format": "int64", "nullable": true }, "charge": { "type": "number", "minimum": -79228162514264337593543950335.0, "maximum": 79228162514264337593543950335.0 }, "cost_center": { "type": "string", "description": "Optional and read-only: the cost center name a read returns, so a cost can be sent back unchanged. It is ignored; the line is saved by cost_center_id, and a name that doesn't match that cost center is explained in a warning.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "required": [ "charge" ] }, "maxItems": 2147483647 } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "anyOf": [ { "required": [ "amount" ] }, { "required": [ "cost_center_breakdown" ] } ], "nullable": true } ], "x-numeric-shorthand": "A number is equivalent to {amount:number}.", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": { "amount": 125.50 } } ``` Declared schema for `tagged_user_ids` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "array", "items": { "type": "string" }, "maxItems": 2147483647, "nullable": true, "x-maximum-depth": 2, "x-empty-create-means-omitted": true, "example": [ "user-id" ] } ``` #### Hidden Misc. Expenses & Credits tab If the Event's Misc. Expenses & Credits tab is hidden, adding, changing or deleting its expenses and credits returns HTTP 400 (not_allowed). Show the tab in ExhibitDay first. Example — curl: ```bash curl -X PATCH "https://api.exhibitday.com/v1/events/misc_expenses_credits" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"id\":12345,\"description\":\"Updated description\"}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/misc_expenses_credits", { method: "PATCH", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "id": 12345, "description": "Updated description" }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.patch( "https://api.exhibitday.com/v1/events/misc_expenses_credits", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"id": 12345, "description": "Updated description"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PatchAsync("https://api.exhibitday.com/v1/events/misc_expenses_credits", JsonContent.Create(new { id = 12345, description = "Updated description" })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/misc_expenses_credits")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("PATCH", HttpRequest.BodyPublishers.ofString("{\"id\":12345,\"description\":\"Updated description\"}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"id":12345,"description":"Updated description"}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/misc_expenses_credits') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"id":12345,"description":"Updated description"}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/events/misc_expenses_credits", strings.NewReader("{\"id\":12345,\"description\":\"Updated description\"}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): PATCH /v1/events/misc_expenses_credits - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Event Miscellaneous Expense/Credit Update Successful. Event Miscellaneous Expense/Credit properties that were changed: description", "errors": [] } ``` ### Delete a Misc. Expense / Credit `DELETE https://api.exhibitday.com/v1/events/misc_expenses_credits` Documentation: https://api.exhibitday.com/Help/V1?epf=100#delete-v1-events-misc_expenses_credits Permanently deletes an event's miscellaneous expense/credit. It cannot be undone. Older path, still accepted: /v1/events/miscexpensecredit. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The id of the event miscellaneous expense/credit you would like to delete. | | #### Hidden Misc. Expenses & Credits tab If the Event's Misc. Expenses & Credits tab is hidden, adding, changing or deleting its expenses and credits returns HTTP 400 (not_allowed). Show the tab in ExhibitDay first. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/events/misc_expenses_credits?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/misc_expenses_credits?" + new URLSearchParams({ "id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/events/misc_expenses_credits", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/events/misc_expenses_credits?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/misc_expenses_credits?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/misc_expenses_credits?id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/events/misc_expenses_credits?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/events/misc_expenses_credits - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Event Miscellaneous Expense/Credit Deleted", "errors": [] } ``` ### Download Misc. Expense / Credit Invoice Attachment `GET https://api.exhibitday.com/v1/events/misc_expenses_credits/invoice_attachment/download` Documentation: https://api.exhibitday.com/Help/V1?epf=100#get-v1-events-misc_expenses_credits-invoice_attachment-download Downloads the original Invoice Attachment for this Misc. Expense / Credit. Use this method to retrieve the file itself. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | misc_expense_credit_id | Number | Yes | The ID of the Misc. Expense / Credit, from Retrieve Misc. Expenses / Credits (GET /v1/events/misc_expenses_credits) or its add response. | | #### Finding the file In the web app, this is the invoice control beside the Misc. Expense / Credit's cost and payment details. Each cost has one Invoice Attachment even when its amount is split among cost centers. For file metadata, retrieve the parent record with GET /v1/events/misc_expenses_credits and read invoice_attachment. Use this download method for the contents. No attachment ID or invoice flag is needed. #### Download response A successful response contains the original uploaded file, with a safe download filename. API errors use the usual JSON response. If no invoice is attached, this method returns HTTP 404. Current record, financial and invoice permissions apply. A locked tab can still be read. Permitted downloads remain available on the Free plan. #### Files still being copied If this file is still being copied, the download returns HTTP 409 with file_copy_pending. Try the download again in a few minutes. #### Hidden tab If the Event's Misc. Expenses & Credits tab is hidden, this request returns HTTP 400 (not_allowed), and the message says the tab is hidden. Show the tab in ExhibitDay first. A locked tab can still be read. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X GET "https://api.exhibitday.com/v1/events/misc_expenses_credits/invoice_attachment/download?misc_expense_credit_id=12345" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi mv response-body.tmp 'invoice.pdf' ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const response = await fetch("https://api.exhibitday.com/v1/events/misc_expenses_credits/invoice_attachment/download?misc_expense_credit_id=12345", { method: "GET", headers: { Authorization: 'Bearer YOUR_API_KEY' } }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); await writeFile("invoice.pdf", new Uint8Array(await response.arrayBuffer())); ``` Example — Python: ```python import requests import json response = requests.request("GET", "https://api.exhibitday.com/v1/events/misc_expenses_credits/invoice_attachment/download?misc_expense_credit_id=12345", headers={'Authorization': 'Bearer YOUR_API_KEY'}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') with open("invoice.pdf", 'wb') as destination: destination.write(response.content) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.exhibitday.com/v1/events/misc_expenses_credits/invoice_attachment/download?misc_expense_credit_id=12345"); using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); await File.WriteAllBytesAsync("invoice.pdf", await response.Content.ReadAsByteArrayAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/misc_expenses_credits/invoice_attachment/download?misc_expense_credit_id=12345")).header("Authorization", "Bearer YOUR_API_KEY"); HttpResponse response = HttpClient.newHttpClient().send(request.method("GET", HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); Files.write(Path.of("invoice.pdf"), response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); file_put_contents('invoice.pdf', $response); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/misc_expenses_credits/invoice_attachment/download?misc_expense_credit_id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' File.binwrite('invoice.pdf', response.body) ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/misc_expenses_credits/invoice_attachment/download?misc_expense_credit_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } if err := os.WriteFile("invoice.pdf", data, 0600); err != nil { log.Fatal(err) } fmt.Println("File saved") } ``` HTTP 200: Returns the original uploaded file as a private download, using a safe filename. If the file cannot be downloaded, the response contains the usual JSON API error instead. Media: application/octet-stream. The body is the authorized file's real bytes, not JSON or base64. Errors are JSON status responses; check HTTP status before saving the file. ### Add Misc. Expense / Credit Invoice Attachment `POST https://api.exhibitday.com/v1/events/misc_expenses_credits/invoice_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=100#post-v1-events-misc_expenses_credits-invoice_attachment Adds one Invoice Attachment to this Misc. Expense / Credit. You can attach an invoice, receipt or other payment document when no invoice file is currently attached. A credit note or refund confirmation can be attached for a credit. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | misc_expense_credit_id | Number | Yes | The ID of the Misc. Expense / Credit, from Retrieve Misc. Expenses / Credits (GET /v1/events/misc_expenses_credits) or its add response. | | | file | File (multipart) | Yes | The Invoice Attachment to upload. | Send exactly one complete, nonempty multipart/form-data file part named file. The supported extensions and current per-file limit are shown below; the complete request limit also includes multipart overhead. A missing or null file is invalid and does not remove an existing invoice. | | Idempotency-Key | String | No | A unique key for safely retrying this upload. | Optional HTTP header: 1 to 255 visible ASCII characters without spaces or commas. Retry the identical request with the same key to replay its first saved response. Use a new key for a different upload. | Declared schema for `file` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "string", "format": "binary", "x-maximum-bytes": 26214400, "x-allowed-extensions": [ "png", "jpg", "jpeg", "bmp", "gif", "pdf", "msg", "eml", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "rtf", "odp", "odt", "ods", "txt", "wks", "zip" ] } ``` #### Before you upload POST requires an empty invoice slot. If an invoice is already attached, the API returns HTTP 409; use PATCH to replace it. An Invoice Attachment is separate from the record's supporting File Attachments. Use the invoice control beside the Misc. Expense / Credit's cost and payment details in the web app. #### After the upload The response's invoice_attachment contains the attached file's id, filename and attachment_created_timestamp. The amount, payment fields, cost-center breakdown and other files are unchanged. The upload is recorded in Event history. Attaching an invoice does not mark the record as paid. #### Access and retries A current upload-enabled plan, record and financial permissions, and an editable applicable tab are required. Each uploaded file must fit its supported type and size limits. expected_revision is not supported by this file method. If the save outcome cannot be confirmed, retrieve the current parent record with GET /v1/events/misc_expenses_credits and inspect invoice_attachment before deciding whether to retry. #### Hidden or locked tab If the Event's Misc. Expenses & Credits tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X POST "https://api.exhibitday.com/v1/events/misc_expenses_credits/invoice_attachment" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}" --form-string "misc_expense_credit_id=12345" --form "file=@invoice.pdf;type=application/octet-stream") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi cat response-body.tmp ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const form = new FormData(); form.append("misc_expense_credit_id", "12345"); form.append("file", new Blob([await readFile("invoice.pdf")], { type: "application/octet-stream" }), "invoice.pdf"); const response = await fetch("https://api.exhibitday.com/v1/events/misc_expenses_credits/invoice_attachment", { method: "POST", headers: { Authorization: 'Bearer YOUR_API_KEY' }, body: form }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); console.log(await response.json()); ``` Example — Python: ```python import requests import json from contextlib import ExitStack with ExitStack() as stack: files = [ ("file", ("invoice.pdf", stack.enter_context(open("invoice.pdf", 'rb')), "application/octet-stream")), ] response = requests.request("POST", "https://api.exhibitday.com/v1/events/misc_expenses_credits/invoice_attachment", headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data={"misc_expense_credit_id": "12345"}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') print(response.json()) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.exhibitday.com/v1/events/misc_expenses_credits/invoice_attachment"); var form = new MultipartFormDataContent(); form.Add(new StringContent("12345"), "misc_expense_credit_id"); var file0 = new StreamContent(File.OpenRead("invoice.pdf")); file0.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(file0, "file", "invoice.pdf"); request.Content = form; using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/misc_expenses_credits/invoice_attachment")).header("Authorization", "Bearer YOUR_API_KEY"); String boundary = "ExhibitDay-" + UUID.randomUUID(); ByteArrayOutputStream form = new ByteArrayOutputStream(); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"misc_expense_credit_id\"\r\n\r\n" + "12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"invoice.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8)); form.write(Files.readAllBytes(Path.of("invoice.pdf"))); form.write("\r\n".getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); request.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpResponse response = HttpClient.newHttpClient().send(request.method("POST", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); System.out.println(new String(response.body(), StandardCharsets.UTF_8)); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], CURLOPT_POSTFIELDS => [ 'misc_expense_credit_id' => '12345', 'file' => new CURLFile('invoice.pdf', 'application/octet-stream', 'invoice.pdf'), ], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); echo $response; ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/misc_expenses_credits/invoice_attachment') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' files = [] begin parts = [ ['misc_expense_credit_id', '12345'], ['file', (files << File.open('invoice.pdf', 'rb')).last, {filename: 'invoice.pdf', content_type: 'application/octet-stream'}], ] request.set_form(parts, 'multipart/form-data') response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' puts response.body ensure files.each(&:close) end ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" "bytes" "mime/multipart" "net/textproto" ) func main() { var form bytes.Buffer writer := multipart.NewWriter(&form) if err := writer.WriteField("misc_expense_credit_id", "12345"); err != nil { log.Fatal(err) } header0 := textproto.MIMEHeader{} header0.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"invoice.pdf\"") header0.Set("Content-Type", "application/octet-stream") part0, err := writer.CreatePart(header0) if err != nil { log.Fatal(err) } file0, err := os.Open("invoice.pdf") if err != nil { log.Fatal(err) } if _, err = io.Copy(part0, file0); err != nil { log.Fatal(err) } file0.Close() if err := writer.Close(); err != nil { log.Fatal(err) } request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/events/misc_expenses_credits/invoice_attachment", &form) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", writer.FormDataContentType()) response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } fmt.Printf("%s\n", data) } ``` Example HTTP response body (JSON): POST /v1/events/misc_expenses_credits/invoice_attachment - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "invoice_attachment": { "id": 12345, "filename": "invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } } ``` ### Replace Misc. Expense / Credit Invoice Attachment `PATCH https://api.exhibitday.com/v1/events/misc_expenses_credits/invoice_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=100#patch-v1-events-misc_expenses_credits-invoice_attachment Replaces this Misc. Expense / Credit's current Invoice Attachment with one uploaded file. Use this method when an invoice file is already attached. A credit note or refund confirmation can be attached for a credit. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | misc_expense_credit_id | Number | Yes | The ID of the Misc. Expense / Credit, from Retrieve Misc. Expenses / Credits (GET /v1/events/misc_expenses_credits) or its add response. | | | file | File (multipart) | Yes | The Invoice Attachment to upload. | Send exactly one complete, nonempty multipart/form-data file part named file. The supported extensions and current per-file limit are shown below; the complete request limit also includes multipart overhead. A missing or null file is invalid and does not remove an existing invoice. | Declared schema for `file` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "string", "format": "binary", "x-maximum-bytes": 26214400, "x-allowed-extensions": [ "png", "jpg", "jpeg", "bmp", "gif", "pdf", "msg", "eml", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "rtf", "odp", "odt", "ods", "txt", "wks", "zip" ] } ``` #### Replacing the current file PATCH requires a current invoice file. If none is attached, the API returns HTTP 404. Upload exactly one file; the previous attachment ID is not needed. If another request changes the current invoice during your upload, the API refuses this request instead of replacing a different file. Even identical replacement contents receive a new attachment ID. #### After the replacement The response's invoice_attachment contains the attached file's id, filename and attachment_created_timestamp. The amount, payment fields, cost-center breakdown and other files are unchanged. The previous file is scheduled for physical cleanup after a confirmed save; cleanup may finish later. The replacement is recorded in Event history. #### Access and retries A current upload-enabled plan, record and financial permissions, and an editable applicable tab are required. Each uploaded file must fit its supported type and size limits. expected_revision is not supported by this file method. PATCH does not use Idempotency-Key replay. If the save outcome cannot be confirmed, retrieve the current parent record with GET /v1/events/misc_expenses_credits and inspect invoice_attachment before deciding whether to retry. #### Hidden or locked tab If the Event's Misc. Expenses & Credits tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X PATCH "https://api.exhibitday.com/v1/events/misc_expenses_credits/invoice_attachment" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}" --form-string "misc_expense_credit_id=12345" --form "file=@invoice.pdf;type=application/octet-stream") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi cat response-body.tmp ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const form = new FormData(); form.append("misc_expense_credit_id", "12345"); form.append("file", new Blob([await readFile("invoice.pdf")], { type: "application/octet-stream" }), "invoice.pdf"); const response = await fetch("https://api.exhibitday.com/v1/events/misc_expenses_credits/invoice_attachment", { method: "PATCH", headers: { Authorization: 'Bearer YOUR_API_KEY' }, body: form }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); console.log(await response.json()); ``` Example — Python: ```python import requests import json from contextlib import ExitStack with ExitStack() as stack: files = [ ("file", ("invoice.pdf", stack.enter_context(open("invoice.pdf", 'rb')), "application/octet-stream")), ] response = requests.request("PATCH", "https://api.exhibitday.com/v1/events/misc_expenses_credits/invoice_attachment", headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data={"misc_expense_credit_id": "12345"}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') print(response.json()) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("PATCH"), "https://api.exhibitday.com/v1/events/misc_expenses_credits/invoice_attachment"); var form = new MultipartFormDataContent(); form.Add(new StringContent("12345"), "misc_expense_credit_id"); var file0 = new StreamContent(File.OpenRead("invoice.pdf")); file0.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(file0, "file", "invoice.pdf"); request.Content = form; using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/misc_expenses_credits/invoice_attachment")).header("Authorization", "Bearer YOUR_API_KEY"); String boundary = "ExhibitDay-" + UUID.randomUUID(); ByteArrayOutputStream form = new ByteArrayOutputStream(); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"misc_expense_credit_id\"\r\n\r\n" + "12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"invoice.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8)); form.write(Files.readAllBytes(Path.of("invoice.pdf"))); form.write("\r\n".getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); request.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpResponse response = HttpClient.newHttpClient().send(request.method("PATCH", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); System.out.println(new String(response.body(), StandardCharsets.UTF_8)); } } ``` Example — PHP: ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], CURLOPT_POSTFIELDS => [ 'misc_expense_credit_id' => '12345', 'file' => new CURLFile('invoice.pdf', 'application/octet-stream', 'invoice.pdf'), ], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); echo $response; ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/misc_expenses_credits/invoice_attachment') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' files = [] begin parts = [ ['misc_expense_credit_id', '12345'], ['file', (files << File.open('invoice.pdf', 'rb')).last, {filename: 'invoice.pdf', content_type: 'application/octet-stream'}], ] request.set_form(parts, 'multipart/form-data') response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' puts response.body ensure files.each(&:close) end ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" "bytes" "mime/multipart" "net/textproto" ) func main() { var form bytes.Buffer writer := multipart.NewWriter(&form) if err := writer.WriteField("misc_expense_credit_id", "12345"); err != nil { log.Fatal(err) } header0 := textproto.MIMEHeader{} header0.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"invoice.pdf\"") header0.Set("Content-Type", "application/octet-stream") part0, err := writer.CreatePart(header0) if err != nil { log.Fatal(err) } file0, err := os.Open("invoice.pdf") if err != nil { log.Fatal(err) } if _, err = io.Copy(part0, file0); err != nil { log.Fatal(err) } file0.Close() if err := writer.Close(); err != nil { log.Fatal(err) } request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/events/misc_expenses_credits/invoice_attachment", &form) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", writer.FormDataContentType()) response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } fmt.Printf("%s\n", data) } ``` Example HTTP response body (JSON): PATCH /v1/events/misc_expenses_credits/invoice_attachment - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "invoice_attachment": { "id": 12345, "filename": "invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } } ``` ### Remove Misc. Expense / Credit Invoice Attachment `DELETE https://api.exhibitday.com/v1/events/misc_expenses_credits/invoice_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=100#delete-v1-events-misc_expenses_credits-invoice_attachment Removes this Misc. Expense / Credit's Invoice Attachment. The cost, payment details and other File Attachments stay in place. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | misc_expense_credit_id | Number | Yes | The ID of the Misc. Expense / Credit, from Retrieve Misc. Expenses / Credits (GET /v1/events/misc_expenses_credits) or its add response. | | #### After the removal The Invoice Attachment is cleared and the removal is recorded in Event history. Its physical file is scheduled for cleanup after a confirmed save; cleanup may finish later. Costs, payment fields, cost-center allocations and supporting files stay unchanged. If no invoice is attached, DELETE returns HTTP 404 Not Found with the message "This Misc. Expense / Credit has no invoice to remove." No saved data or history is changed. Current access and the record's binding are still checked. Do not send file parts with this request. #### Access and retries Current record, financial and invoice permissions and applicable tab-edit access are required. Permitted removals remain available on the Free plan. expected_revision is not supported, and DELETE does not use Idempotency-Key replay. If the save outcome cannot be confirmed, retrieve the current parent record with GET /v1/events/misc_expenses_credits and inspect invoice_attachment before deciding whether to retry. #### Hidden or locked tab If the Event's Misc. Expenses & Credits tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/events/misc_expenses_credits/invoice_attachment?misc_expense_credit_id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/misc_expenses_credits/invoice_attachment?" + new URLSearchParams({ "misc_expense_credit_id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/events/misc_expenses_credits/invoice_attachment", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"misc_expense_credit_id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/events/misc_expenses_credits/invoice_attachment?misc_expense_credit_id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/misc_expenses_credits/invoice_attachment?misc_expense_credit_id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/misc_expenses_credits/invoice_attachment?misc_expense_credit_id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/events/misc_expenses_credits/invoice_attachment?misc_expense_credit_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/events/misc_expenses_credits/invoice_attachment - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Attachment removed.", "errors": [] } ``` ### Retrieve Misc. Expense / Credit General File Attachments `GET https://api.exhibitday.com/v1/events/misc_expenses_credits/attachments` Documentation: https://api.exhibitday.com/Help/V1?epf=100#get-v1-events-misc_expenses_credits-attachments Retrieves the General File Attachments on this Misc. Expense / Credit. Each result includes the file's ID, name and added time; use the download method for its contents. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | misc_expense_credit_id | Number | Yes | The ID of the Misc. Expense / Credit, from Retrieve Misc. Expenses / Credits (GET /v1/events/misc_expenses_credits) or its add response. | | | $limit | Number | No | The most File Attachments to return. | A positive whole number. Omit for all remaining matching files. | | $offset | Number | No | The number of matching File Attachments to skip. | A whole number of 0 or more. Default: 0. | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records. | Allowed values: `array` | | If-None-Match | String | No | An ETag from an earlier response to this GET. | Optional HTTP header. If the successful response is unchanged, the API returns HTTP 304 with no body. | #### Reading the file list Files are ordered by added time, then attachment ID, lowest first. Only files available under your current access are included. Paging totals and X-Total-Count count all matching files before $limit and $offset are applied. A record with no files you can view returns an empty list. This list does not return edit revisions or support changed-since filtering. #### Supporting files and invoices These are the record's General File Attachments. Its cost Invoice Attachment is separate and has its own download and upload methods. Use this list's id values for these supporting-file downloads and removals. #### Access The record's Event and tab must be available, and the tab must not be hidden. A locked tab can still be read. #### Hidden tab If the Event's Misc. Expenses & Credits tab is hidden, this request returns HTTP 400 (not_allowed), and the message says the tab is hidden. Show the tab in ExhibitDay first. A locked tab can still be read. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/events/misc_expenses_credits/attachments?misc_expense_credit_id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/misc_expenses_credits/attachments?" + new URLSearchParams({ "misc_expense_credit_id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/events/misc_expenses_credits/attachments", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"misc_expense_credit_id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/events/misc_expenses_credits/attachments?misc_expense_credit_id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/misc_expenses_credits/attachments?misc_expense_credit_id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/misc_expenses_credits/attachments?misc_expense_credit_id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/misc_expenses_credits/attachments?misc_expense_credit_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/events/misc_expenses_credits/attachments - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "attachment", "list_data": [ { "id": 12345, "filename": "attachment.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } ] } ``` ### Add Misc. Expense / Credit General File Attachments `POST https://api.exhibitday.com/v1/events/misc_expenses_credits/attachments` Documentation: https://api.exhibitday.com/Help/V1?epf=100#post-v1-events-misc_expenses_credits-attachments Adds one or more General File Attachments to this Misc. Expense / Credit. Send each file as a multipart upload part named file. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | misc_expense_credit_id | Number | Yes | The ID of the Misc. Expense / Credit, from Retrieve Misc. Expenses / Credits (GET /v1/events/misc_expenses_credits) or its add response. | | | file | File (multipart) | Yes | The File Attachments to upload. | Send one or more complete, nonempty multipart/form-data parts, each named file. Supported types and the current per-file limit are shown below. The complete request limit includes all files and multipart overhead; split larger batches. A missing or null upload is not a removal request. | | Idempotency-Key | String | No | A unique key for safely retrying this upload. | Optional HTTP header: 1 to 255 visible ASCII characters without spaces or commas. Retry the identical request with the same key to replay its first saved response. Use a new key for a different upload. | Declared schema for `file` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "array", "items": { "type": "string", "format": "binary", "x-maximum-bytes": 26214400, "x-allowed-extensions": [ "png", "jpg", "jpeg", "bmp", "gif", "pdf", "msg", "eml", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "rtf", "odp", "odt", "ods", "txt", "wks", "zip" ] } } ``` #### After the upload The response's list_data contains the newly attached files, including each id, filename and attachment_created_timestamp. Existing files are kept. Use each returned id to download or remove that file. Identical repeated files in one request are attached once when their cleaned filename, length and contents match. Files with different contents remain separate even when their names match. This does not remove or replace files already attached to the record. #### Choosing the right file method These uploads add General File Attachments. Use this record's Invoice Attachment methods for its cost invoice or receipt. Adding supporting files does not change amounts, payments or cost-center allocations. #### Access Current record and file-change permissions and applicable Event/tab locks must allow this upload. An upload-enabled paid plan is required. #### History and retries A confirmed file change is recorded in history. expected_revision is not supported by these file methods. If the save outcome cannot be confirmed, retrieve the current file list before deciding whether to retry; the API does not automatically repeat an uncertain change. Supporting File Attachments have no PATCH replacement. To replace one, add the new file and remove the old one using their separate requests; each request has its own outcome. #### Hidden or locked tab If the Event's Misc. Expenses & Credits tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X POST "https://api.exhibitday.com/v1/events/misc_expenses_credits/attachments" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}" --form-string "misc_expense_credit_id=12345" --form "file=@attachment.pdf;type=application/octet-stream") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi cat response-body.tmp ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const form = new FormData(); form.append("misc_expense_credit_id", "12345"); form.append("file", new Blob([await readFile("attachment.pdf")], { type: "application/octet-stream" }), "attachment.pdf"); const response = await fetch("https://api.exhibitday.com/v1/events/misc_expenses_credits/attachments", { method: "POST", headers: { Authorization: 'Bearer YOUR_API_KEY' }, body: form }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); console.log(await response.json()); ``` Example — Python: ```python import requests import json from contextlib import ExitStack with ExitStack() as stack: files = [ ("file", ("attachment.pdf", stack.enter_context(open("attachment.pdf", 'rb')), "application/octet-stream")), ] response = requests.request("POST", "https://api.exhibitday.com/v1/events/misc_expenses_credits/attachments", headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data={"misc_expense_credit_id": "12345"}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') print(response.json()) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.exhibitday.com/v1/events/misc_expenses_credits/attachments"); var form = new MultipartFormDataContent(); form.Add(new StringContent("12345"), "misc_expense_credit_id"); var file0 = new StreamContent(File.OpenRead("attachment.pdf")); file0.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(file0, "file", "attachment.pdf"); request.Content = form; using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/misc_expenses_credits/attachments")).header("Authorization", "Bearer YOUR_API_KEY"); String boundary = "ExhibitDay-" + UUID.randomUUID(); ByteArrayOutputStream form = new ByteArrayOutputStream(); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"misc_expense_credit_id\"\r\n\r\n" + "12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"attachment.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8)); form.write(Files.readAllBytes(Path.of("attachment.pdf"))); form.write("\r\n".getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); request.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpResponse response = HttpClient.newHttpClient().send(request.method("POST", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); System.out.println(new String(response.body(), StandardCharsets.UTF_8)); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], CURLOPT_POSTFIELDS => [ 'misc_expense_credit_id' => '12345', 'file' => new CURLFile('attachment.pdf', 'application/octet-stream', 'attachment.pdf'), ], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); echo $response; ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/misc_expenses_credits/attachments') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' files = [] begin parts = [ ['misc_expense_credit_id', '12345'], ['file', (files << File.open('attachment.pdf', 'rb')).last, {filename: 'attachment.pdf', content_type: 'application/octet-stream'}], ] request.set_form(parts, 'multipart/form-data') response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' puts response.body ensure files.each(&:close) end ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" "bytes" "mime/multipart" "net/textproto" ) func main() { var form bytes.Buffer writer := multipart.NewWriter(&form) if err := writer.WriteField("misc_expense_credit_id", "12345"); err != nil { log.Fatal(err) } header0 := textproto.MIMEHeader{} header0.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"attachment.pdf\"") header0.Set("Content-Type", "application/octet-stream") part0, err := writer.CreatePart(header0) if err != nil { log.Fatal(err) } file0, err := os.Open("attachment.pdf") if err != nil { log.Fatal(err) } if _, err = io.Copy(part0, file0); err != nil { log.Fatal(err) } file0.Close() if err := writer.Close(); err != nil { log.Fatal(err) } request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/events/misc_expenses_credits/attachments", &form) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", writer.FormDataContentType()) response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } fmt.Printf("%s\n", data) } ``` Example HTTP response body (JSON): POST /v1/events/misc_expenses_credits/attachments - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "attachment", "list_data": [ { "id": 12345, "filename": "attachment.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } ] } ``` ### Remove a Misc. Expense / Credit General File Attachment `DELETE https://api.exhibitday.com/v1/events/misc_expenses_credits/attachments` Documentation: https://api.exhibitday.com/Help/V1?epf=100#delete-v1-events-misc_expenses_credits-attachments Removes one General File Attachment from this Misc. Expense / Credit. Other attached files and the record's details stay in place. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the File Attachment. | Use the id from the attachment list. The API finds the record the file belongs to, so no record ID is sent. An Invoice Attachment is not selected by this method. | #### After the removal Only the selected file association is removed. Its physical file is scheduled for cleanup after a confirmed save; cleanup may finish later. Other attached files stay in place. Send only the file's id; the API finds the record it belongs to. A missing, already removed or unavailable attachment returns HTTP 404 Not Found. Do not send file parts with DELETE. #### Access Current record and file-removal permissions and applicable Event/tab locks must allow this change. Permitted removals remain available on the Free plan. #### History and retries A confirmed file change is recorded in history. expected_revision is not supported by these file methods. DELETE does not use Idempotency-Key replay. If the save outcome cannot be confirmed, retrieve the current file list before deciding whether to retry; the API does not automatically repeat an uncertain change. Supporting File Attachments have no PATCH replacement. To replace one, add the new file and remove the old one using their separate requests; each request has its own outcome. #### Hidden or locked tab If the Event's Misc. Expenses & Credits tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/events/misc_expenses_credits/attachments?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/misc_expenses_credits/attachments?" + new URLSearchParams({ "id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/events/misc_expenses_credits/attachments", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/events/misc_expenses_credits/attachments?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/misc_expenses_credits/attachments?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/misc_expenses_credits/attachments?id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/events/misc_expenses_credits/attachments?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/events/misc_expenses_credits/attachments - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Attachment removed.", "errors": [] } ``` ### Download a Misc. Expense / Credit General File Attachment `GET https://api.exhibitday.com/v1/events/misc_expenses_credits/attachments/download` Documentation: https://api.exhibitday.com/Help/V1?epf=100#get-v1-events-misc_expenses_credits-attachments-download Downloads one original General File Attachment from this Misc. Expense / Credit. Select the file using its ID from the attachment list. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the File Attachment. | Use the id from the attachment list. The API finds the record the file belongs to, so no record ID is sent. An Invoice Attachment is not selected by this method. | #### Download response A successful response contains the original uploaded file with a safe download filename. API errors use the usual JSON response. A missing or unavailable file returns HTTP 404. Send only the file's id from the attachment list to download that one file; the API finds the record it belongs to. The download leaves the record unchanged. #### Access The record's Event and tab must be available, and the tab must not be hidden. A locked tab can still be read. #### Files still being copied If this file is still being copied, the download returns HTTP 409 with file_copy_pending. Try the download again in a few minutes. #### Hidden tab If the Event's Misc. Expenses & Credits tab is hidden, this request returns HTTP 400 (not_allowed), and the message says the tab is hidden. Show the tab in ExhibitDay first. A locked tab can still be read. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X GET "https://api.exhibitday.com/v1/events/misc_expenses_credits/attachments/download?id=12345" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi mv response-body.tmp 'attachment.pdf' ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const response = await fetch("https://api.exhibitday.com/v1/events/misc_expenses_credits/attachments/download?id=12345", { method: "GET", headers: { Authorization: 'Bearer YOUR_API_KEY' } }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); await writeFile("attachment.pdf", new Uint8Array(await response.arrayBuffer())); ``` Example — Python: ```python import requests import json response = requests.request("GET", "https://api.exhibitday.com/v1/events/misc_expenses_credits/attachments/download?id=12345", headers={'Authorization': 'Bearer YOUR_API_KEY'}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') with open("attachment.pdf", 'wb') as destination: destination.write(response.content) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.exhibitday.com/v1/events/misc_expenses_credits/attachments/download?id=12345"); using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); await File.WriteAllBytesAsync("attachment.pdf", await response.Content.ReadAsByteArrayAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/events/misc_expenses_credits/attachments/download?id=12345")).header("Authorization", "Bearer YOUR_API_KEY"); HttpResponse response = HttpClient.newHttpClient().send(request.method("GET", HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); Files.write(Path.of("attachment.pdf"), response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); file_put_contents('attachment.pdf', $response); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/misc_expenses_credits/attachments/download?id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' File.binwrite('attachment.pdf', response.body) ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/misc_expenses_credits/attachments/download?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } if err := os.WriteFile("attachment.pdf", data, 0600); err != nil { log.Fatal(err) } fmt.Println("File saved") } ``` HTTP 200: Returns the original uploaded file as a private download, using a safe filename. If the file cannot be downloaded, the response contains the usual JSON API error instead. Media: application/octet-stream. The body is the authorized file's real bytes, not JSON or base64. Errors are JSON status responses; check HTTP status before saving the file. ## Events - Objectives Event Objectives: their type, importance and achievement ratings. Documentation page: https://api.exhibitday.com/Help/V1?epf=1&topic=objectives ### Retrieve a Single Event Objective by ID `GET https://api.exhibitday.com/v1/events/objectives/info` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=objectives#get-v1-events-objectives-info Retrieves an Event Objective by its ID, including its importance and achievement rating. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Event Objective. | | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` \| `object` | | $include_record_revision | Boolean | No | Whether to include a record_revision for a later update. | Default: false. Set true to include the token described below. | | $on_error_return_empty_result | Boolean | No | Whether an invalid or unavailable Objective should return an empty result. | Default: false. True returns HTTP 200 with {} (or [] for array format) for invalid IDs or an unavailable Objective. Authentication failures, records that change while they are read and unexpected errors keep their normal status. | | If-None-Match | String | No | An ETag from an earlier response to this GET. | Optional HTTP header. If the successful response is unchanged, the API returns HTTP 304 with no body. | #### What $include_record_revision covers Setting $include_record_revision=true returns record_revision for use as expected_revision on a later update. The token covers this Objective's type, name, importance, achievement rating and current Event. Read it again if an update reports that the Objective changed. #### Access Your workspace plan must include ROI, and you need read access to the Event's ROI / ROO area. The tab can be locked while you read it. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/events/objectives/info?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/objectives/info?" + new URLSearchParams({ "id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/events/objectives/info", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/events/objectives/info?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/objectives/info?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/objectives/info?id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/objectives/info?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/events/objectives/info - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "id": 12345, "event_id": 23456, "event_name": "Illustrative Event", "objective_type_id": 1, "objective_type": "Lead Generation", "name": "Lead Generation", "importance_id": 2, "importance": "Medium", "achievement_rating": 8, "objective_created_timestamp": "2030-01-03T14:30:00Z" } ``` ### Retrieve Event Objectives `GET https://api.exhibitday.com/v1/events/objectives` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=objectives#get-v1-events-objectives Retrieves objectives across readable Events. Use filter_by_event_id to retrieve the objectives for one Event. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | filter_by_event_id | Number | No | Only include Objectives from this Event. | Omit to search readable Events across your workspace. | | $limit | Number | No | The most Objectives to return. | A positive whole number. Omit for all remaining Objectives. | | $offset | Number | No | The number of Objectives to skip. | A whole number of 0 or more. Default: 0. | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | | If-None-Match | String | No | An ETag from an earlier response to this GET. | Optional HTTP header. If the successful response is unchanged, the API returns HTTP 304 with no body. | #### Filtering and paging Omit filter_by_event_id for all readable Events in your workspace. The current plan, Budget View permission and each Event's ROI visibility apply before counts and paging. A supplied Event that is missing or unavailable returns an empty list with a warning. A readable Event with no objectives returns an empty list without that warning. Results are ordered by added timestamp, then objective ID. Omit $limit for all remaining matching objectives; $offset defaults to 0. Each objective retains its actual event_id and Event name. #### Events with a hidden ROI tab Records on Events whose ROI tab is hidden are not listed. If filter_by_event_id names such an Event, the response is HTTP 200 with no records for it and a warning that names the tab and the Event. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/events/objectives" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/objectives", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/events/objectives", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/events/objectives"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/objectives")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/objectives') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/objectives", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/events/objectives - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "list_type": "objective", "list_data": [ { "id": 12345, "event_id": 23456, "event_name": "Illustrative Event", "objective_type_id": 1, "objective_type": "Lead Generation", "name": "Lead Generation", "importance_id": 2, "importance": "Medium", "achievement_rating": 8, "objective_created_timestamp": "2030-01-03T14:30:00Z" }, { "id": 12346, "event_id": 23456, "event_name": "Illustrative Event", "objective_type_id": 11, "objective_type": "Other", "name": "Meet potential partners", "importance_id": 3, "importance": "High", "achievement_rating": null, "objective_created_timestamp": "2030-01-03T14:30:00Z" } ], "records_found": 2, "total_records": 2, "has_more": false } ``` ### Add an Event Objective `POST https://api.exhibitday.com/v1/events/objectives` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=objectives#post-v1-events-objectives Adds an Objective to an Event so you can track its importance and rate its achievement. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | event_id | Number | Yes | The ID of the Event. | | | objective_type_id | Number | Yes | The type of Objective to add. | Use an ID from Objective Types. For Other (11), also supply name. | | name | String | When objective_type_id is 11 (Other) | The name of an Other Objective. | Up to 75 characters, excluding surrounding spaces. Must not be blank for Other. Ignored for other types. For a name containing commas, use JSON, a form field or a query parameter. | | importance_id | Number | No | How important this Objective is. Omit or send null for Medium. Choose an importance currently available in the workspace. | Allowed values: `1` (Low) \| `2` (Medium) \| `3` (High) | | achievement_rating | Number | No | How well this Objective was achieved. | A whole number from 0 through 10. Omit or send null for Not Rated Yet. | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` \| `object` | | Idempotency-Key | String | No | A unique key for safely retrying this add request. | Optional HTTP header: 1 to 255 visible ASCII characters without spaces. Retry with the same key and identical request to replay its first saved response. Use a new key for a different request. | #### Choosing an Objective Choose a type from GET /v1/references/objective_types. It lists the built-in types and your workspace's named custom Objectives. Each type can be added once per Event, except Other (11), which permits several differently named Objectives. Other names are compared without regard to case. A duplicate returns HTTP 400. The type and name are fixed when the Objective is added. To change either later, delete that Objective and add another one. #### After the add A successful request returns the new Objective, including its id, and adds one entry to Event history. It sends no notification. If the save outcome cannot be confirmed, retrieve the Event's Objectives before deciding whether to retry. #### Access Your workspace plan must include ROI. The Event's ROI / ROO area must be available and unlocked, and you need permission to edit it. #### Hidden or locked tab If the Event's ROI tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. An Event that is not in your workspace returns HTTP 404. Example — curl: ```bash curl -X POST "https://api.exhibitday.com/v1/events/objectives" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"event_id\":23456,\"objective_type_id\":1,\"importance_id\":2}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/objectives", { method: "POST", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "event_id": 23456, "objective_type_id": 1, "importance_id": 2 }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.post( "https://api.exhibitday.com/v1/events/objectives", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"event_id": 23456, "objective_type_id": 1, "importance_id": 2}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PostAsync("https://api.exhibitday.com/v1/events/objectives", JsonContent.Create(new { event_id = 23456, objective_type_id = 1, importance_id = 2 })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/objectives")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("POST", HttpRequest.BodyPublishers.ofString("{\"event_id\":23456,\"objective_type_id\":1,\"importance_id\":2}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"event_id":23456,"objective_type_id":1,"importance_id":2}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/objectives') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"event_id":23456,"objective_type_id":1,"importance_id":2}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/events/objectives", strings.NewReader("{\"event_id\":23456,\"objective_type_id\":1,\"importance_id\":2}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): POST /v1/events/objectives - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "id": 12345, "event_id": 23456, "event_name": "Illustrative Event", "objective_type_id": 1, "objective_type": "Lead Generation", "name": "Lead Generation", "importance_id": 2, "importance": "Medium", "achievement_rating": null, "objective_created_timestamp": "2030-01-03T14:30:00Z" } ``` ### Update an Event Objective `PATCH https://api.exhibitday.com/v1/events/objectives` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=objectives#patch-v1-events-objectives Updates an Event Objective's importance or achievement rating. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Event Objective. | | | importance_id | Number | No | How important this Objective is. Omit or leave blank to keep it; null cannot clear it. Choose an importance currently available in the workspace. | Allowed values: `1` (Low) \| `2` (Medium) \| `3` (High) | | achievement_rating | Number | No | How well this Objective was achieved. | A whole number from 0 through 10. Omitted or blank values leave the rating unchanged. Null resets it to Not Rated Yet. | | expected_revision | String | No | The record_revision from a previous read of this Objective. | Optional. Obtain it from GET /v1/events/objectives/info with $include_record_revision=true. A changed Objective returns HTTP 409 without saving this update. | | $ignore_params_with_empty_values | Boolean | No | Whether to leave a JSON null achievement_rating unchanged. | Default: false. With true, JSON null is ignored. The text null still resets the rating to Not Rated Yet. Blank values already leave fields unchanged. | #### Choosing what to change Send importance_id, achievement_rating, or both. Omit a value to keep it. To remove the rating, send achievement_rating=null. A change adds one entry to Event history. An unchanged request saves no data or history and keeps the same revision. It sends no notification. #### Using expected_revision 1. Retrieve this Objective with GET /v1/events/objectives/info and $include_record_revision=true. 2. Send its unchanged record_revision value as expected_revision with this update. 3. If the API returns HTTP 409 because the Objective changed, read the current Objective and decide what to update. #### Access and an unconfirmed save Your workspace plan must include ROI. The Event's ROI / ROO area must be available and unlocked, and you need permission to edit it. If the save outcome cannot be confirmed, read the Objective before deciding whether to retry. #### Hidden or locked tab If the Event's ROI tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. An Event that is not in your workspace returns HTTP 404. Example — curl: ```bash curl -X PATCH "https://api.exhibitday.com/v1/events/objectives" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"id\":12345,\"achievement_rating\":8}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/objectives", { method: "PATCH", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "id": 12345, "achievement_rating": 8 }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.patch( "https://api.exhibitday.com/v1/events/objectives", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"id": 12345, "achievement_rating": 8}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PatchAsync("https://api.exhibitday.com/v1/events/objectives", JsonContent.Create(new { id = 12345, achievement_rating = 8 })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/objectives")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("PATCH", HttpRequest.BodyPublishers.ofString("{\"id\":12345,\"achievement_rating\":8}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"id":12345,"achievement_rating":8}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/objectives') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"id":12345,"achievement_rating":8}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/events/objectives", strings.NewReader("{\"id\":12345,\"achievement_rating\":8}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): PATCH /v1/events/objectives - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Objective updated.", "errors": [] } ``` ### Delete an Event Objective `DELETE https://api.exhibitday.com/v1/events/objectives` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=objectives#delete-v1-events-objectives Deletes an Event Objective. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Event Objective. | | #### After the deletion The Objective is removed from the Event's ROI / ROO area and the deletion is recorded once in Event history. It sends no notification. Deleting an Objective that is no longer available returns HTTP 404. If the save outcome cannot be confirmed, retrieve the current Objectives before deciding whether to retry. #### Access Your workspace plan must include ROI. The Event's ROI / ROO area must be available and unlocked, and you need permission to delete its content. #### Hidden or locked tab If the Event's ROI tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. An Event that is not in your workspace returns HTTP 404. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/events/objectives?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/objectives?" + new URLSearchParams({ "id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/events/objectives", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/events/objectives?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/objectives?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/objectives?id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/events/objectives?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/events/objectives - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Objective removed.", "errors": [] } ``` ## Events - Related Tasks & Items Links between Tasks and Event items: read, link and unlink them by their typed keys. Documentation page: https://api.exhibitday.com/Help/V1?epf=1&topic=related-tasks-and-items ### Retrieve a Related Item Link `GET https://api.exhibitday.com/v1/related_items/info` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=related-tasks-and-items#get-v1-related_items-info Retrieves one link by its ID: the two linked records. Links work in both directions and have no direction of their own, so the source is the record that comes first by item type ID, then asset type, then ID, whichever record the link was added from. A link to a record on a hidden Event tab is not available. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The link's ID, from the record's links or GET /v1/related_items. | | #### Linking related items A link connects two records on the same Event and works in both directions. The source is the record the link was added from. When you read a record's links, each entry describes the other record. Types: 1 Task; 2 Playbook Activity; 3 Booth Service; 4 Shipment; 5 Asset Reservation; 6 Giveaway; 7 Sponsorship; 8 Misc. Expense / Credit; 9 Travel Reservation; 10 Attendee / Registration. GET /v1/references/related_item_types lists them with the types each can be linked to. For an Asset Reservation, also send the asset type: 1 Capital or 2 Collateral. For GET /v1/related_items, source_item_type names the record whose links are listed, and related_item_name and related_item_exhibitday_url describe each linked record. Opening related_item_exhibitday_url checks the user's ExhibitDay access again. Links are added and removed only with POST and DELETE /v1/related_items. General Tasks (Tasks without an Event) can't be linked. Records on hidden Event tabs can't be linked or read here. A record on a locked tab can be linked from an unlocked record, but its own links can't be changed while its area is locked. An Asset Reservation can be the source while the Event's Assets tab is visible and unlocked, including a reservation of an Asset shared with you by another workspace. A link works both ways: it is listed from both records, and posting a pair that is already linked from the other side changes nothing. Deleting either record removes its links, and moving a Task to another Event or making it a General Task removes the Task's links. Adding or removing a link counts as a change to both records (each gets a new revision, so an update that still expects the older revision is refused) and is recorded in the Event's history; it sends no email. When an Event is copied, links between records that were copied are copied too; links to records that were not copied are left out. A Giveaway takes Asset Reservations only when its Source includes inventory: for PATCH /v1/events/giveaways, item_source_id 2 (Existing Inventory) or 3 (From a Supplier + Existing Inventory). Linking an Asset Reservation to a Supplier-only Giveaway is refused from either side. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/related_items/info?id=5551" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/related_items/info?" + new URLSearchParams({ "id": "5551" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/related_items/info", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": "5551"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/related_items/info?id=5551"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/related_items/info?id=5551")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/related_items/info?id=5551') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/related_items/info?id=5551", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/related_items/info - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "id": 5551, "event_id": 12345, "source_item_id": 23456, "source_item_exhibitday_url": "https://www.exhibitday.com/Workspace/RelatedItemView/98765?typeId=7&subTypeId=0&rid=23456", "source_item_type_id": 7, "source_item_type": "Sponsorship", "source_item_asset_type_id": null, "source_item_name": "Lanyard sponsorship", "related_item_id": 67890, "related_item_exhibitday_url": "https://www.exhibitday.com/Workspace/TaskView/98765?tid=67890", "related_item_type_id": 1, "related_item_type": "Task", "related_item_asset_type_id": null, "related_item_name": "Send lanyard artwork to the organizer", "related_item_created_timestamp": "2030-01-10T14:03:00Z" } ``` ### Retrieve Related Items `GET https://api.exhibitday.com/v1/related_items` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=related-tasks-and-items#get-v1-related_items Retrieves the Tasks and items linked to one record, in the same order as the record's Related Items tab in ExhibitDay: Tasks first, then the other types, oldest link first. Every single-record GET also includes these links. Records on hidden Event tabs are not included. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | source_item_type_id | Number | Yes | The type of the record whose links you want: 1 Task, 2 Playbook Activity, 3 Booth Service, 4 Shipment, 5 Asset Reservation, 6 Giveaway, 7 Sponsorship, 8 Misc. Expense / Credit, 9 Travel Reservation, 10 Attendee / Registration. | | | source_item_id | Number | Yes | The ID of the record whose links you want, for the type in source_item_type_id: 1 Task: the Task ID (GET /v1/tasks); 2 Playbook Activity: the Playbook Activity ID (GET /v1/events/playbook_activities); 3 Booth Service: the Booth Service ID (GET /v1/events/booth_services); 4 Shipment: the Shipment ID (GET /v1/events/shipments); 5 Asset Reservation: the Asset Reservation ID (GET /v1/assets/reservations); 6 Giveaway: the Event Giveaway ID (GET /v1/events/giveaways); 7 Sponsorship: the Sponsorship ID (GET /v1/events/sponsorships); 8 Misc. Expense / Credit: the Misc. Expense / Credit ID (GET /v1/events/miscexpensecredits); 9 Travel Reservation: the Travel Reservation ID (GET /v1/events/travel_reservations); 10 Attendee / Registration: the Staff / Registration entry ID (GET /v1/events/staff). For example, for a Booth Service send its Booth Service ID, and for a Giveaway send the Event Giveaway's ID. | | | source_item_asset_type_id | Number | No | Asset Reservations only: 1 Capital or 2 Collateral. Leave it out for every other type. | | | $limit | Number | No | The most links to return: a positive whole number. Leave it out to return all remaining links. | | | $offset | Number | No | How many links to skip: zero or a positive whole number; zero by default. | | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | #### Linking related items A link connects two records on the same Event and works in both directions. The source is the record the link was added from. When you read a record's links, each entry describes the other record. Types: 1 Task; 2 Playbook Activity; 3 Booth Service; 4 Shipment; 5 Asset Reservation; 6 Giveaway; 7 Sponsorship; 8 Misc. Expense / Credit; 9 Travel Reservation; 10 Attendee / Registration. GET /v1/references/related_item_types lists them with the types each can be linked to. For an Asset Reservation, also send the asset type: 1 Capital or 2 Collateral. For GET /v1/related_items, source_item_type names the record whose links are listed, and related_item_name and related_item_exhibitday_url describe each linked record. Opening related_item_exhibitday_url checks the user's ExhibitDay access again. Links are added and removed only with POST and DELETE /v1/related_items. General Tasks (Tasks without an Event) can't be linked. Records on hidden Event tabs can't be linked or read here. A record on a locked tab can be linked from an unlocked record, but its own links can't be changed while its area is locked. An Asset Reservation can be the source while the Event's Assets tab is visible and unlocked, including a reservation of an Asset shared with you by another workspace. A link works both ways: it is listed from both records, and posting a pair that is already linked from the other side changes nothing. Deleting either record removes its links, and moving a Task to another Event or making it a General Task removes the Task's links. Adding or removing a link counts as a change to both records (each gets a new revision, so an update that still expects the older revision is refused) and is recorded in the Event's history; it sends no email. When an Event is copied, links between records that were copied are copied too; links to records that were not copied are left out. A Giveaway takes Asset Reservations only when its Source includes inventory: for PATCH /v1/events/giveaways, item_source_id 2 (Existing Inventory) or 3 (From a Supplier + Existing Inventory). Linking an Asset Reservation to a Supplier-only Giveaway is refused from either side. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/related_items?source_item_type_id=7&source_item_id=23456" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/related_items?" + new URLSearchParams({ "source_item_type_id": "7", "source_item_id": "23456" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/related_items", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"source_item_type_id": "7", "source_item_id": "23456"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/related_items?source_item_type_id=7&source_item_id=23456"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/related_items?source_item_type_id=7&source_item_id=23456")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/related_items?source_item_type_id=7&source_item_id=23456') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/related_items?source_item_type_id=7&source_item_id=23456", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/related_items - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "records_found": 2, "total_records": 2, "has_more": false, "list_type": "related_item", "source_item_id": 23456, "source_item_type_id": 7, "source_item_type": "Sponsorship", "source_item_asset_type_id": null, "list_data": [ { "id": 5551, "related_item_id": 67890, "related_item_exhibitday_url": "https://www.exhibitday.com/Workspace/TaskView/98765?tid=67890", "related_item_type_id": 1, "related_item_type": "Task", "related_item_asset_type_id": null, "related_item_name": "Send lanyard artwork to the organizer", "related_item_created_timestamp": "2030-01-10T14:03:00Z" }, { "id": 5552, "related_item_id": 4321, "related_item_exhibitday_url": "https://www.exhibitday.com/Workspace/RelatedItemView/98765?typeId=5&subTypeId=2&rid=4321", "related_item_type_id": 5, "related_item_type": "Asset Reservation", "related_item_asset_type_id": 2, "related_item_name": "Brochures (200)", "related_item_created_timestamp": "2030-01-10T14:03:00Z" } ] } ``` ### Link Related Items `POST https://api.exhibitday.com/v1/related_items` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=related-tasks-and-items#post-v1-related_items Links one record to one or more existing records on the same Event. Send one related item or an array of up to 100. All are linked, or none are. An already-linked record is left unchanged. Neither record is changed. Linking requires permission to edit the source record's area, and that area must not be locked on the Event. The related records only need to be readable: a record on a locked tab can be linked, a record on a hidden tab cannot. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | source_item_type_id | Number | Yes | The type of the record you are linking from: 1 Task, 2 Playbook Activity, 3 Booth Service, 4 Shipment, 5 Asset Reservation, 6 Giveaway, 7 Sponsorship, 8 Misc. Expense / Credit, 9 Travel Reservation, 10 Attendee / Registration. | | | source_item_id | Number | Yes | The ID of the record you are linking from, for the type in source_item_type_id: 1 Task: the Task ID (GET /v1/tasks); 2 Playbook Activity: the Playbook Activity ID (GET /v1/events/playbook_activities); 3 Booth Service: the Booth Service ID (GET /v1/events/booth_services); 4 Shipment: the Shipment ID (GET /v1/events/shipments); 5 Asset Reservation: the Asset Reservation ID (GET /v1/assets/reservations); 6 Giveaway: the Event Giveaway ID (GET /v1/events/giveaways); 7 Sponsorship: the Sponsorship ID (GET /v1/events/sponsorships); 8 Misc. Expense / Credit: the Misc. Expense / Credit ID (GET /v1/events/miscexpensecredits); 9 Travel Reservation: the Travel Reservation ID (GET /v1/events/travel_reservations); 10 Attendee / Registration: the Staff / Registration entry ID (GET /v1/events/staff). For example, for a Booth Service send its Booth Service ID, and for a Giveaway send the Event Giveaway's ID. | | | related_items | JSON object/list | Yes | The record or records to link: one JSON object or a JSON array of up to 100 objects, each with related_item_type_id, related_item_id and, for Asset Reservations only, related_item_asset_type_id (1 Capital, 2 Collateral). Example: [{"related_item_type_id":1,"related_item_id":67890},{"related_item_type_id":4,"related_item_id":45678}]. All are linked, or none are. | | | source_item_asset_type_id | Number | No | Asset Reservations only: 1 Capital or 2 Collateral. Leave it out for every other type. | | Declared schema for `related_items` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "oneOf": [ { "type": "object", "additionalProperties": false, "properties": { "related_item_type_id": { "type": "integer", "format": "int32", "description": "The type of the record to link, from GET /v1/references/related_item_types: 1 Task, 2 Playbook Activity, 3 Booth Service, 4 Shipment, 5 Asset Reservation, 6 Giveaway, 7 Sponsorship, 8 Misc. Expense / Credit, 9 Travel Reservation, 10 Attendee / Registration." }, "related_item_id": { "type": "integer", "format": "int64", "description": "The ID of the record to link, for the type in related_item_type_id: 1 Task: the Task ID (GET /v1/tasks); 2 Playbook Activity: the Playbook Activity ID (GET /v1/events/playbook_activities); 3 Booth Service: the Booth Service ID (GET /v1/events/booth_services); 4 Shipment: the Shipment ID (GET /v1/events/shipments); 5 Asset Reservation: the Asset Reservation ID (GET /v1/assets/reservations); 6 Giveaway: the Event Giveaway ID (GET /v1/events/giveaways); 7 Sponsorship: the Sponsorship ID (GET /v1/events/sponsorships); 8 Misc. Expense / Credit: the Misc. Expense / Credit ID (GET /v1/events/miscexpensecredits); 9 Travel Reservation: the Travel Reservation ID (GET /v1/events/travel_reservations); 10 Attendee / Registration: the Staff / Registration entry ID (GET /v1/events/staff)." }, "related_item_asset_type_id": { "type": "integer", "format": "int32", "description": "Asset Reservations only: 1 Capital or 2 Collateral. Leave it out for every other type.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "required": [ "related_item_type_id", "related_item_id" ] }, { "type": "array", "items": { "type": "object", "additionalProperties": false, "properties": { "related_item_type_id": { "type": "integer", "format": "int32", "description": "The type of the record to link, from GET /v1/references/related_item_types: 1 Task, 2 Playbook Activity, 3 Booth Service, 4 Shipment, 5 Asset Reservation, 6 Giveaway, 7 Sponsorship, 8 Misc. Expense / Credit, 9 Travel Reservation, 10 Attendee / Registration." }, "related_item_id": { "type": "integer", "format": "int64", "description": "The ID of the record to link, for the type in related_item_type_id: 1 Task: the Task ID (GET /v1/tasks); 2 Playbook Activity: the Playbook Activity ID (GET /v1/events/playbook_activities); 3 Booth Service: the Booth Service ID (GET /v1/events/booth_services); 4 Shipment: the Shipment ID (GET /v1/events/shipments); 5 Asset Reservation: the Asset Reservation ID (GET /v1/assets/reservations); 6 Giveaway: the Event Giveaway ID (GET /v1/events/giveaways); 7 Sponsorship: the Sponsorship ID (GET /v1/events/sponsorships); 8 Misc. Expense / Credit: the Misc. Expense / Credit ID (GET /v1/events/miscexpensecredits); 9 Travel Reservation: the Travel Reservation ID (GET /v1/events/travel_reservations); 10 Attendee / Registration: the Staff / Registration entry ID (GET /v1/events/staff)." }, "related_item_asset_type_id": { "type": "integer", "format": "int32", "description": "Asset Reservations only: 1 Capital or 2 Collateral. Leave it out for every other type.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "required": [ "related_item_type_id", "related_item_id" ] }, "maxItems": 100 } ], "x-normalization": "one object becomes a one-item array", "nullable": false, "x-maximum-depth": 2, "x-empty-create-means-omitted": false, "example": [ { "related_item_type_id": 1, "related_item_id": 67890 }, { "related_item_type_id": 4, "related_item_id": 45678 } ] } ``` #### Linking related items A link connects two records on the same Event and works in both directions. The source is the record the link was added from. When you read a record's links, each entry describes the other record. Types: 1 Task; 2 Playbook Activity; 3 Booth Service; 4 Shipment; 5 Asset Reservation; 6 Giveaway; 7 Sponsorship; 8 Misc. Expense / Credit; 9 Travel Reservation; 10 Attendee / Registration. GET /v1/references/related_item_types lists them with the types each can be linked to. For an Asset Reservation, also send the asset type: 1 Capital or 2 Collateral. For GET /v1/related_items, source_item_type names the record whose links are listed, and related_item_name and related_item_exhibitday_url describe each linked record. Opening related_item_exhibitday_url checks the user's ExhibitDay access again. Links are added and removed only with POST and DELETE /v1/related_items. General Tasks (Tasks without an Event) can't be linked. Records on hidden Event tabs can't be linked or read here. A record on a locked tab can be linked from an unlocked record, but its own links can't be changed while its area is locked. An Asset Reservation can be the source while the Event's Assets tab is visible and unlocked, including a reservation of an Asset shared with you by another workspace. A link works both ways: it is listed from both records, and posting a pair that is already linked from the other side changes nothing. Deleting either record removes its links, and moving a Task to another Event or making it a General Task removes the Task's links. Adding or removing a link counts as a change to both records (each gets a new revision, so an update that still expects the older revision is refused) and is recorded in the Event's history; it sends no email. When an Event is copied, links between records that were copied are copied too; links to records that were not copied are left out. A Giveaway takes Asset Reservations only when its Source includes inventory: for PATCH /v1/events/giveaways, item_source_id 2 (Existing Inventory) or 3 (From a Supplier + Existing Inventory). Linking an Asset Reservation to a Supplier-only Giveaway is refused from either side. Example — curl: ```bash curl -X POST "https://api.exhibitday.com/v1/related_items" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"source_item_type_id\":\"7\",\"source_item_id\":\"23456\",\"related_items\":[{\"related_item_type_id\":1,\"related_item_id\":67890},{\"related_item_type_id\":4,\"related_item_id\":45678}]}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/related_items", { method: "POST", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "source_item_type_id": "7", "source_item_id": "23456", "related_items": [{"related_item_type_id":1,"related_item_id":67890},{"related_item_type_id":4,"related_item_id":45678}] }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests import json response = requests.post( "https://api.exhibitday.com/v1/related_items", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"source_item_type_id": "7", "source_item_id": "23456", "related_items": json.loads("[{\"related_item_type_id\":1,\"related_item_id\":67890},{\"related_item_type_id\":4,\"related_item_id\":45678}]")}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Text.Json; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PostAsync("https://api.exhibitday.com/v1/related_items", JsonContent.Create(new { source_item_type_id = "7", source_item_id = "23456", related_items = JsonDocument.Parse("[{\"related_item_type_id\":1,\"related_item_id\":67890},{\"related_item_type_id\":4,\"related_item_id\":45678}]").RootElement.Clone() })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/related_items")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("POST", HttpRequest.BodyPublishers.ofString("{\"source_item_type_id\":\"7\",\"source_item_id\":\"23456\",\"related_items\":[{\"related_item_type_id\":1,\"related_item_id\":67890},{\"related_item_type_id\":4,\"related_item_id\":45678}]}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"source_item_type_id":"7","source_item_id":"23456","related_items":[{"related_item_type_id":1,"related_item_id":67890},{"related_item_type_id":4,"related_item_id":45678}]}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/related_items') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"source_item_type_id":"7","source_item_id":"23456","related_items":[{"related_item_type_id":1,"related_item_id":67890},{"related_item_type_id":4,"related_item_id":45678}]}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/related_items", strings.NewReader("{\"source_item_type_id\":\"7\",\"source_item_id\":\"23456\",\"related_items\":[{\"related_item_type_id\":1,\"related_item_id\":67890},{\"related_item_type_id\":4,\"related_item_id\":45678}]}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): POST /v1/related_items - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "changed": true, "list_data": [ { "id": 5551, "related_item_id": 67890, "related_item_exhibitday_url": "https://www.exhibitday.com/Workspace/TaskView/98765?tid=67890", "related_item_type_id": 1, "related_item_type": "Task", "related_item_asset_type_id": null, "related_item_name": "Send lanyard artwork to the organizer", "related_item_created_timestamp": "2030-01-10T14:03:00Z" }, { "id": 5552, "related_item_id": 4321, "related_item_exhibitday_url": "https://www.exhibitday.com/Workspace/RelatedItemView/98765?typeId=5&subTypeId=2&rid=4321", "related_item_type_id": 5, "related_item_type": "Asset Reservation", "related_item_asset_type_id": 2, "related_item_name": "Brochures (200)", "related_item_created_timestamp": "2030-01-10T14:03:00Z" } ] } ``` ### Unlink Related Items `DELETE https://api.exhibitday.com/v1/related_items` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=related-tasks-and-items#delete-v1-related_items Removes one or more links by their IDs. All links in one request must belong to the same record. All are removed, or none are. Both records keep their fields, costs, files and other links. Removing requires permission to edit that record's area, and that area must not be locked on the Event. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | ids | String | Yes | The link ID to remove, or a JSON array of up to 100 link IDs, such as [5551,5552,5553]. Send it in the query string (?ids=[5551,5552]) or in a JSON request body ({"ids":[5551,5552]}). All links in one request must belong to the same record. All are removed, or none are. | | #### Linking related items A link connects two records on the same Event and works in both directions. The source is the record the link was added from. When you read a record's links, each entry describes the other record. Types: 1 Task; 2 Playbook Activity; 3 Booth Service; 4 Shipment; 5 Asset Reservation; 6 Giveaway; 7 Sponsorship; 8 Misc. Expense / Credit; 9 Travel Reservation; 10 Attendee / Registration. GET /v1/references/related_item_types lists them with the types each can be linked to. For an Asset Reservation, also send the asset type: 1 Capital or 2 Collateral. For GET /v1/related_items, source_item_type names the record whose links are listed, and related_item_name and related_item_exhibitday_url describe each linked record. Opening related_item_exhibitday_url checks the user's ExhibitDay access again. Links are added and removed only with POST and DELETE /v1/related_items. General Tasks (Tasks without an Event) can't be linked. Records on hidden Event tabs can't be linked or read here. A record on a locked tab can be linked from an unlocked record, but its own links can't be changed while its area is locked. An Asset Reservation can be the source while the Event's Assets tab is visible and unlocked, including a reservation of an Asset shared with you by another workspace. A link works both ways: it is listed from both records, and posting a pair that is already linked from the other side changes nothing. Deleting either record removes its links, and moving a Task to another Event or making it a General Task removes the Task's links. Adding or removing a link counts as a change to both records (each gets a new revision, so an update that still expects the older revision is refused) and is recorded in the Event's history; it sends no email. When an Event is copied, links between records that were copied are copied too; links to records that were not copied are left out. A Giveaway takes Asset Reservations only when its Source includes inventory: for PATCH /v1/events/giveaways, item_source_id 2 (Existing Inventory) or 3 (From a Supplier + Existing Inventory). Linking an Asset Reservation to a Supplier-only Giveaway is refused from either side. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/related_items?ids=5551" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/related_items?" + new URLSearchParams({ "ids": "5551" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/related_items", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"ids": "5551"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/related_items?ids=5551"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/related_items?ids=5551")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/related_items?ids=5551') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/related_items?ids=5551", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/related_items - HTTP 200 Illustrative response. ```json { "changed": true, "removed_ids": [ 5551, 5552 ] } ``` ## Events - Logs The activity history of one Event. Documentation page: https://api.exhibitday.com/Help/V1?epf=1&topic=logs ### Retrieve an Event's Logs `GET https://api.exhibitday.com/v1/events/logs` Documentation: https://api.exhibitday.com/Help/V1?epf=1&topic=logs#get-v1-events-logs Retrieves activity history recorded for an Event. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | event_id | Number | Yes | The ID of the Event whose activity history you want to retrieve. | | | $limit | Number | No | The most entries to return (a whole number of 1 or more). Leave it out to return all remaining matching entries. | | | $offset | Number | No | How many matching entries to skip (a whole number of 0 or more; 0 by default). Use this with $limit to read the next page. | | | $result_sort | String | No | Sort entries newest first (the default) or oldest first. The full saved timestamp is used, with the entry ID breaking ties in the same direction. Responses display whole seconds. Unsupported values are refused. Use the values exactly as shown (lowercase). | Allowed values: `create_timestamp_desc` (newest first) \| `create_timestamp_asc` (oldest first) | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | | filter_by_actor_user_id | String | No | Only include entries written by the user with this id. Treat the id as text. Older entries can match a former user without exposing their account information. | | | filter_by_log_entry_contains_text | String | No | Only include entries containing this text, up to 3,000 characters. The characters are matched as sent; they are not converted from HTML or treated as wildcards. | | | filter_by_create_timestamp_greater_than_or_equal_to | String | No | Include entries created at or after this timestamp. Filters use the whole seconds shown in responses, so a fractional lower bound starts at the next whole second. | | | filter_by_create_timestamp_smaller_than_or_equal_to | String | No | Include entries created at or before this timestamp, including every entry in its displayed second. It can't be earlier than the lower bound. | | | filter_by_event_id | Number | No | Only include entries filed under this Event id in your workspace history. | | | filter_by_event_tab_id | Number | No | Only include entries filed under this Event tab ID. GET /v1/references/event_tabs lists your workspace's tabs; the Presentations tab is accepted only where your workspace has it. | Allowed values: `1` (Info) \| `2` (Booth) \| `3` (Staff) \| `4` (Travel) \| `5` (Assets) \| `6` (Shipments) \| `7` (Sponsorships) \| `8` (Tasks) \| `9` (Playbook) \| `10` (Attachments) \| `11` (Misc. Expenses & Credits) \| `12` (Budget) \| `13` (ROI) \| `14` (Event Settings) \| `16` (Binder) \| `17` (Copy Event) \| `19` (Logs) \| `20` (Delete Event) \| `21` (Giveaways) \| `22` (Special Tab, shown under your workspace's name for it) | | filter_by_context_type | String | No | Only return entries associated with the selected context. Omit to include all contexts. Workspace means an entry with none of the other associations; an entry can belong to more than one other context. Unsupported values are refused. Values are case-insensitive. | Allowed values: `workspace` \| `event` \| `task` \| `asset` \| `storage_location` | #### What the history includes Includes user-visible business history, including changes that do not appear in the Activity Feed. Internal diagnostics, impersonation activity, IP addresses, device details and security information are not included. Each request reads the current history. Use these results to review activity; they are not a complete feed of record changes or deletions. #### Filtering entries When you supply several filters, an entry must match all of them. The total count and the returned page use those same filters. Text searches match the characters you enter literally, without wildcard matching. #### Reading dates and times Returned timestamps are in UTC and show whole seconds. Sorting uses the full saved timestamp, then the entry ID to break ties; entries showing the same second can still have a distinct order. Timestamp filters use the displayed whole-second precision. An upper bound includes all entries in that displayed second. A fractional lower bound starts at the next whole second. A filter value with a time-zone offset is converted to US Eastern time for comparison. A value without an offset is interpreted as US Eastern time. #### Reading the actor `actor_user_id` is the ID of the user who made the change. `actor_display_name` is the name saved with the entry at that time; it does not change if the user is renamed later. Entries recorded by the API have a null `actor_user_id` and show the label saved with them, such as `API`. #### Event history Includes entries filed under this Event. Separate history for its child records is not combined into this list. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/events/logs?event_id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/logs?" + new URLSearchParams({ "event_id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/events/logs", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"event_id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/events/logs?event_id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/logs?event_id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/logs?event_id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/events/logs?event_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/events/logs - HTTP 200 Illustrative response. Assume the Event exists in your workspace and has one visible history entry. IDs, names and entry text are illustrative. Request inputs: {"event_id":12345}. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "workspace_log", "list_data": [ { "id": 67890, "log_entry_created_timestamp": "2026-01-02T08:04:05Z", "actor_user_id": "11111111-2222-4333-8444-555555555555", "actor_display_name": "Illustrative user", "log_entry": "Illustrative user updated event information.", "event_id": 12345, "event_name": "Illustrative owned event", "event_tab_id": 1, "task_id": null, "task_name": null, "asset_id": null, "asset_name": null, "storage_location_id": null, "storage_location_name": null } ] } ``` ## Tasks Create, read, update and delete Tasks and Task Sections, import Tasks from another Event, and work with Task file attachments and exports. Documentation page: https://api.exhibitday.com/Help/V1?epf=2 ### Retrieve a Single Task by ID `GET https://api.exhibitday.com/v1/tasks/info` Documentation: https://api.exhibitday.com/Help/V1?epf=2#get-v1-tasks-info Retrieves information about a specific task (using the "id" parameter). The response includes `assigned_by`, who assigned the task to its current assignee (a User Lite object, or null), and `contributors`, the task’s contributors as User Lite objects. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | Id of the specific task that you would like to retrieve. | | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` | | $on_error_return_empty_result | Boolean | No | For a missing or invalid task id, or a task not found, return HTTP 200 with {} (or [] when $result_format=array). Authentication, rate-limit and unexpected server errors keep their normal HTTP status. | Default: false. | | $include_record_revision | Boolean | No | Set to true to include record_revision in the response. Send that value as expected_revision when updating to check for conflicting changes. | Default: false. | #### Hidden Tasks tab Hiding an Event's Tasks tab does not hide its Tasks from the Task Board or the API. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/tasks/info?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/tasks/info?" + new URLSearchParams({ "id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/tasks/info", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/tasks/info?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/tasks/info?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/tasks/info?id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/tasks/info?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/tasks/info - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "id": 12345, "exhibitday_url": "https://www.exhibitday.com/Workspace/TaskView/98765?tid=12345", "event_task_section_id": null, "event_task_section": null, "display_rank": 0, "name": "Sample task", "due_date": null, "assignee": null, "assigned_by": null, "contributors": [ { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, { "id": "66666666-7777-4888-8999-aaaaaaaaaaaa", "first_name": "Alex", "last_name": "Morgan", "display_name": "Alex Morgan", "email": "alex@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true } ], "is_completed": false, "task_completed_timestamp": null, "task_completed_by": null, "details": "", "comments": [ { "id": 16346, "comment": "I will confirm the remaining details.", "comment_created_timestamp": "2026-11-21T17:01:00Z", "comment_last_update_timestamp": "2026-11-21T17:01:00Z", "commenter": { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true } }, { "id": 16347, "comment": "The setup checklist is ready.", "comment_created_timestamp": "2026-11-21T17:02:00Z", "comment_last_update_timestamp": "2026-11-21T17:02:00Z", "commenter": { "id": "66666666-7777-4888-8999-aaaaaaaaaaaa", "first_name": "Alex", "last_name": "Jordan", "display_name": "Alex Jordan", "email": "alex@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true } } ], "event": null, "task_created_by": { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, "task_created_timestamp": "2026-11-21T17:00:00Z", "task_last_update_timestamp": "2026-11-21T17:02:00Z", "integration_metadata_field_1": "", "integration_metadata_field_2": "", "integration_metadata_field_3": "", "integration_metadata_field_4": "", "integration_metadata_field_5": "", "related_items": [ { "id": 5551, "related_item_id": 67890, "related_item_exhibitday_url": "https://www.exhibitday.com/Workspace/TaskView/98765?tid=67890", "related_item_type_id": 1, "related_item_type": "Task", "related_item_asset_type_id": null, "related_item_name": "Confirm booth graphics with the printer", "related_item_created_timestamp": "2030-01-10T14:03:00Z" }, { "id": 5552, "related_item_id": 45678, "related_item_exhibitday_url": "https://www.exhibitday.com/Workspace/RelatedItemView/98765?typeId=4&subTypeId=0&rid=45678", "related_item_type_id": 4, "related_item_type": "Shipment", "related_item_asset_type_id": null, "related_item_name": "Booth crates to convention center", "related_item_created_timestamp": "2030-01-10T14:03:00Z" } ] } ``` ### Retrieve Tasks `GET https://api.exhibitday.com/v1/tasks` Documentation: https://api.exhibitday.com/Help/V1?epf=2#get-v1-tasks Find Tasks in your workspace. Tasks must match every filter you supply. For example, combine `filter_by_no_due_date=true` with `filter_by_event_id=12345` to find Tasks without a due date for that Event. `filter_by_contributor_user_ids` accepts one ID or an array of IDs. The match parameter, `filter_by_contributor_user_ids_match_type` (any or all), applies before counting and paging. Each other filter accepts one value. The response includes `assigned_by`, who assigned the task to its current assignee (a User Lite object, or null), and `contributors`, the task’s contributors as User Lite objects. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | filter_by_event_id | Number | No | Only include tasks from this given event. | | | filter_by_general_tasks_only | Boolean | No | Only include general tasks (tasks on the main task board that do not belong to a particular event). Note: this filter cannot be used in conjunction with the filter_by_event_id filter. | Default: false. | | filter_by_incomplete_only | Boolean | No | If you pass in the value "true" for this parameter, the result will only include tasks that are NOT marked as Completed. | Default: false. | | filter_by_completed_only | Boolean | No | If you pass in the value "true" for this parameter, the result will only include tasks that are marked as Completed. | Default: false. | | filter_by_no_due_date | Boolean | No | If you pass in the value "true" for this parameter, the result will only include tasks that do not have a due date set. | Default: false. | | filter_by_due_date_greater_than_or_equal_to | Date | No | Only include tasks that have a due date greater than or equal to the value passed in for this filter parameter. Use this date format: YYYY-MM-DD. You can also pass in "today", "yesterday" or "tomorrow" (based on your workspace's time zone). Note: this filter cannot be used in conjunction with the filter_by_no_due_date filter. | | | filter_by_due_date_smaller_than_or_equal_to | Date | No | Only include tasks that have a due date smaller than or equal to the value passed in for this filter parameter. Use this date format: YYYY-MM-DD. You can also pass in "today", "yesterday" or "tomorrow" (based on your workspace's time zone). Note: this filter cannot be used in conjunction with the filter_by_no_due_date filter. | | | filter_by_has_assignee | Boolean | No | Only include tasks that have an assignee. Unassigned tasks will get excluded. | Default: false. | | filter_by_assignee_user_id | String | No | Only include tasks that are assigned to this user. You can get a list of UserIds in your workspace from the /v1/references/users_and_resources endpoint. Note: If you want to retrieve the tasks that are unassigned, include this parameter and pass in the word "null" as the value for it. | | | filter_by_task_name_contains_text | String | No | Only include tasks that have the given text in the task Name. For example: If you want to retrieve all the tasks that have the word “order” in the task Name field, pass in the value “order” for the filter_by_task_name_contains_text parameter. Note: this text search is not case-sensitive. | | | hydrate_related_items | Boolean | No | Set to true to include each record's related_items: the Tasks and items linked to it, with the key to use when adding or removing a link. Omit it or send false to leave related_items out of list results. Single-record GETs always include related_items. | Default: false. | | filter_by_integration_metadata_field_1 | String | No | Only include tasks that have their integration_metadata_field_1 property equal to the value you pass in for this parameter. Note: A task's integration_metadata_field_1 property is an integration-specific text field only accessible via the ExhibitDay API. This field is typically used to store metadata or information about a particular task (e.g., the "external id" of the task from another system you're integrating with). | Max length: 3000. | | filter_by_integration_metadata_field_2 | String | No | Only include tasks that have their integration_metadata_field_2 property equal to the value you pass in for this parameter. Note: A task's integration_metadata_field_2 property is an integration-specific text field only accessible via the ExhibitDay API. This field is typically used to store metadata or information about a particular task (e.g., the "external id" of the task from another system you're integrating with). | Max length: 3000. | | filter_by_integration_metadata_field_3 | String | No | Only include tasks that have their integration_metadata_field_3 property equal to the value you pass in for this parameter. Note: A task's integration_metadata_field_3 property is an integration-specific text field only accessible via the ExhibitDay API. This field is typically used to store metadata or information about a particular task (e.g., the "external id" of the task from another system you're integrating with). | Max length: 3000. | | filter_by_integration_metadata_field_4 | String | No | Only include tasks that have their integration_metadata_field_4 property equal to the value you pass in for this parameter. Note: A task's integration_metadata_field_4 property is an integration-specific text field only accessible via the ExhibitDay API. This field is typically used to store metadata or information about a particular task (e.g., the "external id" of the task from another system you're integrating with). | Max length: 3000. | | filter_by_integration_metadata_field_5 | String | No | Only include tasks that have their integration_metadata_field_5 property equal to the value you pass in for this parameter. Note: A task's integration_metadata_field_5 property is an integration-specific text field only accessible via the ExhibitDay API. This field is typically used to store metadata or information about a particular task (e.g., the "external id" of the task from another system you're integrating with). | Max length: 3000. | | hydrate_task_comments | Boolean | No | Set to `true` to include the comments for each full Task. This increases response size and can slow the request. Task Lite results never include comments. | Default: false. | | filter_by_contributor_user_ids | String or JSON array | No | Only return Tasks with these contributors. Send one user ID or an array of user IDs, for example "user-id" or ["user-id","other-user-id"]. Omit, leave blank or send [] for no contributor filter. Duplicate IDs collapse. Inactive and deactivated people, and people no longer in this workspace, still match the Tasks they are contributors on; IDs never added as a contributor in this workspace match nothing. Use filter_by_contributor_user_ids_match_type to require at least one or every selected person. This filter combines with every other filter before counting and paging, and also applies when $return_task_lites is true. | Use IDs from GET /v1/references/users_and_resources. Each ID is text of up to 128 characters. Arrays contain strings, not numbers; a comma-separated text is one ID, not a list. Invalid values return HTTP 400, also when $on_error_return_empty_result is true. | | filter_by_contributor_user_ids_match_type | String | No | How to match the selected contributors. Omit or leave blank to return Tasks with at least one selected contributor (the default), or require every selected contributor; Tasks can have other contributors too. This combines with the other filters before counting and paging. If filter_by_contributor_user_ids has no IDs, this option is ignored and the response includes a warning. Values are case-insensitive. | Allowed values: `any` \| `all` | | filter_by_completer_user_id | String | No | Only include the tasks that were completed by this user. Use the user's id from /v1/references/users_and_resources. You can only pass in one id. | | | $result_sort | String | No | Sorts Tasks by when they were created or last updated. Omit, or use an unrecognized value, to group Tasks by Event in Event start date order and retain their Task board order within each Event. | Allowed values: `create_timestamp_asc` (oldest created first) \| `create_timestamp_desc` (newest created first) \| `last_update_timestamp_asc` (least recently updated first) \| `last_update_timestamp_desc` (most recently updated first) | | $return_task_lites | Boolean | No | Set to `true` to return shorter Task records for faster reads. Each Task Lite includes the Task ID, name, `exhibitday_url`, display rank, due date, assignee ID, completion status, completion time and user ID, the Event, the creator ID, created and updated timestamps, and integration metadata. It omits comments. Its `task_completed_timestamp_est` contains the same UTC value as `task_completed_timestamp` in the full Task. | Default: false. | | filter_by_last_update_timestamp_greater_than_or_equal_to | String | No | Only include tasks that were added or changed on or after this date and time, for example 2026-10-14T18:30:00 (a date alone, such as 2026-10-14, means midnight). Responses give task_last_update_timestamp in UTC (it ends in Z), and that value can be passed back unchanged; a value without an offset is read as US Eastern time, and any other offset (e.g., 2026-10-14T18:30:00-04:00) is converted. To sync changes, process and save every page before advancing the cursor. Save the latest task_last_update_timestamp you receive and pass it in next time (tasks changed at exactly that time come back again, upsert every returned record by id, including boundary records). Deleted tasks are not returned. Any other value is rejected with an error. | | | $limit | Number | No | The most tasks to return (a whole number of 1 or more). Use it with $offset to read a long list in pages: total_records in the response counts every matching task and has_more is true while more pages follow (the X-Total-Count header carries the total too). Without $limit, every matching task is returned. | | | $offset | Number | No | How many tasks to skip before the first one returned (a whole number; 0 by default). For the next page, add the number of tasks you received to $offset. | | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | | $on_error_return_empty_result | Boolean | No | For this endpoint's ID, filter or paging validation errors, return HTTP 200 with no matching records in the selected result format. Authentication, rate-limit and unexpected server errors keep their normal HTTP status. | Default: false. | Declared schema for `filter_by_contributor_user_ids` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "oneOf": [ { "type": "string", "minLength": 1, "maxLength": 128, "pattern": "\\S" }, { "type": "array", "items": { "type": "string", "minLength": 1, "maxLength": 128, "pattern": "\\S" } } ], "x-normalization": "one string becomes a one-item array; trimmed distinct IDs; no record-count cap", "nullable": false, "x-maximum-depth": 1, "x-empty-create-means-omitted": false, "example": [ "user-id", "other-user-id" ] } ``` #### Hidden Tasks tab Hiding an Event's Tasks tab does not hide its Tasks from the Task Board or the API. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/tasks?filter_by_contributor_user_ids=%5B%22user-id%22%2C%22other-user-id%22%5D&filter_by_contributor_user_ids_match_type=all" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/tasks?" + new URLSearchParams({ "filter_by_contributor_user_ids": "[\"user-id\",\"other-user-id\"]", "filter_by_contributor_user_ids_match_type": "all" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/tasks", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"filter_by_contributor_user_ids": "[\"user-id\",\"other-user-id\"]", "filter_by_contributor_user_ids_match_type": "all"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Text.Json; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/tasks?filter_by_contributor_user_ids=%5B%22user-id%22%2C%22other-user-id%22%5D&filter_by_contributor_user_ids_match_type=all"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/tasks?filter_by_contributor_user_ids=%5B%22user-id%22%2C%22other-user-id%22%5D&filter_by_contributor_user_ids_match_type=all")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/tasks?filter_by_contributor_user_ids=%5B%22user-id%22%2C%22other-user-id%22%5D&filter_by_contributor_user_ids_match_type=all') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/tasks?filter_by_contributor_user_ids=%5B%22user-id%22%2C%22other-user-id%22%5D&filter_by_contributor_user_ids_match_type=all", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/tasks - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "task", "list_data": [ { "id": 12345, "exhibitday_url": "https://www.exhibitday.com/Workspace/TaskView/98765?tid=12345", "event_task_section_id": null, "event_task_section": null, "display_rank": 0, "name": "Sample task", "due_date": null, "assignee": null, "assigned_by": null, "contributors": [ { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, { "id": "66666666-7777-4888-8999-aaaaaaaaaaaa", "first_name": "Alex", "last_name": "Morgan", "display_name": "Alex Morgan", "email": "alex@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true } ], "is_completed": false, "task_completed_timestamp": null, "task_completed_by": null, "details": "", "comments": null, "event": null, "task_created_by": { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, "task_created_timestamp": "2026-11-21T17:00:00Z", "task_last_update_timestamp": "2026-11-21T17:00:00Z", "integration_metadata_field_1": "", "integration_metadata_field_2": "", "integration_metadata_field_3": "", "integration_metadata_field_4": "", "integration_metadata_field_5": "" } ] } ``` ### Add a Task `POST https://api.exhibitday.com/v1/tasks` Documentation: https://api.exhibitday.com/Help/V1?epf=2#post-v1-tasks The response will contain an object representing the newly added task. The response includes `assigned_by`, who assigned the task to its current assignee (a User Lite object, or null), and `contributors`, the task’s contributors as User Lite objects. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | name | String | Yes | The name/short description of the task. | Max length: 400. | | event_id | Number | No | The id of the event you would like to add the task under. If this value is not provided, the task will be added as a general (non-event-specific) task in your workspace (under the main Task Board). | | | task_section_id | Number | No | The id of the event task section that the task should be placed under. Leave this value blank if you don't want to place/categorize the task under a specific event task section. Note: you can get a list of available Task Section Ids for a given event using the /v1/events/info endpoint. event_task_section_id, the name Task reads return, is also accepted for this parameter; if you send both and task_section_id isn't blank, task_section_id is used. If you send only event_task_section_id and it isn't a section of the task's Event, it is ignored with a warning. | | | is_completed | Boolean | No | Whether the task is complete. Use true or false. If omitted or blank, the default is false. | Default: false. | | due_date | Date | No | Task due date (format: YYYY-MM-DD). | | | assignee_user_id | String | No | The id of the user you would like to assign the task to. If you want the task to be unassigned, leave the value for this parameter blank. Use `GET /v1/references/users_and_resources` to find a workspace user ID. The `can_have_tasks_assigned` field is `true` for users eligible for assignment. | | | contributor_user_ids | String or JSON array | No | The contributors (tagged users) for this task: a JSON array of unique user IDs from your workspace, for example ["user-id","other-user-id"], or one user ID. In form or query requests, send the array as text. Each ID must be a user who can be assigned tasks. Contributors are notified by email if their notification settings allow it. | | | details | String | No | Task details as plain text, with line breaks. HTML tags are removed. GET returns the details as stored HTML. Convert `
` to line breaks and decode HTML entities before comparing or resubmitting. Resubmitting rich text from the web app keeps its text but loses its formatting. The stored details can be up to 30,000 characters. A line break uses five stored characters, and special characters such as ampersands, quotes and accented letters can use more than one. Longer details are refused, and the Task is not added. | Max length: 30000. | | integration_metadata_field_1 | String | No | This is an integration-specific text field only accessible via the ExhibitDay API. This field can be used to store whatever metadata or information you'd like about a particular task. For example, you can use it to store the "external id" of the task (from another system you're integrating with). Or, you can use it to store the last sync timestamp. Note: when you retrieve a list of tasks (using the /v1/tasks endpoint), you can filter down the results by the value of this field. | Max length: 3000. | | integration_metadata_field_2 | String | No | This is an integration-specific text field only accessible via the ExhibitDay API. This field can be used to store whatever metadata or information you'd like about a particular task. For example, you can use it to store the "external id" of the task (from another system you're integrating with). Or, you can use it to store the last sync timestamp. Note: when you retrieve a list of tasks (using the /v1/tasks endpoint), you can filter down the results by the value of this field. | Max length: 3000. | | integration_metadata_field_3 | String | No | This is an integration-specific text field only accessible via the ExhibitDay API. This field can be used to store whatever metadata or information you'd like about a particular task. For example, you can use it to store the "external id" of the task (from another system you're integrating with). Or, you can use it to store the last sync timestamp. Note: when you retrieve a list of tasks (using the /v1/tasks endpoint), you can filter down the results by the value of this field. | Max length: 3000. | | integration_metadata_field_4 | String | No | This is an integration-specific text field only accessible via the ExhibitDay API. This field can be used to store whatever metadata or information you'd like about a particular task. For example, you can use it to store the "external id" of the task (from another system you're integrating with). Or, you can use it to store the last sync timestamp. Note: when you retrieve a list of tasks (using the /v1/tasks endpoint), you can filter down the results by the value of this field. | Max length: 3000. | | integration_metadata_field_5 | String | No | This is an integration-specific text field only accessible via the ExhibitDay API. This field can be used to store whatever metadata or information you'd like about a particular task. For example, you can use it to store the "external id" of the task (from another system you're integrating with). Or, you can use it to store the last sync timestamp. Note: when you retrieve a list of tasks (using the /v1/tasks endpoint), you can filter down the results by the value of this field. | Max length: 3000. | #### Hidden Tasks tab Hiding an Event's Tasks tab does not hide its Tasks from the Task Board or the API. Example — curl: ```bash curl -X POST "https://api.exhibitday.com/v1/tasks" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"name\":\"Sample task\"}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/tasks", { method: "POST", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "name": "Sample task" }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.post( "https://api.exhibitday.com/v1/tasks", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"name": "Sample task"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PostAsync("https://api.exhibitday.com/v1/tasks", JsonContent.Create(new { name = "Sample task" })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/tasks")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("POST", HttpRequest.BodyPublishers.ofString("{\"name\":\"Sample task\"}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"name":"Sample task"}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/tasks') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"name":"Sample task"}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/tasks", strings.NewReader("{\"name\":\"Sample task\"}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): POST /v1/tasks - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "id": 23456, "exhibitday_url": "https://www.exhibitday.com/Workspace/TaskView/98765?tid=23456", "event_task_section_id": null, "event_task_section": null, "display_rank": 0, "name": "Sample task", "due_date": null, "assignee": null, "assigned_by": null, "contributors": [ { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, { "id": "66666666-7777-4888-8999-aaaaaaaaaaaa", "first_name": "Alex", "last_name": "Morgan", "display_name": "Alex Morgan", "email": "alex@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true } ], "is_completed": false, "task_completed_timestamp": null, "task_completed_by": null, "details": "", "comments": [], "event": null, "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": "2026-11-21T17:00:00Z", "task_last_update_timestamp": "2026-11-21T17:00:00Z", "integration_metadata_field_1": "", "integration_metadata_field_2": "", "integration_metadata_field_3": "", "integration_metadata_field_4": "", "integration_metadata_field_5": "" } ``` ### Update a Task `PATCH https://api.exhibitday.com/v1/tasks` Documentation: https://api.exhibitday.com/Help/V1?epf=2#patch-v1-tasks To update a task, only pass in the properties that you want to update. To clear a property that supports clearing, pass in null; an empty value leaves the property unchanged (the warnings property in the response names any such parameters). If the update is successful, the message property in the response will contain a list of task properties that were actually changed. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The Id of the task you would like to update. | | | name | String | No | The name/short description of the task. | Max length: 400. | | event_id | Number | No | The id of the event you would like to move the task to. To make it a general task (one that is not under any event), pass in null. A moved task is placed at the top of its new task list and taken out of its task section; to place it under one of the new event's task sections, also pass in task_section_id. Links between the task and items of its previous event are removed. A task cannot be moved into or out of an event whose tasks are locked. | | | task_section_id | Number | No | The id of the event task section that the task should be placed under. If you don't want to place/categorize the task under a specific event task section, pass in the value "null" for this parameter. Note: you can get a list of available Task Section Ids for a given event using the /v1/events/info endpoint. event_task_section_id, the name Task reads return, is also accepted for this parameter; if you send both and task_section_id isn't blank, task_section_id is used. If you send only event_task_section_id and it isn't a section of the task's Event, it is ignored with a warning. | | | is_completed | Boolean | No | Whether the task is complete. Use true or false. Omission or a blank value leaves its completion status unchanged. | | | due_date | Date | No | Task due date in YYYY-MM-DD format. To remove the due date, pass in null (JSON null or the string "null"). Omit this parameter, or pass in an empty value, to leave the due date unchanged. | | | assignee_user_id | String | No | The User Id of the user you would like to assign the task to. If you want the task to be unassigned, pass in the value "null" for this parameter. Use `GET /v1/references/users_and_resources` to find a workspace user ID. The `can_have_tasks_assigned` field is `true` for users eligible for assignment. | | | contributor_user_ids | String or JSON array | No | The complete list of contributors (tagged users) for this task: a JSON array of unique user IDs from your workspace, for example ["user-id","other-user-id"], or one user ID. In form or query requests, send the array as text. Sending it replaces the current contributors; [] or null removes them all. Omit it to keep the current contributors. Newly added contributors are notified by email if their notification settings allow it. | | | details | String | No | Task details as plain text, with line breaks. HTML tags are removed. GET returns the details as stored HTML. Convert `
` to line breaks and decode HTML entities before comparing or resubmitting. Resubmitting rich text from the web app keeps its text but loses its formatting. The stored details can be up to 30,000 characters. A line break uses five stored characters, and special characters such as ampersands, quotes and accented letters can use more than one. Longer details are refused without saving changes. Existing details over the limit can stay as they are or change without increasing their stored length. To clear this field, send JSON null or the string `null`. | Max length: 30000. | | integration_metadata_field_1 | String | No | This is an integration-specific text field only accessible via the ExhibitDay API. This field can be used to store whatever metadata or information you'd like about a particular task. For example, you can use it to store the "external id" of the task (from another system you're integrating with). Or, you can use it to store the last sync timestamp. Note: when you retrieve a list of tasks (using the /v1/tasks endpoint), you can filter down the results by the value of this field. | Max length: 3000. | | integration_metadata_field_2 | String | No | This is an integration-specific text field only accessible via the ExhibitDay API. This field can be used to store whatever metadata or information you'd like about a particular task. For example, you can use it to store the "external id" of the task (from another system you're integrating with). Or, you can use it to store the last sync timestamp. Note: when you retrieve a list of tasks (using the /v1/tasks endpoint), you can filter down the results by the value of this field. | Max length: 3000. | | integration_metadata_field_3 | String | No | This is an integration-specific text field only accessible via the ExhibitDay API. This field can be used to store whatever metadata or information you'd like about a particular task. For example, you can use it to store the "external id" of the task (from another system you're integrating with). Or, you can use it to store the last sync timestamp. Note: when you retrieve a list of tasks (using the /v1/tasks endpoint), you can filter down the results by the value of this field. | Max length: 3000. | | integration_metadata_field_4 | String | No | This is an integration-specific text field only accessible via the ExhibitDay API. This field can be used to store whatever metadata or information you'd like about a particular task. For example, you can use it to store the "external id" of the task (from another system you're integrating with). Or, you can use it to store the last sync timestamp. Note: when you retrieve a list of tasks (using the /v1/tasks endpoint), you can filter down the results by the value of this field. | Max length: 3000. | | integration_metadata_field_5 | String | No | This is an integration-specific text field only accessible via the ExhibitDay API. This field can be used to store whatever metadata or information you'd like about a particular task. For example, you can use it to store the "external id" of the task (from another system you're integrating with). Or, you can use it to store the last sync timestamp. Note: when you retrieve a list of tasks (using the /v1/tasks endpoint), you can filter down the results by the value of this field. | Max length: 3000. | | expected_revision | String | No | The record_revision returned when you retrieved this record. Include it to avoid overwriting someone else's changes. Omit it to skip this check. | | #### Hidden Tasks tab Hiding an Event's Tasks tab does not hide its Tasks from the Task Board or the API. Example — curl: ```bash curl -X PATCH "https://api.exhibitday.com/v1/tasks" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"id\":12345,\"name\":\"Updated task name\"}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/tasks", { method: "PATCH", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "id": 12345, "name": "Updated task name" }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.patch( "https://api.exhibitday.com/v1/tasks", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"id": 12345, "name": "Updated task name"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PatchAsync("https://api.exhibitday.com/v1/tasks", JsonContent.Create(new { id = 12345, name = "Updated task name" })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/tasks")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("PATCH", HttpRequest.BodyPublishers.ofString("{\"id\":12345,\"name\":\"Updated task name\"}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"id":12345,"name":"Updated task name"}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/tasks') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"id":12345,"name":"Updated task name"}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/tasks", strings.NewReader("{\"id\":12345,\"name\":\"Updated task name\"}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): PATCH /v1/tasks - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Task Update Successful. Task properties that were changed: name", "errors": [] } ``` ### Delete a Task `DELETE https://api.exhibitday.com/v1/tasks` Documentation: https://api.exhibitday.com/Help/V1?epf=2#delete-v1-tasks Permanently deletes a task. It cannot be undone. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The id of the task you would like to delete. | | #### Hidden Tasks tab Hiding an Event's Tasks tab does not hide its Tasks from the Task Board or the API. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/tasks?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/tasks?" + new URLSearchParams({ "id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/tasks", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/tasks?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/tasks?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/tasks?id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/tasks?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/tasks - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Task Deleted", "errors": [] } ``` ### Retrieve a Single Task Section by ID `GET https://api.exhibitday.com/v1/tasks/sections/info` Documentation: https://api.exhibitday.com/Help/V1?epf=2#get-v1-tasks-sections-info Retrieve one saved task section, including its name, Event and display order. Task sections group an Event's work. General Tasks do not have saved sections; Uncategorized is the group for tasks without a section and is not a stored section returned here. Current Task-board and Event access apply; hiding the Event Tasks navigation tab alone does not remove Task-board access. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The section ID from Task Sections, its Info response or the Create response. Its Event is determined from that section; do not send another Event ID. | | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` \| `object` | | $include_record_revision | Boolean | No | Set to true to include record_revision in the response. Send that value as expected_revision when updating to check for conflicting changes. | Default: false. | | $on_error_return_empty_result | Boolean | No | For an invalid or unavailable section ID, return HTTP 200 with {} or [] in array format. API key errors, conflicts with a change in progress and unexpected errors keep their usual status. | | #### Hidden Tasks tab Hiding an Event's Tasks tab does not hide its Tasks from the Task Board or the API. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/tasks/sections/info?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/tasks/sections/info?" + new URLSearchParams({ "id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/tasks/sections/info", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/tasks/sections/info?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/tasks/sections/info?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/tasks/sections/info?id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/tasks/sections/info?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/tasks/sections/info - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "id": 12345, "event_id": 23456, "event_name": "Sample Event", "name": "Pre-event planning", "display_rank": 1, "task_section_created_timestamp": "2030-01-15T12:00:00Z" } ``` ### Retrieve Task Sections `GET https://api.exhibitday.com/v1/tasks/sections` Documentation: https://api.exhibitday.com/Help/V1?epf=2#get-v1-tasks-sections Retrieves saved Task sections across Events you can access. Use filter_by_event_id to retrieve sections for one Event. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | filter_by_event_id | Number | No | Return records for this Event only. Omit for all readable Events in your workspace. | | | $limit | Number | No | The most sections to return, as a positive whole number. Leave this out for all remaining sections. | | | $offset | Number | No | How many sections to skip: 0 or more, with 0 as the default. | | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | #### Filtering and paging Omit filter_by_event_id for all accessible Event sections. The workspace Task permission and current Event access rules apply before counts and paging. A supplied Event that is missing or unavailable returns an empty list with a warning. An accessible Event with no saved sections returns an empty list without that warning. Uncategorized is not a saved section and has no record in this list. Results are ordered by Event ID, then display rank, then section ID, so each Event's sections stay together across pages. Omit $limit for all remaining matching sections; $offset defaults to 0. Each returned section retains its actual event_id and Event name. #### Hidden Tasks tab Hiding an Event's Tasks tab does not hide its Tasks from the Task Board or the API. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/tasks/sections" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/tasks/sections", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/tasks/sections", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/tasks/sections"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/tasks/sections")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/tasks/sections') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/tasks/sections", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/tasks/sections - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "list_type": "task_section", "list_data": [ { "id": 12345, "event_id": 23456, "event_name": "Sample Event", "name": "Pre-event planning", "display_rank": 1, "task_section_created_timestamp": "2030-01-15T12:00:00Z" } ], "records_found": 1, "total_records": 1, "has_more": false } ``` ### Add a Task Section `POST https://api.exhibitday.com/v1/tasks/sections` Documentation: https://api.exhibitday.com/Help/V1?epf=2#post-v1-tasks-sections Add a section at the top of an Event's task list, such as Pre-event planning or On-site activities. Duplicate names are allowed. Your current permission must allow managing tasks for anyone, and applicable shallow or deep Tasks locks must allow the change. A locked Tasks tab returns HTTP `400` (`not_allowed`). Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | event_id | Number | Yes | The existing Event in your workspace whose task sections you want to use. | | | name | String | Yes | The section name, up to 100 UTF-16 characters. It can't be blank. Uncategorized and its reserved variants represent tasks without a saved section. Duplicate section names are allowed. | Max length: 100. | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` \| `object` | **Saving a Task Section**: If the save outcome cannot be confirmed, retrieve the current section and its tasks before deciding whether to retry. The API does not automatically repeat the change or imply a confirmed revision in that error response. You can send a parameter more than once if every copy has the same value. If the copies differ, the API returns HTTP 400. Use JSON, query or form for a name containing commas. Optional Idempotency-Key replay applies to POST. PATCH and DELETE ignore that header. #### Hidden Tasks tab Hiding an Event's Tasks tab does not hide its Tasks from the Task Board or the API. Example — curl: ```bash curl -X POST "https://api.exhibitday.com/v1/tasks/sections" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"event_id\":23456,\"name\":\"Pre-event planning\"}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/tasks/sections", { method: "POST", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "event_id": 23456, "name": "Pre-event planning" }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.post( "https://api.exhibitday.com/v1/tasks/sections", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"event_id": 23456, "name": "Pre-event planning"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PostAsync("https://api.exhibitday.com/v1/tasks/sections", JsonContent.Create(new { event_id = 23456, name = "Pre-event planning" })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/tasks/sections")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("POST", HttpRequest.BodyPublishers.ofString("{\"event_id\":23456,\"name\":\"Pre-event planning\"}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"event_id":23456,"name":"Pre-event planning"}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/tasks/sections') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"event_id":23456,"name":"Pre-event planning"}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/tasks/sections", strings.NewReader("{\"event_id\":23456,\"name\":\"Pre-event planning\"}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): POST /v1/tasks/sections - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "id": 12345, "event_id": 23456, "event_name": "Sample Event", "name": "Pre-event planning", "display_rank": 1, "task_section_created_timestamp": "2030-01-15T12:00:00Z" } ``` ### Import Tasks from Another Event `POST https://api.exhibitday.com/v1/tasks/import_from_event` Documentation: https://api.exhibitday.com/Help/V1?epf=2#post-v1-tasks-import_from_event Copy all or selected Tasks from another Event into an existing Event in your workspace. This is available with the Premium and Enterprise plans. The source Tasks stay in place. Each new Task starts as Not Started, with no comments, completion, workflow action or integration identity copied. Names and details are copied as stored. By default, Tasks are unassigned, have no due dates or attachments, and go into Uncategorized. You can keep assignees, choose how to copy due dates, copy saved attachments, and select an existing target Task Section. The copied Tasks appear above the target Event's current Tasks in source display order. Current Task-board access, Event access and target Tasks locks still apply; hiding the Tasks navigation tab alone does not remove Task-board access. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | source_event_id | Number | Yes | The ID of the existing Event whose Tasks you want to copy. It must be a different Event in your workspace. | | | event_id | Number | Yes | The ID of the Event that will receive the copied Tasks. | | | task_ids | JSON object/list | No | An optional nonempty JSON array of distinct positive Task IDs from the source Event, or one Task ID on its own (a list of one). Omit this parameter to copy all its Tasks. An ID that is not (or no longer) a Task of the source Event is skipped: the other Tasks are copied and a warning names each skipped ID. If none of the IDs are Tasks of the source Event, the request is refused with HTTP 404. | | | task_section_id | Number | No | An existing Task Section under the target Event. Omit it, or send JSON null or blank, to place the copied Tasks in Uncategorized. This does not copy the source section. | | | keep_assignees | Boolean | No | Send true to keep current eligible assignees and tagged people. The default false creates unassigned Tasks without tagged people. It sends no new assignment or tagging emails. | Default: false. | | due_date_mode | String | No | Choose how copied Tasks get due dates. Omit this field to leave them empty. You can keep the original dates or keep each Task's calendar-day offset from the source Event start date, measured from the target Event start date. If a resulting date is outside the supported range, no Tasks are copied. Values are case-insensitive. Unrecognized values and JSON null are refused. | Allowed values: `none` (leave due dates empty) \| `same_date` (keep the original dates) \| `same_offset` (keep the day offset from the Event start) | | keep_attachments | Boolean | No | Send true to copy each selected Task's saved attachments that your access allows. The default is false. The attachments are added to the new Tasks right away, and their files are copied in the background shortly after. Source files are never changed. | Default: false. | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` \| `object` | Declared schema for `task_ids` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "array", "items": { "type": "integer", "format": "int64" }, "maxItems": 2147483647, "nullable": false, "x-maximum-depth": 2, "x-empty-create-means-omitted": false, "example": [ 34567 ] } ``` **Checking the Import Result**: The result maps each source_task_id to the new Task id. Each Task is copied as it is when the import reads it. If a selected Task is not a Task in the source Event when the request arrives, or is deleted or moved to another Event while the import runs, it is skipped: the result lists only the copied Tasks, and the response includes a warning naming each skipped Task (for example: The task 'Book hotel' (Task ID 12345) was not copied because it is not a Task in the Event 'Spring Expo'. A Task you cannot read is given by its id only: Task ID 12345 was not copied because ...; a Task deleted or moved while the import runs is also given by its id) and how many of the selected Tasks were imported. When keep_attachments is true, the attachments are added to the new Tasks and their files are copied in the background; each file can be opened once its copy finishes. If a source file is missing or cannot be copied, such as a file with an unsupported name, that attachment is not kept. Source files are never changed. Confirmed imports add one Task history entry per copied Task. Existing due-date reminder behavior applies when an assignee and due date are kept. Optional Idempotency-Key replay applies to this POST. Reuse the same key and identical request only for a retry; it returns the stored original result. If the outcome cannot be confirmed, retrieve the target Event's Tasks before deciding whether to retry. The API does not automatically repeat an uncertain import. You can send a parameter more than once if every copy has the same value. If the copies differ, the API returns HTTP 400 and nothing is changed. Use JSON, query or form for Task ID lists or text containing commas. expected_revision is not supported. #### Hidden Tasks tab Hiding an Event's Tasks tab does not hide its Tasks from the Task Board or the API. Example — curl: ```bash curl -X POST "https://api.exhibitday.com/v1/tasks/import_from_event" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"source_event_id\":12345,\"event_id\":23456}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/tasks/import_from_event", { method: "POST", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "source_event_id": 12345, "event_id": 23456 }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.post( "https://api.exhibitday.com/v1/tasks/import_from_event", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"source_event_id": 12345, "event_id": 23456}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PostAsync("https://api.exhibitday.com/v1/tasks/import_from_event", JsonContent.Create(new { source_event_id = 12345, event_id = 23456 })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/tasks/import_from_event")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("POST", HttpRequest.BodyPublishers.ofString("{\"source_event_id\":12345,\"event_id\":23456}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"source_event_id":12345,"event_id":23456}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/tasks/import_from_event') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"source_event_id":12345,"event_id":23456}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/tasks/import_from_event", strings.NewReader("{\"source_event_id\":12345,\"event_id\":23456}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): POST /v1/tasks/import_from_event - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "source_event_id": 12345, "event_id": 23456, "tasks_copied": 1, "tasks": [ { "source_task_id": 34567, "id": 45678 } ] } ``` ### Update a Task Section `PATCH https://api.exhibitday.com/v1/tasks/sections` Documentation: https://api.exhibitday.com/Help/V1?epf=2#patch-v1-tasks-sections Renames a Task Section. Task Sections group an Event's tasks, for example High Priority or Pre-event Planning. To change their order, use the ExhibitDay web app. Task-management permissions and applicable Tasks locks apply. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Task Section you want to update. | | | name | String | No | The new name, such as High Priority or In Progress. Omit it to keep the current name. | Maximum 100 UTF-16 code units. | | expected_revision | String | No | The `record_revision` returned when you last retrieved this Task Section. Include it to avoid overwriting someone else's changes. Omit it to skip this check. | | | $ignore_params_with_empty_values | Boolean | No | Set to `true` to keep the current name when `name` is sent as JSON `null`. | Default: false. The text `null` is still rejected because a section name cannot be cleared. Blank values already keep the current name. | #### Choosing a section name Omit `name` or send a blank value to keep the current name. A supplied name must contain text. If it matches the current name, the API skips the update and creates no history entry. Multiple sections can have the same name. ExhibitDay reserves Uncategorized and its variants for tasks without a section. A section name cannot be cleared: JSON `null` and the text `null` are rejected. With `$ignore_params_with_empty_values=true`, JSON `null` is ignored and the current name is kept; the text `null` is still rejected. If the name contains a comma, send it in a JSON body, query string or form field rather than a header. #### Avoiding conflicting updates 1. Retrieve the Task Section with `GET /v1/tasks/sections/info` and include `$include_record_revision=true`. 2. In your `PATCH` request, set `expected_revision` to the exact `record_revision` returned by that request. - The revision covers the section's name and Event. If either value now differs from what you read, the API returns HTTP `409` (`record_changed`) and saves nothing. Retrieve the section again, review its current values and decide whether to retry. A value that changed and was later changed back still matches. - When you include `expected_revision`, a successful update returns the section's current `record_revision`. Without that input, the response does not include a revision. - A blank, null or malformed `expected_revision`, or different values sent for it in the same request, produces HTTP `400` (`invalid_request`). #### Retrying a request If you cannot confirm whether the update succeeded, retrieve the section and its tasks before retrying. The API does not retry automatically. This endpoint ignores the `Idempotency-Key` header. #### Hidden Tasks tab Hiding an Event's Tasks tab does not hide its Tasks from the Task Board or the API. Example — curl: ```bash curl -X PATCH "https://api.exhibitday.com/v1/tasks/sections" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"id\":12345,\"name\":\"Pre-event planning\"}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/tasks/sections", { method: "PATCH", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "id": 12345, "name": "Pre-event planning" }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.patch( "https://api.exhibitday.com/v1/tasks/sections", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"id": 12345, "name": "Pre-event planning"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PatchAsync("https://api.exhibitday.com/v1/tasks/sections", JsonContent.Create(new { id = 12345, name = "Pre-event planning" })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/tasks/sections")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("PATCH", HttpRequest.BodyPublishers.ofString("{\"id\":12345,\"name\":\"Pre-event planning\"}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"id":12345,"name":"Pre-event planning"}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/tasks/sections') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"id":12345,"name":"Pre-event planning"}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/tasks/sections", strings.NewReader("{\"id\":12345,\"name\":\"Pre-event planning\"}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): PATCH /v1/tasks/sections - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Task section updated.", "errors": [] } ``` ### Delete a Task Section `DELETE https://api.exhibitday.com/v1/tasks/sections` Documentation: https://api.exhibitday.com/Help/V1?epf=2#delete-v1-tasks-sections Remove a task section. By default, its tasks are kept and placed in Uncategorized after the tasks already there. Send keep_tasks=false only to permanently delete its tasks and their comments, attachments and related-item links as well. This sends no assignment emails. Current task-management permission and applicable Tasks locks must allow the removal; a locked Tasks tab returns HTTP `400` (`not_allowed`). A Task added to the section while the removal is running is kept or deleted with the others; once the section is gone, a create that names it is refused like any unknown id. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The section ID from Task Sections, its Info response or the Create response. Its Event is determined from that section; do not send another Event ID. | | | keep_tasks | Boolean | No | Omit this option, leave it blank, or send true to keep this section's tasks and move them to Uncategorized after its current tasks. Send false only to permanently delete the section's tasks, comments, attachments and related-item links. This does not send assignment emails. JSON null is refused. | Default: true. | **Saving a Task Section**: If the save outcome cannot be confirmed, retrieve the current section and its tasks before deciding whether to retry. The API does not automatically repeat the change or imply a confirmed revision in that error response. You can send a parameter more than once if every copy has the same value. If the copies differ, the API returns HTTP 400. Use JSON, query or form for a name containing commas. Optional Idempotency-Key replay applies to POST. PATCH and DELETE ignore that header. #### Hidden Tasks tab Hiding an Event's Tasks tab does not hide its Tasks from the Task Board or the API. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/tasks/sections?id=12345&keep_tasks=true" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/tasks/sections?" + new URLSearchParams({ "id": "12345", "keep_tasks": "true" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/tasks/sections", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345, "keep_tasks": True}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/tasks/sections?id=12345&keep_tasks=true"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/tasks/sections?id=12345&keep_tasks=true")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/tasks/sections?id=12345&keep_tasks=true') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/tasks/sections?id=12345&keep_tasks=true", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/tasks/sections - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Task section removed.", "errors": [] } ``` ### Retrieve Task General File Attachments `GET https://api.exhibitday.com/v1/tasks/attachments` Documentation: https://api.exhibitday.com/Help/V1?epf=2#get-v1-tasks-attachments Retrieves the General File Attachments on this Task. Each result includes the file's ID, name and added time; use the download method for its contents. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | task_id | Number | Yes | The ID of the Task, from Retrieve Tasks (GET /v1/tasks) or its add response. | This can be an Event Task or a General Task. The server finds its current Event when it has one. | | $limit | Number | No | The most File Attachments to return. | A positive whole number. Omit for all remaining matching files. | | $offset | Number | No | The number of matching File Attachments to skip. | A whole number of 0 or more. Default: 0. | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records. | Allowed values: `array` | | If-None-Match | String | No | An ETag from an earlier response to this GET. | Optional HTTP header. If the successful response is unchanged, the API returns HTTP 304 with no body. | #### Reading the file list Files are ordered by added time, then attachment ID, lowest first. Only files available under your current access are included. Paging totals and X-Total-Count count all matching files before $limit and $offset are applied. A record with no files you can view returns an empty list. This list does not return edit revisions or support changed-since filtering. #### Task Board access The Task may belong to an Event or be a General Task. These files follow the main Task Board's current permissions. Hiding or shallow-locking the Event's Tasks navigation tab alone does not block the Task Board. Current Task read access is required. This method does not grant access to another Task or change its assignment or completion. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/tasks/attachments?task_id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/tasks/attachments?" + new URLSearchParams({ "task_id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/tasks/attachments", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"task_id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/tasks/attachments?task_id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/tasks/attachments?task_id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/tasks/attachments?task_id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/tasks/attachments?task_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/tasks/attachments - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "attachment", "list_data": [ { "id": 12345, "filename": "attachment.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } ] } ``` ### Add Task General File Attachments `POST https://api.exhibitday.com/v1/tasks/attachments` Documentation: https://api.exhibitday.com/Help/V1?epf=2#post-v1-tasks-attachments Adds one or more General File Attachments to this Task. Send each file as a multipart upload part named file. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | task_id | Number | Yes | The ID of the Task, from Retrieve Tasks (GET /v1/tasks) or its add response. | This can be an Event Task or a General Task. The server finds its current Event when it has one. | | file | File (multipart) | Yes | The File Attachments to upload. | Send one or more complete, nonempty multipart/form-data parts, each named file. Supported types and the current per-file limit are shown below. The complete request limit includes all files and multipart overhead; split larger batches. A missing or null upload is not a removal request. | | Idempotency-Key | String | No | A unique key for safely retrying this upload. | Optional HTTP header: 1 to 255 visible ASCII characters without spaces or commas. Retry the identical request with the same key to replay its first saved response. Use a new key for a different upload. | Declared schema for `file` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "array", "items": { "type": "string", "format": "binary", "x-maximum-bytes": 26214400, "x-allowed-extensions": [ "png", "jpg", "jpeg", "bmp", "gif", "pdf", "msg", "eml", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "rtf", "odp", "odt", "ods", "txt", "wks", "zip" ] } } ``` #### After the upload The response's list_data contains the newly attached files, including each id, filename and attachment_created_timestamp. Existing files are kept. Use each returned id to download or remove that file. Identical repeated files in one request are attached once when their cleaned filename, length and contents match. Files with different contents remain separate even when their names match. This does not remove or replace files already attached to the record. #### Task Board access The Task may belong to an Event or be a General Task. These files follow the main Task Board's current permissions. Hiding or shallow-locking the Event's Tasks navigation tab alone does not block the Task Board. A Deep Lock prevents file changes. Current Task management permission is required. Uploading requires an upload-enabled paid plan. File changes update the Task's last-update time while preserving assignment, completion, reminders, notifications, section and order. #### History and retries A confirmed file change is recorded in history. expected_revision is not supported by these file methods. If the save outcome cannot be confirmed, retrieve the current file list before deciding whether to retry; the API does not automatically repeat an uncertain change. Task attachments have no PATCH replacement or Invoice Attachment method. To replace a supporting file, add the new file and remove the old one using their separate requests. #### Hidden or locked tab If the Task's Event has its Tasks tab locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Unlock the tab in ExhibitDay first. Hiding the Tasks tab does not block Task files. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X POST "https://api.exhibitday.com/v1/tasks/attachments" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}" --form-string "task_id=12345" --form "file=@attachment.pdf;type=application/octet-stream") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi cat response-body.tmp ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const form = new FormData(); form.append("task_id", "12345"); form.append("file", new Blob([await readFile("attachment.pdf")], { type: "application/octet-stream" }), "attachment.pdf"); const response = await fetch("https://api.exhibitday.com/v1/tasks/attachments", { method: "POST", headers: { Authorization: 'Bearer YOUR_API_KEY' }, body: form }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); console.log(await response.json()); ``` Example — Python: ```python import requests import json from contextlib import ExitStack with ExitStack() as stack: files = [ ("file", ("attachment.pdf", stack.enter_context(open("attachment.pdf", 'rb')), "application/octet-stream")), ] response = requests.request("POST", "https://api.exhibitday.com/v1/tasks/attachments", headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data={"task_id": "12345"}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') print(response.json()) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.exhibitday.com/v1/tasks/attachments"); var form = new MultipartFormDataContent(); form.Add(new StringContent("12345"), "task_id"); var file0 = new StreamContent(File.OpenRead("attachment.pdf")); file0.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(file0, "file", "attachment.pdf"); request.Content = form; using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/tasks/attachments")).header("Authorization", "Bearer YOUR_API_KEY"); String boundary = "ExhibitDay-" + UUID.randomUUID(); ByteArrayOutputStream form = new ByteArrayOutputStream(); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"task_id\"\r\n\r\n" + "12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"attachment.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8)); form.write(Files.readAllBytes(Path.of("attachment.pdf"))); form.write("\r\n".getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); request.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpResponse response = HttpClient.newHttpClient().send(request.method("POST", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); System.out.println(new String(response.body(), StandardCharsets.UTF_8)); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], CURLOPT_POSTFIELDS => [ 'task_id' => '12345', 'file' => new CURLFile('attachment.pdf', 'application/octet-stream', 'attachment.pdf'), ], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); echo $response; ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/tasks/attachments') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' files = [] begin parts = [ ['task_id', '12345'], ['file', (files << File.open('attachment.pdf', 'rb')).last, {filename: 'attachment.pdf', content_type: 'application/octet-stream'}], ] request.set_form(parts, 'multipart/form-data') response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' puts response.body ensure files.each(&:close) end ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" "bytes" "mime/multipart" "net/textproto" ) func main() { var form bytes.Buffer writer := multipart.NewWriter(&form) if err := writer.WriteField("task_id", "12345"); err != nil { log.Fatal(err) } header0 := textproto.MIMEHeader{} header0.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"attachment.pdf\"") header0.Set("Content-Type", "application/octet-stream") part0, err := writer.CreatePart(header0) if err != nil { log.Fatal(err) } file0, err := os.Open("attachment.pdf") if err != nil { log.Fatal(err) } if _, err = io.Copy(part0, file0); err != nil { log.Fatal(err) } file0.Close() if err := writer.Close(); err != nil { log.Fatal(err) } request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/tasks/attachments", &form) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", writer.FormDataContentType()) response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } fmt.Printf("%s\n", data) } ``` Example HTTP response body (JSON): POST /v1/tasks/attachments - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "attachment", "list_data": [ { "id": 12345, "filename": "attachment.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } ] } ``` ### Remove a Task General File Attachment `DELETE https://api.exhibitday.com/v1/tasks/attachments` Documentation: https://api.exhibitday.com/Help/V1?epf=2#delete-v1-tasks-attachments Removes one General File Attachment from this Task. Other attached files and the record's details stay in place. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the File Attachment. | Use the id from the attachment list. The API finds the record the file belongs to, so no record ID is sent. An Invoice Attachment is not selected by this method. | #### After the removal Only the selected file association is removed. Its physical file is scheduled for cleanup after a confirmed save; cleanup may finish later. Other attached files stay in place. Send only the file's id; the API finds the record it belongs to. A missing, already removed or unavailable attachment returns HTTP 404 Not Found. Do not send file parts with DELETE. #### Task Board access The Task may belong to an Event or be a General Task. These files follow the main Task Board's current permissions. Hiding or shallow-locking the Event's Tasks navigation tab alone does not block the Task Board. A Deep Lock prevents file changes. Current Task management permission is required. Permitted removals remain available on the Free plan. File changes update the Task's last-update time while preserving assignment, completion, reminders, notifications, section and order. #### History and retries A confirmed file change is recorded in history. expected_revision is not supported by these file methods. DELETE does not use Idempotency-Key replay. If the save outcome cannot be confirmed, retrieve the current file list before deciding whether to retry; the API does not automatically repeat an uncertain change. Task attachments have no PATCH replacement or Invoice Attachment method. To replace a supporting file, add the new file and remove the old one using their separate requests. #### Hidden or locked tab If the Task's Event has its Tasks tab locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Unlock the tab in ExhibitDay first. Hiding the Tasks tab does not block Task files. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/tasks/attachments?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/tasks/attachments?" + new URLSearchParams({ "id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/tasks/attachments", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/tasks/attachments?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/tasks/attachments?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/tasks/attachments?id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/tasks/attachments?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/tasks/attachments - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Attachment removed.", "errors": [] } ``` ### Download a Task General File Attachment `GET https://api.exhibitday.com/v1/tasks/attachments/download` Documentation: https://api.exhibitday.com/Help/V1?epf=2#get-v1-tasks-attachments-download Downloads one original General File Attachment from this Task. Select the file using its ID from the attachment list. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the File Attachment. | Use the id from the attachment list. The API finds the record the file belongs to, so no record ID is sent. An Invoice Attachment is not selected by this method. | #### Download response A successful response contains the original uploaded file with a safe download filename. API errors use the usual JSON response. A missing or unavailable file returns HTTP 404. Send only the file's id from the attachment list to download that one file; the API finds the record it belongs to. The download leaves the record unchanged. #### Task Board access The Task may belong to an Event or be a General Task. These files follow the main Task Board's current permissions. Hiding or shallow-locking the Event's Tasks navigation tab alone does not block the Task Board. Current Task read access is required. This method does not grant access to another Task or change its assignment or completion. #### Files still being copied If this file is still being copied, the download returns HTTP 409 with file_copy_pending. Try the download again in a few minutes. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X GET "https://api.exhibitday.com/v1/tasks/attachments/download?id=12345" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi mv response-body.tmp 'attachment.txt' ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const response = await fetch("https://api.exhibitday.com/v1/tasks/attachments/download?id=12345", { method: "GET", headers: { Authorization: 'Bearer YOUR_API_KEY' } }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); await writeFile("attachment.txt", new Uint8Array(await response.arrayBuffer())); ``` Example — Python: ```python import requests import json response = requests.request("GET", "https://api.exhibitday.com/v1/tasks/attachments/download?id=12345", headers={'Authorization': 'Bearer YOUR_API_KEY'}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') with open("attachment.txt", 'wb') as destination: destination.write(response.content) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.exhibitday.com/v1/tasks/attachments/download?id=12345"); using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); await File.WriteAllBytesAsync("attachment.txt", await response.Content.ReadAsByteArrayAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/tasks/attachments/download?id=12345")).header("Authorization", "Bearer YOUR_API_KEY"); HttpResponse response = HttpClient.newHttpClient().send(request.method("GET", HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); Files.write(Path.of("attachment.txt"), response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); file_put_contents('attachment.txt', $response); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/tasks/attachments/download?id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' File.binwrite('attachment.txt', response.body) ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/tasks/attachments/download?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } if err := os.WriteFile("attachment.txt", data, 0600); err != nil { log.Fatal(err) } fmt.Println("File saved") } ``` HTTP 200: Returns the original task attachment as a private download, using a safe filename. If it cannot be downloaded, the response contains the usual JSON API error instead. Media: application/octet-stream. The body is the authorized file's real bytes, not JSON or base64. Errors are JSON status responses; check HTTP status before saving the file. ## Tasks - Comments Comments on a Task: read, add, update and delete them. Documentation page: https://api.exhibitday.com/Help/V1?epf=2&topic=comments ### Retrieve a Single Task Comment by ID `GET https://api.exhibitday.com/v1/tasks/comments/info` Documentation: https://api.exhibitday.com/Help/V1?epf=2&topic=comments#get-v1-tasks-comments-info Retrieves information about a specific task comment (using the "id" parameter). Older path, still accepted: /v1/tasks/comment. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | Id of the specific task comment that you would like to retrieve. | | | $include_record_revision | Boolean | No | Set to true to include record_revision in the response. Send that value as expected_revision when updating to check for conflicting changes. | Default: false. | Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/tasks/comments/info?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/tasks/comments/info?" + new URLSearchParams({ "id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/tasks/comments/info", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/tasks/comments/info?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/tasks/comments/info?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/tasks/comments/info?id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/tasks/comments/info?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/tasks/comments/info - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "id": 12345, "comment": "Sample comment", "comment_created_timestamp": "2026-11-21T17:00:00Z", "comment_last_update_timestamp": "2026-11-21T17:00:00Z", "commenter": { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, "event_id": null, "task_id": 12345, "task": { "id": 12345, "exhibitday_url": "https://www.exhibitday.com/Workspace/TaskView/98765?tid=12345", "event_task_section_id": null, "event_task_section": "Uncategorized", "display_rank": 0, "name": "Sample task", "due_date": null, "assignee": null, "is_completed": false, "task_completed_timestamp": null, "task_created_timestamp": "2026-11-21T17:00:00Z", "task_last_update_timestamp": "2026-11-21T17:00:00Z" } } ``` ### Retrieve Task Comments `GET https://api.exhibitday.com/v1/tasks/comments` Documentation: https://api.exhibitday.com/Help/V1?epf=2&topic=comments#get-v1-tasks-comments Find Task comments in your workspace. Comments must match every filter you supply. Use `filter_by_event_id` for comments on Tasks from one Event, or `filter_by_task_id` for comments on one Task. Each filter accepts one value. Omit all filters to retrieve comments across your workspace. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | filter_by_event_id | Number | No | Only include task comments for tasks from this given event. | | | filter_by_task_id | Number | No | Only include task comments for this specific task. | | | hydrate_task | Boolean | No | Set to `true` to include the Task object with each comment. This increases response size and can slow the request. | Default: false. | | filter_by_commenter_user_id | String | No | Only include the comments made by this user. Use the user's id from /v1/references/users_and_resources. | | | $result_sort | String | No | Sorts comments by when they were created or last updated. Omit, or use an unrecognized value, to group comments by Task in the Retrieve Tasks order, oldest first within each Task. | Allowed values: `create_timestamp_asc` (oldest created first) \| `create_timestamp_desc` (newest created first) \| `last_update_timestamp_asc` (least recently updated first) \| `last_update_timestamp_desc` (most recently updated first) | | filter_by_last_update_timestamp_greater_than_or_equal_to | String | No | Only include task comments that were added or changed on or after this date and time, for example 2026-10-14T18:30:00 (a date alone, such as 2026-10-14, means midnight). Responses give comment_last_update_timestamp in UTC (it ends in Z), and that value can be passed back unchanged; a value without an offset is read as US Eastern time, and any other offset (e.g., 2026-10-14T18:30:00-04:00) is converted. To sync changes, process and save every page before advancing the cursor. Save the latest comment_last_update_timestamp you receive and pass it in next time (task comments changed at exactly that time come back again, upsert every returned record by id, including boundary records). Deleted task comments are not returned. Any other value is rejected with an error. | | | $limit | Number | No | The most task comments to return (a whole number of 1 or more). Use it with $offset to read a long list in pages: total_records in the response counts every matching task comment and has_more is true while more pages follow (the X-Total-Count header carries the total too). Without $limit, every matching task comment is returned. | | | $offset | Number | No | How many task comments to skip before the first one returned (a whole number; 0 by default). For the next page, add the number of task comments you received to $offset. | | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/tasks/comments" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/tasks/comments", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/tasks/comments", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/tasks/comments"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/tasks/comments")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/tasks/comments') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/tasks/comments", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/tasks/comments - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "task_comment", "list_data": [ { "id": 12345, "comment": "Sample comment", "comment_created_timestamp": "2026-11-21T17:00:00Z", "comment_last_update_timestamp": "2026-11-21T17:00:00Z", "commenter": { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, "event_id": null, "task_id": 12345, "task": { "id": 12345, "exhibitday_url": "https://www.exhibitday.com/Workspace/TaskView/98765?tid=12345", "event_task_section_id": null, "event_task_section": "Uncategorized", "display_rank": 0, "name": "Sample task", "due_date": null, "assignee": null, "is_completed": false, "task_completed_timestamp": null, "task_created_timestamp": "2026-11-21T17:00:00Z", "task_last_update_timestamp": "2026-11-21T17:00:00Z" } } ] } ``` ### Add a Comment to a Task `POST https://api.exhibitday.com/v1/tasks/comments` Documentation: https://api.exhibitday.com/Help/V1?epf=2&topic=comments#post-v1-tasks-comments The response will contain an object representing the newly added task comment. Older path, still accepted: /v1/tasks/comment. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | task_id | Number | Yes | The id of the task you would like to add the comment to. | | | comment | String | Yes | The text of the comment you would like to add. Only accepts plain text. Any HTML tags will be stripped. Newline characters are displayed as line breaks in ExhibitDay and remain newline characters in API responses. Accepts up to 15,000 characters (some symbols count as two characters). | | Example — curl: ```bash curl -X POST "https://api.exhibitday.com/v1/tasks/comments" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"task_id\":12345,\"comment\":\"Sample comment\"}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/tasks/comments", { method: "POST", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "task_id": 12345, "comment": "Sample comment" }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.post( "https://api.exhibitday.com/v1/tasks/comments", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"task_id": 12345, "comment": "Sample comment"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PostAsync("https://api.exhibitday.com/v1/tasks/comments", JsonContent.Create(new { task_id = 12345, comment = "Sample comment" })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/tasks/comments")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("POST", HttpRequest.BodyPublishers.ofString("{\"task_id\":12345,\"comment\":\"Sample comment\"}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"task_id":12345,"comment":"Sample comment"}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/tasks/comments') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"task_id":12345,"comment":"Sample comment"}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/tasks/comments", strings.NewReader("{\"task_id\":12345,\"comment\":\"Sample comment\"}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): POST /v1/tasks/comments - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "id": 23456, "comment": "Sample comment", "comment_created_timestamp": "2026-11-21T17:00:00Z", "comment_last_update_timestamp": "2026-11-21T17:00:00Z", "commenter": { "id": null, "first_name": "ExhibitDay", "last_name": "API", "display_name": "ExhibitDay API", "email": null, "type": null, "workspace_role": null, "is_active": true }, "event_id": null, "task_id": 12345, "task": { "id": 12345, "exhibitday_url": "https://www.exhibitday.com/Workspace/TaskView/98765?tid=12345", "event_task_section_id": null, "event_task_section": "Uncategorized", "display_rank": 0, "name": "Sample task", "due_date": null, "assignee": null, "is_completed": false, "task_completed_timestamp": null, "task_created_timestamp": "2026-11-21T17:00:00Z", "task_last_update_timestamp": "2026-11-21T17:00:00Z" } } ``` ### Update a Task Comment `PATCH https://api.exhibitday.com/v1/tasks/comments` Documentation: https://api.exhibitday.com/Help/V1?epf=2&topic=comments#patch-v1-tasks-comments Updates the text of a given comment on a task. A comment cannot be moved to another task. If the text you send is the comment's current text, nothing is saved: the comment, its last update time and its history stay unchanged. Older path, still accepted: /v1/tasks/comment. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The Id of the task comment you would like to update. | | | comment | String | Yes | The text that will replace the existing comment, including any formatting previously applied in ExhibitDay. Only accepts plain text. Any HTML tags will be stripped. Newline characters are displayed as line breaks in ExhibitDay and remain newline characters in API responses. Accepts up to 15,000 characters (some symbols count as two characters). A comment cannot be blank: an empty value (or null) is rejected with an error. | | | expected_revision | String | No | The record_revision returned when you retrieved this record. Include it to avoid overwriting someone else's changes. Omit it to skip this check. | | Example — curl: ```bash curl -X PATCH "https://api.exhibitday.com/v1/tasks/comments" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"id\":12345,\"comment\":\"Updated comment\"}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/tasks/comments", { method: "PATCH", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "id": 12345, "comment": "Updated comment" }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.patch( "https://api.exhibitday.com/v1/tasks/comments", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"id": 12345, "comment": "Updated comment"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PatchAsync("https://api.exhibitday.com/v1/tasks/comments", JsonContent.Create(new { id = 12345, comment = "Updated comment" })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/tasks/comments")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("PATCH", HttpRequest.BodyPublishers.ofString("{\"id\":12345,\"comment\":\"Updated comment\"}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"id":12345,"comment":"Updated comment"}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/tasks/comments') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"id":12345,"comment":"Updated comment"}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/tasks/comments", strings.NewReader("{\"id\":12345,\"comment\":\"Updated comment\"}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): PATCH /v1/tasks/comments - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Task Comment Update Successful. Task comment updated via API.", "errors": [] } ``` ### Delete a Task Comment `DELETE https://api.exhibitday.com/v1/tasks/comments` Documentation: https://api.exhibitday.com/Help/V1?epf=2&topic=comments#delete-v1-tasks-comments Permanently deletes a task comment. It cannot be undone. Older path, still accepted: /v1/tasks/comment. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The Id of the task comment you would like to delete. | | Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/tasks/comments?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/tasks/comments?" + new URLSearchParams({ "id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/tasks/comments", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/tasks/comments?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/tasks/comments?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/tasks/comments?id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/tasks/comments?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/tasks/comments - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Task Comment Deleted", "errors": [] } ``` ## Tasks - Logs The activity history of one Task. Documentation page: https://api.exhibitday.com/Help/V1?epf=2&topic=logs ### Retrieve a Task's Logs `GET https://api.exhibitday.com/v1/tasks/history` Documentation: https://api.exhibitday.com/Help/V1?epf=2&topic=logs#get-v1-tasks-history Retrieves activity history recorded for a Task, including entries recorded while it belonged to an earlier Event. A Task with no matching history returns an empty list. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | task_id | Number | Yes | The ID of the Task whose history you want to retrieve. Use an ID from GET /v1/tasks. | | | $limit | Number | No | The most entries to return (a whole number of 1 or more). Leave it out to return all remaining matching entries. | | | $offset | Number | No | How many matching entries to skip (a whole number of 0 or more; 0 by default). Use this with $limit to read the next page. | | | $result_sort | String | No | Sort entries newest first (the default) or oldest first. The full saved timestamp is used, with the entry ID breaking ties in the same direction. Responses display whole seconds. Unsupported values are refused. Use the values exactly as shown (lowercase). | Allowed values: `create_timestamp_desc` (newest first) \| `create_timestamp_asc` (oldest first) | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | | filter_by_actor_user_id | String | No | Only include entries written by the user with this id. Treat the id as text. Older entries can match a former user without exposing their account information. | | | filter_by_log_entry_contains_text | String | No | Only include entries containing this text, up to 3,000 characters. The characters are matched as sent; they are not converted from HTML or treated as wildcards. | | | filter_by_create_timestamp_greater_than_or_equal_to | String | No | Include entries created at or after this timestamp. Filters use the whole seconds shown in responses, so a fractional lower bound starts at the next whole second. | | | filter_by_create_timestamp_smaller_than_or_equal_to | String | No | Include entries created at or before this timestamp, including every entry in its displayed second. It can't be earlier than the lower bound. | | | filter_by_event_id | Number | No | Only include entries recorded under this Event ID. Useful when the Task has moved between Events. | | | filter_by_event_tab_id | Number | No | Only include entries filed under this Event tab ID. GET /v1/references/event_tabs lists your workspace's tabs; the Presentations tab is accepted only where your workspace has it. | Allowed values: `1` (Info) \| `2` (Booth) \| `3` (Staff) \| `4` (Travel) \| `5` (Assets) \| `6` (Shipments) \| `7` (Sponsorships) \| `8` (Tasks) \| `9` (Playbook) \| `10` (Attachments) \| `11` (Misc. Expenses & Credits) \| `12` (Budget) \| `13` (ROI) \| `14` (Event Settings) \| `16` (Binder) \| `17` (Copy Event) \| `19` (Logs) \| `20` (Delete Event) \| `21` (Giveaways) \| `22` (Special Tab, shown under your workspace's name for it) | #### What the history includes Includes user-visible business history, including changes that do not appear in the Activity Feed. Internal diagnostics, impersonation activity, IP addresses, device details and security information are not included. Each request reads the current history. Use these results to review activity; they are not a complete feed of record changes or deletions. #### Filtering entries When you supply several filters, an entry must match all of them. The total count and the returned page use those same filters. Text searches match the characters you enter literally, without wildcard matching. #### Reading dates and times Returned timestamps are in UTC and show whole seconds. Sorting uses the full saved timestamp, then the entry ID to break ties; entries showing the same second can still have a distinct order. Timestamp filters use the displayed whole-second precision. An upper bound includes all entries in that displayed second. A fractional lower bound starts at the next whole second. A filter value with a time-zone offset is converted to US Eastern time for comparison. A value without an offset is interpreted as US Eastern time. #### Reading the actor `actor_user_id` is the ID of the user who made the change. `actor_display_name` is the name saved with the entry at that time; it does not change if the user is renamed later. Entries recorded by the API have a null `actor_user_id` and show the label saved with them, such as `API`. #### Task history A Task keeps its history when it moves to another Event. Entries recorded before the move still show the earlier Event's ID and name. A deleted Task, or a Task in another workspace, returns HTTP 404. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/tasks/history?task_id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/tasks/history?" + new URLSearchParams({ "task_id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/tasks/history", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"task_id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/tasks/history?task_id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/tasks/history?task_id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/tasks/history?task_id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/tasks/history?task_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/tasks/history - HTTP 200 Illustrative response. Assume the selected Task exists in your workspace and has one visible history entry. IDs, names and entry text are illustrative. Request inputs: {"task_id":12345}. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "workspace_log", "list_data": [ { "id": 67890, "log_entry_created_timestamp": "2026-01-02T08:04:05Z", "actor_user_id": "11111111-2222-4333-8444-555555555555", "actor_display_name": "Illustrative coordinator", "log_entry": "Illustrative coordinator linked 1 related item(s) to task 'Prepare the display'.", "event_id": 23456, "event_name": "Illustrative owned Event", "event_tab_id": 8, "task_id": 12345, "task_name": "Prepare the display", "asset_id": null, "asset_name": null, "storage_location_id": null, "storage_location_name": null } ] } ``` ## Assets Create, read, update, archive and restore Assets, with their custom file attachments. Documentation page: https://api.exhibitday.com/Help/V1?epf=5 ### Retrieve a Single Asset by ID `GET https://api.exhibitday.com/v1/assets/info` Documentation: https://api.exhibitday.com/Help/V1?epf=5#get-v1-assets-info Retrieves one Asset’s details, including tags, custom fields, Optional Accessories, images, current status and storage quantities. Reservations are left out unless you request them. Capital Assets are individual reusable items; Collateral is tracked in quantities. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Asset to retrieve. | Use `id` for this method. Use `filter_by_asset_id` on `GET /v1/assets`. | | hydrate_reservations | Boolean | No | Whether to include the reservations you can read. | Default: false. True includes the full readable reservation list, without granting extra access. | | $include_record_revision | Boolean | No | Whether to include record_revision for a later change. | Default: false. A revision can be used when updating, archiving or restoring this Asset. | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` | | $on_error_return_empty_result | Boolean | No | Whether to return an empty result for validation or not-found errors. | Default: false. True returns {} or [] with HTTP 200. Authentication, rate limits and unexpected failures keep their normal errors. | | $include_error_list_in_response_message | Boolean | No | Whether to add validation errors to the error message. | Default: false. | | If-None-Match | String | No | An ETag from an earlier response to this GET. | Optional HTTP header. If the successful response still matches, the API returns HTTP 304 with no response body. | #### Current inventory status current_status describes Available / In Storage, a checked-out Event or Other Purpose reservation, multiple active reservations, Archived, or Collateral quantities. Archived Collateral keeps its actual Quantity Available in Storage and Projected Future Balance, including zero and negative balances. Dates in current_status and returns_to_storage use the full English month, day and year, such as May 4, 2026. returns_to_storage also says when a current Capital reservation ends; it is empty when no current return is reported. When a shared Asset is checked out for another workspace's Event, current_status names that Event, as in the Assets area. With hydrate_reservations=true, each reservation also shows the Event name and the reservation notes. Because the Event belongs to another workspace, event_id is null and Event methods can't open it with this key. Your own Events keep their IDs. A borrowing workspace reads its own reservation through GET /v1/assets/reservations; sharing does not open the owner's full Asset details. #### Retrieving the Asset 1. Supply the Asset’s id. 2. Set hydrate_reservations=true only if you also need its readable reservations. 3. If you plan to change the Asset, set $include_record_revision=true and keep the returned record_revision for that later request. #### Access and returned details Sharing an Asset or using it in an old reservation does not grant access to the other workspace’s full Asset details. This method retrieves Assets in your workspace, including Archived Assets. Custom dates stay calendar dates. Custom times retain their recorded wall-clock time and time-zone label. An unreadable saved custom value is marked value_state=invalid rather than shown as an empty valid date. File metadata does not grant extra download permission or provide a permanent public URL. #### What $include_record_revision covers Set `$include_record_revision=true` to receive `record_revision` in this GET response. It covers editable Asset fields, tags, custom values and sharing settings. It excludes availability, reservations, Optional Accessories, images and file contents. Use it as expected_revision with a later update, archive or restore. A stale revision returns HTTP 409 with error_code=record_changed; retrieve the current Asset and review it before trying again. A record that keeps changing while it is read can also return this error. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/assets/info?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/info?" + new URLSearchParams({ "id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/assets/info", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/assets/info?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/info?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/info?id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/assets/info?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/assets/info - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "workspace_id": 98765, "id": 12345, "asset_reservation_policy_id": 1, "exhibitday_url": "https://www.exhibitday.com/Workspace/Asset/98765?aid=12345", "internal_identifier": "", "asset_type_id": 1, "make_or_model": "", "asset_status_id": 1, "asset_status": "Active", "description": "", "name": "Display stand", "default_storage_location_id": 2345, "current_status": "Available / In Storage", "storage_location_name": "Main Warehouse", "returns_to_storage": "", "storage_location_address_display_name": "Boston, MA", "storage_area": "", "pull_notes": "", "status_message": null, "in_progress_reservation_count": 0, "quantity_available_in_storage": 1, "status_message_expires": null, "projected_future_balance": 1, "cost": { "amount": 0.00 }, "current_storage_footprint": 0.00, "dimensions_length": null, "projected_future_footprint": 0.00, "dimensions_width": null, "dimensions_unit": "in", "dimensions_height": null, "volume_unit": "cu ft", "dimensions_notes": "", "has_complete_dimensions": false, "dimensions_packaged_length": null, "dimensions_packaged_width": null, "dimensions_packaged_height": null, "dimensions_packaged_notes": "", "weight": null, "weight_notes": "", "weight_packaged": null, "weight_packaged_notes": "", "integration_metadata_field_1": null, "integration_metadata_field_2": null, "integration_metadata_field_3": null, "integration_metadata_field_4": null, "integration_metadata_field_5": null, "asset_created_timestamp": "2030-01-02T17:00:00Z", "weight_unit": "lb", "tags": [ "Trade shows", "East coast" ], "optional_accessories": [ { "id": 13001, "optional_accessory_status_id": 1, "optional_accessory_status": "Active", "name": "Transport case", "description": "Protective case for the display stand.", "max_quantity": 1, "default_quantity": 1, "optional_accessory_created_timestamp": "2030-01-02T17:00:00Z" }, { "id": 13002, "optional_accessory_status_id": 1, "optional_accessory_status": "Active", "name": "Spotlight", "description": "Clip-on display lighting.", "max_quantity": 2, "default_quantity": 1, "optional_accessory_created_timestamp": "2030-01-02T17:00:00Z" } ], "custom_fields": [ { "id": 12001, "field_type_id": 1000000, "name": "Responsible team", "is_multi_line": false, "value": "Event operations", "value_state": "set", "file": null, "date_time": null, "url": null }, { "id": 12002, "field_type_id": 5000000, "name": "Setup guide", "is_multi_line": false, "value": null, "value_state": "set", "file": null, "date_time": null, "url": { "url": "https://example.com/setup-guide", "display_name": "Setup guide" } } ], "images": [ { "display_rank": 1, "image_filename": "11111111-1111-4111-8111-111111111111.jpg", "image_last_update_timestamp": "2030-01-02T17:00:00Z" }, { "display_rank": 2, "image_filename": "22222222-2222-4222-8222-222222222222.jpg", "image_last_update_timestamp": "2030-01-02T17:00:00Z" } ], "reservations": null } ``` ### Retrieve Assets `GET https://api.exhibitday.com/v1/assets` Documentation: https://api.exhibitday.com/Help/V1?epf=5#get-v1-assets Retrieves Assets in your workspace. By default, the API returns both Active and Archived Assets, sorted by name, with full Asset details. An Asset must match every filter you send to appear in the results. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | filter_by_asset_id | Number | No | The ID of the Asset you want to retrieve. The result is still a list. For a single Asset object, use `GET /v1/assets/info` with `id`. | | | filter_by_asset_type_id | Number | With any reservation date filter | Include Assets of the selected type. Capital tracks individual items, such as display stands. Collateral tracks quantities, such as brochures. Omit to include both types. | Allowed values: `1` (Capital) \| `2` (Collateral) | | filter_by_asset_status_id | Number | No | Include Assets with the selected status. Omit to include both Active and Archived Assets. | Allowed values: `1` (Active) \| `2` (Archived) | | filter_by_asset_name_contains_text | String | No | Text to find anywhere in the Asset name. `%`, `_` and square brackets are treated as literal characters. | Maximum: 300 characters. | | filter_by_asset_tag | String | No | The Asset tag to match. Matching follows the same case and accent rules as Asset search in ExhibitDay. | Maximum: 150 characters. | | filter_by_default_storage_location_id | Number | No | Include Capital Assets whose saved default Storage Location is this ID. Collateral/Multi-quantity items don't have a default Storage Location, so they are never included when you use this filter. To check stock or availability at a location, use `GET /v1/assets/availability`. | | | filter_by_integration_metadata_field_1 | String | No | The value to match in integration metadata field 1. | Maximum: 3,000 characters. | | filter_by_integration_metadata_field_2 | String | No | The value to match in integration metadata field 2. | Maximum: 3,000 characters. | | filter_by_integration_metadata_field_3 | String | No | The value to match in integration metadata field 3. | Maximum: 3,000 characters. | | filter_by_integration_metadata_field_4 | String | No | The value to match in integration metadata field 4. | Maximum: 3,000 characters. | | filter_by_integration_metadata_field_5 | String | No | The value to match in integration metadata field 5. | Maximum: 3,000 characters. | | filter_by_custom_field_value_setting_id | Number | With a custom field value | The ID of a visible Asset text or dropdown custom field in your workspace. | | | filter_by_custom_field_value_setting_value | String | With a custom field ID | The value to match in the selected field. An empty string matches Assets whose saved value is empty or missing. | | | filter_by_reservation_date_greater_than_or_equal_to | Date | No | The earliest checkout date for Capital Assets or the earliest Reservation Date for Collateral. | YYYY-MM-DD. | | filter_by_reservation_date_smaller_than_or_equal_to | Date | No | The latest checkout date for Capital Assets or the latest Reservation Date for Collateral. | YYYY-MM-DD. | | filter_by_reservation_return_date_greater_than_or_equal_to | Date | No | The earliest reservation return date. Capital Assets only. | YYYY-MM-DD. | | filter_by_reservation_return_date_smaller_than_or_equal_to | Date | No | The latest reservation return date. Capital Assets only. | YYYY-MM-DD. | | filter_by_reservation_overlaps_start_date | Date | When filtering by overlap | The first day of the period you want to check. Send both overlap dates. Capital Assets only. | YYYY-MM-DD. | | filter_by_reservation_overlaps_end_date | Date | When filtering by overlap | The last day of the period you want to check. Send both overlap dates. Capital Assets only. | YYYY-MM-DD. | | $result_sort | String | No | Order Assets by name, creation time or ID. Omit for name ascending. Name and creation-time ties use the lower Asset ID first. Unsupported values are refused. | Allowed values: `name_asc` \| `name_desc` \| `create_timestamp_asc` \| `create_timestamp_desc` \| `id_asc` \| `id_desc` | | $limit | Number | No | The maximum number of Assets to return. Omit to return all remaining matches. | A whole number of 1 or more. | | $offset | Number | No | How many matching Assets to skip. For the next page, add the number of Assets you received to the current offset. | A whole number of 0 or more. Default `0`. | | hydrate_reservations | Boolean | No | Set to `true` to include all reservations you can access for each full Asset result. | Default: false. Applies to full results only. | | $return_asset_lites | Boolean | No | Set to `true` for a shorter result with Asset identification, current status, quantities and storage summaries. | Default: false. | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | | $on_error_return_empty_result | Boolean | No | Set to `true` to receive an empty result for supported validation or not-found errors. Authentication errors, rate limits, read conflicts and unexpected server errors still return an error response. | Default: false. | | $include_error_list_in_response_message | Boolean | No | Set to `true` to include individual validation errors in the error message. | Default: false. | #### Current inventory status current_status describes Available / In Storage, a checked-out Event or Other Purpose reservation, multiple active reservations, Archived, or Collateral quantities. Archived Collateral keeps its actual Quantity Available in Storage and Projected Future Balance, including zero and negative balances. Dates in current_status and returns_to_storage use the full English month, day and year, such as May 4, 2026. returns_to_storage also says when a current Capital reservation ends; it is empty when no current return is reported. When a shared Asset is checked out for another workspace's Event, current_status names that Event, as in the Assets area. With hydrate_reservations=true, each reservation also shows the Event name and the reservation notes. Because the Event belongs to another workspace, event_id is null and Event methods can't open it with this key. Your own Events keep their IDs. A borrowing workspace reads its own reservation through GET /v1/assets/reservations; sharing does not open the owner's full Asset details. #### Filtering by metadata or a custom field For integration metadata, omit a parameter to skip that filter. Sending an empty string applies the filter and looks for an empty value. For a custom field, send both its ID and the value to match. For dropdown fields, the API uses the saved selection. If an Asset has no saved selection, the configured default choice does not count as a match. Hidden fields, other field types and fields from another workspace cannot be used for this filter. #### Filtering by reservation dates Use `YYYY-MM-DD` for all dates. For Capital Assets, checkout-date filters find reservations that start during a period; the two overlap filters find reservations that cover any part of the period, including those that started earlier. All date filters you combine must match the same reservation. A reservation with no return date does not match return-date or overlap filters. There is no separate filter for an unknown return date. For Collateral, use the Reservation Date filters. Return-date and overlap filters are rejected. Manual inventory adjustments are separate from Event reservations. Reservation filters determine which Assets appear. With `hydrate_reservations=true`, each matching Asset includes all reservations you can access for it, including reservations outside the filter’s date range. #### Paging through results There is no default page size or fixed maximum number of results. To retrieve 50 Assets at a time, start with `$limit=50&$offset=0`, then use `$limit=50&$offset=50` for the next page. Keep the same filters and sort order between requests. Results and counts can change if another request edits Assets between pages. In the standard response, `records_found` counts Assets returned on this page, `total_records` counts all Assets matching your filters before paging, and `has_more` tells you whether more matches remain after this page. `list_data` contains the Assets. With `$result_format=array`, only that list is returned. #### Choosing how much detail to return Full Asset results include custom field values, Optional Accessories, image details, current status and storage quantities. Use `$return_asset_lites=true` when you only need identification and inventory details. Short results omit longer text, custom fields, Optional Accessories, files and reservations; setting `hydrate_reservations=true` does not add reservations to a short result. To obtain a revision for a later update, retrieve the individual Asset with `GET /v1/assets/info` and set `$include_record_revision=true`. This list response does not include `record_revision`. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/assets" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/assets", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/assets"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/assets", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/assets - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "asset", "list_data": [ { "workspace_id": 98765, "id": 12345, "asset_reservation_policy_id": 1, "exhibitday_url": "https://www.exhibitday.com/Workspace/Asset/98765?aid=12345", "internal_identifier": "", "asset_type_id": 1, "make_or_model": "", "asset_status_id": 1, "asset_status": "Active", "description": "", "name": "Display stand", "default_storage_location_id": 2345, "current_status": "Available / In Storage", "storage_location_name": "Main Warehouse", "returns_to_storage": "", "storage_location_address_display_name": "Boston, MA", "storage_area": "", "pull_notes": "", "status_message": null, "in_progress_reservation_count": 0, "quantity_available_in_storage": 1, "status_message_expires": null, "projected_future_balance": 1, "cost": { "amount": 0.00 }, "current_storage_footprint": 0.00, "dimensions_length": null, "projected_future_footprint": 0.00, "dimensions_width": null, "dimensions_unit": "in", "dimensions_height": null, "volume_unit": "cu ft", "dimensions_notes": "", "has_complete_dimensions": false, "dimensions_packaged_length": null, "dimensions_packaged_width": null, "dimensions_packaged_height": null, "dimensions_packaged_notes": "", "weight": null, "weight_notes": "", "weight_packaged": null, "weight_packaged_notes": "", "integration_metadata_field_1": null, "integration_metadata_field_2": null, "integration_metadata_field_3": null, "integration_metadata_field_4": null, "integration_metadata_field_5": null, "asset_created_timestamp": "2030-01-02T17:00:00Z", "weight_unit": "lb", "tags": [], "optional_accessories": [], "custom_fields": [], "images": [], "reservations": null } ] } ``` ### Add an Asset `POST https://api.exhibitday.com/v1/assets` Documentation: https://api.exhibitday.com/Help/V1?epf=5#post-v1-assets Creates an Active Capital Asset or Collateral item. Capital Assets are individual reusable items, such as display stands; Collateral is tracked in quantities, such as brochures. Capital needs a default Storage Location; Collateral inventory is added separately. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | asset_type_id | Number | Yes | The type of Asset to create. Capital tracks one item; Collateral tracks quantities. The new Asset is Active, and its type cannot be changed later. | Allowed values: `1` (Capital) \| `2` (Collateral) | | name | String | No | The Asset name. | Up to 300 characters after text cleanup. Omitted, blank or null uses the name Asset. | | default_storage_location_id | Number | When asset_type_id=1 | The default Storage Location for a Capital Asset. | Use a Storage Location in your workspace. This changes the default setting, not inventory, and cannot be cleared. Collateral/Multi-quantity items don't have a default Storage Location; a value sent for one is ignored with a warning. | | asset_reservation_policy_id | Number | No | For Capital, Strict blocks every day of an existing reservation, including checkout and return; Moderate allows those first and last days; Liberal allows overlaps. Omit to use your workspace default for Capital. Collateral always uses Liberal; any other value is refused. | Allowed values: `1` (Strict) \| `2` (Moderate) \| `3` (Liberal) | | internal_identifier | String | No | Your internal identifier for the Asset. | Text, up to 100 characters. | | make_or_model | String | No | The Asset’s type, make or model. | Text, up to 500 characters. | | description | String | No | The Asset description as plain text. | Line breaks are retained. Both the saved value and the editor’s count must fit within 30,000 characters; encoded characters count toward these limits. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | storage_area | String | No | A more specific storage area, such as a shelf or bin. | Text, up to 500 characters. This does not move inventory. | | pull_notes | String | No | Plain-text instructions for preparing or pulling this Asset. | Line breaks are retained. Both the saved value and the editor’s count must fit within 30,000 characters. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | cost | Number or cost object | No | The Asset cost, as a number or an object containing amount. [Record Costs and Split Them Across Cost Centers](/Help/V1?guide=entering-costs). | No cost center breakdowns. Omit on PATCH to keep the cost; new Assets default to zero. | | dimensions_length | Number | No | The unpackaged length. | A nonnegative number up to 99999999999999999.99 in your workspace’s dimension unit, rounded to two decimal places. This does not change the unit setting. Omit for no measurement. | | dimensions_width | Number | No | The unpackaged width. | A nonnegative number up to 99999999999999999.99 in your workspace’s dimension unit, rounded to two decimal places. This does not change the unit setting. Omit for no measurement. | | dimensions_height | Number | No | The unpackaged height. | A nonnegative number up to 99999999999999999.99 in your workspace’s dimension unit, rounded to two decimal places. This does not change the unit setting. Omit for no measurement. | | dimensions_notes | String | No | Notes about the unpackaged dimensions. | Text, up to 150 characters. | | dimensions_packaged_length | Number | No | The packaged length. | A nonnegative number up to 99999999999999999.99 in your workspace’s dimension unit, rounded to two decimal places. This does not change the unit setting. Omit for no measurement. | | dimensions_packaged_width | Number | No | The packaged width. | A nonnegative number up to 99999999999999999.99 in your workspace’s dimension unit, rounded to two decimal places. This does not change the unit setting. Omit for no measurement. | | dimensions_packaged_height | Number | No | The packaged height. | A nonnegative number up to 99999999999999999.99 in your workspace’s dimension unit, rounded to two decimal places. This does not change the unit setting. Omit for no measurement. | | dimensions_packaged_notes | String | No | Notes about the packaged dimensions. | Text, up to 150 characters. | | weight | Number | No | The unpackaged weight. | A nonnegative number up to 99999999999999999.99 in your workspace’s weight unit, rounded to two decimal places. This does not change the unit setting. Omit for no measurement. | | weight_notes | String | No | Notes about the unpackaged weight. | Text, up to 150 characters. | | weight_packaged | Number | No | The packaged weight. | A nonnegative number up to 99999999999999999.99 in your workspace’s weight unit, rounded to two decimal places. This does not change the unit setting. Omit for no measurement. | | weight_packaged_notes | String | No | Notes about the packaged weight. | Text, up to 150 characters. | | integration_metadata_field_1 | String | No | A text value for your integration, such as an ID from another system. | Up to 3,000 characters. The value is not copied into history. | | integration_metadata_field_2 | String | No | A text value for your integration, such as an ID from another system. | Up to 3,000 characters. The value is not copied into history. | | integration_metadata_field_3 | String | No | A text value for your integration, such as an ID from another system. | Up to 3,000 characters. The value is not copied into history. | | integration_metadata_field_4 | String | No | A text value for your integration, such as an ID from another system. | Up to 3,000 characters. The value is not copied into history. | | integration_metadata_field_5 | String | No | A text value for your integration, such as an ID from another system. | Up to 3,000 characters. The value is not copied into history. | | tags | JSON object/list | No | The complete list of tags for this Asset. | Send an array of strings, such as ["Conference","Reusable"]. The same separator cleanup as the Asset page applies. A comma inside one entry of a JSON array splits it into separate tags, with a warning. Duplicate tags are combined without regard to case; each cleaned tag allows 30 characters. Omitted, blank, null or [] creates no tags. There is no fixed tag-count limit. asset_tags is an older name for this parameter and is still accepted; send one of them (if you send both, they must have the same value). | | custom_NNNNNN | Varies by field | No | A visible Asset custom field. | The value depends on the configured field: text, a dropdown choice, a URL object or a date/time object. Replace NNNNNN with the field `id` from `GET /v1/references/asset_custom_fields`. Its digit count can vary. File fields use the separate file-attachment methods. | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` | | Idempotency-Key | String | No | A unique key for safely repeating this create request. | Optional HTTP header: 1–255 visible ASCII characters, with no spaces. Reuse it only for the same request; the replay window is 24 hours. | Declared schema for `cost` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "anyOf": [ { "type": "number", "minimum": 0, "description": "Shorthand for an object with amount. The amount is rounded to cents before the supported storage range is checked.", "nullable": true }, { "type": "object", "additionalProperties": false, "properties": { "amount": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "required": [ "amount" ], "nullable": true }, { "type": "string", "description": "Existing Asset numeric text is supported: an invariant decimal, including grouping separators and an exponent. Blank/null retain the documented omission/clear rules.", "nullable": true } ], "x-numeric-shorthand": "A number is equivalent to {amount:number}.", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": { "amount": 125.50 } } ``` Declared schema for `tags` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "array", "items": { "type": "string" }, "maxItems": 2147483647, "nullable": true, "x-maximum-depth": 2, "x-empty-create-means-omitted": true, "example": [ "Conference", "Reusable" ] } ``` Dynamic Asset fields (the current locked field definition determines the applicable shape; native JSON uses the union, form values use text or JSON-encoded object text): ```json [ { "namePattern": "^custom_\\d+$", "description": "Use a positive Int64 definition ID suffix. Repeated copies for the same ID count once when they match. Different copies are refused.", "schema": { "nullable": true, "anyOf": [ { "type": "string", "description": "Text/rich text (1000000) or literal current dropdown option (3000000), selected by the current definition. Dropdown labels are not HTML-stripped." }, { "type": "object", "additionalProperties": false, "properties": { "url": { "type": "string", "nullable": true, "maxLength": 4000 }, "display_name": { "type": "string", "nullable": true, "maxLength": 2000 } }, "x-asset-field-type-id": 5000000 }, { "type": "object", "additionalProperties": false, "properties": { "start_date": { "type": "string", "nullable": true, "description": "YYYY-MM-DD calendar date, blank or null; no UTC conversion." }, "end_date": { "type": "string", "nullable": true, "pattern": "^\\s*$", "description": "Not applicable to this definition; omit or supply blank/null." }, "start_time": { "type": "string", "nullable": true, "pattern": "^\\s*$", "description": "Not applicable to this definition; omit or supply blank/null." }, "end_time": { "type": "string", "nullable": true, "pattern": "^\\s*$", "description": "Not applicable to this definition; omit or supply blank/null." }, "timezone": { "type": "string", "nullable": true, "pattern": "^\\s*$", "description": "Not applicable to this definition; omit or supply blank/null.", "maxLength": 20 }, "notes": { "type": "string", "nullable": true, "maxLength": 1000 } }, "x-asset-field-type-id": 4000000, "x-applicable-members": [ "start_date", "notes" ], "description": "Selected only by current owned visible definition type 4000000. Parts are independent and optional; partial/reversed ranges and overnight times follow the existing form." }, { "type": "object", "additionalProperties": false, "properties": { "start_date": { "type": "string", "nullable": true, "description": "YYYY-MM-DD calendar date, blank or null; no UTC conversion." }, "end_date": { "type": "string", "nullable": true, "description": "YYYY-MM-DD calendar date, blank or null; no UTC conversion." }, "start_time": { "type": "string", "nullable": true, "pattern": "^\\s*$", "description": "Not applicable to this definition; omit or supply blank/null." }, "end_time": { "type": "string", "nullable": true, "pattern": "^\\s*$", "description": "Not applicable to this definition; omit or supply blank/null." }, "timezone": { "type": "string", "nullable": true, "pattern": "^\\s*$", "description": "Not applicable to this definition; omit or supply blank/null.", "maxLength": 20 }, "notes": { "type": "string", "nullable": true, "maxLength": 1000 } }, "x-asset-field-type-id": 4100000, "x-applicable-members": [ "start_date", "end_date", "notes" ], "description": "Selected only by current owned visible definition type 4100000. Parts are independent and optional; partial/reversed ranges and overnight times follow the existing form." }, { "type": "object", "additionalProperties": false, "properties": { "start_date": { "type": "string", "nullable": true, "description": "YYYY-MM-DD calendar date, blank or null; no UTC conversion." }, "end_date": { "type": "string", "nullable": true, "pattern": "^\\s*$", "description": "Not applicable to this definition; omit or supply blank/null." }, "start_time": { "type": "string", "nullable": true, "description": "24-hour HH:mm local wall-clock time, blank or null; no UTC conversion." }, "end_time": { "type": "string", "nullable": true, "pattern": "^\\s*$", "description": "Not applicable to this definition; omit or supply blank/null." }, "timezone": { "type": "string", "nullable": true, "maxLength": 20 }, "notes": { "type": "string", "nullable": true, "maxLength": 1000 } }, "x-asset-field-type-id": 4200000, "x-applicable-members": [ "start_date", "start_time", "timezone", "notes" ], "description": "Selected only by current owned visible definition type 4200000. Parts are independent and optional; partial/reversed ranges and overnight times follow the existing form." }, { "type": "object", "additionalProperties": false, "properties": { "start_date": { "type": "string", "nullable": true, "pattern": "^\\s*$", "description": "Not applicable to this definition; omit or supply blank/null." }, "end_date": { "type": "string", "nullable": true, "pattern": "^\\s*$", "description": "Not applicable to this definition; omit or supply blank/null." }, "start_time": { "type": "string", "nullable": true, "description": "24-hour HH:mm local wall-clock time, blank or null; no UTC conversion." }, "end_time": { "type": "string", "nullable": true, "pattern": "^\\s*$", "description": "Not applicable to this definition; omit or supply blank/null." }, "timezone": { "type": "string", "nullable": true, "maxLength": 20 }, "notes": { "type": "string", "nullable": true, "maxLength": 1000 } }, "x-asset-field-type-id": 4300000, "x-applicable-members": [ "start_time", "timezone", "notes" ], "description": "Selected only by current owned visible definition type 4300000. Parts are independent and optional; partial/reversed ranges and overnight times follow the existing form." }, { "type": "object", "additionalProperties": false, "properties": { "start_date": { "type": "string", "nullable": true, "description": "YYYY-MM-DD calendar date, blank or null; no UTC conversion." }, "end_date": { "type": "string", "nullable": true, "pattern": "^\\s*$", "description": "Not applicable to this definition; omit or supply blank/null." }, "start_time": { "type": "string", "nullable": true, "description": "24-hour HH:mm local wall-clock time, blank or null; no UTC conversion." }, "end_time": { "type": "string", "nullable": true, "description": "24-hour HH:mm local wall-clock time, blank or null; no UTC conversion." }, "timezone": { "type": "string", "nullable": true, "maxLength": 20 }, "notes": { "type": "string", "nullable": true, "maxLength": 1000 } }, "x-asset-field-type-id": 4400000, "x-applicable-members": [ "start_date", "start_time", "end_time", "timezone", "notes" ], "description": "Selected only by current owned visible definition type 4400000. Parts are independent and optional; partial/reversed ranges and overnight times follow the existing form." }, { "type": "object", "additionalProperties": false, "properties": { "start_date": { "type": "string", "nullable": true, "description": "YYYY-MM-DD calendar date, blank or null; no UTC conversion." }, "end_date": { "type": "string", "nullable": true, "description": "YYYY-MM-DD calendar date, blank or null; no UTC conversion." }, "start_time": { "type": "string", "nullable": true, "description": "24-hour HH:mm local wall-clock time, blank or null; no UTC conversion." }, "end_time": { "type": "string", "nullable": true, "description": "24-hour HH:mm local wall-clock time, blank or null; no UTC conversion." }, "timezone": { "type": "string", "nullable": true, "maxLength": 20 }, "notes": { "type": "string", "nullable": true, "maxLength": 1000 } }, "x-asset-field-type-id": 4500000, "x-applicable-members": [ "start_date", "end_date", "start_time", "end_time", "timezone", "notes" ], "description": "Selected only by current owned visible definition type 4500000. Parts are independent and optional; partial/reversed ranges and overnight times follow the existing form." } ], "description": "Current owned visible transaction-locked Asset definitions select the shape. Unknown, mixed and repeated members, arrays and non-text members are refused. Empty URL/date objects clear. PATCH blank keeps the field; JSON null or text null clears. Optional POST blank/null is omitted. Plain text limit 2999; multiline rich text uses the existing 30000 inline limit, preserving/shortening existing longer values. File fields use scoped file operations.", "x-definition-validation": "Asset custom inputs use current owned visible definitions. Before saving custom fields, the API validates the type, applicable parts and literal dropdown choices. A refused update rolls back earlier changes from the same request.", "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants refused" } } ] ``` #### Creating a Capital Asset or Collateral item 1. Choose asset_type_id=1 for an individual Capital Asset, or 2 for quantity-tracked Collateral. 2. For Capital, supply a default_storage_location_id; for Collateral it is ignored with a warning. Optionally choose a name, reservation policy, cost, measurements, tags and visible custom values. 3. Save the returned Asset ID. Collateral starts without an inventory movement; add stock separately through the inventory-adjustment method. #### Defaults and plan limits An omitted, blank or null name becomes Asset. Cost defaults to zero. Capital uses your workspace’s default reservation policy; Collateral uses Liberal. Optional text is empty and omitted measurements have no value. On the Lite and Professional plans, creating an Asset is refused if one of that type already exists, including an Archived Asset. This method does not create sharing settings, images, Optional Accessories, reservations or files. #### Understanding the reservation policy - `1` — Strict: every day of an existing Capital reservation is blocked, including checkout and return. - `2` — Moderate: another reservation can use the checkout and return days; only the days between them are blocked. A one- or two-day reservation therefore blocks no days. - `3` — Liberal: overlapping reservations are allowed. Collateral always uses this policy. #### Custom-field values and formats Get the field `id` and type from `GET /v1/references/asset_custom_fields`. Add the `custom_` prefix to the ID to form the input name. Sending an object does not change a text field into another type. Hidden, removed, foreign or unsupported definitions are refused. Text and dropdown fields take JSON strings. Single-line text allows 2,999 saved characters; multiline text uses the same 30,000-character saved/editor limits as Description. An existing longer text value can be kept or shortened. Choose a current dropdown option; surrounding spaces and letter case do not affect the match. URL fields take an object with `url` and optional `display_name`, both text or null. URL input allows 4,000 characters and the label 2,000. Line breaks and control separators are removed. If a nonempty URL lacks http:// or https://, http:// is added; an empty URL clears the whole value. Date/time fields take an object containing only their enabled parts: `start_date`, `end_date`, `start_time`, `end_time`, `timezone` and `notes`. Members are optional text or null. Dates use YYYY-MM-DD; times use 24-hour HH:mm. The time-zone label allows 20 characters and notes 1,000. These are recorded calendar dates and wall-clock times, without conversion to UTC. A supplied URL or date/time object replaces that custom value as a whole; it does not merge omitted object members into the old value. Partial ranges, reversed dates and overnight times follow the existing form. Omit an inapplicable part; a nonblank value for one is refused. #### Sending custom fields 1. Use `GET /v1/references/asset_custom_fields` to find the field `id`, type and any choices. 2. For a text field with `id` 123456, send `"custom_123456":"Checked and ready"`. For a dropdown field, send one of its returned choices as text. 3. For a URL field, a value can be `{"url":"https://example.com/setup","display_name":"Setup guide"}`. For a date-only field, a value can be `{"start_date":"2030-05-14","notes":"Annual inspection"}`. 4. Send each value under `custom_` followed by the field `id`, as in the examples above. The IDs and field types in these examples are illustrative; they must match your workspace’s current definitions. #### Receiving the result and repeating a request A successful response contains the new Asset. Core fields, tags and supplied custom values are created together; an invalid value does not leave a partial Asset. Use the optional Idempotency-Key header when you need to repeat the same create request safely. Keep the key and request unchanged; do not create a new key merely because the first response was interrupted. If the outcome could not be confirmed, retrieve the current state before repeating a create. #### What happens after saving Confirmed changes are recorded in Asset history and the activity feed. This request does not send business notifications or create an Event expense, payment or invoice. A history-writing error does not undo a saved change. If the server reports that the outcome could not be confirmed, retrieve the current Asset before deciding what to do next. Do not assume the change was rolled back or automatically repeat it. Example — curl: ```bash curl -X POST "https://api.exhibitday.com/v1/assets" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"asset_type_id\":1,\"name\":\"Sample Asset\",\"default_storage_location_id\":12345}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets", { method: "POST", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "asset_type_id": 1, "name": "Sample Asset", "default_storage_location_id": 12345 }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.post( "https://api.exhibitday.com/v1/assets", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"asset_type_id": 1, "name": "Sample Asset", "default_storage_location_id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PostAsync("https://api.exhibitday.com/v1/assets", JsonContent.Create(new { asset_type_id = 1, name = "Sample Asset", default_storage_location_id = 12345 })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("POST", HttpRequest.BodyPublishers.ofString("{\"asset_type_id\":1,\"name\":\"Sample Asset\",\"default_storage_location_id\":12345}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"asset_type_id":1,"name":"Sample Asset","default_storage_location_id":12345}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"asset_type_id":1,"name":"Sample Asset","default_storage_location_id":12345}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/assets", strings.NewReader("{\"asset_type_id\":1,\"name\":\"Sample Asset\",\"default_storage_location_id\":12345}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): POST /v1/assets - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "workspace_id": 98765, "id": 6789, "asset_reservation_policy_id": 1, "exhibitday_url": "https://www.exhibitday.com/Workspace/Asset/98765?aid=6789", "internal_identifier": "", "asset_type_id": 1, "make_or_model": "", "asset_status_id": 1, "asset_status": "Active", "description": "", "name": "Sample Asset", "default_storage_location_id": 12345, "current_status": "Available / In Storage", "storage_location_name": "Main Warehouse", "returns_to_storage": "", "storage_location_address_display_name": "Boston, MA", "storage_area": "", "pull_notes": "", "status_message": null, "in_progress_reservation_count": 0, "quantity_available_in_storage": 1, "status_message_expires": null, "projected_future_balance": 1, "cost": { "amount": 0.00 }, "current_storage_footprint": 0.00, "dimensions_length": null, "projected_future_footprint": 0.00, "dimensions_width": null, "dimensions_unit": "in", "dimensions_height": null, "volume_unit": "cu ft", "dimensions_notes": "", "has_complete_dimensions": false, "dimensions_packaged_length": null, "dimensions_packaged_width": null, "dimensions_packaged_height": null, "dimensions_packaged_notes": "", "weight": null, "weight_notes": "", "weight_packaged": null, "weight_packaged_notes": "", "integration_metadata_field_1": null, "integration_metadata_field_2": null, "integration_metadata_field_3": null, "integration_metadata_field_4": null, "integration_metadata_field_5": null, "asset_created_timestamp": "2030-01-02T17:00:00Z", "weight_unit": "lb", "tags": [], "optional_accessories": [], "custom_fields": [], "images": [], "reservations": null } ``` ### Update an Asset `PATCH https://api.exhibitday.com/v1/assets` Documentation: https://api.exhibitday.com/Help/V1?epf=5#patch-v1-assets Updates an Asset’s details, tags and visible custom-field values. Send only the fields you want to change. Its type stays the same, and changing its default Storage Location does not move inventory. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Asset to update. | | | asset_type_id | Number | No | Optionally confirm the existing Asset type. Capital tracks one item; Collateral tracks quantities. If supplied, it must match; the type cannot be changed or cleared. | Allowed values: `1` (Capital) \| `2` (Collateral) | | name | String | No | The Asset name. | Up to 300 characters after text cleanup. Cannot be cleared. | | default_storage_location_id | Number | No | The default Storage Location for a Capital Asset. | Use a Storage Location in your workspace. This changes the default setting, not inventory, and cannot be cleared. Collateral/Multi-quantity items don't have a default Storage Location; a value sent for one is ignored with a warning. | | asset_reservation_policy_id | Number | No | For Capital, Strict blocks every day of an existing reservation, including checkout and return; Moderate allows those first and last days; Liberal allows overlaps. Collateral only accepts Liberal. Omit to keep the current policy. It cannot be cleared. | Allowed values: `1` (Strict) \| `2` (Moderate) \| `3` (Liberal) | | internal_identifier | String | No | Your internal identifier for the Asset. | Text, up to 100 characters. | | make_or_model | String | No | The Asset’s type, make or model. | Text, up to 500 characters. | | description | String | No | The Asset description as plain text. | Line breaks are retained. Both the saved value and the editor’s count must fit within 30,000 characters; encoded characters count toward these limits. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | storage_area | String | No | A more specific storage area, such as a shelf or bin. | Text, up to 500 characters. This does not move inventory. | | pull_notes | String | No | Plain-text instructions for preparing or pulling this Asset. | Line breaks are retained. Both the saved value and the editor’s count must fit within 30,000 characters. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | cost | Number or cost object | No | The Asset cost, as a number or an object containing amount. [Record Costs and Split Them Across Cost Centers](/Help/V1?guide=entering-costs). | No cost center breakdowns. Omit on PATCH to keep the cost; new Assets default to zero. | | dimensions_length | Number | No | The unpackaged length. | A nonnegative number up to 99999999999999999.99 in your workspace’s dimension unit, rounded to two decimal places. This does not change the unit setting. Null clears the measurement. | | dimensions_width | Number | No | The unpackaged width. | A nonnegative number up to 99999999999999999.99 in your workspace’s dimension unit, rounded to two decimal places. This does not change the unit setting. Null clears the measurement. | | dimensions_height | Number | No | The unpackaged height. | A nonnegative number up to 99999999999999999.99 in your workspace’s dimension unit, rounded to two decimal places. This does not change the unit setting. Null clears the measurement. | | dimensions_notes | String | No | Notes about the unpackaged dimensions. | Text, up to 150 characters. | | dimensions_packaged_length | Number | No | The packaged length. | A nonnegative number up to 99999999999999999.99 in your workspace’s dimension unit, rounded to two decimal places. This does not change the unit setting. Null clears the measurement. | | dimensions_packaged_width | Number | No | The packaged width. | A nonnegative number up to 99999999999999999.99 in your workspace’s dimension unit, rounded to two decimal places. This does not change the unit setting. Null clears the measurement. | | dimensions_packaged_height | Number | No | The packaged height. | A nonnegative number up to 99999999999999999.99 in your workspace’s dimension unit, rounded to two decimal places. This does not change the unit setting. Null clears the measurement. | | dimensions_packaged_notes | String | No | Notes about the packaged dimensions. | Text, up to 150 characters. | | weight | Number | No | The unpackaged weight. | A nonnegative number up to 99999999999999999.99 in your workspace’s weight unit, rounded to two decimal places. This does not change the unit setting. Null clears the measurement. | | weight_notes | String | No | Notes about the unpackaged weight. | Text, up to 150 characters. | | weight_packaged | Number | No | The packaged weight. | A nonnegative number up to 99999999999999999.99 in your workspace’s weight unit, rounded to two decimal places. This does not change the unit setting. Null clears the measurement. | | weight_packaged_notes | String | No | Notes about the packaged weight. | Text, up to 150 characters. | | integration_metadata_field_1 | String | No | A text value for your integration, such as an ID from another system. | Up to 3,000 characters. The value is not copied into history. | | integration_metadata_field_2 | String | No | A text value for your integration, such as an ID from another system. | Up to 3,000 characters. The value is not copied into history. | | integration_metadata_field_3 | String | No | A text value for your integration, such as an ID from another system. | Up to 3,000 characters. The value is not copied into history. | | integration_metadata_field_4 | String | No | A text value for your integration, such as an ID from another system. | Up to 3,000 characters. The value is not copied into history. | | integration_metadata_field_5 | String | No | A text value for your integration, such as an ID from another system. | Up to 3,000 characters. The value is not copied into history. | | tags | JSON object/list | No | The complete list of tags for this Asset. | Send an array of strings, such as ["Conference","Reusable"]. The same separator cleanup as the Asset page applies. A comma inside one entry of a JSON array splits it into separate tags, with a warning. Duplicate tags are combined without regard to case; each cleaned tag allows 30 characters. This replaces the old list. Use [] or null to clear it. There is no fixed tag-count limit. asset_tags is an older name for this parameter and is still accepted; send one of them (if you send both, they must have the same value). | | custom_NNNNNN | Varies by field | No | A visible Asset custom field. | The value depends on the configured field: text, a dropdown choice, a URL object or a date/time object. Replace NNNNNN with the field `id` from `GET /v1/references/asset_custom_fields`. Its digit count can vary. File fields use the separate file-attachment methods. | | expected_revision | String | No | The record_revision returned when you retrieved this record. Include it to avoid overwriting someone else's changes. Omit it to skip this check. | Optional. Blank, null, malformed or conflicting copies are refused with HTTP 400. A stale revision returns HTTP 409 with error_code=record_changed. | | $ignore_params_with_empty_values | Boolean | No | Whether to ignore empty values instead of applying their empty-value meaning. | Default: false. With true, real JSON null and blank values are omitted. The text "null" still clears a clearable field. This does not hide an invalid expected_revision. | Declared schema for `cost` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "anyOf": [ { "type": "number", "minimum": 0, "description": "Shorthand for an object with amount. The amount is rounded to cents before the supported storage range is checked.", "nullable": true }, { "type": "object", "additionalProperties": false, "properties": { "amount": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "required": [ "amount" ], "nullable": true }, { "type": "string", "description": "Existing Asset numeric text is supported: an invariant decimal, including grouping separators and an exponent. Blank/null retain the documented omission/clear rules.", "nullable": true } ], "x-numeric-shorthand": "A number is equivalent to {amount:number}.", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": { "amount": 125.50 } } ``` Declared schema for `tags` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "array", "items": { "type": "string" }, "maxItems": 2147483647, "nullable": true, "x-maximum-depth": 2, "x-empty-create-means-omitted": true, "example": [ "Conference", "Reusable" ] } ``` Dynamic Asset fields (the current locked field definition determines the applicable shape; native JSON uses the union, form values use text or JSON-encoded object text): ```json [ { "namePattern": "^custom_\\d+$", "description": "Use a positive Int64 definition ID suffix. Repeated copies for the same ID count once when they match. Different copies are refused.", "schema": { "nullable": true, "anyOf": [ { "type": "string", "description": "Text/rich text (1000000) or literal current dropdown option (3000000), selected by the current definition. Dropdown labels are not HTML-stripped." }, { "type": "object", "additionalProperties": false, "properties": { "url": { "type": "string", "nullable": true, "maxLength": 4000 }, "display_name": { "type": "string", "nullable": true, "maxLength": 2000 } }, "x-asset-field-type-id": 5000000 }, { "type": "object", "additionalProperties": false, "properties": { "start_date": { "type": "string", "nullable": true, "description": "YYYY-MM-DD calendar date, blank or null; no UTC conversion." }, "end_date": { "type": "string", "nullable": true, "pattern": "^\\s*$", "description": "Not applicable to this definition; omit or supply blank/null." }, "start_time": { "type": "string", "nullable": true, "pattern": "^\\s*$", "description": "Not applicable to this definition; omit or supply blank/null." }, "end_time": { "type": "string", "nullable": true, "pattern": "^\\s*$", "description": "Not applicable to this definition; omit or supply blank/null." }, "timezone": { "type": "string", "nullable": true, "pattern": "^\\s*$", "description": "Not applicable to this definition; omit or supply blank/null.", "maxLength": 20 }, "notes": { "type": "string", "nullable": true, "maxLength": 1000 } }, "x-asset-field-type-id": 4000000, "x-applicable-members": [ "start_date", "notes" ], "description": "Selected only by current owned visible definition type 4000000. Parts are independent and optional; partial/reversed ranges and overnight times follow the existing form." }, { "type": "object", "additionalProperties": false, "properties": { "start_date": { "type": "string", "nullable": true, "description": "YYYY-MM-DD calendar date, blank or null; no UTC conversion." }, "end_date": { "type": "string", "nullable": true, "description": "YYYY-MM-DD calendar date, blank or null; no UTC conversion." }, "start_time": { "type": "string", "nullable": true, "pattern": "^\\s*$", "description": "Not applicable to this definition; omit or supply blank/null." }, "end_time": { "type": "string", "nullable": true, "pattern": "^\\s*$", "description": "Not applicable to this definition; omit or supply blank/null." }, "timezone": { "type": "string", "nullable": true, "pattern": "^\\s*$", "description": "Not applicable to this definition; omit or supply blank/null.", "maxLength": 20 }, "notes": { "type": "string", "nullable": true, "maxLength": 1000 } }, "x-asset-field-type-id": 4100000, "x-applicable-members": [ "start_date", "end_date", "notes" ], "description": "Selected only by current owned visible definition type 4100000. Parts are independent and optional; partial/reversed ranges and overnight times follow the existing form." }, { "type": "object", "additionalProperties": false, "properties": { "start_date": { "type": "string", "nullable": true, "description": "YYYY-MM-DD calendar date, blank or null; no UTC conversion." }, "end_date": { "type": "string", "nullable": true, "pattern": "^\\s*$", "description": "Not applicable to this definition; omit or supply blank/null." }, "start_time": { "type": "string", "nullable": true, "description": "24-hour HH:mm local wall-clock time, blank or null; no UTC conversion." }, "end_time": { "type": "string", "nullable": true, "pattern": "^\\s*$", "description": "Not applicable to this definition; omit or supply blank/null." }, "timezone": { "type": "string", "nullable": true, "maxLength": 20 }, "notes": { "type": "string", "nullable": true, "maxLength": 1000 } }, "x-asset-field-type-id": 4200000, "x-applicable-members": [ "start_date", "start_time", "timezone", "notes" ], "description": "Selected only by current owned visible definition type 4200000. Parts are independent and optional; partial/reversed ranges and overnight times follow the existing form." }, { "type": "object", "additionalProperties": false, "properties": { "start_date": { "type": "string", "nullable": true, "pattern": "^\\s*$", "description": "Not applicable to this definition; omit or supply blank/null." }, "end_date": { "type": "string", "nullable": true, "pattern": "^\\s*$", "description": "Not applicable to this definition; omit or supply blank/null." }, "start_time": { "type": "string", "nullable": true, "description": "24-hour HH:mm local wall-clock time, blank or null; no UTC conversion." }, "end_time": { "type": "string", "nullable": true, "pattern": "^\\s*$", "description": "Not applicable to this definition; omit or supply blank/null." }, "timezone": { "type": "string", "nullable": true, "maxLength": 20 }, "notes": { "type": "string", "nullable": true, "maxLength": 1000 } }, "x-asset-field-type-id": 4300000, "x-applicable-members": [ "start_time", "timezone", "notes" ], "description": "Selected only by current owned visible definition type 4300000. Parts are independent and optional; partial/reversed ranges and overnight times follow the existing form." }, { "type": "object", "additionalProperties": false, "properties": { "start_date": { "type": "string", "nullable": true, "description": "YYYY-MM-DD calendar date, blank or null; no UTC conversion." }, "end_date": { "type": "string", "nullable": true, "pattern": "^\\s*$", "description": "Not applicable to this definition; omit or supply blank/null." }, "start_time": { "type": "string", "nullable": true, "description": "24-hour HH:mm local wall-clock time, blank or null; no UTC conversion." }, "end_time": { "type": "string", "nullable": true, "description": "24-hour HH:mm local wall-clock time, blank or null; no UTC conversion." }, "timezone": { "type": "string", "nullable": true, "maxLength": 20 }, "notes": { "type": "string", "nullable": true, "maxLength": 1000 } }, "x-asset-field-type-id": 4400000, "x-applicable-members": [ "start_date", "start_time", "end_time", "timezone", "notes" ], "description": "Selected only by current owned visible definition type 4400000. Parts are independent and optional; partial/reversed ranges and overnight times follow the existing form." }, { "type": "object", "additionalProperties": false, "properties": { "start_date": { "type": "string", "nullable": true, "description": "YYYY-MM-DD calendar date, blank or null; no UTC conversion." }, "end_date": { "type": "string", "nullable": true, "description": "YYYY-MM-DD calendar date, blank or null; no UTC conversion." }, "start_time": { "type": "string", "nullable": true, "description": "24-hour HH:mm local wall-clock time, blank or null; no UTC conversion." }, "end_time": { "type": "string", "nullable": true, "description": "24-hour HH:mm local wall-clock time, blank or null; no UTC conversion." }, "timezone": { "type": "string", "nullable": true, "maxLength": 20 }, "notes": { "type": "string", "nullable": true, "maxLength": 1000 } }, "x-asset-field-type-id": 4500000, "x-applicable-members": [ "start_date", "end_date", "start_time", "end_time", "timezone", "notes" ], "description": "Selected only by current owned visible definition type 4500000. Parts are independent and optional; partial/reversed ranges and overnight times follow the existing form." } ], "description": "Current owned visible transaction-locked Asset definitions select the shape. Unknown, mixed and repeated members, arrays and non-text members are refused. Empty URL/date objects clear. PATCH blank keeps the field; JSON null or text null clears. Optional POST blank/null is omitted. Plain text limit 2999; multiline rich text uses the existing 30000 inline limit, preserving/shortening existing longer values. File fields use scoped file operations.", "x-definition-validation": "Asset custom inputs use current owned visible definitions. Before saving custom fields, the API validates the type, applicable parts and literal dropdown choices. A refused update rolls back earlier changes from the same request.", "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants refused" } } ] ``` #### Updating only the values you mean to change Omit a field to keep its current value. A blank or whitespace-only value also keeps it and may add an empty-field warning. For a clearable field, real JSON null or the text "null" clears it; cost resets to zero. Name, type, default Storage Location and reservation policy cannot be cleared. With $ignore_params_with_empty_values=true, a real JSON null is omitted instead of clearing. The text "null" still asks to clear. A supplied tag list replaces the old list; [] is an explicit clear. Core fields, tags and supplied custom values are saved together. An invalid value refuses the change rather than saving the other fields. An unchanged saved result returns No changes were made. #### Storage, measurements and existing long text A new default Storage Location must belong to your workspace. Omitting the setting keeps the current default. Changing this setting does not move the Asset or its inventory. Measurements use the units already configured for your workspace. Description and Pull Notes accept plain text, preserve line breaks and store safe formatting. Existing text above a normal limit can be kept or shortened, but cannot grow beyond the existing allowed count. #### Understanding the reservation policy - `1` — Strict: every day of an existing Capital reservation is blocked, including checkout and return. - `2` — Moderate: another reservation can use the checkout and return days; only the days between them are blocked. A one- or two-day reservation therefore blocks no days. - `3` — Liberal: overlapping reservations are allowed. Collateral always uses this policy. #### Custom-field values and formats Get the field `id` and type from `GET /v1/references/asset_custom_fields`. Add the `custom_` prefix to the ID to form the input name. Sending an object does not change a text field into another type. Hidden, removed, foreign or unsupported definitions are refused. Text and dropdown fields take JSON strings. Single-line text allows 2,999 saved characters; multiline text uses the same 30,000-character saved/editor limits as Description. An existing longer text value can be kept or shortened. Choose a current dropdown option; surrounding spaces and letter case do not affect the match. URL fields take an object with `url` and optional `display_name`, both text or null. URL input allows 4,000 characters and the label 2,000. Line breaks and control separators are removed. If a nonempty URL lacks http:// or https://, http:// is added; an empty URL clears the whole value. Date/time fields take an object containing only their enabled parts: `start_date`, `end_date`, `start_time`, `end_time`, `timezone` and `notes`. Members are optional text or null. Dates use YYYY-MM-DD; times use 24-hour HH:mm. The time-zone label allows 20 characters and notes 1,000. These are recorded calendar dates and wall-clock times, without conversion to UTC. A supplied URL or date/time object replaces that custom value as a whole; it does not merge omitted object members into the old value. Partial ranges, reversed dates and overnight times follow the existing form. Omit an inapplicable part; a nonblank value for one is refused. #### Sending custom fields 1. Use `GET /v1/references/asset_custom_fields` to find the field `id`, type and any choices. 2. For a text field with `id` 123456, send `"custom_123456":"Checked and ready"`. For a dropdown field, send one of its returned choices as text. 3. For a URL field, a value can be `{"url":"https://example.com/setup","display_name":"Setup guide"}`. For a date-only field, a value can be `{"start_date":"2030-05-14","notes":"Annual inspection"}`. 4. Send each value under `custom_` followed by the field `id`, as in the examples above. The IDs and field types in these examples are illustrative; they must match your workspace’s current definitions. #### Avoiding overwriting another change This revision covers the editable Asset fields, tags, custom values and sharing settings. It does not cover availability, reservations, Optional Accessories, images or file contents. A successful request includes the new record_revision only when expected_revision was supplied. 1. Retrieve this Asset through `/v1/assets/info`, using its `id` and `$include_record_revision=true`. 2. Send that response’s `record_revision` as `expected_revision` with this request. Treat it as an opaque value. 3. If the API returns HTTP 409 with `error_code=record_changed`, retrieve the current Asset, review it and decide whether to send the request again. The API does not retry it for you. #### What happens after saving Confirmed changes are recorded in Asset history and the activity feed. This request does not send business notifications or create an Event expense, payment or invoice. A history-writing error does not undo a saved change. If the server reports that the outcome could not be confirmed, retrieve the current Asset before deciding what to do next. Do not assume the change was rolled back or automatically repeat it. Example — curl: ```bash curl -X PATCH "https://api.exhibitday.com/v1/assets" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"id\":12345,\"name\":\"Updated asset name\"}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets", { method: "PATCH", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "id": 12345, "name": "Updated asset name" }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.patch( "https://api.exhibitday.com/v1/assets", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"id": 12345, "name": "Updated asset name"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PatchAsync("https://api.exhibitday.com/v1/assets", JsonContent.Create(new { id = 12345, name = "Updated asset name" })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("PATCH", HttpRequest.BodyPublishers.ofString("{\"id\":12345,\"name\":\"Updated asset name\"}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"id":12345,"name":"Updated asset name"}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"id":12345,"name":"Updated asset name"}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/assets", strings.NewReader("{\"id\":12345,\"name\":\"Updated asset name\"}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): PATCH /v1/assets - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Asset updated.", "errors": [] } ``` ### Archive an Asset `POST https://api.exhibitday.com/v1/assets/archive` Documentation: https://api.exhibitday.com/Help/V1?epf=5#post-v1-assets-archive Marks an Asset as Archived and, by default, stops sharing it with other workspaces. Choose whether to keep its sharing settings. Upcoming reservations can prevent archiving. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Asset to archive. | | | unshare_on_archive | Boolean | No | Whether to remove the Asset’s sharing settings. | Default: true. A blank value uses the default. Send false to keep the sharing settings. JSON null is refused. | | expected_revision | String | No | The record_revision returned when you retrieved this record. Include it to avoid overwriting someone else's changes. Omit it to skip this check. | Optional. Blank, null, malformed or conflicting copies are refused with HTTP 400. A stale revision returns HTTP 409 with error_code=record_changed. | #### Before archiving Capital cannot be archived while it has an upcoming or in-progress reservation, including an Other Purpose reservation. Collateral cannot be archived while it has a future Event reservation. Manual inventory adjustments do not count as Event reservations for this check. The checks also run when the Asset is already Archived. Archiving does not cancel reservations, move inventory or delete files. #### Choosing what happens to sharing - Omit unshare_on_archive, or send true, to remove sharing settings. This also removes remaining shares on an already Archived Asset. - Send unshare_on_archive=false to retain the current sharing settings. Restoring the Asset later does not recreate shares that were removed. #### Avoiding overwriting another change This revision covers the editable Asset fields, tags, custom values and sharing settings. It does not cover availability, reservations, Optional Accessories, images or file contents. A successful request includes the new record_revision only when expected_revision was supplied. 1. Retrieve this Asset through `/v1/assets/info`, using its `id` and `$include_record_revision=true`. 2. Send that response’s `record_revision` as `expected_revision` with this request. Treat it as an opaque value. 3. If the API returns HTTP 409 with `error_code=record_changed`, retrieve the current Asset, review it and decide whether to send the request again. The API does not retry it for you. #### Sending this action Do not send Idempotency-Key: this conditional action does not accept that header. The optional expected_revision protects against another change; it is not an idempotency key. The response is a status object. If there is a real change it is recorded in history; a true no-op preserves the revision. #### What happens after saving Confirmed changes are recorded in Asset history and the activity feed. This request does not send business notifications or create an Event expense, payment or invoice. A history-writing error does not undo a saved change. If the server reports that the outcome could not be confirmed, retrieve the current Asset before deciding what to do next. Do not assume the change was rolled back or automatically repeat it. Example — curl: ```bash curl -X POST "https://api.exhibitday.com/v1/assets/archive" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"id\":12345}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/archive", { method: "POST", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "id": 12345 }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.post( "https://api.exhibitday.com/v1/assets/archive", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PostAsync("https://api.exhibitday.com/v1/assets/archive", JsonContent.Create(new { id = 12345 })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/archive")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("POST", HttpRequest.BodyPublishers.ofString("{\"id\":12345}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"id":12345}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/archive') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"id":12345}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/assets/archive", strings.NewReader("{\"id\":12345}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): POST /v1/assets/archive - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Asset archived.", "errors": [] } ``` ### Restore an Archived Asset `POST https://api.exhibitday.com/v1/assets/unarchive` Documentation: https://api.exhibitday.com/Help/V1?epf=5#post-v1-assets-unarchive Makes an Archived Asset Active again, so it can be used normally. It does not restore sharing settings or other records that were previously removed. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Asset to restore. | | | expected_revision | String | No | The record_revision returned when you retrieved this record. Include it to avoid overwriting someone else's changes. Omit it to skip this check. | Optional. Blank, null, malformed or conflicting copies are refused with HTTP 400. A stale revision returns HTTP 409 with error_code=record_changed. | #### What restoring changes The Asset becomes Active again. Restoring does not recreate removed sharing settings, deleted records, inventory movements or cancelled reservations. If it is already Active and nothing changes, the request returns No changes were made and does not add another history entry. #### Avoiding overwriting another change This revision covers the editable Asset fields, tags, custom values and sharing settings. It does not cover availability, reservations, Optional Accessories, images or file contents. A successful request includes the new record_revision only when expected_revision was supplied. 1. Retrieve this Asset through `/v1/assets/info`, using its `id` and `$include_record_revision=true`. 2. Send that response’s `record_revision` as `expected_revision` with this request. Treat it as an opaque value. 3. If the API returns HTTP 409 with `error_code=record_changed`, retrieve the current Asset, review it and decide whether to send the request again. The API does not retry it for you. #### Sending this action Do not send Idempotency-Key: this conditional action does not accept that header. The optional expected_revision protects against another change; it is not an idempotency key. The response is a status object. If there is a real change it is recorded in history; a true no-op preserves the revision. #### What happens after saving Confirmed changes are recorded in Asset history and the activity feed. This request does not send business notifications or create an Event expense, payment or invoice. A history-writing error does not undo a saved change. If the server reports that the outcome could not be confirmed, retrieve the current Asset before deciding what to do next. Do not assume the change was rolled back or automatically repeat it. Example — curl: ```bash curl -X POST "https://api.exhibitday.com/v1/assets/unarchive" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"id\":12345}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/unarchive", { method: "POST", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "id": 12345 }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.post( "https://api.exhibitday.com/v1/assets/unarchive", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PostAsync("https://api.exhibitday.com/v1/assets/unarchive", JsonContent.Create(new { id = 12345 })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/unarchive")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("POST", HttpRequest.BodyPublishers.ofString("{\"id\":12345}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"id":12345}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/unarchive') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"id":12345}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/assets/unarchive", strings.NewReader("{\"id\":12345}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): POST /v1/assets/unarchive - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Asset unarchived.", "errors": [] } ``` ### Retrieve an Asset Custom File Attachment `GET https://api.exhibitday.com/v1/assets/custom_fields/file_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=5#get-v1-assets-custom_fields-file_attachment Retrieves an Asset's selected custom File field and its attached-file details. An empty field returns file_attachment: null. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | asset_id | Number | Yes | The ID of the Asset, from Retrieve Assets (GET /v1/assets) or its create response. | The Asset must be owned by your workspace. Sharing an Asset does not grant access to its custom files here. | | field_name | String | Yes | The custom File field to retrieve or change. | Use the File field ID with the `custom_` prefix, for example `custom_12345`. `GET /v1/references/asset_custom_fields` lists File field definitions, including hidden fields by default. The ID after custom_ must be positive with no leading zeros; the whole name is at most 26 characters. Use the query string, a header or a form field. Matching copies of the same selector count once. Copies with different values are refused. Cookies and JSON-body selectors do not select these file fields. | | If-None-Match | String | No | An ETag from an earlier response to this GET. | Optional HTTP header. If the successful response is unchanged, the API returns HTTP 304 with no body. | #### Choosing a custom File field This is a workspace-defined File field on the Asset's Information tab. Select the field with field_name; no attachment ID or tab flag is needed. Other custom fields, standard Event documents and cost invoices use their own methods. In `GET /v1/assets/custom_fields/file_attachment`, `is_hidden` indicates whether the field is hidden on the form. You can select a known hidden File field if your access permits it. #### Reading the field The response identifies field_name and field_label, with file metadata in file_attachment. A valid empty field returns HTTP 200 with file_attachment set to null. A populated field includes the file's id, filename and attachment_created_timestamp. Use the download method for its contents. Conflicting duplicate saved values or an invalid file reference are refused; the API does not choose a value or expose another record's file. #### Access Current Assets read access is required. The Asset must belong to your workspace; archived Assets follow the same file permissions. Permitted reads remain available on the Free plan. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/assets/custom_fields/file_attachment?asset_id=12345&field_name=custom_12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/custom_fields/file_attachment?" + new URLSearchParams({ "asset_id": "12345", "field_name": "custom_12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/assets/custom_fields/file_attachment", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"asset_id": 12345, "field_name": "custom_12345"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/assets/custom_fields/file_attachment?asset_id=12345&field_name=custom_12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/custom_fields/file_attachment?asset_id=12345&field_name=custom_12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/custom_fields/file_attachment?asset_id=12345&field_name=custom_12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/assets/custom_fields/file_attachment?asset_id=12345&field_name=custom_12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/assets/custom_fields/file_attachment - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "field_name": "custom_12345", "field_label": "Integration status", "is_hidden": false, "file_attachment": { "id": 12345, "filename": "attachment.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } } ``` ### Add an Asset Custom File Attachment `POST https://api.exhibitday.com/v1/assets/custom_fields/file_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=5#post-v1-assets-custom_fields-file_attachment Adds one File Attachment to an empty custom File field on an Asset. Use PATCH to replace a file that is already attached. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | asset_id | Number | Yes | The ID of the Asset, from Retrieve Assets (GET /v1/assets) or its create response. | The Asset must be owned by your workspace. Sharing an Asset does not grant access to its custom files here. | | field_name | String | Yes | The custom File field to retrieve or change. | Use the File field ID with the `custom_` prefix, for example `custom_12345`. `GET /v1/references/asset_custom_fields` lists File field definitions, including hidden fields by default. The ID after custom_ must be positive with no leading zeros; the whole name is at most 26 characters. Use the query string, a header or a form field. Matching copies of the same selector count once. Copies with different values are refused. Cookies and JSON-body selectors do not select these file fields. | | file | File (multipart) | Yes | The Asset Custom File Attachment to upload. | Send exactly one complete, nonempty multipart/form-data part named file. Supported types and the current per-file limit are shown below; the complete request limit also includes multipart overhead. A website link, missing file or null file does not upload or remove a file. | | Idempotency-Key | String | No | A unique key for safely retrying this upload. | Optional HTTP header: 1 to 255 visible ASCII characters without spaces or commas. Retry the identical request with the same key to replay its first saved response. Use a new key for a different upload. | Declared schema for `file` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "string", "format": "binary", "x-maximum-bytes": 26214400, "x-allowed-extensions": [ "png", "jpg", "jpeg", "bmp", "gif", "pdf", "msg", "eml", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "rtf", "odp", "odt", "ods", "txt", "wks", "zip" ] } ``` #### Choosing a custom File field This is a workspace-defined File field on the Asset's Information tab. Select the field with field_name; no attachment ID or tab flag is needed. Other custom fields, standard Event documents and cost invoices use their own methods. In `GET /v1/assets/custom_fields/file_attachment`, `is_hidden` indicates whether the field is hidden on the form. You can select a known hidden File field if your access permits it. #### Before you upload POST requires an empty field. An occupied field returns HTTP 409, including one holding an unavailable saved reference. Use PATCH to replace a valid existing file. The selected field and its current binding are checked again before saving. If the definition, value or file changes during your upload, the request is refused instead of replacing a different file. #### After the upload The response includes the selected field and the new file's metadata. Only this selected custom File field changes. A successful change is recorded in Asset history. Use DELETE to remove a file; an empty or null upload is invalid and is not a removal request. #### Access and retries Current Asset edit access and an upload-enabled paid plan are required. The standard Event Information documents' Free-plan upload exception does not apply to custom File fields. expected_revision is not supported by this file method. If the save outcome cannot be confirmed, retrieve this field's current metadata before deciding whether to submit another change. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X POST "https://api.exhibitday.com/v1/assets/custom_fields/file_attachment" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}" --form-string "asset_id=12345" --form-string "field_name=custom_12345" --form "file=@attachment.pdf;type=application/octet-stream") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi cat response-body.tmp ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const form = new FormData(); form.append("asset_id", "12345"); form.append("field_name", "custom_12345"); form.append("file", new Blob([await readFile("attachment.pdf")], { type: "application/octet-stream" }), "attachment.pdf"); const response = await fetch("https://api.exhibitday.com/v1/assets/custom_fields/file_attachment", { method: "POST", headers: { Authorization: 'Bearer YOUR_API_KEY' }, body: form }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); console.log(await response.json()); ``` Example — Python: ```python import requests import json from contextlib import ExitStack with ExitStack() as stack: files = [ ("file", ("attachment.pdf", stack.enter_context(open("attachment.pdf", 'rb')), "application/octet-stream")), ] response = requests.request("POST", "https://api.exhibitday.com/v1/assets/custom_fields/file_attachment", headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data={"asset_id": "12345", "field_name": "custom_12345"}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') print(response.json()) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.exhibitday.com/v1/assets/custom_fields/file_attachment"); var form = new MultipartFormDataContent(); form.Add(new StringContent("12345"), "asset_id"); form.Add(new StringContent("custom_12345"), "field_name"); var file0 = new StreamContent(File.OpenRead("attachment.pdf")); file0.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(file0, "file", "attachment.pdf"); request.Content = form; using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/assets/custom_fields/file_attachment")).header("Authorization", "Bearer YOUR_API_KEY"); String boundary = "ExhibitDay-" + UUID.randomUUID(); ByteArrayOutputStream form = new ByteArrayOutputStream(); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"asset_id\"\r\n\r\n" + "12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"field_name\"\r\n\r\n" + "custom_12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"attachment.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8)); form.write(Files.readAllBytes(Path.of("attachment.pdf"))); form.write("\r\n".getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); request.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpResponse response = HttpClient.newHttpClient().send(request.method("POST", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); System.out.println(new String(response.body(), StandardCharsets.UTF_8)); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], CURLOPT_POSTFIELDS => [ 'asset_id' => '12345', 'field_name' => 'custom_12345', 'file' => new CURLFile('attachment.pdf', 'application/octet-stream', 'attachment.pdf'), ], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); echo $response; ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/custom_fields/file_attachment') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' files = [] begin parts = [ ['asset_id', '12345'], ['field_name', 'custom_12345'], ['file', (files << File.open('attachment.pdf', 'rb')).last, {filename: 'attachment.pdf', content_type: 'application/octet-stream'}], ] request.set_form(parts, 'multipart/form-data') response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' puts response.body ensure files.each(&:close) end ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" "bytes" "mime/multipart" "net/textproto" ) func main() { var form bytes.Buffer writer := multipart.NewWriter(&form) if err := writer.WriteField("asset_id", "12345"); err != nil { log.Fatal(err) } if err := writer.WriteField("field_name", "custom_12345"); err != nil { log.Fatal(err) } header0 := textproto.MIMEHeader{} header0.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"attachment.pdf\"") header0.Set("Content-Type", "application/octet-stream") part0, err := writer.CreatePart(header0) if err != nil { log.Fatal(err) } file0, err := os.Open("attachment.pdf") if err != nil { log.Fatal(err) } if _, err = io.Copy(part0, file0); err != nil { log.Fatal(err) } file0.Close() if err := writer.Close(); err != nil { log.Fatal(err) } request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/assets/custom_fields/file_attachment", &form) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", writer.FormDataContentType()) response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } fmt.Printf("%s\n", data) } ``` Example HTTP response body (JSON): POST /v1/assets/custom_fields/file_attachment - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "field_name": "custom_12345", "field_label": "Integration status", "is_hidden": false, "file_attachment": { "id": 12345, "filename": "attachment.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } } ``` ### Replace an Asset Custom File Attachment `PATCH https://api.exhibitday.com/v1/assets/custom_fields/file_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=5#patch-v1-assets-custom_fields-file_attachment Replaces the File Attachment in an Asset's selected custom File field. A valid existing file is required. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | asset_id | Number | Yes | The ID of the Asset, from Retrieve Assets (GET /v1/assets) or its create response. | The Asset must be owned by your workspace. Sharing an Asset does not grant access to its custom files here. | | field_name | String | Yes | The custom File field to retrieve or change. | Use the File field ID with the `custom_` prefix, for example `custom_12345`. `GET /v1/references/asset_custom_fields` lists File field definitions, including hidden fields by default. The ID after custom_ must be positive with no leading zeros; the whole name is at most 26 characters. Use the query string, a header or a form field. Matching copies of the same selector count once. Copies with different values are refused. Cookies and JSON-body selectors do not select these file fields. | | file | File (multipart) | Yes | The Asset Custom File Attachment to upload. | Send exactly one complete, nonempty multipart/form-data part named file. Supported types and the current per-file limit are shown below; the complete request limit also includes multipart overhead. A website link, missing file or null file does not upload or remove a file. | Declared schema for `file` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "string", "format": "binary", "x-maximum-bytes": 26214400, "x-allowed-extensions": [ "png", "jpg", "jpeg", "bmp", "gif", "pdf", "msg", "eml", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "rtf", "odp", "odt", "ods", "txt", "wks", "zip" ] } ``` #### Choosing a custom File field This is a workspace-defined File field on the Asset's Information tab. Select the field with field_name; no attachment ID or tab flag is needed. Other custom fields, standard Event documents and cost invoices use their own methods. In `GET /v1/assets/custom_fields/file_attachment`, `is_hidden` indicates whether the field is hidden on the form. You can select a known hidden File field if your access permits it. #### Replacing the current file PATCH requires a valid current file. An empty field returns HTTP 404; a malformed or unavailable saved reference is refused. The replacement receives a new file ID even when its contents are identical. The selected field and its current binding are checked again before saving. If the definition, value or file changes during your upload, the request is refused instead of replacing a different file. #### After the replacement The response includes the selected field and the new file's metadata. Only this selected custom File field changes. A successful change is recorded in Asset history. An old file that is safe to remove is scheduled for physical cleanup after the save; cleanup may finish later. Other fields and items that still own that file retain their references and file. #### Access and retries Current Asset edit access and an upload-enabled paid plan are required. The standard Event Information documents' Free-plan upload exception does not apply to custom File fields. expected_revision is not supported by this file method. PATCH does not use Idempotency-Key replay. If the save outcome cannot be confirmed, retrieve this field's current metadata before deciding whether to submit another change. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X PATCH "https://api.exhibitday.com/v1/assets/custom_fields/file_attachment" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}" --form-string "asset_id=12345" --form-string "field_name=custom_12345" --form "file=@attachment.pdf;type=application/octet-stream") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi cat response-body.tmp ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const form = new FormData(); form.append("asset_id", "12345"); form.append("field_name", "custom_12345"); form.append("file", new Blob([await readFile("attachment.pdf")], { type: "application/octet-stream" }), "attachment.pdf"); const response = await fetch("https://api.exhibitday.com/v1/assets/custom_fields/file_attachment", { method: "PATCH", headers: { Authorization: 'Bearer YOUR_API_KEY' }, body: form }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); console.log(await response.json()); ``` Example — Python: ```python import requests import json from contextlib import ExitStack with ExitStack() as stack: files = [ ("file", ("attachment.pdf", stack.enter_context(open("attachment.pdf", 'rb')), "application/octet-stream")), ] response = requests.request("PATCH", "https://api.exhibitday.com/v1/assets/custom_fields/file_attachment", headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data={"asset_id": "12345", "field_name": "custom_12345"}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') print(response.json()) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("PATCH"), "https://api.exhibitday.com/v1/assets/custom_fields/file_attachment"); var form = new MultipartFormDataContent(); form.Add(new StringContent("12345"), "asset_id"); form.Add(new StringContent("custom_12345"), "field_name"); var file0 = new StreamContent(File.OpenRead("attachment.pdf")); file0.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(file0, "file", "attachment.pdf"); request.Content = form; using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/assets/custom_fields/file_attachment")).header("Authorization", "Bearer YOUR_API_KEY"); String boundary = "ExhibitDay-" + UUID.randomUUID(); ByteArrayOutputStream form = new ByteArrayOutputStream(); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"asset_id\"\r\n\r\n" + "12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"field_name\"\r\n\r\n" + "custom_12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"attachment.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8)); form.write(Files.readAllBytes(Path.of("attachment.pdf"))); form.write("\r\n".getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); request.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpResponse response = HttpClient.newHttpClient().send(request.method("PATCH", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); System.out.println(new String(response.body(), StandardCharsets.UTF_8)); } } ``` Example — PHP: ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], CURLOPT_POSTFIELDS => [ 'asset_id' => '12345', 'field_name' => 'custom_12345', 'file' => new CURLFile('attachment.pdf', 'application/octet-stream', 'attachment.pdf'), ], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); echo $response; ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/custom_fields/file_attachment') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' files = [] begin parts = [ ['asset_id', '12345'], ['field_name', 'custom_12345'], ['file', (files << File.open('attachment.pdf', 'rb')).last, {filename: 'attachment.pdf', content_type: 'application/octet-stream'}], ] request.set_form(parts, 'multipart/form-data') response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' puts response.body ensure files.each(&:close) end ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" "bytes" "mime/multipart" "net/textproto" ) func main() { var form bytes.Buffer writer := multipart.NewWriter(&form) if err := writer.WriteField("asset_id", "12345"); err != nil { log.Fatal(err) } if err := writer.WriteField("field_name", "custom_12345"); err != nil { log.Fatal(err) } header0 := textproto.MIMEHeader{} header0.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"attachment.pdf\"") header0.Set("Content-Type", "application/octet-stream") part0, err := writer.CreatePart(header0) if err != nil { log.Fatal(err) } file0, err := os.Open("attachment.pdf") if err != nil { log.Fatal(err) } if _, err = io.Copy(part0, file0); err != nil { log.Fatal(err) } file0.Close() if err := writer.Close(); err != nil { log.Fatal(err) } request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/assets/custom_fields/file_attachment", &form) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", writer.FormDataContentType()) response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } fmt.Printf("%s\n", data) } ``` Example HTTP response body (JSON): PATCH /v1/assets/custom_fields/file_attachment - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "field_name": "custom_12345", "field_label": "Integration status", "is_hidden": false, "file_attachment": { "id": 12345, "filename": "attachment.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } } ``` ### Remove an Asset Custom File Attachment `DELETE https://api.exhibitday.com/v1/assets/custom_fields/file_attachment` Documentation: https://api.exhibitday.com/Help/V1?epf=5#delete-v1-assets-custom_fields-file_attachment Removes the File Attachment from an Asset's selected custom File field. If the field is already empty, the response is 404 Not Found and nothing changes. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | asset_id | Number | Yes | The ID of the Asset, from Retrieve Assets (GET /v1/assets) or its create response. | The Asset must be owned by your workspace. Sharing an Asset does not grant access to its custom files here. | | field_name | String | Yes | The custom File field to retrieve or change. | Use the File field ID with the `custom_` prefix, for example `custom_12345`. `GET /v1/references/asset_custom_fields` lists File field definitions, including hidden fields by default. The ID after custom_ must be positive with no leading zeros; the whole name is at most 26 characters. Use the query string, a header or a form field. Matching copies of the same selector count once. Copies with different values are refused. Cookies and JSON-body selectors do not select these file fields. | #### Choosing a custom File field This is a workspace-defined File field on the Asset's Information tab. Select the field with field_name; no attachment ID or tab flag is needed. Other custom fields, standard Event documents and cost invoices use their own methods. In `GET /v1/assets/custom_fields/file_attachment`, `is_hidden` indicates whether the field is hidden on the form. You can select a known hidden File field if your access permits it. #### After the removal Only the selected custom File field is cleared. If the field is already empty, DELETE returns HTTP 404 Not Found and changes no saved metadata or history. A real change is recorded in Asset history. DELETE can also clear a single malformed, dangling or foreign saved reference while leaving that other file untouched. Files still referenced by another field or a structured record are preserved. Conflicting duplicate saved values return HTTP 409 rather than choosing which value to clear. An unshared owned file that is safe to remove is scheduled for physical cleanup after the save; cleanup may finish later. Other custom fields, Asset information and standard documents stay in place. #### Access and retries Current Asset edit access and attachment add/remove permission are required. Permitted removals remain available on the Free plan. Do not send file parts with DELETE. expected_revision is not supported, and DELETE does not use Idempotency-Key replay. If the save outcome cannot be confirmed, retrieve this field's current metadata before deciding whether to submit another change. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/assets/custom_fields/file_attachment?asset_id=12345&field_name=custom_12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/custom_fields/file_attachment?" + new URLSearchParams({ "asset_id": "12345", "field_name": "custom_12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/assets/custom_fields/file_attachment", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"asset_id": 12345, "field_name": "custom_12345"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/assets/custom_fields/file_attachment?asset_id=12345&field_name=custom_12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/custom_fields/file_attachment?asset_id=12345&field_name=custom_12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/custom_fields/file_attachment?asset_id=12345&field_name=custom_12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/assets/custom_fields/file_attachment?asset_id=12345&field_name=custom_12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/assets/custom_fields/file_attachment - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Custom File field cleared.", "errors": [] } ``` ### Download an Asset Custom File Attachment `GET https://api.exhibitday.com/v1/assets/custom_fields/file_attachment/download` Documentation: https://api.exhibitday.com/Help/V1?epf=5#get-v1-assets-custom_fields-file_attachment-download Downloads the original File Attachment in an Asset's selected custom File field. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | asset_id | Number | Yes | The ID of the Asset, from Retrieve Assets (GET /v1/assets) or its create response. | The Asset must be owned by your workspace. Sharing an Asset does not grant access to its custom files here. | | field_name | String | Yes | The custom File field to retrieve or change. | Use the File field ID with the `custom_` prefix, for example `custom_12345`. `GET /v1/references/asset_custom_fields` lists File field definitions, including hidden fields by default. The ID after custom_ must be positive with no leading zeros; the whole name is at most 26 characters. Use the query string, a header or a form field. Matching copies of the same selector count once. Copies with different values are refused. Cookies and JSON-body selectors do not select these file fields. | #### Choosing a custom File field This is a workspace-defined File field on the Asset's Information tab. Select the field with field_name; no attachment ID or tab flag is needed. Other custom fields, standard Event documents and cost invoices use their own methods. In `GET /v1/assets/custom_fields/file_attachment`, `is_hidden` indicates whether the field is hidden on the form. You can select a known hidden File field if your access permits it. #### Download response A successful response contains the original uploaded file with a safe download filename. An empty field returns HTTP 404; API errors use the usual JSON response. Conflicting duplicate saved values or an invalid file reference are refused; the API does not choose a value or expose another record's file. #### Access Current Assets read access is required. The Asset must belong to your workspace; archived Assets follow the same file permissions. Permitted reads remain available on the Free plan. #### Files still being copied If this file is still being copied, the download returns HTTP 409 with file_copy_pending. Try the download again in a few minutes. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X GET "https://api.exhibitday.com/v1/assets/custom_fields/file_attachment/download?asset_id=12345&field_name=custom_12345" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi mv response-body.tmp 'attachment.pdf' ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const response = await fetch("https://api.exhibitday.com/v1/assets/custom_fields/file_attachment/download?asset_id=12345&field_name=custom_12345", { method: "GET", headers: { Authorization: 'Bearer YOUR_API_KEY' } }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); await writeFile("attachment.pdf", new Uint8Array(await response.arrayBuffer())); ``` Example — Python: ```python import requests import json response = requests.request("GET", "https://api.exhibitday.com/v1/assets/custom_fields/file_attachment/download?asset_id=12345&field_name=custom_12345", headers={'Authorization': 'Bearer YOUR_API_KEY'}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') with open("attachment.pdf", 'wb') as destination: destination.write(response.content) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.exhibitday.com/v1/assets/custom_fields/file_attachment/download?asset_id=12345&field_name=custom_12345"); using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); await File.WriteAllBytesAsync("attachment.pdf", await response.Content.ReadAsByteArrayAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/assets/custom_fields/file_attachment/download?asset_id=12345&field_name=custom_12345")).header("Authorization", "Bearer YOUR_API_KEY"); HttpResponse response = HttpClient.newHttpClient().send(request.method("GET", HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); Files.write(Path.of("attachment.pdf"), response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); file_put_contents('attachment.pdf', $response); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/custom_fields/file_attachment/download?asset_id=12345&field_name=custom_12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' File.binwrite('attachment.pdf', response.body) ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/assets/custom_fields/file_attachment/download?asset_id=12345&field_name=custom_12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } if err := os.WriteFile("attachment.pdf", data, 0600); err != nil { log.Fatal(err) } fmt.Println("File saved") } ``` HTTP 200: Downloads the selected field's original uploaded file. An empty field has no file to download; errors use the usual JSON response. Media: application/octet-stream. The body is the authorized file's real bytes, not JSON or base64. Errors are JSON status responses; check HTTP status before saving the file. ## Assets - Storage Locations Storage Locations: where Assets are kept, the Capital Assets and Collateral transactions at each, and their logs. Documentation page: https://api.exhibitday.com/Help/V1?epf=5&topic=storage-locations ### Retrieve a Single Storage Location by ID `GET https://api.exhibitday.com/v1/assets/storage_locations/info` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=storage-locations#get-v1-assets-storage_locations-info Retrieves one Storage Location and its saved address and contact details. Set `$include_record_revision=true` if you plan to update it and want to check for changes before saving. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Storage Location you want to retrieve. | | | $include_record_revision | Boolean | No | Set to `true` to include a `record_revision` for checking later updates. | Default: false. Use this value with PATCH /v1/assets/storage_locations. | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` | | $on_error_return_empty_result | Boolean | No | Set to `true` to return an empty result instead of a supported validation or not-found error. | Default: false. Authentication, malformed or ambiguous inputs, conflicts and unexpected errors keep their error status. | | $include_error_list_in_response_message | Boolean | No | Set to `true` to include individual validation errors in the response message. | Default: false. The error list remains available in the normal error response. | | If-None-Match | String | No | Send the ETag from an earlier response when checking whether this result changed. | Optional request header. A matching current result returns HTTP 304 with no body; reuse your earlier response. This header compares GET responses. It cannot prevent a conflicting update. | #### What the response includes Each location includes its saved name, address, address display label, contact details and creation time. Assets, inventory transactions, history, followers and notification recipients are not included. `address_display_name` is derived from the address lookup. It can be empty when no label was found. Coordinates and separate postal, country, city and state fields are not exposed through the API. Older locations may have a null, blank or short saved address. GET returns those saved values without inventing an address or hiding the location. Other missing text is returned as an empty string. Sharing an Asset does not share its owner’s Storage Location or contact details. #### Getting a revision for an update 1. Retrieve this location with `$include_record_revision=true`. 2. Send the returned `record_revision` as `expected_revision` in PATCH /v1/assets/storage_locations. #### What $include_record_revision covers Set `$include_record_revision=true` to receive `record_revision` in this GET response. It covers the location name, entered address and contact details. It does not cover the derived map details, creation time, Assets or inventory transactions. A stale revision makes PATCH return HTTP `409` with `error_code=record_changed` without saving changes. Retrieve the location again and review its current values before deciding whether to retry. #### Handling empty results and errors Use `$on_error_return_empty_result=true` only when your application can handle a missing record or supported validation error as an empty result. Current API access is still checked. Matching copies of a parameter count once. Malformed inputs, conflicting copies, authentication errors, HTTP `409` conflicts and unexpected errors keep their normal error response. If a concurrent change prevents the read, the API returns HTTP `409` with `error_code=record_changed`; retrieve the data again. This read does not change any data. #### Checking whether a response changed Normal API-key and access checks still apply. This header compares the response; it does not authorize access or protect an update. 1. Save the response body and its `ETag` header from an earlier GET. 2. Repeat the same GET, including the same filters and response options, with that ETag in the `If-None-Match` header. 3. If the response is HTTP `304`, keep using your saved body. If it is HTTP `200`, use the new body and ETag. #### Open in ExhibitDay Each record includes exhibitday_url, a link that opens its Storage Location page in ExhibitDay. Sign in to ExhibitDay with an account that can view that workspace and Storage Location. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/assets/storage_locations/info?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/storage_locations/info?" + new URLSearchParams({ "id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/assets/storage_locations/info", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/assets/storage_locations/info?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/storage_locations/info?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/storage_locations/info?id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/assets/storage_locations/info?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/assets/storage_locations/info - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "id": 12345, "name": "Main Warehouse", "address": "100 Main Street, Boston, MA 02110", "address_display_name": "Boston, MA", "point_of_contact_name": "Warehouse Contact", "point_of_contact_phone": "+1 617 555 0100", "point_of_contact_email": "warehouse@example.test", "storage_location_created_timestamp": "2030-01-02T12:00:00Z", "exhibitday_url": "https://www.exhibitday.com/Workspace/StorageLocation/98765?sid=12345" } ``` ### Retrieve Storage Locations `GET https://api.exhibitday.com/v1/assets/storage_locations` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=storage-locations#get-v1-assets-storage_locations Retrieves Storage Locations and their saved address and contact details. By default, it sorts by name and returns all matching locations. Add a location filter, or use paging when you need a smaller result. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | filter_by_storage_location_id | Number | No | Only return this Storage Location. | | | $result_sort | String | No | Order locations by name, ID or creation time. Omit for name ascending. Name ties use ID descending; creation-time ties use ID ascending. Unsupported values are refused. Use the values exactly as shown (lowercase). | Allowed values: `name_asc` \| `name_desc` \| `create_timestamp_asc` \| `create_timestamp_desc` \| `id_asc` \| `id_desc` | | $limit | Number | No | The maximum number of locations to return. | One positive whole number. Omit to return all matching locations after `$offset`; there is no fixed page-size cap. | | $offset | Number | No | The number of matching locations to skip. | Default: 0. Send a nonnegative whole number. | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | | $on_error_return_empty_result | Boolean | No | Set to `true` to return an empty collection for supported validation errors. | Default: false. Authentication, malformed or ambiguous inputs, conflicts and unexpected errors keep their error status. | | $include_error_list_in_response_message | Boolean | No | Set to `true` to include individual validation errors in the response message. | Default: false. The error list remains available in the normal error response. | | If-None-Match | String | No | Send the ETag from an earlier response when checking whether this result changed. | Optional request header. A matching current result returns HTTP 304 with no body; reuse your earlier response. This header compares GET responses. It cannot prevent a conflicting update. | #### Filtering and paging The location filter returns only the Storage Location you choose. `records_found` is the number of locations in this response; `total_records` is the number matching the filters before paging. `has_more` tells you whether matching rows remain after this page. Counts and pages can change if someone edits locations between requests. This collection does not return edit revisions or support changed-since filtering. Use a location’s Info response when you need a revision for PATCH. #### What the response includes Each location includes its saved name, address, address display label, contact details and creation time. Assets, inventory transactions, history, followers and notification recipients are not included. `address_display_name` is derived from the address lookup. It can be empty when no label was found. Coordinates and separate postal, country, city and state fields are not exposed through the API. Older locations may have a null, blank or short saved address. GET returns those saved values without inventing an address or hiding the location. Other missing text is returned as an empty string. Sharing an Asset does not share its owner’s Storage Location or contact details. #### Handling empty results and errors No matching locations normally returns an empty list. Use `$on_error_return_empty_result=true` only when your application can also treat a supported validation error as an empty collection. Current API access is still checked. Matching copies of a parameter count once. Malformed inputs, conflicting copies, authentication errors, HTTP `409` conflicts and unexpected errors keep their normal error response. If a concurrent change prevents the read, the API returns HTTP `409` with `error_code=record_changed`; retrieve the data again. This read does not change any data. #### Checking whether a response changed Normal API-key and access checks still apply. This header compares the response; it does not authorize access or protect an update. 1. Save the response body and its `ETag` header from an earlier GET. 2. Repeat the same GET, including the same filters and response options, with that ETag in the `If-None-Match` header. 3. If the response is HTTP `304`, keep using your saved body. If it is HTTP `200`, use the new body and ETag. #### Open in ExhibitDay Each record includes exhibitday_url, a link that opens its Storage Location page in ExhibitDay. Sign in to ExhibitDay with an account that can view that workspace and Storage Location. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/assets/storage_locations" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/storage_locations", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/assets/storage_locations", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/assets/storage_locations"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/storage_locations")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/storage_locations') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/assets/storage_locations", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/assets/storage_locations - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "storage_location", "list_data": [ { "id": 2345, "name": "Main Warehouse", "address": "100 Main Street, Boston, MA 02110", "address_display_name": "Boston, MA", "point_of_contact_name": "Warehouse Contact", "point_of_contact_phone": "+1 617 555 0100", "point_of_contact_email": "warehouse@example.test", "storage_location_created_timestamp": "2030-01-02T12:00:00Z", "exhibitday_url": "https://www.exhibitday.com/Workspace/StorageLocation/98765?sid=2345" } ] } ``` ### Add a Storage Location `POST https://api.exhibitday.com/v1/assets/storage_locations` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=storage-locations#post-v1-assets-storage_locations Adds a Storage Location with a name and full street address. You can also save contact details. The response contains the new location, including its ID. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | name | String | Yes | The name of the Storage Location. | 1–120 characters, excluding surrounding spaces. | | address | String | Yes | The full street address of the Storage Location. | 10–500 characters, excluding surrounding spaces. | | point_of_contact_name | String | No | The name of the contact for this location. | Up to 150 characters, excluding surrounding spaces. | | point_of_contact_phone | String | No | The contact phone number for this location. | Up to 100 characters, excluding surrounding spaces. | | point_of_contact_email | String | No | The contact email text for this location. | Up to 150 characters, excluding surrounding spaces. This field does not send an email. | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` | | Idempotency-Key | String | No | Send a unique key if you may retry this same create request. | Optional request header: 1–255 visible ASCII characters without spaces, such as a UUID. Reuse the same key only for the same request. Successful responses can be replayed for 24 hours. | #### Adding a location 1. Send `name` and `address`. Add any contact fields you want to save. 2. Read the new location’s `id` from the response. Use that ID when selecting the location for an Asset or another supported operation. #### Address lookup and contact details Name, address and contact lengths exclude surrounding spaces. A missing, blank or null name or address is refused. Optional contact fields that are blank or null are left empty. The API attempts an address lookup. Your entered address is saved even if lookup is unavailable or finds no result. The derived `address_display_name` may therefore be empty. You cannot supply the display label, coordinates or separate postal, country, city and state values. This method does not add Assets or inventory, move existing items, subscribe followers or send business notifications. A saved location is added to history; failure to write history does not undo the location. #### Retrying the same create request To reduce the chance of duplicates, send `Idempotency-Key` as a request header and reuse that key with the same request if you retry. A matching completed request returns its earlier result. A key used with a different request is refused. If the API cannot confirm whether the save succeeded, check the current locations before trying again. The API does not automatically repeat the create. `expected_revision` is not supported on POST. #### Sending text with commas Use JSON, the query string or a form field for addresses or other text containing commas. #### Open in ExhibitDay The created Storage Location includes exhibitday_url, a link that opens its Storage Location page in ExhibitDay. It is the same link that GET /v1/assets/storage_locations/info returns for this Storage Location. Sign in to ExhibitDay with an account that can view that workspace and Storage Location. Example — curl: ```bash curl -X POST "https://api.exhibitday.com/v1/assets/storage_locations" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"name\":\"Main Warehouse\",\"address\":\"100 Main Street, Boston, MA 02110\"}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/storage_locations", { method: "POST", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "name": "Main Warehouse", "address": "100 Main Street, Boston, MA 02110" }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.post( "https://api.exhibitday.com/v1/assets/storage_locations", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"name": "Main Warehouse", "address": "100 Main Street, Boston, MA 02110"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PostAsync("https://api.exhibitday.com/v1/assets/storage_locations", JsonContent.Create(new { name = "Main Warehouse", address = "100 Main Street, Boston, MA 02110" })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/storage_locations")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("POST", HttpRequest.BodyPublishers.ofString("{\"name\":\"Main Warehouse\",\"address\":\"100 Main Street, Boston, MA 02110\"}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"name":"Main Warehouse","address":"100 Main Street, Boston, MA 02110"}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/storage_locations') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"name":"Main Warehouse","address":"100 Main Street, Boston, MA 02110"}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/assets/storage_locations", strings.NewReader("{\"name\":\"Main Warehouse\",\"address\":\"100 Main Street, Boston, MA 02110\"}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): POST /v1/assets/storage_locations - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "id": 2345, "name": "Main Warehouse", "address": "100 Main Street, Boston, MA 02110", "address_display_name": "Boston, MA", "point_of_contact_name": "Warehouse Contact", "point_of_contact_phone": "+1 617 555 0100", "point_of_contact_email": "warehouse@example.test", "storage_location_created_timestamp": "2030-01-02T12:00:00Z", "exhibitday_url": "https://www.exhibitday.com/Workspace/StorageLocation/98765?sid=2345" } ``` ### Update a Storage Location `PATCH https://api.exhibitday.com/v1/assets/storage_locations` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=storage-locations#patch-v1-assets-storage_locations Updates the supplied name, address or contact details of a Storage Location. Omitted fields keep their saved values. This method does not move Assets or inventory. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Storage Location you want to update. | | | name | String | No | The name of the Storage Location. | 1–120 characters, excluding surrounding spaces. | | address | String | If the saved address is invalid | The full street address of the Storage Location. | 10–500 characters, excluding surrounding spaces. | | point_of_contact_name | String | No | The name of the contact for this location. | Up to 150 characters, excluding surrounding spaces. | | point_of_contact_phone | String | No | The contact phone number for this location. | Up to 100 characters, excluding surrounding spaces. | | point_of_contact_email | String | No | The contact email text for this location. | Up to 150 characters, excluding surrounding spaces. This field does not send an email. | | expected_revision | String | No | The record_revision returned when you retrieved this record. Include it to avoid overwriting someone else's changes. Omit it to skip this check. | | | $ignore_params_with_empty_values | Boolean | No | Set to `true` to ignore contact fields sent as JSON `null`. | Default: false. The text `"null"` still clears a contact field. Name and address cannot be blank or null, including when this option is true. | #### Choosing what to update Include `id` and send only the fields you want to change. Sending unchanged valid values makes no change to the location, revision or history. Name and address cannot be blank or null. If an older location has a missing, short or overlong address, provide a valid address in the same request before saving any change. If you omit name, a saved name that doesn't meet today's rules is kept unchanged; a name you supply must meet the current limit. For contact fields, omission or blank text keeps the saved value. JSON `null` or the text `"null"` clears a contact field. With `$ignore_params_with_empty_values=true`, real JSON `null` is ignored, while the text `"null"` still clears it. #### Changing the address The API checks the address length after trimming surrounding spaces and attempts an address lookup. If the address actually changes, it clears the old derived map details and saves any lookup results for the new address. If lookup is unavailable or returns no result, the entered address is still saved and the display label may be empty. Sending the same address does not refresh its derived map details by itself. You cannot set the display label, coordinates or the separate postal, country, city and state values. #### Avoiding conflicting updates 1. Retrieve the location with GET /v1/assets/storage_locations/info and `$include_record_revision=true`. 2. Send that exact `record_revision` as `expected_revision` in your PATCH request. #### Handling revisions and conflicts The revision covers the name, entered address and contact details. Derived map details, creation time, Assets and inventory are outside its scope. If a covered value differs from what you read, the API returns HTTP `409` with `error_code=record_changed` and saves nothing. Retrieve the current location, review the changes and decide whether to retry. A value that changed and later changed back still matches. A blank, null or malformed revision is refused with HTTP `400` and `error_code=invalid_request`. A successful PATCH includes the current `record_revision` only when you supplied `expected_revision`. #### Retrying an update This method ignores the `Idempotency-Key` header. If the save outcome cannot be confirmed, retrieve the location before deciding whether to retry. The API does not repeat the action automatically. A confirmed change is added to history. A history-writing failure does not undo the saved change. Updating a location sends no business notifications. #### Sending text with commas Use JSON, the query string or a form field for addresses or other text containing commas. Example — curl: ```bash curl -X PATCH "https://api.exhibitday.com/v1/assets/storage_locations" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"id\":12345,\"name\":\"Updated location name\"}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/storage_locations", { method: "PATCH", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "id": 12345, "name": "Updated location name" }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.patch( "https://api.exhibitday.com/v1/assets/storage_locations", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"id": 12345, "name": "Updated location name"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PatchAsync("https://api.exhibitday.com/v1/assets/storage_locations", JsonContent.Create(new { id = 12345, name = "Updated location name" })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/storage_locations")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("PATCH", HttpRequest.BodyPublishers.ofString("{\"id\":12345,\"name\":\"Updated location name\"}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"id":12345,"name":"Updated location name"}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/storage_locations') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"id":12345,"name":"Updated location name"}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/assets/storage_locations", strings.NewReader("{\"id\":12345,\"name\":\"Updated location name\"}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): PATCH /v1/assets/storage_locations - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Storage Location updated.", "errors": [] } ``` ### Delete a Storage Location `DELETE https://api.exhibitday.com/v1/assets/storage_locations` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=storage-locations#delete-v1-assets-storage_locations Permanently deletes a Storage Location. You can delete it without a destination if no Asset uses it as its default Storage Location and it has no Collateral inventory transactions. Otherwise, provide a transfer destination in the same request. You can choose another Storage Location in your workspace or create a new one. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Storage Location you want to delete. | | | transfer_to_storage_location_id | Number | For an existing destination | The ID of the Storage Location that will receive the Assets and inventory records. It must be a different location in your workspace. | | | new_storage_location_name | String | For a new destination | The name of the Storage Location you want to create. | 1–120 characters, excluding surrounding spaces. | | new_storage_location_address | String | For a new destination | The full street address of the new Storage Location. | 10–500 characters, excluding surrounding spaces. | #### Moving inventory before deletion Use the option that applies to your request. - **Delete an empty location.** Omit all three transfer parameters. - **Transfer to an existing location.** Send only `transfer_to_storage_location_id` as the transfer parameter. - **Transfer to a new location.** Send both `new_storage_location_name` and `new_storage_location_address`. The API creates the new location only if the transfer succeeds. Do not combine them with an existing destination. #### What the transfer changes Assets use the destination as their saved default Storage Location, and Collateral inventory transactions move to that location. Reservation and inventory dates and quantities stay the same. The transfer does not check in Assets or cancel reservations. For a new destination, the address is saved even if map details cannot be found. An existing destination keeps its address and contact details. This action sends no business notifications. #### Retrying a request If you cannot confirm whether the deletion succeeded, check the Storage Location and its inventory before retrying. The API does not repeat the deletion automatically. This method ignores the `Idempotency-Key` header. `expected_revision` is not supported. A history-writing failure does not undo a deletion that was saved. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/assets/storage_locations?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/storage_locations?" + new URLSearchParams({ "id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/assets/storage_locations", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/assets/storage_locations?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/storage_locations?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/storage_locations?id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/assets/storage_locations?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/assets/storage_locations - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Storage Location deleted.", "errors": [] } ``` ### Retrieve Capital Assets at a Storage Location `GET https://api.exhibitday.com/v1/assets/storage_locations/capital_assets` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=storage-locations#get-v1-assets-storage_locations-capital_assets Retrieves Capital Assets whose saved default Storage Location is the location you select. A Capital Asset is one item, such as a display stand. Active and Archived Assets are included by default. The saved location is not a guarantee that an item is currently in storage. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | storage_location_id | Number | Yes | The ID of the Storage Location you want to read. | The Storage Location must belong to your workspace. | | filter_by_asset_id | Number | No | The ID of the Asset you want to retrieve. The result is still a list. For a single Asset object, use `GET /v1/assets/info` with `id`. | | | filter_by_asset_status_id | Number | No | Only include Capital Assets with the selected status. Omit to include both Active and Archived Assets. | Allowed values: `1` (Active) \| `2` (Archived) | | filter_by_asset_name_contains_text | String | No | Text to find anywhere in the Asset name. `%`, `_` and square brackets are treated as literal characters. | Maximum: 300 characters. | | filter_by_asset_tag | String | No | The Asset tag to match. Matching follows the same case and accent rules as Asset search in ExhibitDay. | Maximum: 150 characters. | | filter_by_integration_metadata_field_1 | String | No | The value to match in integration metadata field 1. | Maximum: 3,000 characters. | | filter_by_integration_metadata_field_2 | String | No | The value to match in integration metadata field 2. | Maximum: 3,000 characters. | | filter_by_integration_metadata_field_3 | String | No | The value to match in integration metadata field 3. | Maximum: 3,000 characters. | | filter_by_integration_metadata_field_4 | String | No | The value to match in integration metadata field 4. | Maximum: 3,000 characters. | | filter_by_integration_metadata_field_5 | String | No | The value to match in integration metadata field 5. | Maximum: 3,000 characters. | | filter_by_custom_field_value_setting_id | Number | With a custom field value | The ID of a visible Asset text or dropdown custom field in your workspace. | | | filter_by_custom_field_value_setting_value | String | With a custom field ID | The value to match in the selected field. An empty string matches Assets whose saved value is empty or missing. | | | filter_by_reservation_date_greater_than_or_equal_to | Date | No | The earliest checkout date for Capital Assets or the earliest Reservation Date for Collateral. | YYYY-MM-DD. | | filter_by_reservation_date_smaller_than_or_equal_to | Date | No | The latest checkout date for Capital Assets or the latest Reservation Date for Collateral. | YYYY-MM-DD. | | filter_by_reservation_return_date_greater_than_or_equal_to | Date | No | The earliest reservation return date. Capital Assets only. | YYYY-MM-DD. | | filter_by_reservation_return_date_smaller_than_or_equal_to | Date | No | The latest reservation return date. Capital Assets only. | YYYY-MM-DD. | | filter_by_reservation_overlaps_start_date | Date | When filtering by overlap | The first day of the period you want to check. Send both overlap dates. Capital Assets only. | YYYY-MM-DD. | | filter_by_reservation_overlaps_end_date | Date | When filtering by overlap | The last day of the period you want to check. Send both overlap dates. Capital Assets only. | YYYY-MM-DD. | | $result_sort | String | No | Order Assets by name, creation time or ID. Omit for name ascending. Name and creation-time ties use the lower Asset ID first. Unsupported values are refused. | Allowed values: `name_asc` \| `name_desc` \| `create_timestamp_asc` \| `create_timestamp_desc` \| `id_asc` \| `id_desc` | | $limit | Number | No | Maximum number of Assets to return. Omit to return all remaining matches. | Whole number of 1 or more; no fixed cap. | | $offset | Number | No | Number of matching Assets to skip. | Whole number of 0 or more. Default: 0. | | hydrate_reservations | Boolean | No | Set to `true` to include all reservations you can access for each full Asset result. | Default: false. Applies to full results only. | | $return_asset_lites | Boolean | No | Set to `true` for a shorter result with Asset identification, current status, quantities and storage summaries. | Default: false. | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | | If-None-Match | String | No | Send the ETag from an earlier response when checking whether this result changed. | Optional request header. A matching current result returns HTTP 304 with no body; reuse your earlier response. This header compares GET responses. It cannot prevent a conflicting update. | #### Default location and availability Both the selected location and the Assets must belong to your workspace. Shared-Asset access does not grant access to the owner’s location or full Asset details. A listed Asset may be checked out for an Event or another purpose. Use Asset Availability to check whether you can reserve it for particular dates. This method already selects Capital Assets at the required location. It does not accept another Asset-type or default-location filter. #### Filtering and optional details Filters work together before counting and paging. All date and overlap conditions must match the same Capital reservation. An unknown Return Date does not match return-date or overlap predicates. Full Asset details are returned by default. Set `$return_asset_lites=true` for a smaller identification and inventory summary. Lite results do not include long text, custom fields, Optional Accessories, files or reservations. For full results, `hydrate_reservations=true` loads all readable reservations on each selected Asset, not just the reservations that matched your filters. #### Paging the result `records_found` is the number of rows in this response; `total_records` is the filtered count before paging. `has_more` indicates whether more matching rows remain. Results can change while the data is edited. Omit `$limit` for all matches after `$offset`, or use the two options to read smaller pages. There is no fixed page-size cap. This list does not return edit revisions or support changed-since filtering. #### Handling missing records and errors An invalid Storage Location ID returns HTTP `404` with `error_code=not_found`, even if no rows would match your filters. This method has no empty-result-on-error option. Invalid inputs keep their error status. If concurrent changes prevent the read, HTTP `409` with `error_code=record_changed` means you should retrieve the data again. The read changes no data. #### Sending filter values Use the query string, form data or JSON for a text filter that contains a comma. #### Checking whether a response changed Normal API-key and access checks still apply. This header compares the response; it does not authorize access or protect an update. 1. Save the response body and its `ETag` header from an earlier GET. 2. Repeat the same GET, including the same filters and response options, with that ETag in the `If-None-Match` header. 3. If the response is HTTP `304`, keep using your saved body. If it is HTTP `200`, use the new body and ETag. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/assets/storage_locations/capital_assets?storage_location_id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/storage_locations/capital_assets?" + new URLSearchParams({ "storage_location_id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/assets/storage_locations/capital_assets", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"storage_location_id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/assets/storage_locations/capital_assets?storage_location_id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/storage_locations/capital_assets?storage_location_id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/storage_locations/capital_assets?storage_location_id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/assets/storage_locations/capital_assets?storage_location_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/assets/storage_locations/capital_assets - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "asset", "list_data": [ { "workspace_id": 98765, "id": 12345, "asset_reservation_policy_id": 1, "exhibitday_url": "https://www.exhibitday.com/Workspace/Asset/98765?aid=12345", "internal_identifier": "", "asset_type_id": 1, "make_or_model": "", "asset_status_id": 1, "asset_status": "Active", "description": "", "name": "Display stand", "default_storage_location_id": 12345, "current_status": "Available / In Storage", "storage_location_name": "Main Warehouse", "returns_to_storage": "", "storage_location_address_display_name": "Boston, MA", "storage_area": "", "pull_notes": "", "status_message": null, "in_progress_reservation_count": 0, "quantity_available_in_storage": 1, "status_message_expires": null, "projected_future_balance": 1, "cost": { "amount": 0.00 }, "current_storage_footprint": 0.00, "dimensions_length": null, "projected_future_footprint": 0.00, "dimensions_width": null, "dimensions_unit": "in", "dimensions_height": null, "volume_unit": "cu ft", "dimensions_notes": "", "has_complete_dimensions": false, "dimensions_packaged_length": null, "dimensions_packaged_width": null, "dimensions_packaged_height": null, "dimensions_packaged_notes": "", "weight": null, "weight_notes": "", "weight_packaged": null, "weight_packaged_notes": "", "integration_metadata_field_1": null, "integration_metadata_field_2": null, "integration_metadata_field_3": null, "integration_metadata_field_4": null, "integration_metadata_field_5": null, "asset_created_timestamp": "2030-01-02T17:00:00Z", "weight_unit": "lb", "tags": [], "optional_accessories": [], "custom_fields": [], "images": [], "reservations": null } ] } ``` ### Retrieve Collateral Transactions at a Storage Location `GET https://api.exhibitday.com/v1/assets/storage_locations/collateral_transactions` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=storage-locations#get-v1-assets-storage_locations-collateral_transactions Retrieves the Collateral inventory transactions recorded at one Storage Location, including manual increases and decreases and Event reservations. Collateral is tracked in quantities, such as brochures. Older and future transactions are included, ordered newest first by default. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | storage_location_id | Number | Yes | The ID of the Storage Location you want to read. | The Storage Location must belong to your workspace. | | filter_by_asset_id | Number | No | Only return transactions for this Collateral item. | | | filter_by_asset_status_id | Number | No | Only return transactions for Assets with the selected status. Omit to include both Active and Archived Assets. | Allowed values: `1` (Active) \| `2` (Archived) | | filter_by_asset_name_contains_text | String | No | Only return transactions for Assets whose names contain this text. | Up to 300 characters. Search characters are matched as text, not as wildcards. | | filter_by_event_reservations_only | Boolean | No | Choose Event reservations or manual inventory changes. | `true` returns Event reservations only; `false` returns manual changes only. Omit to include both. | | filter_by_effective_date_greater_than_or_equal_to | Date | No | Only return transactions effective on or after this date. | Use `YYYY-MM-DD`. | | filter_by_effective_date_smaller_than_or_equal_to | Date | No | Only return transactions effective on or before this date. | Use `YYYY-MM-DD`. It must not be before the lower date when both are supplied. | | $result_sort | String | No | Order transactions by effective date or ID. Omit for effective date descending. Date ties use ID in the same direction. Unsupported values are refused. Use the values exactly as shown (lowercase). | Allowed values: `effective_date_asc` \| `effective_date_desc` \| `id_asc` \| `id_desc` | | $limit | Number | No | The maximum number of matching transactions to return. | One positive whole number. Omit for all matches after `$offset`. | | $offset | Number | No | The number of matching transactions to skip. | Default: 0. Send a nonnegative whole number. | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | | If-None-Match | String | No | Send the ETag from an earlier response when checking whether this result changed. | Optional request header. A matching current result returns HTTP 304 with no body; reuse your earlier response. This header compares GET responses. It cannot prevent a conflicting update. | #### Understanding the quantities `quantity_adjustment` is signed: increases are positive and decreases are negative. `quantity` gives the size of the change without its sign. Older zero or unsupported quantities remain readable; `is_quantity_editable` describes quantity support, not permission to edit. `inventory_balance_on_date` is this Asset’s balance at the location after all changes on that calendar date, including scheduled returns. It uses the Asset’s complete history at this location, even when your filters show only some transactions. A saved `return_date` reverses the quantity change from that date onward. It is not confirmation of a physical return and does not create another transaction row. #### Identifying the source record `is_event_reservation` distinguishes Event reservations from manual changes. `reservation_id` is set for an Event reservation; `inventory_adjustment_id` is set for a manual adjustment. Use the corresponding method for that record, even if another family has the same numeric ID. Only transactions for your workspace’s Collateral items are returned. When a shared Asset is reserved for another workspace’s Event, the transaction shows that Event’s name and the reservation notes, as in the Assets area. Because the Event belongs to another workspace, `event_id` is null and Event methods can’t open it with this key. The inventory effect remains visible. This does not grant additional Event, file or editing access. #### Paging the result `records_found` is the number of rows in this response; `total_records` is the filtered count before paging. `has_more` indicates whether more matching rows remain. Results can change while the data is edited. Omit `$limit` for all matches after `$offset`, or use the two options to read smaller pages. There is no fixed page-size cap. This list does not return edit revisions or support changed-since filtering. #### Handling missing records and errors An invalid Storage Location ID returns HTTP `404` with `error_code=not_found`, even if no rows would match your filters. This method has no empty-result-on-error option. Invalid inputs keep their error status. If concurrent changes prevent the read, HTTP `409` with `error_code=record_changed` means you should retrieve the data again. The read changes no data. #### Sending filter values Use the query string, form data or JSON for a text filter that contains a comma. #### Checking whether a response changed Normal API-key and access checks still apply. This header compares the response; it does not authorize access or protect an update. 1. Save the response body and its `ETag` header from an earlier GET. 2. Repeat the same GET, including the same filters and response options, with that ETag in the `If-None-Match` header. 3. If the response is HTTP `304`, keep using your saved body. If it is HTTP `200`, use the new body and ETag. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/assets/storage_locations/collateral_transactions?storage_location_id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/storage_locations/collateral_transactions?" + new URLSearchParams({ "storage_location_id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/assets/storage_locations/collateral_transactions", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"storage_location_id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/assets/storage_locations/collateral_transactions?storage_location_id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/storage_locations/collateral_transactions?storage_location_id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/storage_locations/collateral_transactions?storage_location_id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/assets/storage_locations/collateral_transactions?storage_location_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/assets/storage_locations/collateral_transactions - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "storage_collateral_transaction", "list_data": [ { "exhibitday_url": "https://www.exhibitday.com/Workspace/Asset/98765?aid=4567&reservation_id=3456", "id": 3456, "asset_id": 4567, "asset_name": "Printed brochures", "asset_status_id": 1, "storage_location_id": 12345, "storage_location_name": "Main Storage", "effective_date": "2030-01-02", "return_date": null, "quantity_adjustment": 20, "quantity": 20, "is_quantity_editable": true, "inventory_balance_on_date": 120, "is_event_reservation": false, "reservation_id": null, "inventory_adjustment_id": 3456, "event_id": null, "event_name": "", "notes": "Additional printed brochures", "shipping_logistics_id": 1, "is_flagged": false, "is_starred": false, "is_checked": false, "collateral_transaction_created_timestamp": "2030-01-02T12:00:00Z" } ] } ``` ### Retrieve a Storage Location's Logs `GET https://api.exhibitday.com/v1/assets/storage_locations/logs` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=storage-locations#get-v1-assets-storage_locations-logs Retrieves the visible business history filed under one Storage Location. Filters work together to narrow its history. Results are ordered newest first by default. This is the selected record’s history, not a combined history of every child record. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | storage_location_id | Number | Yes | The ID of the Storage Location whose history you want to read. | Use the Storage Location's record ID. | | filter_by_actor_user_id | String | No | Only return entries written by this user. | Use the opaque `actor_user_id` from a log entry. Up to 128 characters; treat it as text. Historical IDs can match former users. | | filter_by_log_entry_contains_text | String | No | Only return entries containing this text. | Up to 3,000 characters after trimming surrounding spaces. Text is matched literally; HTML is not converted and search characters are not wildcards. | | filter_by_create_timestamp_greater_than_or_equal_to | String | No | Only return entries at or after this timestamp. | Use an ISO 8601 timestamp. A fractional lower bound starts at the next whole second. Include an offset or `Z` to state the time zone. | | filter_by_create_timestamp_smaller_than_or_equal_to | String | No | Only return entries at or before this timestamp. | Includes every entry in the displayed second. It must not precede the lower bound. | | filter_by_event_id | Number | No | Only return entries filed under this Event ID in your workspace’s history. | | | filter_by_event_tab_id | Number | No | Only return entries filed under this Event tab ID. GET /v1/references/event_tabs lists your workspace's tabs; the Presentations tab is accepted only where your workspace has it. | Allowed values: `1` (Info) \| `2` (Booth) \| `3` (Staff) \| `4` (Travel) \| `5` (Assets) \| `6` (Shipments) \| `7` (Sponsorships) \| `8` (Tasks) \| `9` (Playbook) \| `10` (Attachments) \| `11` (Misc. Expenses & Credits) \| `12` (Budget) \| `13` (ROI) \| `14` (Event Settings) \| `16` (Binder) \| `17` (Copy Event) \| `19` (Logs) \| `20` (Delete Event) \| `21` (Giveaways) \| `22` (Special Tab, shown under your workspace's name for it) | | filter_by_context_type | String | No | Only return entries associated with the selected context. Omit to include all contexts. Workspace means an entry with none of the other associations; an entry can belong to more than one other context. Unsupported values are refused. Values are case-insensitive. | Allowed values: `workspace` \| `event` \| `task` \| `asset` \| `storage_location` | | $result_sort | String | No | Sort entries newest first (the default) or oldest first. The full saved timestamp is used, with the entry ID breaking ties in the same direction. Responses display whole seconds. Unsupported values are refused. Use the values exactly as shown (lowercase). | Allowed values: `create_timestamp_desc` (newest first) \| `create_timestamp_asc` (oldest first) | | $limit | Number | No | The maximum number of matching entries to return. | One positive whole number. Omit for all matches after `$offset`; there is no fixed page-size cap. | | $offset | Number | No | The number of matching entries to skip. | Default: 0. Send a nonnegative whole number. | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | | If-None-Match | String | No | Send the ETag from an earlier response when checking whether this result changed. | Optional request header. A matching current result returns HTTP 304 with no body; reuse your earlier response. This header compares GET responses. It cannot prevent a conflicting update. | #### Choosing the record Use the Storage Location ID to choose the history you want to retrieve. Only entries filed under the selected record are included. Sharing or borrowing an Asset does not grant access to its owner’s history. Only history visible to workspace users is returned. Hidden or technical entries, impersonation activity, IP addresses, device details and security information are excluded. #### Filtering by time and context Returned timestamps use UTC and display whole seconds. Timestamp filters use that displayed precision: the upper bound includes the entire displayed second, and a fractional lower bound starts at the next whole second. An input with an offset or `Z` is converted for comparison. A timestamp without an offset is interpreted as US Eastern time. Include an offset when you want an unambiguous instant. `workspace` context selects entries with no Event, Task, Asset or Storage Location association. The other contexts select entries with that association, and an entry can have several associations. Every result must still be filed under this selected Storage Location, so a context filter can legitimately produce no matches. #### Paging the result `records_found` is the number of rows in this response; `total_records` is the filtered count before paging. `has_more` indicates whether more matching rows remain. Results can change while the data is edited. Omit `$limit` for all matches after `$offset`, or use the two options to read smaller pages. There is no fixed page-size cap. This list does not return edit revisions or support changed-since filtering. #### Handling errors This method has no empty-result-on-error option. Invalid inputs retain their error status. If concurrent changes prevent the read, HTTP `409` with `error_code=record_changed` means you should read again. Each row has the same fields as an entry from `GET /v1/workspace_settings/logs`. It does not change the selected record, issue an edit revision or provide a feed of changes and deletions. #### Sending filter values Use the query string, form data or JSON for a text filter that contains a comma. #### Checking whether a response changed Normal API-key and access checks still apply. This header compares the response; it does not authorize access or protect an update. 1. Save the response body and its `ETag` header from an earlier GET. 2. Repeat the same GET, including the same filters and response options, with that ETag in the `If-None-Match` header. 3. If the response is HTTP `304`, keep using your saved body. If it is HTTP `200`, use the new body and ETag. #### Reading the actor `actor_user_id` is the ID of the user who made the change. `actor_display_name` is the name saved with the entry at that time; it does not change if the user is renamed later. Entries recorded by the API have a null `actor_user_id` and show the label saved with them, such as `API`. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/assets/storage_locations/logs?storage_location_id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/storage_locations/logs?" + new URLSearchParams({ "storage_location_id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/assets/storage_locations/logs", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"storage_location_id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/assets/storage_locations/logs?storage_location_id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/storage_locations/logs?storage_location_id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/storage_locations/logs?storage_location_id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/assets/storage_locations/logs?storage_location_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/assets/storage_locations/logs - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "workspace_log", "list_data": [ { "id": 67890, "log_entry_created_timestamp": "2026-01-02T08:04:05Z", "actor_user_id": "11111111-2222-4333-8444-555555555555", "actor_display_name": "Illustrative user", "log_entry": "Illustrative user updated the selected record.", "event_id": null, "event_name": null, "event_tab_id": 0, "task_id": null, "task_name": null, "asset_id": null, "asset_name": "", "storage_location_id": 12345, "storage_location_name": "Main Storage" } ] } ``` ## Assets - Inventory Adjustments Manual inventory increases and decreases: read, add, update and delete them. Documentation page: https://api.exhibitday.com/Help/V1?epf=5&topic=inventory-adjustments ### Retrieve a Single Inventory Adjustment by ID `GET https://api.exhibitday.com/v1/assets/inventory_adjustments/info` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=inventory-adjustments#get-v1-assets-inventory_adjustments-info Retrieves one manual Collateral inventory adjustment. Set `$include_record_revision=true` if you plan to update it and want to check for changes before saving. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the manual inventory adjustment. | Use an ID from this inventory-adjustment collection. Event and Capital reservation IDs are different records, even if the numbers match. | | $include_record_revision | Boolean | No | Set to `true` to include a `record_revision` for checking a later update. | Default: false. Use the returned value with PATCH /v1/assets/inventory_adjustments or DELETE /v1/assets/inventory_adjustments. | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` | | $on_error_return_empty_result | Boolean | No | Set to `true` to return an empty result for supported validation or not-found errors. | Default: false. Other errors keep their normal status. | | $include_error_list_in_response_message | Boolean | No | Set to `true` to include individual validation errors in the response message. | Default: false. The normal error response still includes its error list. | | If-None-Match | String | No | Send the ETag from an earlier response when checking whether this result changed. | Optional request header. A matching current result returns HTTP 304 with no body; reuse your earlier response. This header compares GET responses. It cannot prevent a conflicting update. | #### Understanding the quantity and dates `quantity_adjustment` is the signed change: positive for an increase and negative for a decrease. `quantity` is its size without the sign. For example, a decrease of 10 has `quantity_adjustment=-10` and `quantity=10`. Older zero adjustments remain visible. `is_quantity_editable=false` marks an inherited quantity outside the editing range; it remains readable. An older `return_date` is the date when the adjustment’s quantity effect was scheduled to reverse. It does not confirm that an item was physically returned. GET preserves that historical date; new manual adjustments normally have no return date. #### What the response includes The response contains the adjustment itself, its Collateral item, saved description and formatting, Shipping Logistics choice, flag, star and checked status, and location when it is available to your workspace. It does not include attachments, Logistical Records or related-item links. The Storage Location ID and name are included only when the location is in your workspace. Shared-Asset access does not grant access to the owner’s manual inventory. `description` is returned as text: HTML-encoded, with line breaks as
. Formatting added in ExhibitDay is not returned. Account identifiers and file-storage details are not exposed. #### Getting a revision for an update 1. Retrieve the adjustment with `$include_record_revision=true`. 2. Send the returned `record_revision` as `expected_revision` in PATCH /v1/assets/inventory_adjustments, or in DELETE /v1/assets/inventory_adjustments to delete it only if it is unchanged. #### What $include_record_revision covers Set `$include_record_revision=true` to receive `record_revision` in this GET response. It covers the adjustment fields, formatting saved in ExhibitDay, Logistical Records and related-item links. Attachment metadata and file contents are outside its scope. A stale revision makes PATCH or DELETE return HTTP `409` with `error_code=record_changed` and change nothing. Retrieve the adjustment again and review the current values before deciding whether to retry. #### Handling a missing adjustment A missing or inaccessible adjustment returns HTTP `404`. Set `$on_error_return_empty_result=true` for an empty object instead, or an empty array when `$result_format=array`. Current API access is still checked. Matching copies of a parameter count once. Malformed inputs, conflicting copies, authentication errors, read conflicts and unexpected errors retain their normal status. A read conflict returns HTTP `409` with `error_code=record_changed`; retrieve the record again. #### Checking whether a response changed Normal API-key and access checks still apply. This header compares the response; it does not authorize access or protect an update. 1. Save the response body and its `ETag` header from an earlier GET. 2. Repeat the same GET, including the same filters and response options, with that ETag in the `If-None-Match` header. 3. If the response is HTTP `304`, keep using your saved body. If it is HTTP `200`, use the new body and ETag. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/assets/inventory_adjustments/info?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/inventory_adjustments/info?" + new URLSearchParams({ "id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/assets/inventory_adjustments/info", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/assets/inventory_adjustments/info?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/inventory_adjustments/info?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/inventory_adjustments/info?id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/assets/inventory_adjustments/info?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/assets/inventory_adjustments/info - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "exhibitday_url": "https://www.exhibitday.com/Workspace/Asset/98765?aid=12346&reservation_id=12345", "id": 12345, "asset_id": 12346, "asset_name": "Printed brochures", "storage_location_id": 2345, "storage_location_name": "Main Warehouse", "effective_date": "2030-01-02", "return_date": null, "quantity_adjustment": 10, "quantity": 10, "is_increase": true, "is_quantity_editable": true, "description": "Additional printed brochures arrived", "shipping_logistics_id": 1, "is_flagged": false, "is_starred": false, "is_checked": false, "inventory_adjustment_created_timestamp": "2030-01-01T17:00:00Z" } ``` ### Retrieve Inventory Adjustments `GET https://api.exhibitday.com/v1/assets/inventory_adjustments` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=inventory-adjustments#get-v1-assets-inventory_adjustments Retrieves manual increases and decreases in Collateral inventory, such as newly received brochures or stock removed from storage. These entries are not assigned to an Event. By default, it returns all matching adjustments in Effective Date order. Add filters or paging to narrow the result. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | filter_by_inventory_adjustment_id | Number | No | Only return this manual inventory adjustment. | | | filter_by_asset_id | Number | No | Only return adjustments for this Collateral item. | | | filter_by_storage_location_id | Number | No | Only return adjustments at this Storage Location. | | | filter_by_effective_date_greater_than_or_equal_to | Date | No | Only return adjustments effective on or after this date. | Use `YYYY-MM-DD`. The whole calendar date is compared, including older entries saved with a time of day. | | filter_by_effective_date_smaller_than_or_equal_to | Date | No | Only return adjustments effective on or before this date. | Use `YYYY-MM-DD`. It must not be before the lower date when both are supplied. | | $result_sort | String | No | Order adjustments by effective date, creation time or ID. Omit for effective date ascending. Date and time ties use ID ascending. Unsupported values are refused. Use the values exactly as shown (lowercase). | Allowed values: `effective_date_asc` \| `effective_date_desc` \| `create_timestamp_asc` \| `create_timestamp_desc` \| `id_asc` \| `id_desc` | | $limit | Number | No | The maximum number of matching adjustments to return. | Send one positive whole number. Omit to return all matches after `$offset`; there is no fixed page-size cap. | | $offset | Number | No | The number of matching adjustments to skip. | Default: 0. Send a nonnegative whole number. | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | | $on_error_return_empty_result | Boolean | No | Set to `true` to return an empty collection for supported validation errors. | Default: false. No matching adjustments normally returns an empty collection. | | $include_error_list_in_response_message | Boolean | No | Set to `true` to include individual validation errors in the response message. | Default: false. The normal error response still includes its error list. | | If-None-Match | String | No | Send the ETag from an earlier response when checking whether this result changed. | Optional request header. A matching current result returns HTTP 304 with no body; reuse your earlier response. This header compares GET responses. It cannot prevent a conflicting update. | #### Filtering and paging Filters work together. A matching adjustment must satisfy every ID and date filter you provide. Event reservations and Capital Asset reservations are excluded; these manual entries are always for Collateral inventory. `records_found` is the number of rows in this response; `total_records` is the filtered count before paging. `has_more` indicates whether more matches remain. Counts and pages may change while inventory is edited. The collection does not issue revisions and does not support changed-since filtering. #### Understanding the quantity and dates `quantity_adjustment` is the signed change: positive for an increase and negative for a decrease. `quantity` is its size without the sign. For example, a decrease of 10 has `quantity_adjustment=-10` and `quantity=10`. Older zero adjustments remain visible. `is_quantity_editable=false` marks an inherited quantity outside the editing range; it remains readable. An older `return_date` is the date when the adjustment’s quantity effect was scheduled to reverse. It does not confirm that an item was physically returned. GET preserves that historical date; new manual adjustments normally have no return date. #### What the response includes The response contains the adjustment itself, its Collateral item, saved description and formatting, Shipping Logistics choice, flag, star and checked status, and location when it is available to your workspace. It does not include attachments, Logistical Records or related-item links. The Storage Location ID and name are included only when the location is in your workspace. Shared-Asset access does not grant access to the owner’s manual inventory. `description` is returned as text: HTML-encoded, with line breaks as
. Formatting added in ExhibitDay is not returned. Account identifiers and file-storage details are not exposed. #### Handling errors Matching copies of a parameter count once. Malformed inputs, conflicting copies, authentication errors, read conflicts and unexpected errors keep their normal error response, even when `$on_error_return_empty_result=true`. If concurrent changes prevent the read, HTTP `409` with `error_code=record_changed` means you should retrieve the data again. This read changes no data. #### Checking whether a response changed Normal API-key and access checks still apply. This header compares the response; it does not authorize access or protect an update. 1. Save the response body and its `ETag` header from an earlier GET. 2. Repeat the same GET, including the same filters and response options, with that ETag in the `If-None-Match` header. 3. If the response is HTTP `304`, keep using your saved body. If it is HTTP `200`, use the new body and ETag. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/assets/inventory_adjustments" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/inventory_adjustments", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/assets/inventory_adjustments", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/assets/inventory_adjustments"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/inventory_adjustments")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/inventory_adjustments') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/assets/inventory_adjustments", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/assets/inventory_adjustments - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "inventory_adjustment", "list_data": [ { "exhibitday_url": "https://www.exhibitday.com/Workspace/Asset/98765?aid=12346&reservation_id=12345", "id": 12345, "asset_id": 12346, "asset_name": "Printed brochures", "storage_location_id": 2345, "storage_location_name": "Main Warehouse", "effective_date": "2030-01-02", "return_date": null, "quantity_adjustment": 10, "quantity": 10, "is_increase": true, "is_quantity_editable": true, "description": "Additional printed brochures arrived", "shipping_logistics_id": 1, "is_flagged": false, "is_starred": false, "is_checked": false, "inventory_adjustment_created_timestamp": "2030-01-01T17:00:00Z" } ] } ``` ### Add an Inventory Adjustment `POST https://api.exhibitday.com/v1/assets/inventory_adjustments` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=inventory-adjustments#post-v1-assets-inventory_adjustments Records a manual increase or decrease in Collateral stock without assigning it to an Event. The quantity takes effect on the chosen Effective Date. Use an existing Storage Location, or create a new location when adding stock. The response includes exhibitday_url, the record's page in ExhibitDay. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | asset_id | Number | Yes | The ID of the Active Collateral/Multi-quantity item whose inventory you want to adjust. Capital Assets are not accepted. | | | quantity | Number | Yes | The size of the increase or decrease. | One positive whole number from 1 through 2,147,483,647. Send the direction separately with `is_increase`. | | is_increase | Boolean | Yes | Set to `true` to add stock, or `false` to remove stock. | | | description | String | Yes | The description explaining this inventory change. | Plain text, up to 1,000 characters. Line breaks are preserved. GET returns the description as text: HTML-encoded, with line breaks as
. The description cannot be blank. | | is_effective_immediately | Boolean | No | Set to `true` to use today, or `false` when choosing an Effective Date. | Uses today in your workspace’s time zone. `true` overrides a supplied `effective_date`. If omitted, a supplied date is used; otherwise the date defaults to today. | | effective_date | Date | When is_effective_immediately=false | The date when this inventory change should take effect. | Use `YYYY-MM-DD`. | | storage_location_id | Number | For an existing location | The Storage Location for this inventory change. | Choose an existing location, or supply both new-location fields for an increase. Do not combine the two choices. | | new_storage_location_name | String | For a new location | The name of a new Storage Location for this increase. | 1–120 characters, excluding surrounding spaces. A new location is available only when `is_increase=true`. | | new_storage_location_address | String | For a new location | The full street address of the new Storage Location. | 10–500 characters, excluding surrounding spaces. | | shipping_logistics_id | Number | No | The Shipping Logistics choice to record for this adjustment. Omit for Unspecified. | Allowed values: `1` (Unspecified) \| `2` (Advance Warehouse) \| `3` (Direct Shipment) \| `4` (Other) | | is_flagged | Boolean | No | Whether to flag this inventory entry. | Default: false. | | is_starred | Boolean | No | Whether to star this inventory entry. | Default: false. | | is_checked | Boolean | No | Whether to mark this inventory entry as checked. | Default: false. | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` | | Idempotency-Key | String | No | Send a unique key if you may retry this same create request. | Optional request header: 1–255 visible ASCII characters without spaces, such as a UUID. Reuse the same key only for the same request. Successful responses can be replayed for 24 hours. | #### Recording an inventory change 1. Send `asset_id`, a positive `quantity`, the direction in `is_increase`, and a description. 2. Choose the Effective Date and one Storage Location option below. 3. Read the created adjustment from the response. An increase adds the quantity; a decrease subtracts it. #### Choosing the date - For today, omit both date options or send `is_effective_immediately=true`. - For another date, send `effective_date`. You can also send `is_effective_immediately=false`, which requires the date. - If `is_effective_immediately=true` and a date are both supplied, today is used. #### Choosing the Storage Location - For an existing location, send its `storage_location_id`. It must be in your workspace. - For a new location, send `is_increase=true`, `new_storage_location_name` and `new_storage_location_address`, and omit `storage_location_id`. - The new location and inventory increase are saved together. A refused adjustment leaves no unused new location. Address lookup is best effort; a failed lookup keeps the entered address. #### Inventory limits and side effects A new adjustment requires an Active Collateral/Multi-quantity item. Shared-Asset access does not grant access to the owner’s manual inventory. Capital Assets cannot be adjusted because they are single-quantity items. Capital Asset and Event reservations use `/v1/assets/reservations`. Inventory totals may be negative. The API refuses an adjustment that would put a resulting stored total outside the supported whole-number range. It does not impose a rule that every total must stay nonnegative. This method does not create an Event reservation, related-item links, attachments or a scheduled return. It sends no follower or business notifications. A confirmed change is recorded in history; a history-writing failure does not undo the saved adjustment. #### Retrying the same create Use the optional `Idempotency-Key` request header if you may retry the same create request. Reuse that key only with the same request so a completed response can be replayed without creating another adjustment. If the save outcome cannot be confirmed, check the adjustment and inventory before retrying. The API does not automatically repeat the action. `expected_revision` is not supported on POST. #### Sending text with commas Use JSON, the query string or a form field for a description or new location that contains a comma. Example — curl: ```bash curl -X POST "https://api.exhibitday.com/v1/assets/inventory_adjustments" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"asset_id\":12345,\"storage_location_id\":12345,\"quantity\":10,\"is_increase\":true,\"description\":\"Additional printed brochures arrived\"}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/inventory_adjustments", { method: "POST", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "asset_id": 12345, "storage_location_id": 12345, "quantity": 10, "is_increase": true, "description": "Additional printed brochures arrived" }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.post( "https://api.exhibitday.com/v1/assets/inventory_adjustments", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"asset_id": 12345, "storage_location_id": 12345, "quantity": 10, "is_increase": True, "description": "Additional printed brochures arrived"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PostAsync("https://api.exhibitday.com/v1/assets/inventory_adjustments", JsonContent.Create(new { asset_id = 12345, storage_location_id = 12345, quantity = 10, is_increase = true, description = "Additional printed brochures arrived" })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/inventory_adjustments")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("POST", HttpRequest.BodyPublishers.ofString("{\"asset_id\":12345,\"storage_location_id\":12345,\"quantity\":10,\"is_increase\":true,\"description\":\"Additional printed brochures arrived\"}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"asset_id":12345,"storage_location_id":12345,"quantity":10,"is_increase":true,"description":"Additional printed brochures arrived"}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/inventory_adjustments') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"asset_id":12345,"storage_location_id":12345,"quantity":10,"is_increase":true,"description":"Additional printed brochures arrived"}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/assets/inventory_adjustments", strings.NewReader("{\"asset_id\":12345,\"storage_location_id\":12345,\"quantity\":10,\"is_increase\":true,\"description\":\"Additional printed brochures arrived\"}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): POST /v1/assets/inventory_adjustments - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "exhibitday_url": "https://www.exhibitday.com/Workspace/Asset/98765?aid=12345&reservation_id=23456", "id": 23456, "asset_id": 12345, "asset_name": "Printed brochures", "storage_location_id": 12345, "storage_location_name": "Main Warehouse", "effective_date": "2030-01-02", "return_date": null, "quantity_adjustment": 10, "quantity": 10, "is_increase": true, "is_quantity_editable": true, "description": "Additional printed brochures arrived", "shipping_logistics_id": 1, "is_flagged": false, "is_starred": false, "is_checked": false, "inventory_adjustment_created_timestamp": "2030-01-01T17:00:00Z" } ``` ### Update an Inventory Adjustment `PATCH https://api.exhibitday.com/v1/assets/inventory_adjustments` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=inventory-adjustments#patch-v1-assets-inventory_adjustments Updates a manual inventory adjustment for a Collateral/Multi-quantity item. An adjustment increases or decreases the quantity at a Storage Location. Its Effective Date determines when that change affects inventory totals. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the manual inventory adjustment you want to update. | | | effective_date | Date | No | The date the adjustment affects inventory. Omit to keep the saved date and any previously stored time of day. | YYYY-MM-DD. | | storage_location_id | Number | No | The ID of the Storage Location for the adjustment. To move the adjustment, choose another Storage Location in your workspace. | | | quantity | Number | No | The corrected number of units for this adjustment. Use `is_increase` to set the direction. | Whole number from 1 through 2,147,483,647. | | is_increase | Boolean | No | Set to `true` for an inventory increase or `false` for a decrease. Omit to keep the saved direction. | | | description | String | No | The reason for the adjustment, in plain text. An older description that exceeds a limit can retain its existing length. | Plain text, up to 1,000 characters. Line breaks are preserved. GET returns the description as text: HTML-encoded, with line breaks as
. | | shipping_logistics_id | Number | No | The Shipping Logistics choice. Omit to keep the current choice. | Allowed values: `1` (Unspecified) \| `2` (Advance Warehouse) \| `3` (Direct Shipment) \| `4` (Other) | | is_flagged | Boolean | No | Set to `true` to flag the adjustment or `false` to remove the flag. | | | is_starred | Boolean | No | Set to `true` to star the adjustment or `false` to remove the star. | | | is_checked | Boolean | No | Set to `true` to mark the adjustment as checked or `false` to uncheck it. | | | expected_revision | String | No | The record_revision returned when you retrieved this record. Include it to avoid overwriting someone else's changes. Omit it to skip this check. | | | $ignore_params_with_empty_values | Boolean | No | Set to `true` to ignore editable fields sent as JSON `null`. The string `"null"` still requests a clear and is rejected. | Default: false. | #### Changing adjustment values Include `id` in every request. Send only the editable fields you want to change. For example, to correct an increase from 12 units to 10, send `quantity=10` and omit `is_increase`. The adjustment will add 10 units instead of 12. Omitting an editable field or sending a blank value keeps its saved value. These fields cannot be cleared. If a description contains a comma, send it in a JSON body, query string or form field. Inventory totals may be negative. A change is rejected if a resulting total falls outside the supported whole-number range. An older adjustment whose saved quantity is outside the editing range cannot be updated. Existing adjustments on an archived item can still be corrected. Shared-Asset access does not grant access to the owner’s manual inventory. #### Updating an older adjustment with a return date `GET /v1/assets/inventory_adjustments/info` can return a `return_date` for older adjustments. On that date, the adjustment's effect on inventory is reversed. **Editing one of these adjustments removes its scheduled reversal.** This also applies if you change only the flag, star or checked status. If every value you send matches the saved values and there is no other effective change, the API keeps the reversal and makes no change to the saved dates, formatting, revision or history. #### Avoiding conflicting updates 1. Retrieve the adjustment with `GET /v1/assets/inventory_adjustments/info` and set `$include_record_revision=true`. 2. In your PATCH request, set `expected_revision` to the exact `record_revision` returned by GET. #### Handling revisions and conflicts The revision covers the adjustment fields, formatting saved in ExhibitDay, Logistical Records and related-item links. Attachment metadata and file contents are outside its scope. If any covered value differs from what you read, the API returns HTTP `409` with `error_code=record_changed` and saves nothing. Retrieve the adjustment again, review its current values and decide whether to retry. A value that changed and was later changed back still matches. When you send `expected_revision`, a successful response includes the adjustment’s current `record_revision`. A blank, null or malformed revision, or different revision values sent in the same request, returns HTTP `400` with `error_code=invalid_request`. #### Retrying a request If you cannot tell whether the update succeeded, retrieve the adjustment and check the item’s inventory before retrying. The API does not retry automatically. This endpoint ignores the `Idempotency-Key` header. A history-writing failure does not undo an update that was saved. Updating a manual inventory adjustment sends no follower or business notifications. Example — curl: ```bash curl -X PATCH "https://api.exhibitday.com/v1/assets/inventory_adjustments" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"id\":12345,\"description\":\"Additional printed brochures arrived\"}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/inventory_adjustments", { method: "PATCH", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "id": 12345, "description": "Additional printed brochures arrived" }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.patch( "https://api.exhibitday.com/v1/assets/inventory_adjustments", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"id": 12345, "description": "Additional printed brochures arrived"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PatchAsync("https://api.exhibitday.com/v1/assets/inventory_adjustments", JsonContent.Create(new { id = 12345, description = "Additional printed brochures arrived" })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/inventory_adjustments")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("PATCH", HttpRequest.BodyPublishers.ofString("{\"id\":12345,\"description\":\"Additional printed brochures arrived\"}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"id":12345,"description":"Additional printed brochures arrived"}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/inventory_adjustments') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"id":12345,"description":"Additional printed brochures arrived"}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/assets/inventory_adjustments", strings.NewReader("{\"id\":12345,\"description\":\"Additional printed brochures arrived\"}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): PATCH /v1/assets/inventory_adjustments - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Inventory Adjustment updated.", "errors": [] } ``` ### Delete an Inventory Adjustment `DELETE https://api.exhibitday.com/v1/assets/inventory_adjustments` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=inventory-adjustments#delete-v1-assets-inventory_adjustments Permanently removes a manual Collateral inventory adjustment. This removes its quantity effect from inventory totals, together with any older scheduled reversal. Review the entry before deleting it; this action cannot be undone. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the manual adjustment to remove. | Its Collateral/Multi-quantity item is found automatically. Event and Capital reservation IDs are not accepted. | | expected_revision | String | No | The record_revision returned when you retrieved this adjustment. Include it to delete the adjustment only if it is unchanged since that read. Omit it to skip this check. | | #### What deletion changes The adjustment and its formatting saved in ExhibitDay, Logistical Records, related-item links and removable attachments are removed. Linked Tasks or other records themselves remain. Removing an increase removes the stock it added; removing a decrease removes that reduction. Any inherited return date and its scheduled reversal are removed as well. A return date is not confirmation of a physical return. Existing adjustments on archived items can be removed. Older adjustments outside the editing range can also be removed if the resulting totals stay in range. The API refuses deletion if a resulting stored total would fall outside the supported whole-number range. Negative totals are permitted. #### Content that cannot be removed The key must be allowed to remove the entry’s associated content. If content cannot safely be removed, the action refuses the request without deleting the adjustment. It does not grant access to another workspace’s Event information. Review any restricted content in ExhibitDay with an authorized account before deciding how to proceed. A stored file still referenced elsewhere is kept; later file-cleanup failure does not undo a confirmed deletion. #### Deleting only an unchanged adjustment If the adjustment, its formatting saved in ExhibitDay, Logistical Records or related-item links changed since your read, the API returns HTTP `409` with `error_code=record_changed` and deletes nothing. Retrieve the adjustment again and decide whether to delete it. A value that changed and was later changed back still matches. A blank, null or malformed revision, or different revision values sent in the same request, returns HTTP `400` with `error_code=invalid_request`. Omit `expected_revision` to delete without this check. A successful deletion returns no new revision, because the adjustment no longer exists. 1. Retrieve the adjustment with `GET /v1/assets/inventory_adjustments/info` and set `$include_record_revision=true`. 2. In your DELETE request, set `expected_revision` to the exact `record_revision` returned by GET. #### Retrying a deletion This method ignores the `Idempotency-Key` header. If the save outcome cannot be confirmed, retrieve the adjustment and check inventory before retrying. The API does not automatically repeat the deletion. A confirmed deletion is added to history. A history-writing failure does not undo it. Deletion sends no follower or business notifications. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/assets/inventory_adjustments?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/inventory_adjustments?" + new URLSearchParams({ "id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/assets/inventory_adjustments", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/assets/inventory_adjustments?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/inventory_adjustments?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/inventory_adjustments?id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/assets/inventory_adjustments?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/assets/inventory_adjustments - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Inventory Adjustment removed.", "errors": [] } ``` ## Assets - Availability Check an Asset's available dates and quantities before reserving it. Documentation page: https://api.exhibitday.com/Help/V1?epf=5&topic=availability ### Retrieve Asset Reservation Availability `GET https://api.exhibitday.com/v1/assets/availability` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=availability#get-v1-assets-availability Checks an Active Asset before you reserve it. For Capital, check a proposed checkout-to-return period against its reservation policy. For Collateral, check how much is available on a chosen date. This request does not reserve anything. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | asset_id | Number | Yes | The ID of the Asset to check. | | | asset_type_id | Number | Yes | The type of Asset whose availability to check. Capital tracks one item; Collateral tracks quantities. Supply it even when you know the Asset ID. | Allowed values: `1` (Capital) \| `2` (Collateral) | | start_date | Date | When asset_type_id=1 | The first day of the proposed Capital reservation. | YYYY-MM-DD, without a time. Supply with end_date; omit for Collateral. | | end_date | Date | When asset_type_id=1 | The return date of the proposed Capital reservation. | YYYY-MM-DD, on or after start_date. Both endpoints are included. Omit for Collateral. | | as_of_date | Date | No | The date on which to check Collateral quantity. | YYYY-MM-DD. Default: today in your workspace time zone. Omit for Capital. | | storage_location_id | Number | No | A Storage Location to restrict the Collateral quantity check to. | Optional. It must belong to the Asset’s owner. Omit to include the applicable locations. Not accepted for Capital. | | excluded_reservation_id | Number | No | The existing reservation being edited, to exclude from this check. | It must belong to this Asset and be readable by your workspace. A manual inventory adjustment is not accepted. For Collateral, both its checkout and scheduled return are excluded. | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` | | $on_error_return_empty_result | Boolean | No | Whether to return an empty result for validation or not-found errors. | Default: false. True returns {} or [] with HTTP 200. Authentication, rate limits and unexpected failures keep their normal errors. | | $include_error_list_in_response_message | Boolean | No | Whether to add validation errors to the error message. | Default: false. | | If-None-Match | String | No | An ETag from an earlier response to this GET. | Optional HTTP header. If the successful response still matches, the API returns HTTP 304 with no response body. | #### Choosing the availability check - For Capital, supply asset_type_id=1 and both start_date and end_date. Do not send as_of_date or storage_location_id. - For Collateral, supply asset_type_id=2. Optionally choose as_of_date and storage_location_id. Do not send start_date or end_date. - When editing an existing reservation, send its excluded_reservation_id so its current allocation is not counted against the check. #### Understanding the reservation policy - `1` — Strict: every day of an existing Capital reservation is blocked, including checkout and return. - `2` — Moderate: another reservation can use the checkout and return days; only the days between them are blocked. A one- or two-day reservation therefore blocks no days. - `3` — Liberal: overlapping reservations are allowed. Collateral always uses this policy. #### Reading Capital availability The response reports both overlapping reservations and those that conflict under the Asset’s policy. Liberal permits overlap; Strict and Moderate apply the different day rules above. When you exclude an existing reservation and keep the same calendar dates, the existing save rule permits that unchanged period. The response identifies this with is_requested_period_unchanged. #### Reading Collateral quantities Available quantity includes manual increases and decreases and Event reservations. A scheduled return reverses its reservation quantity from that date onward. Existing negative inventory is reported as recorded. Projected Future Balance includes increases and decreases that have not been returned, including future entries. A supplied storage_location_id restricts the totals to that location. The Collateral response includes Storage Location choices. For Capital, storage_locations is null. #### Access, privacy and the later save The Asset must be Active and either in your workspace or currently shared with it. Reading an old reservation does not make an unshared Asset eligible for a new reservation. For shared Assets, the location ID, name and short address are returned to help choose a location. Private owner contacts, unrelated Asset details, other Events’ reservations and costs are withheld. Availability and access are checked again when the reservation is saved. This result provides no edit revision and does not guarantee a later save will succeed. This read does not record a return or change inventory. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/assets/availability?asset_id=12345&asset_type_id=1&start_date=2030-01-02&end_date=2030-01-04" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/availability?" + new URLSearchParams({ "asset_id": "12345", "asset_type_id": "1", "start_date": "2030-01-02", "end_date": "2030-01-04" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/assets/availability", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"asset_id": 12345, "asset_type_id": 1, "start_date": "2030-01-02", "end_date": "2030-01-04"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/assets/availability?asset_id=12345&asset_type_id=1&start_date=2030-01-02&end_date=2030-01-04"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/availability?asset_id=12345&asset_type_id=1&start_date=2030-01-02&end_date=2030-01-04")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/availability?asset_id=12345&asset_type_id=1&start_date=2030-01-02&end_date=2030-01-04') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/assets/availability?asset_id=12345&asset_type_id=1&start_date=2030-01-02&end_date=2030-01-04", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/assets/availability - HTTP 200 Illustrative response. ```json { "asset_id": 12345, "asset_type_id": 1, "is_advisory": true, "is_asset_owned_by_this_workspace": true, "start_date": "2030-01-02", "end_date": "2030-01-04", "as_of_date": null, "asset_reservation_policy_id": 1, "is_available_under_reservation_policy": true, "overlapping_reservation_count": 0, "policy_conflict_count": 0, "is_requested_period_unchanged": false, "quantity_available_in_storage": null, "projected_future_balance": null, "storage_locations": null } ``` ## Assets - Reservations Asset Reservations for Events: add, update and cancel them, see the cancellation options, and work with their file attachments. Documentation page: https://api.exhibitday.com/Help/V1?epf=5&topic=reservations ### Retrieve a Single Asset Reservation `GET https://api.exhibitday.com/v1/assets/reservations/info` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=reservations#get-v1-assets-reservations-info Retrieves one Asset reservation using its type and reservation ID. By default, it loads Capital Optional Accessories, eligible Logistical Records and readable attachment metadata. Set the corresponding hydration option to `false` when you do not need those details. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | asset_type_id | Number | Yes | The reservation's Asset type. Capital tracks one item; Collateral tracks quantities. Supply the type even when you know the reservation ID. | Allowed values: `1` (Capital) \| `2` (Collateral) | | id | Number | Yes | The reservation ID for the selected Asset type. | The current Asset and Event are determined automatically. No additional Asset or Event ID is needed. | | hydrate_optional_accessories | Boolean | No | Set to `false` to skip the Capital reservation’s Optional Accessories and quantities. | Default: true. Collateral has no Optional Accessories and returns an empty collection when this option is true. | | hydrate_logistical_records | Boolean | No | Set to `false` to skip the reservation’s Logistical Records. | Default: true when the feature is available; otherwise not loaded. Explicitly requesting true without access is refused. | | hydrate_attachment_metadata | Boolean | No | Set to `false` to skip the attachment metadata. | Default: true. Only files you can read are included; file contents are not downloaded. | | $include_record_revision | Boolean | No | Set to `true` to include a `record_revision` for checking a later update. | Default: false. The revision checks the complete reservation material, regardless of which optional collections you choose to load. | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` | | $on_error_return_empty_result | Boolean | No | Set to `true` to return an empty result for supported validation or not-found errors. | Default: false. Malformed inputs, authentication errors, rate limits, read conflicts and unexpected errors keep their error response. | | $include_error_list_in_response_message | Boolean | No | Set to `true` to include individual validation errors in the response message. | Default: false. The normal error response still includes its error list. | | If-None-Match | String | No | Send the ETag from an earlier response when checking whether this result changed. | Optional request header. A matching current result returns HTTP 304 with no body; reuse your earlier response. This header compares GET responses. It cannot prevent a conflicting update. | #### Reading the reservation The API derives the reservation’s current Asset and Event and checks your access. You do not need to provide extra Asset or Event IDs. A missing or inaccessible reservation normally returns HTTP `404`. A hydration option set to false leaves that collection unloaded with a null value. A requested collection with no applicable or readable items is empty. Skipping a collection does not change the reservation. #### Understanding reservation dates and quantity For Capital, Reservation Date is the checkout date and quantity is always 1. The response also preserves the saved Return Date. For Collateral, Reservation Date is when the signed inventory change takes effect. `quantity` gives its size without a sign; `quantity_adjustment` preserves the signed change. `return_date` is the scheduled Return to Storage / Check-in date, when that quantity change reverses. It does not confirm a physical return. An unknown Collateral return remains unknown. Manual inventory increases and decreases without an Event use the inventory-adjustment methods. Older unsupported quantities remain readable and are marked with `is_quantity_editable=false`. #### Shared Assets and private details For a borrowed Asset, access to a reservation through your Event can remain available after the Asset is unshared. This does not grant access to the owner’s other Assets, private storage details or unrelated reservations. When your shared Asset is reserved for another workspace’s Event, you can read that Event’s name, the reservation notes and, when requested, its Logistical Records, as in the Assets area. `event_id` is null because the Event belongs to the other workspace, so Event methods can’t open it with this key; `exhibitday_url` opens the reservation in your Assets area. A reservation on your own Event keeps its `event_id`. Each Logistical Record’s `logistical_record_created_by` is a User Lite object; someone who is not a current member of your workspace, such as the other workspace’s staff, is shown by name only, with no `id` or email. Each attachment still needs its own file-origin permission. Reading the current reservation does not grant access to every file, and moving the reservation does not change a file’s original Event rights. Attachment metadata contains the file ID, original filename and added time, not file bytes, a storage key or a permanent public download link. Notes are returned as text: HTML-encoded, with line breaks as
. Formatting added in ExhibitDay is not returned. #### Getting a revision before an update 1. Retrieve this Info response with `$include_record_revision=true`. 2. Send that exact `record_revision` as `expected_revision` when updating or deleting one of this reservation’s Logistical Records. #### What $include_record_revision covers Set `$include_record_revision=true` to receive `record_revision` in this GET response. It covers the reservation fields, Capital Optional Accessory quantities, all Logistical Records, note formatting saved in ExhibitDay and related-item links. Attachment metadata and file contents are excluded. Its scope does not shrink when you skip a hydrated collection. If you own the Asset and the reservation is on another workspace’s Event, you still get a `record_revision`. Use it for the changes you can make there, such as dates, flags and shipping logistics. If the reservation’s Event is yours but its Assets tab is hidden, the request returns HTTP `400` with a message naming the tab. The revision grants no additional access. Without this option, no `record_revision` is returned. An ETag for the GET response is separate from the edit revision. If concurrent changes prevent the read, HTTP `409` with `error_code=record_changed` means you should retrieve the reservation again. #### Checking whether a response changed Normal API-key and access checks still apply. This header compares the response; it does not authorize access or protect an update. 1. Save the response body and its `ETag` header from an earlier GET. 2. Repeat the same GET, including the same filters and response options, with that ETag in the `If-None-Match` header. 3. If the response is HTTP `304`, keep using your saved body. If it is HTTP `200`, use the new body and ETag. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/assets/reservations/info?asset_type_id=1&id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/reservations/info?" + new URLSearchParams({ "asset_type_id": "1", "id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/assets/reservations/info", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"asset_type_id": 1, "id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/assets/reservations/info?asset_type_id=1&id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/reservations/info?asset_type_id=1&id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/reservations/info?asset_type_id=1&id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/assets/reservations/info?asset_type_id=1&id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/assets/reservations/info - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "id": 12345, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=45678&riType=5&riSub=1&riId=12345", "asset_type_id": 1, "asset_id": 12345, "asset_name": "Display stand", "is_asset_owned_by_this_workspace": true, "event_id": 45678, "event_name": "Spring industry show", "reservation_date": "2030-01-15", "return_date": "2030-01-16", "storage_location_id": 2345, "storage_location_name": "Main Warehouse", "quantity": 1, "quantity_adjustment": null, "is_quantity_editable": true, "notes": "Pack with the setup guide.", "shipping_logistics_id": 1, "is_flagged": false, "is_starred": false, "is_checked": false, "asset_reservation_created_timestamp": "2030-01-02T17:00:00Z", "optional_accessories": [ { "id": 14001, "optional_accessory_id": 13001, "name": "Transport case", "quantity": 1 }, { "id": 14002, "optional_accessory_id": 13002, "name": "Spotlight", "quantity": 2 } ], "logistical_records": [ { "id": 15001, "asset_type_id": 1, "reservation_id": 12345, "asset_id": 12345, "record_type_id": 1, "record_type": "Prepped", "record_date": "2030-01-14", "description": "Packed and ready for collection.", "logistical_record_created_by": { "id": null, "first_name": "ExhibitDay", "last_name": "API", "display_name": "ExhibitDay API", "email": null, "type": null, "workspace_role": null, "is_active": true }, "logistical_record_created_timestamp": "2030-01-02T17:00:00Z" }, { "id": 15002, "asset_type_id": 1, "reservation_id": 12345, "asset_id": 12345, "record_type_id": 2, "record_type": "Sent", "record_date": "2030-01-15", "description": "Collected by the carrier.", "logistical_record_created_by": { "id": null, "first_name": "ExhibitDay", "last_name": "API", "display_name": "ExhibitDay API", "email": null, "type": null, "workspace_role": null, "is_active": true }, "logistical_record_created_timestamp": "2030-01-02T17:00:00Z" } ], "attachments": [ { "id": 16001, "filename": "packing-list.pdf", "attachment_created_timestamp": "2030-01-02T17:00:00Z" }, { "id": 16002, "filename": "setup-guide.pdf", "attachment_created_timestamp": "2030-01-02T17:00:00Z" } ], "related_items": [ { "id": 5551, "related_item_id": 67890, "related_item_exhibitday_url": "https://www.exhibitday.com/Workspace/TaskView/98765?tid=67890", "related_item_type_id": 1, "related_item_type": "Task", "related_item_asset_type_id": null, "related_item_name": "Confirm booth graphics with the printer", "related_item_created_timestamp": "2030-01-10T14:03:00Z" }, { "id": 5552, "related_item_id": 45678, "related_item_exhibitday_url": "https://www.exhibitday.com/Workspace/RelatedItemView/98765?typeId=4&subTypeId=0&rid=45678", "related_item_type_id": 4, "related_item_type": "Shipment", "related_item_asset_type_id": null, "related_item_name": "Booth crates to convention center", "related_item_created_timestamp": "2030-01-10T14:03:00Z" } ] } ``` ### Retrieve Asset Reservations `GET https://api.exhibitday.com/v1/assets/reservations` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=reservations#get-v1-assets-reservations Retrieves Asset reservations across your workspace. Choose Capital or Collateral with the required `asset_type_id`. Use `filter_by_event_id` to narrow the list to one Event, or omit it for all matching reservations. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | asset_type_id | Number | Yes | The reservation's Asset type. Capital tracks one item; Collateral tracks quantities. Supply the type even when you know the reservation ID. | Allowed values: `1` (Capital) \| `2` (Collateral) | | filter_by_reservation_id | Number | No | Only return this reservation for the selected type. | | | filter_by_asset_id | Number | No | Only return reservations for this Asset. | | | filter_by_event_id | Number | No | Return records for this Event only. Omit for all readable Events in your workspace. | | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | | $on_error_return_empty_result | Boolean | No | Set to `true` to return an empty collection for supported validation errors. | Default: false. No matching reservations normally returns an empty collection. Other errors keep their normal status. | | $include_error_list_in_response_message | Boolean | No | Set to `true` to include individual validation errors in the response message. | Default: false. The normal error response still includes its error list. | | hydrate_optional_accessories | Boolean | No | Set to `true` to load Optional Accessories and quantities for each Capital reservation. | Default: false. Collateral has no Optional Accessories; when requested, its collection is empty. | | hydrate_logistical_records | Boolean | No | Set to `true` to load Logistical Records for each returned reservation. | Default: false. Your workspace needs the feature. Explicitly requesting it without access is refused. | | hydrate_attachment_metadata | Boolean | No | Set to `true` to load attachment metadata you can read for each returned reservation. | Default: false. This does not download file contents. | | filter_by_shipping_logistics_id | Number | No | Only return reservations with this Shipping Logistics ID. | Standard values: 1 (Unspecified), 2 (Advance Warehouse), 3 (Direct Shipment), 4 (Other). | | filter_by_is_flagged | Boolean | No | Only return reservations matching this flag status. | `true` selects flagged; `false` selects unflagged. Omit to include both. | | filter_by_is_starred | Boolean | No | Only return reservations matching this star status. | `true` selects starred; `false` selects unstarred. Omit to include both. | | filter_by_is_checked | Boolean | No | Only return reservations matching this checked status. | `true` selects checked; `false` selects unchecked. Omit to include both. | | filter_by_reservation_date_greater_than_or_equal_to | Date | No | Only return reservations dated on or after this date. | Use `YYYY-MM-DD`. This is Capital checkout or the Collateral inventory Effective Date. | | filter_by_reservation_date_smaller_than_or_equal_to | Date | No | Only return reservations dated on or before this date. | Use `YYYY-MM-DD`. It must not precede the lower date when both are supplied. | | filter_by_reservation_return_date_greater_than_or_equal_to | Date | No | Only return Capital reservations with a saved Return Date on or after this date. | Capital only. Use `YYYY-MM-DD`. An unknown return does not match. | | filter_by_reservation_return_date_smaller_than_or_equal_to | Date | No | Only return Capital reservations with a saved Return Date on or before this date. | Capital only. Use `YYYY-MM-DD`. An unknown return does not match. | | filter_by_reservation_overlaps_start_date | Date | With the overlap end date | The first date of a period that a Capital reservation must overlap. | Capital only. Use `YYYY-MM-DD`. Supply both overlap dates. | | filter_by_reservation_overlaps_end_date | Date | With the overlap start date | The last date of the overlap period. | Capital only. Use `YYYY-MM-DD`, on or after the overlap start. An unknown return does not match. | | $limit | Number | No | The maximum number of matching reservations to return. | One positive whole number. Omit to return all matches after `$offset`; there is no fixed page-size cap. | | $offset | Number | No | The number of matching reservations to skip. | Default: 0. Send a nonnegative whole number. | | $result_sort | String | No | Order reservations by reservation date, creation time or ID. Omit for reservation date ascending. Date and time ties use ID ascending. Unsupported values are refused. | Allowed values: `reservation_date_asc` \| `reservation_date_desc` \| `create_timestamp_asc` \| `create_timestamp_desc` \| `id_asc` \| `id_desc` | | hydrate_related_items | Boolean | No | Set to true to include each record's related_items: the Tasks and items linked to it, with the key to use when adding or removing a link. Omit it or send false to leave related_items out of list results. Single-record GETs always include related_items. | Default: false. | | If-None-Match | String | No | Send the ETag from an earlier response when checking whether this result changed. | Optional request header. A matching current result returns HTTP 304 with no body; reuse your earlier response. This header compares GET responses. It cannot prevent a conflicting update. | #### What the list covers The list includes reservations against your workspace's Assets and readable reservations on its Events for borrowed Assets. A borrowed reservation can remain readable after sharing is removed; this does not open the other workspace's Asset list, storage details or other reservations. Capital Other Purpose reservations can have no Event. Manual Collateral inventory increases and decreases use the Inventory Adjustments methods. Reservations keep the Event name and notes shown in the Assets area, including when a shared Asset is reserved for another workspace’s Event. For that Event, `event_id` is null because it belongs to the other workspace, and Event methods can't open it with this key. Your own Events keep their IDs. #### Choosing and filtering reservations Set `asset_type_id=1` for Capital or `2` for Collateral. The type is always required because the two kinds can have the same reservation ID. Omit `filter_by_event_id` for the workspace list. Supply it to match one of your workspace's Events; a missing or inaccessible Event has no matching rows. The filter does not grant access. Unrecognized parameters are ignored and listed in the `X-API-Warnings` response header. The existing Asset, reservation, date, Shipping Logistics and marker filters combine with AND. An explicit false marker matches unmarked reservations and is not treated as omission. #### Understanding dates and quantity For Capital, Reservation Date is checkout and Return Date is the end of that reservation. For Collateral, Reservation Date is when the quantity change takes effect; a scheduled Return to Storage date is when its quantity effect reverses, not confirmation of a physical return. An unknown Collateral return date remains unknown. Collateral return-date and overlap filters are not supported. Capital overlap filters require both inclusive endpoints. #### Including details Optional Accessories, Logistical Records and attachment metadata are off by default for this collection. Their hydrate options add details only to the selected page. Optional Accessories apply to Capital; Collateral returns an empty collection when that detail is requested. Logistical Records require your workspace's feature. Explicitly requesting them without access returns an error. Attachment metadata follows each file's owning workspace and original Event. Moving a reservation does not grant access to every file. No file content, storage key or permanent download link is included. Notes are returned as text: HTML-encoded, with line breaks as
. Formatting added in ExhibitDay is not returned. #### Reading pages and handling changes Filters and the full count are applied before paging and optional details. The default is Reservation Date ascending, then ID ascending; `$result_sort` retains its existing date, creation-time and ID choices. Omit `$limit` for all remaining matches or use it with `$offset` for successive pages. Current API access is checked even for an empty result. A selected record changing while the page is being read can return HTTP `409`; retrieve the list again. These reads do not update reservations, tags or notifications. #### Events with a hidden Assets tab Records on Events whose Assets tab is hidden are not listed. If filter_by_event_id names such an Event, the response is HTTP 200 with no records for it and a warning that names the tab and the Event. #### Hidden or locked Assets tab Reservations on Events in your workspace whose Assets tab is hidden are left out of this list. If filter_by_event_id names such an Event, the response is HTTP 200 with no records for it and a warning that names the tab and the Event. Show the tab in ExhibitDay to list them. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/assets/reservations?asset_type_id=1" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/reservations?" + new URLSearchParams({ "asset_type_id": "1" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/assets/reservations", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"asset_type_id": 1}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/assets/reservations?asset_type_id=1"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/reservations?asset_type_id=1")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/reservations?asset_type_id=1') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/assets/reservations?asset_type_id=1", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/assets/reservations - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "records_found": 2, "total_records": 2, "has_more": false, "list_type": "asset_reservation", "list_data": [ { "id": 12345, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=23456&riType=5&riSub=1&riId=12345", "asset_type_id": 1, "asset_id": 34567, "asset_name": "Display stand", "is_asset_owned_by_this_workspace": true, "event_id": 23456, "event_name": "Spring industry show", "reservation_date": "2030-01-15", "return_date": "2030-01-16", "storage_location_id": null, "storage_location_name": null, "quantity": 1, "quantity_adjustment": null, "is_quantity_editable": true, "notes": "Pack with the setup guide.", "shipping_logistics_id": 1, "is_flagged": false, "is_starred": false, "is_checked": false, "asset_reservation_created_timestamp": "2030-01-02T12:00:00Z", "optional_accessories": null, "logistical_records": null, "attachments": null }, { "id": 12346, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=23457&riType=5&riSub=1&riId=12346", "asset_type_id": 1, "asset_id": 34568, "asset_name": "Banner kit", "is_asset_owned_by_this_workspace": true, "event_id": 23457, "event_name": "Autumn industry show", "reservation_date": "2030-02-15", "return_date": "2030-02-16", "storage_location_id": null, "storage_location_name": null, "quantity": 1, "quantity_adjustment": null, "is_quantity_editable": true, "notes": "Bring the spare display materials.", "shipping_logistics_id": 1, "is_flagged": false, "is_starred": false, "is_checked": false, "asset_reservation_created_timestamp": "2030-01-03T12:00:00Z", "optional_accessories": null, "logistical_records": null, "attachments": null } ] } ``` ### Add an Asset Reservation `POST https://api.exhibitday.com/v1/assets/reservations` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=reservations#post-v1-assets-reservations Reserves an individual Capital Asset or a quantity of Collateral. Use an Event for Collateral or borrowed Assets. A Capital Asset in your workspace can also be reserved for another purpose, described in its notes. The response includes exhibitday_url, the record's page in ExhibitDay. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | asset_type_id | Number | Yes | The type of Asset to reserve. Capital tracks one item; Collateral tracks quantities. Supply this with the Asset ID. | Allowed values: `1` (Capital) \| `2` (Collateral) | | asset_id | Number | Yes | The ID of the Asset to reserve. | The Asset must be Active and either in your workspace or currently shared with it. | | reservation_date | Date | Yes | The checkout date. | YYYY-MM-DD. | | event_id | Number | For Collateral, or a borrowed Capital Asset | The Event for the new reservation. | Use an Event in your workspace. For a Capital Asset in your workspace, omit it to make an Other Purpose reservation and describe that purpose in notes. | | return_date | Date | For Capital, or Collateral with a known return date | The reservation’s return date. | YYYY-MM-DD, on or after checkout. Required for Capital. For Collateral, omit this date or send JSON null when the return is unknown. | | storage_location_id | Number | When asset_type_id=2 | The Storage Location from which to reserve Collateral. | Collateral only. Use a Storage Location that belongs to the Asset’s owner. | | quantity | Number | When asset_type_id=2 | The quantity of Collateral to reserve. | Collateral only. A whole number from 1 through 2,147,483,647. The matching inventory deduction is saved with the reservation. | | shipping_logistics_id | Number | No | The Shipping Logistics choice. Omit for Unspecified. | Allowed values: `1` (Unspecified) \| `2` (Advance Warehouse) \| `3` (Direct Shipment) \| `4` (Other) | | notes | String | For an Other Purpose Capital reservation | Reservation Notes, or the description of an Other Purpose reservation. | Plain text, up to 1,000 characters. HTML tags are removed and line breaks are preserved. A Capital reservation without an Event needs a purpose, so its notes cannot be blank. | | is_flagged | Boolean | No | Whether to flag this reservation. | Boolean. Default: false. | | is_starred | Boolean | No | Whether to star this reservation. | Boolean. Default: false. | | is_checked | Boolean | No | Whether to mark this reservation as checked. | Boolean. Default: false. | | optional_accessories | JSON object/list | No | The complete Optional Accessory selection for a Capital reservation. | Capital only. Send a JSON array such as [{"optional_accessory_id":12345,"quantity":1}]. IDs must be unique and quantities whole numbers of zero or more. Zero leaves that accessory unselected. Omit to use current defaults; [] selects none. Current choices and quantity limits are checked when saving. | | notify_new_reservation | Boolean | No | Whether to notify eligible Storage Location followers. | Default: true. Existing recipient access and notification preferences apply. | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` | | Idempotency-Key | String | No | A unique key for safely repeating this create request. | Optional HTTP header: 1–255 visible ASCII characters without spaces. Reuse it only for the same request; the replay window is 24 hours. | Declared schema for `optional_accessories` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "array", "items": { "type": "object", "additionalProperties": false, "properties": { "optional_accessory_id": { "type": "integer", "format": "int64", "minimum": 1.0, "maximum": 9223372036854775807.0 }, "quantity": { "type": "integer", "format": "int32", "minimum": 0.0, "maximum": 2147483647.0 } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "required": [ "optional_accessory_id", "quantity" ] }, "maxItems": 2147483647, "x-unique-item-key": [ "optional_accessory_id" ], "nullable": false, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": [ { "optional_accessory_id": 12345, "quantity": 1 } ] } ``` #### Creating the reservation 1. Supply asset_type_id, asset_id and reservation_date. 2. For Capital, supply return_date. For Collateral, also supply an Event, Storage Location and quantity. For Collateral, omit return_date or send JSON null when the return is unknown. 3. Optionally choose Shipping Logistics, notes, markers, Optional Accessories and related-item links. Dates, quantities and these choices are saved together. 4. Keep the returned typed reservation ID for future reads or changes. This request does not add files or Logistical Records. #### How the Asset can be reserved Capital Assets are individual reusable items, such as a display monitor. Collateral is tracked in quantities, such as brochures. - Strict blocks every day of an existing Capital reservation, including checkout and return. - Moderate permits another reservation on checkout and return days and blocks only the days between them. A one- or two-day reservation blocks no days. - Liberal permits overlap. Collateral uses its dated inventory movements and scheduled returns. An availability check does not guarantee that a later save will succeed. #### Archived or unshared Assets A new reservation needs an Active Asset that your workspace owns or that is currently shared with it. Otherwise the request returns HTTP 409 with error_code=invalid_request and error_params lists asset_id; the message names the Asset and how to resolve it. #### Choosing Optional Accessories Optional Accessories apply only to Capital. When omitted, current selectable definitions contribute their saved default quantities. Send an explicit list to choose a different complete selection, or [] to choose none. New selections use current choices and quantity limits. A saved default or existing historical quantity can have a specific legacy exception; it is checked against the current reservation editor rather than silently reduced. #### Repeating the create safely Use the optional Idempotency-Key header when repeating the same create request. Keep both the key and request unchanged. A replay does not make another reservation or send the followers another copy of the same notification. #### Sending values and handling errors Send notes containing commas through JSON, a query string or a form field. An inaccessible or missing typed reservation can return HTTP 404. HTTP 409 with error_code=record_changed means the reservation or its content changed or could not be prepared safely; retrieve it again before deciding whether to retry. Other allocation or cancellation conflicts can return error_code=invalid_request. No automatic retry is performed. #### History and notifications after saving A confirmed change is recorded in history. Notifications are sent afterward to eligible Storage Location followers, subject to their existing access and preferences. Delivery or file-cleanup failure does not undo a saved reservation. If the save outcome could not be confirmed, check the current reservation and inventory before deciding whether to repeat the action. Do not assume the server rolled it back. #### Hidden or locked Assets tab If the reservation's Event is in your workspace and its Assets tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash curl -X POST "https://api.exhibitday.com/v1/assets/reservations" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"asset_type_id\":1,\"asset_id\":12345,\"event_id\":12345,\"reservation_date\":\"2030-01-02\",\"return_date\":\"2030-01-04\",\"notes\":\"Equipment for the demonstration\"}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/reservations", { method: "POST", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "asset_type_id": 1, "asset_id": 12345, "event_id": 12345, "reservation_date": "2030-01-02", "return_date": "2030-01-04", "notes": "Equipment for the demonstration" }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.post( "https://api.exhibitday.com/v1/assets/reservations", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"asset_type_id": 1, "asset_id": 12345, "event_id": 12345, "reservation_date": "2030-01-02", "return_date": "2030-01-04", "notes": "Equipment for the demonstration"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PostAsync("https://api.exhibitday.com/v1/assets/reservations", JsonContent.Create(new { asset_type_id = 1, asset_id = 12345, event_id = 12345, reservation_date = "2030-01-02", return_date = "2030-01-04", notes = "Equipment for the demonstration" })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/reservations")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("POST", HttpRequest.BodyPublishers.ofString("{\"asset_type_id\":1,\"asset_id\":12345,\"event_id\":12345,\"reservation_date\":\"2030-01-02\",\"return_date\":\"2030-01-04\",\"notes\":\"Equipment for the demonstration\"}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"asset_type_id":1,"asset_id":12345,"event_id":12345,"reservation_date":"2030-01-02","return_date":"2030-01-04","notes":"Equipment for the demonstration"}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/reservations') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"asset_type_id":1,"asset_id":12345,"event_id":12345,"reservation_date":"2030-01-02","return_date":"2030-01-04","notes":"Equipment for the demonstration"}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/assets/reservations", strings.NewReader("{\"asset_type_id\":1,\"asset_id\":12345,\"event_id\":12345,\"reservation_date\":\"2030-01-02\",\"return_date\":\"2030-01-04\",\"notes\":\"Equipment for the demonstration\"}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): POST /v1/assets/reservations - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "id": 23456, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=12345&riType=5&riSub=1&riId=23456", "asset_type_id": 1, "asset_id": 12345, "asset_name": "Reusable display", "is_asset_owned_by_this_workspace": true, "event_id": 12345, "event_name": "Annual conference", "reservation_date": "2030-01-02", "return_date": "2030-01-04", "storage_location_id": null, "storage_location_name": "", "quantity": 1, "quantity_adjustment": null, "is_quantity_editable": true, "notes": "Equipment for the demonstration", "shipping_logistics_id": 1, "is_flagged": false, "is_starred": false, "is_checked": false, "asset_reservation_created_timestamp": "2030-01-01T12:00:00Z", "optional_accessories": [], "logistical_records": [], "attachments": [] } ``` ### Update an Asset Reservation `PATCH https://api.exhibitday.com/v1/assets/reservations` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=reservations#patch-v1-assets-reservations Changes a reservation’s dates, quantity, location, notes, markers, Optional Accessories or related-item links. Supply its Asset type and reservation ID; its Asset and current Event are found automatically. Send only the values you intend to change. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | asset_type_id | Number | Yes | The reservation's Asset type. Capital tracks one item; Collateral tracks quantities. Supply the type even when you know the reservation ID. | Allowed values: `1` (Capital) \| `2` (Collateral) | | id | Number | Yes | The reservation’s ID. | Use the ID for the selected Asset type. A manual Collateral inventory adjustment is not a reservation. The Asset and current Event are derived automatically. | | new_event_id | Number | No | A new Event for this reservation, or null for Other Purpose. | Only for an Asset in your workspace. The current Event is derived automatically. Capital may use null to become Other Purpose, with nonblank purpose notes. Collateral must remain with an Event. | | reservation_date | Date | No | A replacement checkout date. | YYYY-MM-DD. Omit to keep it. Resending the same calendar date preserves an older saved time of day. | | return_date | Date | No | The reservation’s return date. | YYYY-MM-DD, on or after checkout. Capital cannot clear it. Collateral can use null to remove its scheduled return. | | storage_location_id | Number | No | The Storage Location from which to reserve Collateral. | Collateral only. A changed location must belong to the Asset’s owner. | | quantity | Number | No | The quantity of Collateral to reserve. | Collateral only. A whole number from 1 through 2,147,483,647. This replaces the reserved quantity. | | shipping_logistics_id | Number | No | The Shipping Logistics choice. Omit to keep the current choice. | Allowed values: `1` (Unspecified) \| `2` (Advance Warehouse) \| `3` (Direct Shipment) \| `4` (Other) | | notes | String | No | Reservation Notes, or the description of an Other Purpose reservation. | Plain text, up to 1,000 characters. HTML tags are removed and line breaks are preserved. If older notes are already longer, their current length remains the maximum. Send null to clear notes unless the reservation requires a purpose. | | is_flagged | Boolean | No | Whether to flag this reservation. | Boolean. Omit to keep the current value. | | is_starred | Boolean | No | Whether to star this reservation. | Boolean. Omit to keep the current value. | | is_checked | Boolean | No | Whether to mark this reservation as checked. | Boolean. Omit to keep the current value. | | optional_accessories | JSON object/list | No | The complete Optional Accessory selection for a Capital reservation. | Capital only. Send a JSON array such as [{"optional_accessory_id":12345,"quantity":1}]. IDs must be unique and quantities whole numbers of zero or more. Zero leaves that accessory unselected. Omit to keep the selection; [] clears it. Null is refused. Current choices and quantity limits are checked when saving. | | notify_reservation_update | Boolean | No | Whether to notify eligible followers about a meaningful reservation change. | Default: true. Dates, Event, notes, quantity or location changes can send mail. Marker, Optional Accessory, Shipping Logistics or formatting-only changes do not. | | expected_revision | String | No | The record_revision from the reservation's Info response. Include it to avoid overwriting changes to that reservation or its Logistical Records. Omit it to skip this check. | Optional. Blank, null, malformed or conflicting copies are refused with HTTP 400. A stale revision returns HTTP 409 with error_code=record_changed. | | $ignore_params_with_empty_values | Boolean | No | Whether to ignore empty values instead of applying their empty-value meaning. | Default: false. True omits real JSON null and blank values. The text "null" still asks to clear an applicable clearable field. This does not hide invalid IDs or expected_revision. | Declared schema for `optional_accessories` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "array", "items": { "type": "object", "additionalProperties": false, "properties": { "optional_accessory_id": { "type": "integer", "format": "int64", "minimum": 1.0, "maximum": 9223372036854775807.0 }, "quantity": { "type": "integer", "format": "int32", "minimum": 0.0, "maximum": 2147483647.0 } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "required": [ "optional_accessory_id", "quantity" ] }, "maxItems": 2147483647, "x-unique-item-key": [ "optional_accessory_id" ], "nullable": false, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": [ { "optional_accessory_id": 12345, "quantity": 1 } ] } ``` #### Keeping, changing and clearing values Omitted and blank values keep the saved values. A blank value can add an empty-field warning. Real JSON null or the text "null" clears only an applicable clearable field: notes, a Collateral return date, or a Capital new_event_id. With $ignore_params_with_empty_values=true, a real JSON null is omitted; the text "null" still asks to clear. Use [] to clear Optional Accessories; null is refused. Inapplicable fields are refused even if they are null or would otherwise be ignored. A true no-op preserves the saved dates, formatting, revision and history. A supplied Optional Accessory list replaces the previous selection. Related add/remove lists change links only. #### Dates, quantities and Storage Locations Capital needs a known return date. For Collateral, omission keeps the saved return date and JSON null makes the return unknown, removing its scheduled return. When a reservation or return date is supplied, the resulting date range must be in order. An unrelated edit can retain a legacy reversed Capital period. Resending the same calendar date preserves its saved time of day. A changed Collateral location must belong to the Asset’s owner. Quantity is the replacement reservation quantity, never a signed inventory adjustment. #### Archived or unshared Assets While an Asset is Archived, or after its owner stops sharing it with your workspace, an existing reservation can’t be moved to another Event, and its return date can’t be moved later to today or a future date. Making a Collateral return date unknown also counts as an extension. The request returns HTTP 409 with error_code=invalid_request; error_params names new_event_id or return_date, and the message names the Asset and how to resolve it. Edits that don’t extend the hold remain available: notes and other fields, a different reservation date with the same return date, an earlier return date, and corrections that stay in the past. "Today" uses your workspace’s time zone. #### Moving to another Event or Other Purpose Use new_event_id to request a move for an Asset in your workspace. Do not supply the previous Event as another selector. The API checks the current and target content access and preserves historical file permissions. Only Capital can become Other Purpose by clearing new_event_id; its notes must explain the purpose. Protected Event content, Logistical Records, related links or files can prevent a move. A borrowed reservation does not gain a new move or content grant. #### Access to the reservation and its Event The typed reservation ID determines its Asset and current Event. Do not send a separate Asset ID or Event ID to select an existing reservation. A change in that binding while the request is being prepared is refused. An existing reservation can remain accessible after sharing ends. The current access and locks still apply. Being able to edit dates or quantities for an Asset does not grant access to another workspace’s private Event notes, related items, files or Logistical Records. Event moves, notes and related-item edits need the corresponding current Event content access. Protected saved content or historical file permissions can prevent a move or cancellation, even when an ordinary scalar edit remains available. #### How the Asset can be reserved Capital Assets are individual reusable items, such as a display monitor. Collateral is tracked in quantities, such as brochures. - Strict blocks every day of an existing Capital reservation, including checkout and return. - Moderate permits another reservation on checkout and return days and blocks only the days between them. A one- or two-day reservation blocks no days. - Liberal permits overlap. Collateral uses its dated inventory movements and scheduled returns. An availability check does not guarantee that a later save will succeed. #### Checking for another change The revision covers the complete reservation fields, Optional Accessory selections, Logistical Records, note formatting saved in ExhibitDay and related-item links. It does not cover attachment metadata or file contents; their permissions and safe handling are checked separately. 1. Retrieve `/v1/assets/reservations/info` with asset_type_id, id and $include_record_revision=true. 2. Send the returned record_revision as expected_revision with this request. Treat it as an opaque value. 3. After HTTP 409 record_changed, retrieve the reservation, review it and decide whether to send the request again. #### Receiving the result The response is a status object. It contains record_revision only when expected_revision was sent. The Idempotency-Key header is ignored for this PATCH; use expected_revision for the optional change check. #### Sending values and handling errors Send notes containing commas through JSON, a query string or a form field. An inaccessible or missing typed reservation can return HTTP 404. HTTP 409 with error_code=record_changed means the reservation or its content changed or could not be prepared safely; retrieve it again before deciding whether to retry. Other allocation or cancellation conflicts can return error_code=invalid_request. No automatic retry is performed. #### History and notifications after saving A confirmed change is recorded in history. Notifications are sent afterward to eligible Storage Location followers, subject to their existing access and preferences. Delivery or file-cleanup failure does not undo a saved reservation. If the save outcome could not be confirmed, check the current reservation and inventory before deciding whether to repeat the action. Do not assume the server rolled it back. #### Hidden or locked Assets tab If the reservation's Event is in your workspace and its Assets tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash curl -X PATCH "https://api.exhibitday.com/v1/assets/reservations" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"asset_type_id\":1,\"id\":12345,\"is_checked\":true}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/reservations", { method: "PATCH", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "asset_type_id": 1, "id": 12345, "is_checked": true }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.patch( "https://api.exhibitday.com/v1/assets/reservations", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"asset_type_id": 1, "id": 12345, "is_checked": True}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PatchAsync("https://api.exhibitday.com/v1/assets/reservations", JsonContent.Create(new { asset_type_id = 1, id = 12345, is_checked = true })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/reservations")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("PATCH", HttpRequest.BodyPublishers.ofString("{\"asset_type_id\":1,\"id\":12345,\"is_checked\":true}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"asset_type_id":1,"id":12345,"is_checked":true}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/reservations') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"asset_type_id":1,"id":12345,"is_checked":true}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/assets/reservations", strings.NewReader("{\"asset_type_id\":1,\"id\":12345,\"is_checked\":true}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): PATCH /v1/assets/reservations - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Asset Reservation updated.", "errors": [] } ``` ### Retrieve Reservation Cancellation Options `GET https://api.exhibitday.com/v1/assets/reservation_cancellation_inventory_options` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=reservations#get-v1-assets-reservation_cancellation_inventory_options Shows what cancelling this reservation would do to its inventory today. Review the available choices, their effects and eligible return locations before you cancel. The reservation’s Asset and current Event are derived from its typed ID. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | asset_type_id | Number | Yes | The reservation's Asset type. Capital tracks one item; Collateral tracks quantities. Supply the type even when you know the reservation ID. | Allowed values: `1` (Capital) \| `2` (Collateral) | | id | Number | Yes | The reservation’s ID. | Use the ID for the selected Asset type. A manual Collateral inventory adjustment is not a reservation. The Asset and current Event are derived automatically. | | If-None-Match | String | No | An ETag from an earlier response to this GET. | Optional HTTP header. A matching successful response returns HTTP 304 with no body. | #### Reviewing the available choices 1. Supply asset_type_id and id. 2. Read can_cancel, suggested_inventory_outcome, has_suggested_outcome, requires_explicit_inventory_outcome and the returned inventory_outcomes and their effects. Older rows can represent recorded history rather than a future allocation. 3. If the automatic suggestion is unavailable, choose a safe explicit alternative only from the returned choices. Do not assume another outcome will be substituted. 4. For a RecordReturn choice, use an eligible receiving location from this response and supply the actual returned quantity and date when cancelling. #### What this review means Only choices this workspace key can currently complete are listed. A choice that would retain, clear or copy protected notes, Logistical Records or attachments can be unavailable, while another safe cancellation outcome remains possible. An Other Purpose Capital reservation is removed directly; it has no Event inventory outcome to choose. This GET changes nothing and sends no notifications. These options are advice, not a hold on the choice. Cancellation checks the current reservation, inventory, permissions and content again. This response provides no edit revision. Use `GET /v1/assets/reservations/info` with `$include_record_revision=true` before a conditional cancellation. #### Access to the reservation and its Event The typed reservation ID determines its Asset and current Event. Do not send a separate Asset ID or Event ID to select an existing reservation. A change in that binding while the request is being prepared is refused. An existing reservation can remain accessible after sharing ends. The current access and locks still apply. Being able to edit dates or quantities for an Asset does not grant access to another workspace’s private Event notes, related items, files or Logistical Records. Event moves, notes and related-item edits need the corresponding current Event content access. Protected saved content or historical file permissions can prevent a move or cancellation, even when an ordinary scalar edit remains available. #### Sending values and handling errors Send notes containing commas through JSON, a query string or a form field. An inaccessible or missing typed reservation can return HTTP 404. HTTP 409 with error_code=record_changed means the reservation or its content changed or could not be prepared safely; retrieve it again before deciding whether to retry. Other allocation or cancellation conflicts can return error_code=invalid_request. No automatic retry is performed. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/assets/reservation_cancellation_inventory_options?asset_type_id=1&id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/reservation_cancellation_inventory_options?" + new URLSearchParams({ "asset_type_id": "1", "id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/assets/reservation_cancellation_inventory_options", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"asset_type_id": 1, "id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/assets/reservation_cancellation_inventory_options?asset_type_id=1&id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/reservation_cancellation_inventory_options?asset_type_id=1&id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/reservation_cancellation_inventory_options?asset_type_id=1&id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/assets/reservation_cancellation_inventory_options?asset_type_id=1&id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/assets/reservation_cancellation_inventory_options - HTTP 200 Illustrative response. ```json { "asset_type_id": 1, "asset_id": 12345, "reservation_id": 12345, "is_event_reservation": true, "can_cancel": true, "can_choose_inventory_outcome": true, "is_recorded_history": false, "suggested_inventory_outcome": "UndoOriginal", "has_suggested_outcome": true, "requires_explicit_inventory_outcome": false, "unavailable_message": "", "inventory_outcomes": [ { "value": "UndoOriginal", "label": "Undo Reservation (as if it never took place)", "effect": "The recorded check-out/return of this asset will be removed from inventory records" }, { "value": "KeepCapital", "label": "Unlink reservation from this event, but keep the asset reserved", "effect": "The asset will remain reserved for the original reservation period, but the reservation will no longer be tied to this event." } ], "can_record_return": false, "suggested_return_quantity": null, "suggested_return_date": "", "suggested_receiving_storage_location_id": null, "receiving_storage_locations": [] } ``` ### Cancel an Asset Reservation `POST https://api.exhibitday.com/v1/assets/cancel_reservation` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=reservations#post-v1-assets-cancel_reservation Cancels a reservation using its current inventory rules. Depending on the available outcome, this can undo an allocation, keep a Capital reservation as Other Purpose, or preserve Collateral use and record a return. It does not delete the Asset. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | asset_type_id | Number | Yes | The reservation's Asset type. Capital tracks one item; Collateral tracks quantities. Supply the type even when you know the reservation ID. | Allowed values: `1` (Capital) \| `2` (Collateral) | | id | Number | Yes | The reservation’s ID. | Use the ID for the selected Asset type. A manual Collateral inventory adjustment is not a reservation. The Asset and current Event are derived automatically. | | inventory_outcome | String | No | The exact outcome value to apply from the current options response. | Case-sensitive. Omit for ExhibitDay’s current automatic choice. An unavailable automatic choice is refused, without fallback. Do not supply this for Other Purpose Capital. | | return_quantity | Number | When inventory_outcome=RecordReturn | The quantity actually returned. | A positive whole number, up to the original quantity and 2,147,483,647. Supply all three return fields together. | | return_date | Date | When inventory_outcome=RecordReturn | The actual return date. | YYYY-MM-DD, on or after checkout. | | receiving_storage_location_id | Number | When inventory_outcome=RecordReturn | The Storage Location receiving the return. | Choose an eligible location from the current options response; it belongs to the Asset’s owner. | | notify_reservation_cancellation | Boolean | No | Whether to notify eligible followers of the affected locations. | Default: true. Recipient access and notification preferences still apply. | | expected_revision | String | No | The record_revision from the reservation's Info response. Include it to avoid overwriting changes to that reservation or its Logistical Records. Omit it to skip this check. | Optional. Blank, null, malformed or conflicting copies are refused with HTTP 400. A stale revision returns HTTP 409 with error_code=record_changed. | #### Choosing how to cancel 1. Review `/v1/assets/reservation_cancellation_inventory_options` with the typed reservation ID. 2. Omit inventory_outcome only when you intend to use the current automatic choice. Otherwise send an exact value from the returned choices. 3. With RecordReturn, send return_quantity, return_date and receiving_storage_location_id together. Do not send those fields with another outcome. 4. Optionally supply expected_revision from reservation Info, then submit the cancellation. #### Automatic and explicit outcomes - An older reservation may be recorded history that should be preserved rather than undone. Read the returned effect before choosing. - If the automatic outcome cannot safely preserve or handle the current content, the API refuses it. It does not silently choose a different result; review the options for a safe explicit alternative. - An Other Purpose Capital reservation is removed directly. Omit inventory_outcome and all return fields. #### Access to the reservation and its Event The typed reservation ID determines its Asset and current Event. Do not send a separate Asset ID or Event ID to select an existing reservation. A change in that binding while the request is being prepared is refused. An existing reservation can remain accessible after sharing ends. The current access and locks still apply. Being able to edit dates or quantities for an Asset does not grant access to another workspace’s private Event notes, related items, files or Logistical Records. Event moves, notes and related-item edits need the corresponding current Event content access. Protected saved content or historical file permissions can prevent a move or cancellation, even when an ordinary scalar edit remains available. #### Checking for another change The revision covers the complete reservation fields, Optional Accessory selections, Logistical Records, note formatting saved in ExhibitDay and related-item links. It does not cover attachment metadata or file contents; their permissions and safe handling are checked separately. 1. Retrieve `/v1/assets/reservations/info` with asset_type_id, id and $include_record_revision=true. 2. Send the returned record_revision as expected_revision with this request. Treat it as an opaque value. 3. After HTTP 409 record_changed, retrieve the reservation, review it and decide whether to send the request again. #### Receiving the result and handling retained records The response is a status object. With expected_revision, a new revision is returned only when your Capital reservation remains readable afterward. Removed or converted records, and borrowed reservations that leave their readable context, have no replacement token. Associated files and saved content follow the chosen outcome and their original permissions. Confirmed pointer changes can be followed by best-effort cleanup; a cleanup or notification failure does not undo the cancellation. Do not send Idempotency-Key: cancellation rejects it and does not automatically repeat the action. Inspect the current reservation and inventory after an uncertain outcome before deciding what to do. #### Sending values and handling errors Send notes containing commas through JSON, a query string or a form field. An inaccessible or missing typed reservation can return HTTP 404. HTTP 409 with error_code=record_changed means the reservation or its content changed or could not be prepared safely; retrieve it again before deciding whether to retry. Other allocation or cancellation conflicts can return error_code=invalid_request. No automatic retry is performed. #### History and notifications after saving A confirmed change is recorded in history. Notifications are sent afterward to eligible Storage Location followers, subject to their existing access and preferences. Delivery or file-cleanup failure does not undo a saved reservation. If the save outcome could not be confirmed, check the current reservation and inventory before deciding whether to repeat the action. Do not assume the server rolled it back. Example — curl: ```bash curl -X POST "https://api.exhibitday.com/v1/assets/cancel_reservation" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"asset_type_id\":1,\"id\":12345}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/cancel_reservation", { method: "POST", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "asset_type_id": 1, "id": 12345 }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.post( "https://api.exhibitday.com/v1/assets/cancel_reservation", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"asset_type_id": 1, "id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PostAsync("https://api.exhibitday.com/v1/assets/cancel_reservation", JsonContent.Create(new { asset_type_id = 1, id = 12345 })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/cancel_reservation")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("POST", HttpRequest.BodyPublishers.ofString("{\"asset_type_id\":1,\"id\":12345}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"asset_type_id":1,"id":12345}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/cancel_reservation') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"asset_type_id":1,"id":12345}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/assets/cancel_reservation", strings.NewReader("{\"asset_type_id\":1,\"id\":12345}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): POST /v1/assets/cancel_reservation - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Asset Reservation canceled.", "errors": [] } ``` ### Retrieve Asset Reservation General File Attachments `GET https://api.exhibitday.com/v1/assets/reservations/attachments` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=reservations#get-v1-assets-reservations-attachments Retrieves the General File Attachments on this Asset Reservation. Each result includes the file's ID, name and added time; use the download method for its contents. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | asset_type_id | Number | Yes | The type of Asset being reserved. Capital tracks one item; Collateral tracks quantities. | Allowed values: `1` (Capital) \| `2` (Collateral) | | reservation_id | Number | Yes | The ID of the Asset Reservation, from Retrieve Asset Reservations (GET /v1/assets/reservations) or its add response. | Use the matching asset_type_id. The server finds the reservation's Asset and current Event; no asset_id or event_id is needed. | | $limit | Number | No | The most File Attachments to return. | A positive whole number. Omit for all remaining matching files. | | $offset | Number | No | The number of matching File Attachments to skip. | A whole number of 0 or more. Default: 0. | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records. | Allowed values: `array` | | If-None-Match | String | No | An ETag from an earlier response to this GET. | Optional HTTP header. If the successful response is unchanged, the API returns HTTP 304 with no body. | #### Reading the file list Files are ordered by attachment ID, lowest first. Each file follows its own current file permissions; files you can't view are left out. Paging totals and X-Total-Count count all matching files before $limit and $offset are applied. A record with no files you can view returns an empty list. This list does not return edit revisions or support changed-since filtering. #### Which reservation to select Capital assets are tracked individually; Collateral items are tracked by quantity. These methods select an actual Asset Reservation. Manual inventory adjustments are separate. #### File access Each file retains its original Event or owning-workspace rules even if the reservation has moved. A permitted file read or removal grants no access to other reservation information or permission to upload. Hidden original Event content remains private. Applicable original Event/file settings are respected. Permitted reads remain available on the Free plan. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/assets/reservations/attachments?asset_type_id=1&reservation_id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/reservations/attachments?" + new URLSearchParams({ "asset_type_id": "1", "reservation_id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/assets/reservations/attachments", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"asset_type_id": 1, "reservation_id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/assets/reservations/attachments?asset_type_id=1&reservation_id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/reservations/attachments?asset_type_id=1&reservation_id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/reservations/attachments?asset_type_id=1&reservation_id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/assets/reservations/attachments?asset_type_id=1&reservation_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/assets/reservations/attachments - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "attachment", "list_data": [ { "id": 12345, "filename": "attachment.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } ] } ``` ### Add Asset Reservation General File Attachments `POST https://api.exhibitday.com/v1/assets/reservations/attachments` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=reservations#post-v1-assets-reservations-attachments Adds one or more General File Attachments to this Asset Reservation. Send each file as a multipart upload part named file. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | asset_type_id | Number | Yes | The type of Asset being reserved. Capital tracks one item; Collateral tracks quantities. | Allowed values: `1` (Capital) \| `2` (Collateral) | | reservation_id | Number | Yes | The ID of the Asset Reservation, from Retrieve Asset Reservations (GET /v1/assets/reservations) or its add response. | Use the matching asset_type_id. The server finds the reservation's Asset and current Event; no asset_id or event_id is needed. | | file | File (multipart) | Yes | The File Attachments to upload. | Send one or more complete, nonempty multipart/form-data parts, each named file. Supported types and the current per-file limit are shown below. The complete request limit includes all files and multipart overhead; split larger batches. A missing or null upload is not a removal request. | | Idempotency-Key | String | No | A unique key for safely retrying this upload. | Optional HTTP header: 1 to 255 visible ASCII characters without spaces or commas. Retry the identical request with the same key to replay its first saved response. Use a new key for a different upload. | Declared schema for `file` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "array", "items": { "type": "string", "format": "binary", "x-maximum-bytes": 26214400, "x-allowed-extensions": [ "png", "jpg", "jpeg", "bmp", "gif", "pdf", "msg", "eml", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "rtf", "odp", "odt", "ods", "txt", "wks", "zip" ] } } ``` #### After the upload The response's list_data contains the newly attached files, including each id, filename and attachment_created_timestamp. Existing files are kept. Use each returned id to download or remove that file. Each uploaded part becomes a separate attachment, including identical parts in the same request. #### Upload access New uploads require current authority for the reservation and its actual Asset/Event context, permission to edit its files, an upload-enabled paid plan and no overdue billing restriction. An existing file does not grant permission to add another one. The API derives the Asset and current Event from reservation_id and asset_type_id. Files already attached keep their original access context. #### History and retries A confirmed file change is recorded in history. expected_revision is not supported by these file methods. If the save outcome cannot be confirmed, retrieve the current file list before deciding whether to retry; the API does not automatically repeat an uncertain change. Supporting File Attachments have no PATCH replacement. To replace one, add the new file and remove the old one using their separate requests; each request has its own outcome. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X POST "https://api.exhibitday.com/v1/assets/reservations/attachments" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}" --form-string "asset_type_id=1" --form-string "reservation_id=12345" --form "file=@attachment.pdf;type=application/octet-stream") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi cat response-body.tmp ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const form = new FormData(); form.append("asset_type_id", "1"); form.append("reservation_id", "12345"); form.append("file", new Blob([await readFile("attachment.pdf")], { type: "application/octet-stream" }), "attachment.pdf"); const response = await fetch("https://api.exhibitday.com/v1/assets/reservations/attachments", { method: "POST", headers: { Authorization: 'Bearer YOUR_API_KEY' }, body: form }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); console.log(await response.json()); ``` Example — Python: ```python import requests import json from contextlib import ExitStack with ExitStack() as stack: files = [ ("file", ("attachment.pdf", stack.enter_context(open("attachment.pdf", 'rb')), "application/octet-stream")), ] response = requests.request("POST", "https://api.exhibitday.com/v1/assets/reservations/attachments", headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data={"asset_type_id": "1", "reservation_id": "12345"}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') print(response.json()) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.exhibitday.com/v1/assets/reservations/attachments"); var form = new MultipartFormDataContent(); form.Add(new StringContent("1"), "asset_type_id"); form.Add(new StringContent("12345"), "reservation_id"); var file0 = new StreamContent(File.OpenRead("attachment.pdf")); file0.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(file0, "file", "attachment.pdf"); request.Content = form; using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/assets/reservations/attachments")).header("Authorization", "Bearer YOUR_API_KEY"); String boundary = "ExhibitDay-" + UUID.randomUUID(); ByteArrayOutputStream form = new ByteArrayOutputStream(); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"asset_type_id\"\r\n\r\n" + "1" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"reservation_id\"\r\n\r\n" + "12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"attachment.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8)); form.write(Files.readAllBytes(Path.of("attachment.pdf"))); form.write("\r\n".getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); request.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpResponse response = HttpClient.newHttpClient().send(request.method("POST", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); System.out.println(new String(response.body(), StandardCharsets.UTF_8)); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], CURLOPT_POSTFIELDS => [ 'asset_type_id' => '1', 'reservation_id' => '12345', 'file' => new CURLFile('attachment.pdf', 'application/octet-stream', 'attachment.pdf'), ], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); echo $response; ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/reservations/attachments') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' files = [] begin parts = [ ['asset_type_id', '1'], ['reservation_id', '12345'], ['file', (files << File.open('attachment.pdf', 'rb')).last, {filename: 'attachment.pdf', content_type: 'application/octet-stream'}], ] request.set_form(parts, 'multipart/form-data') response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' puts response.body ensure files.each(&:close) end ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" "bytes" "mime/multipart" "net/textproto" ) func main() { var form bytes.Buffer writer := multipart.NewWriter(&form) if err := writer.WriteField("asset_type_id", "1"); err != nil { log.Fatal(err) } if err := writer.WriteField("reservation_id", "12345"); err != nil { log.Fatal(err) } header0 := textproto.MIMEHeader{} header0.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"attachment.pdf\"") header0.Set("Content-Type", "application/octet-stream") part0, err := writer.CreatePart(header0) if err != nil { log.Fatal(err) } file0, err := os.Open("attachment.pdf") if err != nil { log.Fatal(err) } if _, err = io.Copy(part0, file0); err != nil { log.Fatal(err) } file0.Close() if err := writer.Close(); err != nil { log.Fatal(err) } request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/assets/reservations/attachments", &form) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", writer.FormDataContentType()) response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } fmt.Printf("%s\n", data) } ``` Example HTTP response body (JSON): POST /v1/assets/reservations/attachments - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. The filename is an example. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "attachment", "list_data": [ { "id": 12345, "filename": "attachment.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" } ] } ``` ### Remove an Asset Reservation General File Attachment `DELETE https://api.exhibitday.com/v1/assets/reservations/attachments` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=reservations#delete-v1-assets-reservations-attachments Removes one General File Attachment from this Asset Reservation. Other attached files and the record's details stay in place. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the File Attachment. | Use the id from the attachment list. The API finds the record the file belongs to, so no record ID is sent. An Invoice Attachment is not selected by this method. | #### After the removal Only the selected file association is removed. Its physical file is scheduled for cleanup after a confirmed save; cleanup may finish later. Other attached files stay in place. Send only the file's id; the API finds the record it belongs to. A missing, already removed or unavailable attachment returns HTTP 404 Not Found. Do not send file parts with DELETE. #### File access Each file retains its original Event or owning-workspace rules even if the reservation has moved. A permitted file read or removal grants no access to other reservation information or permission to upload. Hidden original Event content remains private. Removal also checks the file's original Event attachment, Assets and Deep Lock settings. Permitted removals remain available on the Free plan. #### History and retries A confirmed file change is recorded in history. expected_revision is not supported by these file methods. DELETE does not use Idempotency-Key replay. If the save outcome cannot be confirmed, retrieve the current file list before deciding whether to retry; the API does not automatically repeat an uncertain change. Supporting File Attachments have no PATCH replacement. To replace one, add the new file and remove the old one using their separate requests; each request has its own outcome. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/assets/reservations/attachments?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/reservations/attachments?" + new URLSearchParams({ "id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/assets/reservations/attachments", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/assets/reservations/attachments?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/reservations/attachments?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/reservations/attachments?id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/assets/reservations/attachments?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/assets/reservations/attachments - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Attachment removed.", "errors": [] } ``` ### Download an Asset Reservation General File Attachment `GET https://api.exhibitday.com/v1/assets/reservations/attachments/download` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=reservations#get-v1-assets-reservations-attachments-download Downloads one original General File Attachment from this Asset Reservation. Select the file using its ID from the attachment list. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the File Attachment. | Use the id from the attachment list. The API finds the record the file belongs to, so no record ID is sent. An Invoice Attachment is not selected by this method. | #### Download response A successful response contains the original uploaded file with a safe download filename. API errors use the usual JSON response. A missing or unavailable file returns HTTP 404. Send only the file's id from the attachment list to download that one file; the API finds the record it belongs to. The download leaves the record unchanged. #### File access Each file retains its original Event or owning-workspace rules even if the reservation has moved. A permitted file read or removal grants no access to other reservation information or permission to upload. Hidden original Event content remains private. Applicable original Event/file settings are respected. Permitted reads remain available on the Free plan. #### Files still being copied If this file is still being copied, the download returns HTTP 409 with file_copy_pending. Try the download again in a few minutes. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X GET "https://api.exhibitday.com/v1/assets/reservations/attachments/download?id=12345" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi mv response-body.tmp 'attachment.pdf' ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const response = await fetch("https://api.exhibitday.com/v1/assets/reservations/attachments/download?id=12345", { method: "GET", headers: { Authorization: 'Bearer YOUR_API_KEY' } }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); await writeFile("attachment.pdf", new Uint8Array(await response.arrayBuffer())); ``` Example — Python: ```python import requests import json response = requests.request("GET", "https://api.exhibitday.com/v1/assets/reservations/attachments/download?id=12345", headers={'Authorization': 'Bearer YOUR_API_KEY'}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') with open("attachment.pdf", 'wb') as destination: destination.write(response.content) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.exhibitday.com/v1/assets/reservations/attachments/download?id=12345"); using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); await File.WriteAllBytesAsync("attachment.pdf", await response.Content.ReadAsByteArrayAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/assets/reservations/attachments/download?id=12345")).header("Authorization", "Bearer YOUR_API_KEY"); HttpResponse response = HttpClient.newHttpClient().send(request.method("GET", HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); Files.write(Path.of("attachment.pdf"), response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); file_put_contents('attachment.pdf', $response); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/reservations/attachments/download?id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' File.binwrite('attachment.pdf', response.body) ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/assets/reservations/attachments/download?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } if err := os.WriteFile("attachment.pdf", data, 0600); err != nil { log.Fatal(err) } fmt.Println("File saved") } ``` HTTP 200: The authorized original uploaded file. Media: application/octet-stream. The body is the authorized file's real bytes, not JSON or base64. Errors are JSON status responses; check HTTP status before saving the file. ## Assets - Logistical Records Logistical records on Asset Reservations: read, add, update and remove them. Documentation page: https://api.exhibitday.com/Help/V1?epf=5&topic=logistical-records ### Retrieve a Single Reservation Logistical Record by ID `GET https://api.exhibitday.com/v1/assets/reservation_logistical_records/info` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=logistical-records#get-v1-assets-reservation_logistical_records-info Retrieves a Logistical Record for an Asset reservation. A Logistical Record tracks an action such as preparing, shipping or receiving an Asset. Its Record Date is the date of that action. Your workspace must have the Logistical Records feature enabled. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Logistical Record you want to retrieve. It must belong to this reservation. | | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` | | $on_error_return_empty_result | Boolean | No | Set to `true` to receive an empty result for supported validation or not-found errors. Authentication errors, rate limits, read conflicts and unexpected server errors still return an error response. | Default: false. | | $include_error_list_in_response_message | Boolean | No | Set to `true` to include individual validation errors in the error message. | Default: false. | #### Access to borrowed Assets Supply the Logistical Record's id for your Assets or borrowed Assets. The API finds the reservation’s current Asset and Event and checks access automatically; no extra Asset or Event ID is needed. If the owner stops sharing the Asset, access can continue while the reservation belongs to an Event in your workspace and that Event’s Assets tab is accessible. Borrowed-Asset access does not provide the owner’s private Asset details or other Event reservations. Logistical Records for an Event in another workspace are unavailable. #### Getting the revision for an update This Logistical Record response does not include a revision. Retrieve the parent reservation’s revision before making a conditional update. 1. Retrieve the parent reservation with `GET /v1/assets/reservations/info`, using its `asset_type_id` and setting `id` to this response's `reservation_id`, and set `$include_record_revision=true`. 2. Copy `record_revision` from `GET /v1/assets/reservations/info` and send it unchanged as `expected_revision` in `PATCH /v1/assets/reservation_logistical_records` or `DELETE /v1/assets/reservation_logistical_records`. #### What the reservation revision covers This Logistical Record response does not include a revision. The parent reservation’s revision covers the reservation fields, Optional Accessory quantities, Logistical Records, note formatting saved in ExhibitDay and related-item links; attachment metadata and file contents are excluded. Logistical Records on another workspace’s Event can’t be read or changed, even by the Asset’s owner, so this revision is only useful for reservations on Events in your workspace. #### If the reservation changes during your read Reads take no locks. If a save to the same reservation collides with your read (rare), the API can return HTTP `409` with `error_code=record_changed`. Read the record again. The empty-result option does not replace this conflict response. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/assets/reservation_logistical_records/info?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/reservation_logistical_records/info?" + new URLSearchParams({ "id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/assets/reservation_logistical_records/info", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/assets/reservation_logistical_records/info?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/reservation_logistical_records/info?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/reservation_logistical_records/info?id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/assets/reservation_logistical_records/info?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/assets/reservation_logistical_records/info - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "id": 12345, "asset_type_id": 0, "reservation_id": 0, "asset_id": 0, "record_type_id": 0, "record_type": null, "record_date": null, "description": "Sample description", "logistical_record_created_by": { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, "logistical_record_created_timestamp": "2026-11-21T17:00:00Z" } ``` ### Retrieve Reservation Logistical Records `GET https://api.exhibitday.com/v1/assets/reservation_logistical_records` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=logistical-records#get-v1-assets-reservation_logistical_records Retrieves milestones such as preparation, shipment and receipt for one Asset reservation. Supply the reservation’s type and ID, then optionally filter or page its records. By default, records are ordered by Record Date. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | asset_type_id | Number | Yes | The reservation's Asset type. Capital tracks one item; Collateral tracks quantities. Supply the type even when you know the reservation ID. | Allowed values: `1` (Capital) \| `2` (Collateral) | | reservation_id | Number | Yes | The ID of the reservation for the selected Asset type. | The current Asset and Event are determined automatically. No additional Asset or Event ID is needed. | | filter_by_logistical_record_id | Number | No | Only return the record with this ID on the selected reservation. | | | filter_by_record_type_id | Number | No | Only return records with this Record Type ID. | Standard choices: 1 (Prepped), 2 (Sent), 3 (Received), 4 (Other). | | filter_by_record_date_greater_than_or_equal_to | Date | No | Only return records dated on or after this date. | Use `YYYY-MM-DD`. The whole calendar date is compared, including older entries saved with a time of day. | | filter_by_record_date_smaller_than_or_equal_to | Date | No | Only return records dated on or before this date. | Use `YYYY-MM-DD`. It must not precede the lower date when both are supplied. | | $result_sort | String | No | Order records by record date, creation time or ID. Omit for record date ascending. Date and time ties use ID ascending. Unsupported values are refused. | Allowed values: `record_date_asc` \| `record_date_desc` \| `create_timestamp_asc` \| `create_timestamp_desc` \| `id_asc` \| `id_desc` | | $limit | Number | No | The maximum number of matching records to return. | One positive whole number. Omit to return all matches after `$offset`; there is no fixed page-size cap. | | $offset | Number | No | The number of matching records to skip. | Default: 0. Send a nonnegative whole number. | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | | $on_error_return_empty_result | Boolean | No | Set to `true` to return an empty collection for supported validation or not-found errors. | Default: false. Malformed inputs, authentication errors, rate limits, read conflicts and unexpected errors keep their error response. | | $include_error_list_in_response_message | Boolean | No | Set to `true` to include individual validation errors in the response message. | Default: false. The normal error list remains available. | | If-None-Match | String | No | Send the ETag from an earlier response when checking whether this result changed. | Optional request header. A matching current result returns HTTP 304 with no body; reuse your earlier response. This header compares GET responses. It cannot prevent a conflicting update. | #### Using the reservation’s current context Your workspace needs the Logistical Records feature and access to the selected reservation. The API checks its current Asset and Event automatically. Manual Collateral inventory adjustments use separate methods. Logistical Records for another workspace’s Event are unavailable. Owning the physical Asset does not grant access to that Event’s information. #### Filtering and paging Filters work together and apply only to the selected reservation. A valid reservation with no matching records returns an empty list. A missing or inaccessible reservation can return HTTP `404`; the empty-result option can replace supported not-found or validation errors with an empty collection. `records_found` is the number of records in this response; `total_records` is the filtered count before paging. `has_more` indicates whether matching records remain. Results can change between requests. Each row includes its Record Type, Record Date, description, Recorded By name and creation timestamp. Attachments, parent notes and other reservation details are not included. #### Getting a revision before an edit This collection does not issue `record_revision`. Retrieve the reservation with GET /v1/assets/reservations/info and `$include_record_revision=true` when you want to check for changes before updating or deleting a Logistical Record. If concurrent changes prevent the read, HTTP `409` with `error_code=record_changed` means you should read again. This read changes no data. #### Checking whether a response changed Normal API-key and access checks still apply. This header compares the response; it does not authorize access or protect an update. 1. Save the response body and its `ETag` header from an earlier GET. 2. Repeat the same GET, including the same filters and response options, with that ETag in the `If-None-Match` header. 3. If the response is HTTP `304`, keep using your saved body. If it is HTTP `200`, use the new body and ETag. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/assets/reservation_logistical_records?asset_type_id=1&reservation_id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/reservation_logistical_records?" + new URLSearchParams({ "asset_type_id": "1", "reservation_id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/assets/reservation_logistical_records", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"asset_type_id": 1, "reservation_id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/assets/reservation_logistical_records?asset_type_id=1&reservation_id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/reservation_logistical_records?asset_type_id=1&reservation_id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/reservation_logistical_records?asset_type_id=1&reservation_id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/assets/reservation_logistical_records?asset_type_id=1&reservation_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/assets/reservation_logistical_records - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "asset_reservation_logistical_record", "list_data": [ { "id": 12345, "asset_type_id": 0, "reservation_id": 0, "asset_id": 0, "record_type_id": 0, "record_type": null, "record_date": null, "description": "Sample description", "logistical_record_created_by": { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, "logistical_record_created_timestamp": "2026-11-21T17:00:00Z" } ] } ``` ### Add a Reservation Logistical Record `POST https://api.exhibitday.com/v1/assets/reservation_logistical_records` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=logistical-records#post-v1-assets-reservation_logistical_records Adds a logistical milestone to an Asset reservation, such as when it was prepared, sent or received. Record Type and Record Date are required; the description is optional. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | asset_type_id | Number | Yes | The reservation's Asset type. Capital tracks one item; Collateral tracks quantities. Supply the type even when you know the reservation ID. | Allowed values: `1` (Capital) \| `2` (Collateral) | | reservation_id | Number | Yes | The ID of the reservation for the selected Asset type. | No additional Asset or Event ID is needed. | | record_type_id | Number | Yes | The current Record Type ID for this milestone. | Standard choices are `1` (Prepped), `2` (Sent), `3` (Received) and `4` (Other). | | record_date | Date | Yes | The date when this logistical action took place. | Use `YYYY-MM-DD`. This is the milestone’s calendar date, not a due date or time of day. | | description | String | No | A short description of the milestone. | Up to 200 characters, excluding surrounding spaces. Use JSON, query-string or form values when the text contains commas. | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` | | Idempotency-Key | String | No | Send a unique key if you may retry this same create request. | Optional request header: 1–255 visible ASCII characters without spaces, such as a UUID. Reuse the same key only for the same request. Successful responses can be replayed for 24 hours. | #### Before changing a record Your workspace needs the Logistical Records feature and permission to edit the selected reservation. ExhibitDay checks the reservation, its Asset and its Event automatically. Hidden or locked Event content cannot be changed. Owning the physical Asset does not grant access to another workspace’s Event information. Manual Collateral inventory adjustments use separate methods. #### Adding a milestone 1. Send `asset_type_id` and `reservation_id` to select the reservation. 2. Send the milestone’s `record_type_id` and `record_date`. Add an optional description. 3. Read the created record, including its ID, from the response. Its Recorded By name is `ExhibitDay API`. #### Retrying the same create Send the optional `Idempotency-Key` request header if you may repeat the same create request. Reuse that key only with the same request so a completed response can be replayed without adding another milestone. `expected_revision` is not accepted by POST. If the save outcome cannot be confirmed, check the current records before trying again. #### Sending descriptions with commas Put a description containing commas in a JSON body, query string or form field. #### What stays unchanged This action leaves reservation dates, quantities, availability, related-item links and files unchanged. It sends no notifications. A confirmed change is added to history. A history-writing failure does not undo the saved change. If the save outcome cannot be confirmed, retrieve the current records before deciding whether to retry. The API does not automatically repeat the action. #### Hidden or locked Assets tab If the reservation's Event is in your workspace and its Assets tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash curl -X POST "https://api.exhibitday.com/v1/assets/reservation_logistical_records" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"asset_type_id\":1,\"reservation_id\":12345,\"record_type_id\":1,\"record_date\":\"2026-12-21\"}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/reservation_logistical_records", { method: "POST", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "asset_type_id": 1, "reservation_id": 12345, "record_type_id": 1, "record_date": "2026-12-21" }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.post( "https://api.exhibitday.com/v1/assets/reservation_logistical_records", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"asset_type_id": 1, "reservation_id": 12345, "record_type_id": 1, "record_date": "2026-12-21"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PostAsync("https://api.exhibitday.com/v1/assets/reservation_logistical_records", JsonContent.Create(new { asset_type_id = 1, reservation_id = 12345, record_type_id = 1, record_date = "2026-12-21" })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/reservation_logistical_records")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("POST", HttpRequest.BodyPublishers.ofString("{\"asset_type_id\":1,\"reservation_id\":12345,\"record_type_id\":1,\"record_date\":\"2026-12-21\"}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"asset_type_id":1,"reservation_id":12345,"record_type_id":1,"record_date":"2026-12-21"}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/reservation_logistical_records') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"asset_type_id":1,"reservation_id":12345,"record_type_id":1,"record_date":"2026-12-21"}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/assets/reservation_logistical_records", strings.NewReader("{\"asset_type_id\":1,\"reservation_id\":12345,\"record_type_id\":1,\"record_date\":\"2026-12-21\"}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): POST /v1/assets/reservation_logistical_records - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "id": 23456, "asset_type_id": 1, "reservation_id": 12345, "asset_id": 0, "record_type_id": 1, "record_type": null, "record_date": "2026-12-21", "description": "Sample description", "logistical_record_created_by": { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, "logistical_record_created_timestamp": "2026-11-21T17:00:00Z" } ``` ### Update a Reservation Logistical Record `PATCH https://api.exhibitday.com/v1/assets/reservation_logistical_records` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=logistical-records#patch-v1-assets-reservation_logistical_records Updates the supplied Record Type, Record Date or description of a Logistical Record. Omitted fields keep their saved values. The record’s original Recorded By name and creation time remain unchanged. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Logistical Record. | | | record_type_id | Number | No | The current Record Type ID for this milestone. | Standard choices are `1` (Prepped), `2` (Sent), `3` (Received) and `4` (Other). | | record_date | Date | No | The date when this logistical action took place. | Use `YYYY-MM-DD`. This is the milestone’s calendar date, not a due date or time of day. | | description | String | No | A short description of the milestone. | Up to 200 characters, excluding surrounding spaces. Use JSON, query-string or form values when the text contains commas. | | expected_revision | String | No | The record_revision from the reservation's Info response. Include it to avoid overwriting changes to that reservation or its Logistical Records. Omit it to skip this check. | | | $ignore_params_with_empty_values | Boolean | No | Set to `true` to ignore editable fields sent as JSON `null`. | Default: false. The text `"null"` still requests a clear. Only `description` can be cleared; Record Type and Record Date cannot. | #### Before changing a record Your workspace needs the Logistical Records feature and permission to edit the selected reservation. ExhibitDay checks the reservation, its Asset and its Event automatically. Hidden or locked Event content cannot be changed. Owning the physical Asset does not grant access to another workspace’s Event information. Manual Collateral inventory adjustments use separate methods. #### Changing or clearing fields Include the Logistical Record ID as `id`. Send only the fields you want to change. Omitted or blank fields keep their saved values. JSON `null` or the text `"null"` clears `description`. Record Type and Record Date cannot be cleared. With `$ignore_params_with_empty_values=true`, real JSON `null` is ignored; the text `"null"` still requests a clear. Sending the same displayed Record Date preserves any time saved on an older record. A genuinely changed date is saved as a calendar date. Sending unchanged values makes no change to the record, revision, timestamps or history. #### Avoiding conflicting edits 1. Retrieve the Logistical Record by `id` to find its current `asset_type_id` and `reservation_id`. Retrieve GET /v1/assets/reservations/info with that reservation_id as `id`, its asset_type_id and `$include_record_revision=true`. 2. Send the returned reservation `record_revision` as `expected_revision` in this PATCH request. #### What expected_revision checks Use the reservation’s `record_revision`, retrieved with `$include_record_revision=true`, as `expected_revision` in this request. It checks the whole reservation and all its Logistical Records, including siblings, Optional Accessory quantities, note formatting saved in ExhibitDay and related-item links. Attachment metadata and file contents are excluded. Logistical Record Info does not issue this revision. A covered value that differs from your earlier read returns HTTP `409` with `error_code=record_changed` and saves nothing. Retrieve the reservation again and review its current values before deciding whether to retry. A value that changed and later changed back still matches. Blank, null, malformed or conflicting revision values return HTTP `400` with `error_code=invalid_request`. A successful update includes the reservation’s current revision only if you supplied `expected_revision`. The revision grants no additional permission. #### Retrying an update This method ignores `Idempotency-Key`. If the result is uncertain, retrieve the current record before retrying; the API does not automatically repeat the update. #### Sending descriptions with commas Put a description containing commas in a JSON body, query string or form field. #### What stays unchanged This action leaves reservation dates, quantities, availability, related-item links and files unchanged. It sends no notifications. A confirmed change is added to history. A history-writing failure does not undo the saved change. If the save outcome cannot be confirmed, retrieve the current records before deciding whether to retry. The API does not automatically repeat the action. #### Hidden or locked Assets tab If the reservation's Event is in your workspace and its Assets tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash curl -X PATCH "https://api.exhibitday.com/v1/assets/reservation_logistical_records" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"id\":12345,\"description\":\"Updated description\"}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/reservation_logistical_records", { method: "PATCH", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "id": 12345, "description": "Updated description" }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.patch( "https://api.exhibitday.com/v1/assets/reservation_logistical_records", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"id": 12345, "description": "Updated description"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PatchAsync("https://api.exhibitday.com/v1/assets/reservation_logistical_records", JsonContent.Create(new { id = 12345, description = "Updated description" })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/reservation_logistical_records")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("PATCH", HttpRequest.BodyPublishers.ofString("{\"id\":12345,\"description\":\"Updated description\"}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"id":12345,"description":"Updated description"}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/reservation_logistical_records') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"id":12345,"description":"Updated description"}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/assets/reservation_logistical_records", strings.NewReader("{\"id\":12345,\"description\":\"Updated description\"}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): PATCH /v1/assets/reservation_logistical_records - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Logistical Record updated.", "errors": [] } ``` ### Delete a Reservation Logistical Record `DELETE https://api.exhibitday.com/v1/assets/reservation_logistical_records` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=logistical-records#delete-v1-assets-reservation_logistical_records Permanently removes one Logistical Record from the selected Asset reservation. It removes only that milestone; the reservation and its other records remain. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The ID of the Logistical Record. | | | expected_revision | String | No | The record_revision from the reservation's Info response. Include it to delete the record only if that reservation and its Logistical Records are unchanged since your read. Omit it to skip this check. | | #### Before changing a record Your workspace needs the Logistical Records feature and permission to edit the selected reservation. ExhibitDay checks the reservation, its Asset and its Event automatically. Hidden or locked Event content cannot be changed. Owning the physical Asset does not grant access to another workspace’s Event information. Manual Collateral inventory adjustments use separate methods. #### Removing the record 1. Use the Logistical Record ID as `id` to select the entry. 2. Send the DELETE request with the API key in the `Authorization: Bearer` header. #### Deleting only if nothing changed The revision checks the whole reservation and all its Logistical Records, including other records on it. A covered value that differs from your earlier read returns HTTP `409` with `error_code=record_changed` and deletes nothing. Retrieve the reservation again and review its current values before deciding whether to retry. Blank, null, malformed or conflicting revision values return HTTP `400` with `error_code=invalid_request`. Omit `expected_revision` to delete without this check. A successful deletion includes the reservation’s new `record_revision` only if you supplied `expected_revision`. 1. Retrieve the Logistical Record by `id` to find its current `asset_type_id` and `reservation_id`. Retrieve GET /v1/assets/reservations/info with that reservation_id as `id`, its asset_type_id and `$include_record_revision=true`. 2. Send the returned reservation `record_revision` as `expected_revision` in this DELETE request. #### Retrying a deletion This method ignores `Idempotency-Key`. If the result is uncertain, retrieve the reservation’s current Logistical Records before deciding whether to retry. A concurrent-change refusal returns HTTP `409` with `error_code=record_changed` and changes nothing. #### What stays unchanged This action leaves reservation dates, quantities, availability, related-item links and files unchanged. It sends no notifications. A confirmed change is added to history. A history-writing failure does not undo the saved change. If the save outcome cannot be confirmed, retrieve the current records before deciding whether to retry. The API does not automatically repeat the action. #### Hidden or locked Assets tab If the reservation's Event is in your workspace and its Assets tab is hidden or locked, this request returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/assets/reservation_logistical_records?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/reservation_logistical_records?" + new URLSearchParams({ "id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/assets/reservation_logistical_records", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/assets/reservation_logistical_records?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/reservation_logistical_records?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/reservation_logistical_records?id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/assets/reservation_logistical_records?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/assets/reservation_logistical_records - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Logistical Record removed.", "errors": [] } ``` ## Assets - Pull Sheet Create a PDF or Word Pull Sheet for an Event's Asset Reservations. Documentation page: https://api.exhibitday.com/Help/V1?epf=5&topic=pull-sheet ### Export an Asset Pull Sheet `GET https://api.exhibitday.com/v1/assets/pull_sheet/export` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=pull-sheet#get-v1-assets-pull_sheet-export Creates a Pull Sheet for one Event: a list of Assets to prepare, with quantities, reservation dates, storage details, pull notes and Optional Accessories. Download a PDF to print or a Word document to edit. Choose which details and checkboxes to include. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | event_id | Number | Yes | The ID of the Event whose Pull Sheet you want to create. | The Event must belong to your workspace and have a visible Assets tab. | | file_format | String | No | Choose a printable Pull Sheet or an editable Word document. Omit for a PDF. Values are case-insensitive; a supplied blank, null or unsupported value is refused. | Allowed values: `pdf` (printable Pull Sheet) \| `docx` (editable Word document) | | title | String | No | An optional heading for this Pull Sheet. | Up to 500 characters as sent. Surrounding spaces are ignored. | | instructions | String | No | Optional special instructions printed at the top. | Up to 1,500 characters as sent. Surrounding spaces are ignored. | | include_internal_identifier | Boolean | No | Whether to include the Asset’s internal identifier. | Default: true. | | include_make_or_model | Boolean | No | Whether to include the type, make or model. | Default: true. | | include_weight | Boolean | No | Whether to include item weight. | Default: true. | | include_packaged_weight | Boolean | No | Whether to include packaged weight. | Default: true. | | include_dimensions | Boolean | No | Whether to include item dimensions. | Default: true. | | include_packaged_dimensions | Boolean | No | Whether to include packaged dimensions. | Default: true. | | include_storage_location | Boolean | No | Whether to include the Storage Location. | Default: true. | | include_storage_area | Boolean | No | Whether to include the storage area. | Default: true. | | include_pull_notes | Boolean | No | Whether to include pull notes. | Default: true. | | include_shipping_logistics | Boolean | No | Whether to include Shipping Logistics. | Default: true. | | include_reservation_date | Boolean | No | Whether to include reservation and return dates. | Default: true. | | include_reservation_notes | Boolean | No | Whether to include reservation notes. | Default: true. | | include_pulled_checkboxes | Boolean | No | Whether to print a Pulled checkbox for each reservation and Optional Accessory. | Default: false. | | include_returned_checkboxes | Boolean | No | Whether to print a Returned checkbox for each reservation and Optional Accessory. | Default: false. | | filter_by_asset_type_ids | String | No | Only include selected Asset types. Send a comma-separated string or a JSON array of the IDs; omit it for both types. A supplied list must be nonempty and contain no duplicates. | Allowed values: `1` (Capital) \| `2` (Collateral) | | filter_by_shipping_logistics_ids | String | No | Only include these Shipping Logistics choices. | Optional comma-separated ID string or JSON array. Omit for all choices; a supplied list must be nonempty and have no duplicates. Allowed values: `1` (Unspecified) \| `2` (Advance Warehouse) \| `3` (Direct Shipment) \| `4` (Other) | | filter_by_storage_location_ids | String | No | Only include selected reservations associated with these Storage Location IDs. | Optional comma-separated positive ID string or JSON array. Omit for all locations. The list must be nonempty and have no duplicates. It filters already authorized rows and does not grant access to a location record. | | flags | String | No | Only include reservations matching any selected marker. Send comma-separated choices or a JSON array of them; omit this filter to include all markers. Values are case-insensitive; a supplied list must be nonempty and contain no duplicates. | Allowed values: `none` (no marker is set) \| `starred` (star marker) \| `flagged` (flag marker) \| `checked` (check marker) | #### Creating the Pull Sheet 1. Provide `event_id`. Omit `file_format` for a PDF, or choose `file_format=docx` for Word. 2. Optionally add a title or instructions and choose the fields, checkboxes and filters you need. 3. Save the returned file. Your choices apply only to this request and do not change a person’s saved preferences. #### Filtering the reservations Selections within one filter group work on an OR basis. Different groups work together on an AND basis. For example, selecting both `starred` and `flagged` includes either marker, then a Storage Location filter narrows those matches. Send comma-separated filter lists in query-string, form or JSON string values, not headers. Omit a group to leave it unfiltered. A supplied list must be nonempty and contain no repeated items. The layout follows ExhibitDay’s Pull Sheet, preserves original measurement units for shared Assets and includes permitted related-item summaries. If no reservations match, it produces the normal empty-state message. #### Access and output options The Event and its Assets tab must be visible. A locked tab can still be exported. Existing reservations may include shared or subsequently unshared Assets; this does not open the other workspace’s Asset list or ledger. PDF uses the normal plan watermark. Word output is unavailable on the Lite plan. Related summaries follow current permissions; Tasks, hidden or inaccessible records, attachments and invoice files are not included. #### Receiving the download and handling errors A successful response is the downloadable file, not a JSON object. An unsuccessful request returns the normal JSON API error. The response is private and is not stored by shared caches. Matching copies of a parameter count once. If the values differ, the API returns a 400 error that names the parameter and where it was sent. Blank or null selectors and lists are refused. Send comma-separated lists or text containing commas in query-string, form or JSON values, not headers. This download refuses an expected revision because it cannot check one. Undeclared options, including scope, requests for a record revision, paging, JSON response format and changed-since filters, are ignored and reported in the `X-API-Warnings` response header. The ignore-empty option does not hide an invalid selection. HTTP `409` with `error_code=record_changed` means a concurrent change prevented preparation. Retrieve the current information before deciding whether to repeat the export. No business activity entry or email is created by the export. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X GET "https://api.exhibitday.com/v1/assets/pull_sheet/export?file_format=pdf&event_id=23456" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi mv response-body.tmp 'asset-pull-sheet.pdf' ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const response = await fetch("https://api.exhibitday.com/v1/assets/pull_sheet/export?file_format=pdf&event_id=23456", { method: "GET", headers: { Authorization: 'Bearer YOUR_API_KEY' } }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); await writeFile("asset-pull-sheet.pdf", new Uint8Array(await response.arrayBuffer())); ``` Example — Python: ```python import requests import json response = requests.request("GET", "https://api.exhibitday.com/v1/assets/pull_sheet/export?file_format=pdf&event_id=23456", headers={'Authorization': 'Bearer YOUR_API_KEY'}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') with open("asset-pull-sheet.pdf", 'wb') as destination: destination.write(response.content) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.exhibitday.com/v1/assets/pull_sheet/export?file_format=pdf&event_id=23456"); using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); await File.WriteAllBytesAsync("asset-pull-sheet.pdf", await response.Content.ReadAsByteArrayAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/assets/pull_sheet/export?file_format=pdf&event_id=23456")).header("Authorization", "Bearer YOUR_API_KEY"); HttpResponse response = HttpClient.newHttpClient().send(request.method("GET", HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); Files.write(Path.of("asset-pull-sheet.pdf"), response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); file_put_contents('asset-pull-sheet.pdf', $response); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/pull_sheet/export?file_format=pdf&event_id=23456') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' File.binwrite('asset-pull-sheet.pdf', response.body) ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/assets/pull_sheet/export?file_format=pdf&event_id=23456", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } if err := os.WriteFile("asset-pull-sheet.pdf", data, 0600); err != nil { log.Fatal(err) } fmt.Println("File saved") } ``` HTTP 200: Returns a private download in the requested file_format. An unsuccessful request returns the usual JSON API error. Media: application/pdf, application/vnd.openxmlformats-officedocument.wordprocessingml.document. The body is the authorized file's real bytes, not JSON or base64. Errors are JSON status responses; check HTTP status before saving the file. ## Assets - Images An Asset's gallery images: view, add, download, delete and reorder them. Documentation page: https://api.exhibitday.com/Help/V1?epf=5&topic=images ### Retrieve All Asset Images `GET https://api.exhibitday.com/v1/assets/images` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=images#get-v1-assets-images Retrieves an Asset's images in their current order. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | asset_id | Number | Yes | The ID of the Asset whose images to use, from Retrieve Assets (GET /v1/assets) or its create response. | | | $include_record_revision | Boolean | No | Whether to include the gallery revision. | Default: false. True returns one object containing images and record_revision, including an empty gallery. Omit it for the usual JSON image array. This GET does not offer a separate response format option. | #### Using the image list The gallery contains up to five images. `display_rank` starts at 1 in the returned order. An empty gallery returns an empty array. Use the returned `image_filename` values when retrieving, downloading, deleting or reordering images. #### Checking gallery changes Request `$include_record_revision=true` to receive one `record_revision` for the entire gallery beside its `images` array. Send that `record_revision` as `expected_revision` when deleting or reordering images. `record_revision` covers the saved image references, complete order and gallery times. It does not cover file contents or core Asset details. It belongs to the selected Asset, including when its gallery is empty. #### Image filenames and access Treat the filenames returned by GET /v1/assets/images as opaque values. Use them with the selected Asset ID. Shared Assets' images are managed in the Asset's original workspace. Editing an image on the website gives it a new image_filename. List the images again to get the current names. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/assets/images?asset_id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/images?" + new URLSearchParams({ "asset_id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/assets/images", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"asset_id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/assets/images?asset_id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/images?asset_id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/images?asset_id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/assets/images?asset_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/assets/images - HTTP 200 Illustrative response. ```json [ { "asset_id": 12345, "image_filename": "98765-12345-a1941c59-59cb-4b7d-b7a7-2f82f8bf84ab.jpg", "display_rank": 1, "image_last_update_timestamp": "2026-01-15T17:00:00Z" }, { "asset_id": 12345, "image_filename": "98765-12345-59f0a281-df13-4bc9-acf1-3c12c25b1d25.jpg", "display_rank": 2, "image_last_update_timestamp": "2026-01-15T17:00:00Z" } ] ``` ### Add an Asset Image `POST https://api.exhibitday.com/v1/assets/images` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=images#post-v1-assets-images Adds one image to an Asset's gallery. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | asset_id | Number | Yes | The ID of the Asset whose images to use, from Retrieve Assets (GET /v1/assets) or its create response. | | | file | File (multipart) | Yes | One PNG, JPEG or GIF image. | Send one `file` part using `multipart/form-data`, at most 20,500,000 bytes. The extension must match the actual image format. | | crop | JSON object/list | No | An optional crop rectangle in the uploaded image's raw pixels. | Supply `x`, `y`, `width` and `height` together. The rectangle must fit inside the image and have a 125:94 ratio. Omit it to use the largest centered rectangle of that ratio. | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` \| `object` | | Idempotency-Key | String | No | An optional key for safely retrying the same image upload. | Send it as a header. Use 1 through 255 visible ASCII characters without spaces. Reuse the same key only for the same request; the API can return its saved response. | Declared schema for `file` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "string", "format": "binary", "x-maximum-bytes": 20500000, "x-allowed-extensions": [ "png", "jpg", "jpeg", "gif" ] } ``` Declared schema for `crop` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "x": { "type": "number", "minimum": 0.0, "maximum": 8192.0 }, "y": { "type": "number", "minimum": 0.0, "maximum": 8192.0 }, "width": { "type": "number", "minimum": 0.0000001, "maximum": 8192.0 }, "height": { "type": "number", "minimum": 0.0000001, "maximum": 8192.0 } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "required": [ "x", "y", "width", "height" ], "nullable": false, "x-maximum-depth": 2, "x-empty-create-means-omitted": true, "example": { "x": 0, "y": 0, "width": 125, "height": 94 } } ``` #### Uploading an image 1. Retrieve the image list and check that the gallery has room for another image. 2. Send one complete image as `multipart/form-data`. Add `crop` as a JSON form value if you want a specific crop. 3. Use the returned image filename for later requests. POST does not issue a gallery revision. #### Image preparation The API prepares a JPEG using a 125:94 crop. Transparent areas use a white background, and small images may be enlarged. JPEG and static PNG are supported; for GIF, the first frame is kept. Animated PNG is not accepted. The API uses raw image coordinates and does not apply EXIF rotation. Rotate the source before uploading when needed. Embedded profiles, thumbnails and unneeded metadata are ignored. The image must still decode successfully and match its checked format and dimensions. #### Upload and processing limits Each dimension must be at most 8,192 pixels. JPEG and PNG permit at most 24 million decoded pixels. GIF permits at most 64 frames and 24 million total canvas pixels across its frames. PNG decoded sample bytes must be at most 96 million; 16-bit PNGs can reach that limit sooner. These processing limits are separate from the 20,500,000-byte upload limit. When image preparation is busy, the response is HTTP `429` with `Retry-After`. This is separate from the workspace's per-second request allowance. Uploads require an upgraded workspace plan. #### Retrying an upload Use `Idempotency-Key` when retrying the same upload. If the save outcome cannot be confirmed, inspect the current gallery before sending another upload. `expected_revision` is not supported on POST. #### Image filenames and access Treat the filenames returned by GET /v1/assets/images as opaque values. Use them with the selected Asset ID. Shared Assets' images are managed in the Asset's original workspace. Editing an image on the website gives it a new image_filename. List the images again to get the current names. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X POST "https://api.exhibitday.com/v1/assets/images" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}" --form-string "asset_id=12345" --form "file=@asset-image.png;type=application/octet-stream") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi cat response-body.tmp ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const form = new FormData(); form.append("asset_id", "12345"); form.append("file", new Blob([await readFile("asset-image.png")], { type: "application/octet-stream" }), "asset-image.png"); const response = await fetch("https://api.exhibitday.com/v1/assets/images", { method: "POST", headers: { Authorization: 'Bearer YOUR_API_KEY' }, body: form }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); console.log(await response.json()); ``` Example — Python: ```python import requests import json from contextlib import ExitStack with ExitStack() as stack: files = [ ("file", ("asset-image.png", stack.enter_context(open("asset-image.png", 'rb')), "application/octet-stream")), ] response = requests.request("POST", "https://api.exhibitday.com/v1/assets/images", headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data={"asset_id": "12345"}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') print(response.json()) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.exhibitday.com/v1/assets/images"); var form = new MultipartFormDataContent(); form.Add(new StringContent("12345"), "asset_id"); var file0 = new StreamContent(File.OpenRead("asset-image.png")); file0.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(file0, "file", "asset-image.png"); request.Content = form; using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/assets/images")).header("Authorization", "Bearer YOUR_API_KEY"); String boundary = "ExhibitDay-" + UUID.randomUUID(); ByteArrayOutputStream form = new ByteArrayOutputStream(); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"asset_id\"\r\n\r\n" + "12345" + "\r\n").getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"asset-image.png\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8)); form.write(Files.readAllBytes(Path.of("asset-image.png"))); form.write("\r\n".getBytes(StandardCharsets.UTF_8)); form.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); request.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpResponse response = HttpClient.newHttpClient().send(request.method("POST", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray())).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); System.out.println(new String(response.body(), StandardCharsets.UTF_8)); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], CURLOPT_POSTFIELDS => [ 'asset_id' => '12345', 'file' => new CURLFile('asset-image.png', 'application/octet-stream', 'asset-image.png'), ], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); echo $response; ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/images') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' files = [] begin parts = [ ['asset_id', '12345'], ['file', (files << File.open('asset-image.png', 'rb')).last, {filename: 'asset-image.png', content_type: 'application/octet-stream'}], ] request.set_form(parts, 'multipart/form-data') response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' puts response.body ensure files.each(&:close) end ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" "bytes" "mime/multipart" "net/textproto" ) func main() { var form bytes.Buffer writer := multipart.NewWriter(&form) if err := writer.WriteField("asset_id", "12345"); err != nil { log.Fatal(err) } header0 := textproto.MIMEHeader{} header0.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"asset-image.png\"") header0.Set("Content-Type", "application/octet-stream") part0, err := writer.CreatePart(header0) if err != nil { log.Fatal(err) } file0, err := os.Open("asset-image.png") if err != nil { log.Fatal(err) } if _, err = io.Copy(part0, file0); err != nil { log.Fatal(err) } file0.Close() if err := writer.Close(); err != nil { log.Fatal(err) } request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/assets/images", &form) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", writer.FormDataContentType()) response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } fmt.Printf("%s\n", data) } ``` Example HTTP response body (JSON): POST /v1/assets/images - HTTP 200 Illustrative response. ```json { "asset_id": 12345, "image_filename": "98765-12345-a1941c59-59cb-4b7d-b7a7-2f82f8bf84ab.jpg", "display_rank": 1, "image_last_update_timestamp": "2026-01-15T17:00:00Z" } ``` ### Delete an Asset Image `DELETE https://api.exhibitday.com/v1/assets/images` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=images#delete-v1-assets-images Removes one image from an Asset's gallery. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | asset_id | Number | Yes | The ID of the Asset whose images to use, from Retrieve Assets (GET /v1/assets) or its create response. | | | image_filename | String | Yes | The image_filename from this Asset's image list. | Use the value exactly as returned. Image filenames stay the same when the order changes. | | expected_revision | String | No | The record_revision returned by GET /v1/assets/images with $include_record_revision=true. Include it to avoid overwriting changes to its image gallery. Omit it to skip this check. | | #### Removing an image The image must still be in this Asset's gallery. An already-absent image returns HTTP `404`. The remaining images keep their order. The image disappears from the gallery when the save succeeds. Physical file removal follows later after reference checks. Other Asset content is unchanged. #### Avoiding conflicting changes Retrieve `GET /v1/assets/images` with `$include_record_revision=true`, then send its `record_revision` as `expected_revision`. This optional check covers the whole gallery. If the gallery changed after that read, nothing changes and the response is HTTP `409`. Retrieve the gallery again before deciding whether to retry. A successful request with this condition returns the resulting gallery revision. #### Image filenames and access Treat the filenames returned by GET /v1/assets/images as opaque values. Use them with the selected Asset ID. Shared Assets' images are managed in the Asset's original workspace. Editing an image on the website gives it a new image_filename. List the images again to get the current names. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/assets/images?asset_id=12345&image_filename=98765-12345-a1941c59-59cb-4b7d-b7a7-2f82f8bf84ab.jpg" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/images?" + new URLSearchParams({ "asset_id": "12345", "image_filename": "98765-12345-a1941c59-59cb-4b7d-b7a7-2f82f8bf84ab.jpg" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/assets/images", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"asset_id": 12345, "image_filename": "98765-12345-a1941c59-59cb-4b7d-b7a7-2f82f8bf84ab.jpg"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/assets/images?asset_id=12345&image_filename=98765-12345-a1941c59-59cb-4b7d-b7a7-2f82f8bf84ab.jpg"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/images?asset_id=12345&image_filename=98765-12345-a1941c59-59cb-4b7d-b7a7-2f82f8bf84ab.jpg")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/images?asset_id=12345&image_filename=98765-12345-a1941c59-59cb-4b7d-b7a7-2f82f8bf84ab.jpg') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/assets/images?asset_id=12345&image_filename=98765-12345-a1941c59-59cb-4b7d-b7a7-2f82f8bf84ab.jpg", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/assets/images - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Asset image removed.", "errors": [] } ``` ### Reorder Asset Images `PATCH https://api.exhibitday.com/v1/assets/images/order` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=images#patch-v1-assets-images-order Sets the order of the Asset's current images. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | asset_id | Number | Yes | The ID of the Asset whose images to use, from Retrieve Assets (GET /v1/assets) or its create response. | | | image_filenames | JSON object/list | Yes | Every current image filename, once each, in the desired order. | Send a JSON array with at most five image filenames. An empty array is valid only for an empty gallery. Null or blank cannot clear images. | | expected_revision | String | No | The record_revision returned by GET /v1/assets/images with $include_record_revision=true. Include it to avoid overwriting changes to its image gallery. Omit it to skip this check. | | Declared schema for `image_filenames` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "array", "items": { "type": "string" }, "maxItems": 5, "nullable": false, "x-maximum-depth": 2, "x-empty-create-means-omitted": false, "example": [ "98765-12345-a1941c59-59cb-4b7d-b7a7-2f82f8bf84ab.jpg", "98765-12345-59f0a281-df13-4bc9-acf1-3c12c25b1d25.jpg" ] } ``` #### Reordering images 1. Retrieve the current image list. 2. Put every `image_filename` returned by `GET /v1/assets/images` in `image_filenames`, in the order you want. 3. Submit the complete array. Use DELETE to remove an image. #### When the order is unchanged Sending the current order makes no change to images, timestamps, revision or history. Image filenames and file contents stay the same when the order changes. #### Avoiding conflicting changes Retrieve `GET /v1/assets/images` with `$include_record_revision=true`, then send its `record_revision` as `expected_revision`. This optional check covers the whole gallery. If the gallery changed after that read, nothing changes and the response is HTTP `409`. Retrieve the gallery again before deciding whether to retry. A successful request with this condition returns the resulting gallery revision. #### Image filenames and access Treat the filenames returned by GET /v1/assets/images as opaque values. Use them with the selected Asset ID. Shared Assets' images are managed in the Asset's original workspace. Editing an image on the website gives it a new filename. List the images again to get the current names. Example — curl: ```bash curl -X PATCH "https://api.exhibitday.com/v1/assets/images/order" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"asset_id\":12345,\"image_filenames\":[\"98765-12345-a1941c59-59cb-4b7d-b7a7-2f82f8bf84ab.jpg\",\"98765-12345-59f0a281-df13-4bc9-acf1-3c12c25b1d25.jpg\"]}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/images/order", { method: "PATCH", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "asset_id": 12345, "image_filenames": ["98765-12345-a1941c59-59cb-4b7d-b7a7-2f82f8bf84ab.jpg","98765-12345-59f0a281-df13-4bc9-acf1-3c12c25b1d25.jpg"] }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests import json response = requests.patch( "https://api.exhibitday.com/v1/assets/images/order", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"asset_id": 12345, "image_filenames": json.loads("[\"98765-12345-a1941c59-59cb-4b7d-b7a7-2f82f8bf84ab.jpg\",\"98765-12345-59f0a281-df13-4bc9-acf1-3c12c25b1d25.jpg\"]")}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Text.Json; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PatchAsync("https://api.exhibitday.com/v1/assets/images/order", JsonContent.Create(new { asset_id = 12345, image_filenames = JsonDocument.Parse("[\"98765-12345-a1941c59-59cb-4b7d-b7a7-2f82f8bf84ab.jpg\",\"98765-12345-59f0a281-df13-4bc9-acf1-3c12c25b1d25.jpg\"]").RootElement.Clone() })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/images/order")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("PATCH", HttpRequest.BodyPublishers.ofString("{\"asset_id\":12345,\"image_filenames\":[\"98765-12345-a1941c59-59cb-4b7d-b7a7-2f82f8bf84ab.jpg\",\"98765-12345-59f0a281-df13-4bc9-acf1-3c12c25b1d25.jpg\"]}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"asset_id":12345,"image_filenames":["98765-12345-a1941c59-59cb-4b7d-b7a7-2f82f8bf84ab.jpg","98765-12345-59f0a281-df13-4bc9-acf1-3c12c25b1d25.jpg"]}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/images/order') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"asset_id":12345,"image_filenames":["98765-12345-a1941c59-59cb-4b7d-b7a7-2f82f8bf84ab.jpg","98765-12345-59f0a281-df13-4bc9-acf1-3c12c25b1d25.jpg"]}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/assets/images/order", strings.NewReader("{\"asset_id\":12345,\"image_filenames\":[\"98765-12345-a1941c59-59cb-4b7d-b7a7-2f82f8bf84ab.jpg\",\"98765-12345-59f0a281-df13-4bc9-acf1-3c12c25b1d25.jpg\"]}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): PATCH /v1/assets/images/order - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Asset images reordered.", "errors": [] } ``` ### Download an Asset Image `GET https://api.exhibitday.com/v1/assets/images/download` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=images#get-v1-assets-images-download Downloads one current Asset image. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | asset_id | Number | Yes | The ID of the Asset whose images to use, from Retrieve Assets (GET /v1/assets) or its create response. | | | image_filename | String | Yes | The image_filename from this Asset's image list. | Use the value exactly as returned. Image filenames stay the same when the order changes. | #### Saving the download Use the Asset ID and its current `image_filename`. The response contains the stored image file as an attachment. Older images keep their stored format. A missing stored file returns HTTP `404`. This download does not substitute the default Asset icon or support conditional or partial downloads. #### Image filenames and access Treat the filenames returned by GET /v1/assets/images as opaque values. Use them with the selected Asset ID. Shared Assets' images are managed in the Asset's original workspace. Editing an image on the website gives it a new image_filename. List the images again to get the current names. #### Files still being copied If this file is still being copied, the download returns HTTP 409 with file_copy_pending. Try the download again in a few minutes. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X GET "https://api.exhibitday.com/v1/assets/images/download?asset_id=12345&image_filename=98765-12345-a1941c59-59cb-4b7d-b7a7-2f82f8bf84ab.jpg" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi mv response-body.tmp 'asset-image.jpg' ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const response = await fetch("https://api.exhibitday.com/v1/assets/images/download?asset_id=12345&image_filename=98765-12345-a1941c59-59cb-4b7d-b7a7-2f82f8bf84ab.jpg", { method: "GET", headers: { Authorization: 'Bearer YOUR_API_KEY' } }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); await writeFile("asset-image.jpg", new Uint8Array(await response.arrayBuffer())); ``` Example — Python: ```python import requests import json response = requests.request("GET", "https://api.exhibitday.com/v1/assets/images/download?asset_id=12345&image_filename=98765-12345-a1941c59-59cb-4b7d-b7a7-2f82f8bf84ab.jpg", headers={'Authorization': 'Bearer YOUR_API_KEY'}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') with open("asset-image.jpg", 'wb') as destination: destination.write(response.content) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.exhibitday.com/v1/assets/images/download?asset_id=12345&image_filename=98765-12345-a1941c59-59cb-4b7d-b7a7-2f82f8bf84ab.jpg"); using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); await File.WriteAllBytesAsync("asset-image.jpg", await response.Content.ReadAsByteArrayAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/assets/images/download?asset_id=12345&image_filename=98765-12345-a1941c59-59cb-4b7d-b7a7-2f82f8bf84ab.jpg")).header("Authorization", "Bearer YOUR_API_KEY"); HttpResponse response = HttpClient.newHttpClient().send(request.method("GET", HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); Files.write(Path.of("asset-image.jpg"), response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); file_put_contents('asset-image.jpg', $response); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/images/download?asset_id=12345&image_filename=98765-12345-a1941c59-59cb-4b7d-b7a7-2f82f8bf84ab.jpg') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' File.binwrite('asset-image.jpg', response.body) ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/assets/images/download?asset_id=12345&image_filename=98765-12345-a1941c59-59cb-4b7d-b7a7-2f82f8bf84ab.jpg", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } if err := os.WriteFile("asset-image.jpg", data, 0600); err != nil { log.Fatal(err) } fmt.Println("File saved") } ``` HTTP 200: The current stored image file, with its actual supported image type or a binary type for an older unrecognized representation. Media: image/jpeg, image/png, image/gif, application/octet-stream. The body is the authorized file's real bytes, not JSON or base64. Errors are JSON status responses; check HTTP status before saving the file. ## Assets - Logs The activity history of one Asset. Documentation page: https://api.exhibitday.com/Help/V1?epf=5&topic=logs ### Retrieve an Asset's Logs `GET https://api.exhibitday.com/v1/assets/logs` Documentation: https://api.exhibitday.com/Help/V1?epf=5&topic=logs#get-v1-assets-logs Retrieves the visible business history filed under one Asset. Filters work together to narrow its history. Results are ordered newest first by default. This is the selected record’s history, not a combined history of every child record. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | asset_id | Number | Yes | The ID of the Asset whose history you want to read. | Use the Asset's record ID. | | filter_by_actor_user_id | String | No | Only return entries written by this user. | Use the opaque `actor_user_id` from a log entry. Up to 128 characters; treat it as text. Historical IDs can match former users. | | filter_by_log_entry_contains_text | String | No | Only return entries containing this text. | Up to 3,000 characters after trimming surrounding spaces. Text is matched literally; HTML is not converted and search characters are not wildcards. | | filter_by_create_timestamp_greater_than_or_equal_to | String | No | Only return entries at or after this timestamp. | Use an ISO 8601 timestamp. A fractional lower bound starts at the next whole second. Include an offset or `Z` to state the time zone. | | filter_by_create_timestamp_smaller_than_or_equal_to | String | No | Only return entries at or before this timestamp. | Includes every entry in the displayed second. It must not precede the lower bound. | | filter_by_event_id | Number | No | Only return entries filed under this Event ID in your workspace’s history. | | | filter_by_event_tab_id | Number | No | Only return entries filed under this Event tab ID. GET /v1/references/event_tabs lists your workspace's tabs; the Presentations tab is accepted only where your workspace has it. | Allowed values: `1` (Info) \| `2` (Booth) \| `3` (Staff) \| `4` (Travel) \| `5` (Assets) \| `6` (Shipments) \| `7` (Sponsorships) \| `8` (Tasks) \| `9` (Playbook) \| `10` (Attachments) \| `11` (Misc. Expenses & Credits) \| `12` (Budget) \| `13` (ROI) \| `14` (Event Settings) \| `16` (Binder) \| `17` (Copy Event) \| `19` (Logs) \| `20` (Delete Event) \| `21` (Giveaways) \| `22` (Special Tab, shown under your workspace's name for it) | | filter_by_context_type | String | No | Only return entries associated with the selected context. Omit to include all contexts. Workspace means an entry with none of the other associations; an entry can belong to more than one other context. Unsupported values are refused. Values are case-insensitive. | Allowed values: `workspace` \| `event` \| `task` \| `asset` \| `storage_location` | | $result_sort | String | No | Sort entries newest first (the default) or oldest first. The full saved timestamp is used, with the entry ID breaking ties in the same direction. Responses display whole seconds. Unsupported values are refused. Use the values exactly as shown (lowercase). | Allowed values: `create_timestamp_desc` (newest first) \| `create_timestamp_asc` (oldest first) | | $limit | Number | No | The maximum number of matching entries to return. | One positive whole number. Omit for all matches after `$offset`; there is no fixed page-size cap. | | $offset | Number | No | The number of matching entries to skip. | Default: 0. Send a nonnegative whole number. | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | | If-None-Match | String | No | Send the ETag from an earlier response when checking whether this result changed. | Optional request header. A matching current result returns HTTP 304 with no body; reuse your earlier response. This header compares GET responses. It cannot prevent a conflicting update. | #### Choosing the record Use the Asset ID to choose the history you want to retrieve. Active and Archived Assets are supported. Only entries filed under the selected record are included. Sharing or borrowing an Asset does not grant access to its owner’s history. Only history visible to workspace users is returned. Hidden or technical entries, impersonation activity, IP addresses, device details and security information are excluded. #### Filtering by time and context Returned timestamps use UTC and display whole seconds. Timestamp filters use that displayed precision: the upper bound includes the entire displayed second, and a fractional lower bound starts at the next whole second. An input with an offset or `Z` is converted for comparison. A timestamp without an offset is interpreted as US Eastern time. Include an offset when you want an unambiguous instant. `workspace` context selects entries with no Event, Task, Asset or Storage Location association. The other contexts select entries with that association, and an entry can have several associations. Every result must still be filed under this selected Asset, so a context filter can legitimately produce no matches. #### Paging the result `records_found` is the number of rows in this response; `total_records` is the filtered count before paging. `has_more` indicates whether more matching rows remain. Results can change while the data is edited. Omit `$limit` for all matches after `$offset`, or use the two options to read smaller pages. There is no fixed page-size cap. This list does not return edit revisions or support changed-since filtering. #### Handling errors This method has no empty-result-on-error option. Invalid inputs retain their error status. If concurrent changes prevent the read, HTTP `409` with `error_code=record_changed` means you should read again. Each row has the same fields as an entry from `GET /v1/workspace_settings/logs`. It does not change the selected record, issue an edit revision or provide a feed of changes and deletions. #### Sending filter values Use the query string, form data or JSON for a text filter that contains a comma. #### Checking whether a response changed Normal API-key and access checks still apply. This header compares the response; it does not authorize access or protect an update. 1. Save the response body and its `ETag` header from an earlier GET. 2. Repeat the same GET, including the same filters and response options, with that ETag in the `If-None-Match` header. 3. If the response is HTTP `304`, keep using your saved body. If it is HTTP `200`, use the new body and ETag. #### Reading the actor `actor_user_id` is the ID of the user who made the change. `actor_display_name` is the name saved with the entry at that time; it does not change if the user is renamed later. Entries recorded by the API have a null `actor_user_id` and show the label saved with them, such as `API`. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/assets/logs?asset_id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/assets/logs?" + new URLSearchParams({ "asset_id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/assets/logs", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"asset_id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/assets/logs?asset_id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/assets/logs?asset_id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/assets/logs?asset_id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/assets/logs?asset_id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/assets/logs - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "workspace_log", "list_data": [ { "id": 67890, "log_entry_created_timestamp": "2026-01-02T08:04:05Z", "actor_user_id": "11111111-2222-4333-8444-555555555555", "actor_display_name": "Illustrative user", "log_entry": "Illustrative user updated the selected record.", "event_id": null, "event_name": null, "event_tab_id": 0, "task_id": null, "task_name": null, "asset_id": 12345, "asset_name": "Display stand", "storage_location_id": null, "storage_location_name": "" } ] } ``` ## Financials Annual budgets, the annual budget allocation export and costs by Cost Center. Documentation page: https://api.exhibitday.com/Help/V1?epf=4 ### Retrieve Annual Budgets `GET https://api.exhibitday.com/v1/financials/annual_budgets` Documentation: https://api.exhibitday.com/Help/V1?epf=4#get-v1-financials-annual_budgets Lists the budget years saved in your workspace, with planned budgets, actual costs and the difference between them. Results are ordered by budget year. Years that haven't been set up are left out. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | filter_by_budget_year | Number | No | Return only the saved budget for this year. Omit to list all saved budget years. A year that hasn't been set up returns an empty list. | A four-digit year such as `2026`. | | $limit | Number | No | The maximum number of rows to return. Omit to return all remaining matching rows. | A whole number of 1 or more. | | $offset | Number | No | How many matching rows to skip. | A whole number of 0 or more. Default `0`. | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | | $include_record_revision | Boolean | No | Set to `true` to include each year's `record_revision`. Send that value as `expected_revision` when you update the same year to check for conflicting changes. Changes to formatting saved in ExhibitDay can change the revision even when the Notes look the same. | Default: false. | #### Report details Fiscal years follow your workspace's fiscal-year start month and are named for the year in which they end. Event totals include every Event that starts within that fiscal year, regardless of participation status. Sponsorship costs are shown separately from other Event costs. Miscellaneous annual expenses count toward their saved budget year. Amounts use your workspace currency, and costs on hidden Event tabs are included. Budgeting must be available for your workspace. Notes are returned as saved HTML. The `X-API-Warnings` header lists any parameters ignored because they belong to the Cost Center Breakdown report. #### Report parameters Use whole numbers for years, IDs and paging. Omit unused optional parameters rather than sending an empty value or null. If you repeat a parameter, send the same value each time. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/financials/annual_budgets" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/financials/annual_budgets", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/financials/annual_budgets", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/financials/annual_budgets"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/financials/annual_budgets")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/financials/annual_budgets') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/financials/annual_budgets", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/financials/annual_budgets - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_data": [ { "exhibitday_url": "https://www.exhibitday.com/Workspace/AnnualEventBudgets/98765?year=2030", "id": 12345, "budget_year": 2030, "fiscal_start_date": "2030-01-01", "fiscal_end_date": "2030-12-31", "planned_num_events": 5, "actual_num_events": 0, "planned_exhibit_amount": 10000.00, "planned_sponsorship_amount": 2000.00, "allocated_event_amount": 0.00, "actual_exhibit_amount": 0.00, "actual_sponsorship_amount": 0.00, "planned_annual_misc_amount": 0.00, "actual_annual_misc_amount": 0.00, "total_planned_amount": 12000.00, "total_actual_amount": 0.00, "variance": 12000.00, "notes": "

Annual Event plan

", "annual_budget_created_timestamp": "2029-12-01T17:00:00Z", "annual_budget_last_update_timestamp": "2029-12-01T17:00:00Z" } ] } ``` ### Retrieve Costs by Cost Center `GET https://api.exhibitday.com/v1/financials/cost_center_breakdown` Documentation: https://api.exhibitday.com/Help/V1?epf=4#get-v1-financials-cost_center_breakdown Lists costs by cost center for one saved budget year. Each row shows either the nine cost categories for one Event and cost center or the miscellaneous annual expenses for one cost center. The report includes costs on hidden Event tabs and Events of any participation status. Credits are negative amounts. Payment notes and invoice files are excluded. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | filter_by_budget_year | Number | Yes | The saved budget year to report on. See `GET /v1/references/budget_years` for available years. | A four-digit year such as `2026`. | | filter_by_cost_center_id | Number | No | Omit for all cost centers, use `0` for costs marked Not Specified, or use a cost center ID from your workspace. | | | $limit | Number | No | The maximum number of rows to return. Omit to return all remaining matching rows. | A whole number of 1 or more. | | $offset | Number | No | How many matching rows to skip. | A whole number of 0 or more. Default `0`. | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | #### Report details Results are sorted by cost center name, with Event rows before miscellaneous annual expenses. Budgeting must be available for your workspace. A missing budget or cost center returns HTTP 404. Conflicting saved budget years or costs assigned outside your workspace return HTTP 409. The `X-API-Warnings` header lists any parameters ignored because they belong to the Annual Budgets report. #### Report parameters Use whole numbers for years, IDs and paging. Omit unused optional parameters rather than sending an empty value or null. If you repeat a parameter, send the same value each time. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/financials/cost_center_breakdown?filter_by_budget_year=2030" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/financials/cost_center_breakdown?" + new URLSearchParams({ "filter_by_budget_year": "2030" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/financials/cost_center_breakdown", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"filter_by_budget_year": 2030}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/financials/cost_center_breakdown?filter_by_budget_year=2030"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/financials/cost_center_breakdown?filter_by_budget_year=2030")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/financials/cost_center_breakdown?filter_by_budget_year=2030') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/financials/cost_center_breakdown?filter_by_budget_year=2030", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/financials/cost_center_breakdown - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_data": [ { "cost_center_id": 34567, "cost_center": "Marketing", "expense_type": "event", "event_id": 23456, "event_name": "Technology Trade Show & Exhibit", "booth_reservation": 100.00, "booth_services": 0.00, "attendee_registration_and_tickets": 0.00, "travel_reservations": 0.00, "giveaways": 0.00, "shipments": 0.00, "sponsorships": 25.00, "event_activities": 0.00, "misc_expenses_and_credits": -10.00, "total": 115.00 } ] } ``` ### Update an Annual Budget `PATCH https://api.exhibitday.com/v1/financials/annual_budgets` Documentation: https://api.exhibitday.com/Help/V1?epf=4#patch-v1-financials-annual_budgets Update the planned number of Events, Exhibit budget, Sponsorship budget and Notes for one Annual Budget year. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | budget_year | Number | Yes | The budget year to update. To set up an eligible year, supply at least one budget field and omit `expected_revision`. A saved budget cannot be moved to a different year. | A four-digit year such as `2026`. | | planned_num_events | Number | No | The planned number of Events, as a whole number from 0 through 2,147,483,647. Omit or leave blank to keep the current number. This field cannot be cleared. | | | planned_exhibit_amount | Number | No | The planned Exhibit amount in your workspace currency, from 0 through 999,999,999,999,999.99. Send a number without currency symbols or grouping commas. Values are rounded to two decimal places with midpoint values away from zero, matching the budget editor. Omit or leave blank to keep the current amount; null resets it to 0. Omitted saved values remain unchanged. | | | planned_sponsorship_amount | Number | No | The planned Sponsorship amount in your workspace currency, from 0 through 999,999,999,999,999.99. Send a number without currency symbols or grouping commas. Values are rounded to two decimal places with midpoint values away from zero, matching the budget editor. Omit or leave blank to keep the current amount; null resets it to 0. Omitted saved values remain unchanged. | | | notes | String | No | Send Budget Notes as plain text with line breaks. Omit or leave blank to keep the current Notes. Send `null` to clear them. When saved Notes already exceed a limit, an update can keep or shorten them. | Up to 30,000 characters in both the saved value and the editor, including formatting and encoded characters. Input that exceeds these limits is refused rather than shortened. HTML tags are removed, characters are HTML-encoded and line breaks become
. Responses therefore contain HTML. | | expected_revision | String | No | The revision from the same Annual Budget year. Omit it to initialize an available missing year or save without a revision check. | | #### Choosing the year Use `budget_year` for the year to update. Saved years remain editable. To initialize a missing year, supply at least one budget field and omit `expected_revision`. Available new years are the current calendar year, two years before it and six years after it, or fiscal years used by your workspace's Events. An explicit zero initializes a year; an empty request does not. #### Updating values Omitted or blank fields keep their current values. Null clears Notes and resets a planned amount to zero; the planned number of Events cannot be cleared. With `$ignore_params_with_empty_values=true`, JSON nulls are omitted instead. Send Notes as plain text with line breaks. Amounts use your workspace currency; changing its currency setting does not convert saved amounts. #### Checking for changes To protect a saved year, use `GET /v1/financials/annual_budgets` with `$include_record_revision=true`, then send that year's `record_revision` as `expected_revision`. A changed year returns HTTP 409 and nothing is saved. An unchanged update creates no activity history. If the save outcome cannot be confirmed, read the year and review its values before trying again. Example — curl: ```bash curl -X PATCH "https://api.exhibitday.com/v1/financials/annual_budgets" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"budget_year\":2030,\"planned_num_events\":5}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/financials/annual_budgets", { method: "PATCH", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "budget_year": 2030, "planned_num_events": 5 }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.patch( "https://api.exhibitday.com/v1/financials/annual_budgets", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"budget_year": 2030, "planned_num_events": 5}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PatchAsync("https://api.exhibitday.com/v1/financials/annual_budgets", JsonContent.Create(new { budget_year = 2030, planned_num_events = 5 })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/financials/annual_budgets")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("PATCH", HttpRequest.BodyPublishers.ofString("{\"budget_year\":2030,\"planned_num_events\":5}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"budget_year":2030,"planned_num_events":5}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/financials/annual_budgets') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"budget_year":2030,"planned_num_events":5}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/financials/annual_budgets", strings.NewReader("{\"budget_year\":2030,\"planned_num_events\":5}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): PATCH /v1/financials/annual_budgets - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Annual budget updated.", "errors": [] } ``` ### Export Annual Budget Allocation Breakdown `GET https://api.exhibitday.com/v1/financials/budgets/export` Documentation: https://api.exhibitday.com/Help/V1?epf=4#get-v1-financials-budgets-export Downloads the Allocation Breakdown for one Annual Budget year as an Excel workbook. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | budget_year | Number | Yes | The saved Annual Budget year to export. | A four-digit year such as `2026`. | #### Choosing the year Use a saved `budget_year` from your workspace. Your workspace's fiscal-year start month determines which Events belong to that year. The year must already have a saved Annual Budget. This download does not create a year or update budget values. #### What the workbook includes The 31 columns follow the Allocation Breakdown in ExhibitDay: Event details, planned and actual amounts, percentages, and the nine cost categories. Events marked Not Going with no nonzero saved cost are omitted. Annual miscellaneous expenses are not separate rows in this per-Event workbook. Amounts and percentages use the calculations shown in the Annual Budgets Allocation Breakdown. Financial reports include costs on hidden Event tabs. #### Downloading and handling errors Budgeting and data export must be available on your workspace's current plan. The response is an XLSX download; there is no `scope` or `format` input. A missing saved year returns HTTP `404`. An unsuccessful request returns the usual JSON error response. This read creates no business activity or notification. Example — curl: ```bash # bash; inspect an error body instead of saving it as the requested file. status=$(curl --silent --show-error -X GET "https://api.exhibitday.com/v1/financials/budgets/export?budget_year=2027" -H "Authorization: Bearer YOUR_API_KEY" --output response-body.tmp --write-out "%{http_code}") if [ "$status" != 200 ]; then cat response-body.tmp; exit 1; fi mv response-body.tmp 'Annual_Budget_2027_Breakdown_by_Event__2027-01-30_120000000.xlsx' ``` Example — Node.js: ```javascript // Node.js 18+; use a local file only for a declared multipart operation. import { readFile, writeFile } from 'node:fs/promises'; const response = await fetch("https://api.exhibitday.com/v1/financials/budgets/export?budget_year=2027", { method: "GET", headers: { Authorization: 'Bearer YOUR_API_KEY' } }); if (response.status !== 200) throw new Error(`${response.status}: ${await response.text()}`); await writeFile("Annual_Budget_2027_Breakdown_by_Event__2027-01-30_120000000.xlsx", new Uint8Array(await response.arrayBuffer())); ``` Example — Python: ```python import requests import json response = requests.request("GET", "https://api.exhibitday.com/v1/financials/budgets/export?budget_year=2027", headers={'Authorization': 'Bearer YOUR_API_KEY'}, timeout=30) if response.status_code != 200: raise RuntimeError(f'{response.status_code}: {response.text}') with open("Annual_Budget_2027_Breakdown_by_Event__2027-01-30_120000000.xlsx", 'wb') as destination: destination.write(response.content) ``` Example — C#: ```csharp using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); using var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.exhibitday.com/v1/financials/budgets/export?budget_year=2027"); using var response = await client.SendAsync(request); if ((int)response.StatusCode != 200) throw new Exception(await response.Content.ReadAsStringAsync()); await File.WriteAllBytesAsync("Annual_Budget_2027_Breakdown_by_Event__2027-01-30_120000000.xlsx", await response.Content.ReadAsByteArrayAsync()); ``` Example — Java: ```java import java.net.URI; import java.net.http.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.io.ByteArrayOutputStream; import java.util.UUID; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://api.exhibitday.com/v1/financials/budgets/export?budget_year=2027")).header("Authorization", "Bearer YOUR_API_KEY"); HttpResponse response = HttpClient.newHttpClient().send(request.method("GET", HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) throw new RuntimeException(new String(response.body(), StandardCharsets.UTF_8)); Files.write(Path.of("Annual_Budget_2027_Breakdown_by_Event__2027-01-30_120000000.xlsx"), response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) throw new RuntimeException(curl_error($curl)); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status !== 200) throw new RuntimeException($response); file_put_contents('Annual_Budget_2027_Breakdown_by_Event__2027-01-30_120000000.xlsx', $response); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/financials/budgets/export?budget_year=2027') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) } raise response.body unless response.code == '200' File.binwrite('Annual_Budget_2027_Breakdown_by_Event__2027-01-30_120000000.xlsx', response.body) ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "os" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/financials/budgets/export?budget_year=2027", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() data, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } if response.StatusCode != 200 { log.Fatalf("%d %s", response.StatusCode, data) } if err := os.WriteFile("Annual_Budget_2027_Breakdown_by_Event__2027-01-30_120000000.xlsx", data, 0600); err != nil { log.Fatal(err) } fmt.Println("File saved") } ``` HTTP 200: Downloads the Annual Budget Allocation Breakdown as a private XLSX workbook. Errors use the usual JSON API response. Media: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet. The body is the authorized file's real bytes, not JSON or base64. Errors are JSON status responses; check HTTP status before saving the file. ## Financials - Event Costs Event cost lines for reports and integrations, with an export. Documentation page: https://api.exhibitday.com/Help/V1?epf=4&topic=event-costs ### Retrieve Event Costs `GET https://api.exhibitday.com/v1/financials/event_costs` Documentation: https://api.exhibitday.com/Help/V1?epf=4&topic=event-costs#get-v1-financials-event_costs Retrieves the costs recorded on your Events, one record per cost. The list includes costs on hidden Event tabs. Filter by Event ID, Event dates, a start-date category, or a fiscal budget year. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | filter_by_event_id | Number | No | Return costs for this Event only. Omit to return costs for all Events that match the other filters. | | | filter_by_event_start_date_greater_than_or_equal_to | Date | No | Include Events that start on or after this date. | Use `YYYY-MM-DD`. | | filter_by_event_start_date_smaller_than_or_equal_to | Date | No | Include Events that start on or before this date. | Use `YYYY-MM-DD`. | | filter_by_event_end_date_greater_than_or_equal_to | Date | No | Include Events that end on or after this date. | Use `YYYY-MM-DD`. | | filter_by_event_end_date_smaller_than_or_equal_to | Date | No | Include Events that end on or before this date. | Use `YYYY-MM-DD`. | | filter_by_event_start_date_category | String | No | Choose `all` for every Event, `upcoming` for Events that end today or later (including Events in progress), or `past` for Events that ended before today. A year selects Events that start in that calendar year. Today is based on your workspace's time zone. When you use this filter, the four date filters are ignored. Category values are case-insensitive and ignore surrounding spaces. See `GET /v1/references/event_start_date_categories` for your workspace's categories. | Allowed values: `all` \| `upcoming` \| `past` \| a year such as `2026` | | filter_by_budget_year | Number | No | Include Events that start in this fiscal year, using the same fiscal-year start month as Annual Budgets. Events must also match any start or end date filters you supply. Use either this filter or `filter_by_event_start_date_category`. If the date bounds don't overlap, the response contains an empty list and a warning. | A four-digit year such as `2026`. | | $limit | Number | No | The maximum number of cost records to return. Omit to return all remaining matches. Use `$offset` for paging. `total_records` and the `X-Total-Count` header give the full count. `has_more` tells you whether more records are available. | A whole number of 1 or more. | | $offset | Number | No | How many cost records to skip. For the next page, add the number of records you received to the current offset. | A whole number of 0 or more. Default `0`. | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | | $on_error_return_empty_result | Boolean | No | Set to `true` to return HTTP 200 with an empty list when an ID, date filter or paging value is invalid, or when the Event doesn't exist. Authentication, rate-limit and unexpected server errors keep their normal HTTP status. | Default: false. | #### Cost types For Booth Services, `cost_subtype` gives the selected service type, including "Other" when that is the selected type. For Event Activities, it gives the activity type or category, such as "Presentation (Other)". It returns `null` for Booth Services without a type, General or unspecified Event Activities, and other cost types. The `details` field describes the individual item. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/financials/event_costs" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/financials/event_costs", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/financials/event_costs", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/financials/event_costs"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/financials/event_costs")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/financials/event_costs') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/financials/event_costs", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/financials/event_costs - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "event_cost", "list_data": [ { "id": 12345, "cost_type_id": 6, "cost_type": "Miscellaneous Expense/Credit", "cost_subtype": null, "details": "Sample expense", "cost": { "amount": 125.50, "cost_center_breakdown": [ { "cost_center_id": null, "cost_center": "Not Specified", "charge": 125.50 } ] }, "amount": 125.50, "amount_cost_center_breakdown": [ { "cost_center_id": null, "cost_center": "Not Specified", "charge": 125.50 } ], "payment_due_date": "", "payment_status": { "id": 0, "name": "Not Specified" }, "next_payment_due_date": "", "payment_notes": "", "event": { "id": 12345, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=12345", "name": "Sample Event", "start_date": "2026-12-21", "end_date": "2026-12-23", "participation_type_id": 1, "participation_type": "Committed", "format_id": 1, "format": "In-Person", "event_created_timestamp": "2026-11-21T17:00:00Z", "event_last_update_timestamp": "2026-11-21T17:00:00Z" } } ] } ``` ## Financials - Misc. Annual Expenses Annual miscellaneous expenses: the entries and their costs. Documentation page: https://api.exhibitday.com/Help/V1?epf=4&topic=misc-annual-expenses-credits ### Retrieve a Single Annual Miscellaneous Expense by ID `GET https://api.exhibitday.com/v1/financials/misc_annual_expenses/info` Documentation: https://api.exhibitday.com/Help/V1?epf=4&topic=misc-annual-expenses-credits#get-v1-financials-misc_annual_expenses-info Retrieves an Annual Miscellaneous Expense by its ID, including its planned amount and actual cost. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The id of the annual miscellaneous expense you would like to retrieve or change. Use the id returned for this expense. | | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` | | $include_record_revision | Boolean | No | Set to true to include record_revision in the response. Send that value as expected_revision when updating to check for conflicting changes. | Default: false. | | $on_error_return_empty_result | Boolean | No | For a missing or invalid expense id, or an expense not found, return HTTP 200 with {} (or [] when using array format). Authentication failures, a record that changes while it is read and unexpected errors keep their normal error status. | | #### Working with annual expenses These expenses appear under Annual Budgets and belong to a budget year, such as annual materials storage. The planned amount is your estimate; cost records the actual amount and its cost center breakdown. The id returned by /v1/financials/misc_annual_expense_costs identifies the same expense and can be used with these methods. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/financials/misc_annual_expenses/info?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/financials/misc_annual_expenses/info?" + new URLSearchParams({ "id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/financials/misc_annual_expenses/info", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/financials/misc_annual_expenses/info?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/financials/misc_annual_expenses/info?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/financials/misc_annual_expenses/info?id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/financials/misc_annual_expenses/info?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/financials/misc_annual_expenses/info - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "id": 12345, "budget_year": 2026, "description": "Annual materials storage", "planned_amount": 150.00, "cost": { "amount": 125.50, "cost_center_breakdown": [ { "cost_center_id": 34567, "cost_center": "Marketing", "charge": 75.50 }, { "cost_center_id": 34568, "cost_center": "Operations", "charge": 50.00 } ] } } ``` ### List Annual Miscellaneous Expenses `GET https://api.exhibitday.com/v1/financials/misc_annual_expenses` Documentation: https://api.exhibitday.com/Help/V1?epf=4&topic=misc-annual-expenses-credits#get-v1-financials-misc_annual_expenses Lists the Annual Miscellaneous Expenses of your workspace's annual budgets, ordered by budget year and then id, each with its planned amount and actual cost. Use filter_by_budget_year for one year. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | filter_by_budget_year | Number | No | Only list the expenses of this budget year, for example 2030. Omit it for every year. Get saved years from GET /v1/references/budget_years. | | | $limit | Number | No | The most expenses to return, as a whole number of 1 or more. Omit it for all remaining expenses. | | | $offset | Number | No | How many expenses to skip before the first one returned (0 by default). | | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | #### Working with annual expenses These expenses appear under Annual Budgets and belong to a budget year, such as annual materials storage. The planned amount is your estimate; cost records the actual amount and its cost center breakdown. The id returned by /v1/financials/misc_annual_expense_costs identifies the same expense and can be used with these methods. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/financials/misc_annual_expenses" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/financials/misc_annual_expenses", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/financials/misc_annual_expenses", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/financials/misc_annual_expenses"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/financials/misc_annual_expenses")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/financials/misc_annual_expenses') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/financials/misc_annual_expenses", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/financials/misc_annual_expenses - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "misc_annual_expense", "list_data": [ { "id": 12345, "budget_year": 2026, "description": "Annual materials storage", "planned_amount": 150.00, "cost": { "amount": 0.00, "cost_center_breakdown": [] } } ] } ``` ### Create an Annual Miscellaneous Expense `POST https://api.exhibitday.com/v1/financials/misc_annual_expenses` Documentation: https://api.exhibitday.com/Help/V1?epf=4&topic=misc-annual-expenses-credits#post-v1-financials-misc_annual_expenses Adds a miscellaneous expense to an annual budget. Use cost for the actual amount and its cost center breakdown. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | budget_year | Number | Yes | The budget year to add the expense to, such as 2026. Choose a year from GET /v1/references/budget_years. If that year does not have an annual budget yet, ExhibitDay creates it with zero planned budgets, the same way the Annual Budgets page does. | | | description | String | No | The description shown under Annual Budgets, up to 500 characters. Omit it or leave it blank to use Misc. Expense. | Max length: 500. | | planned_amount | Number | No | The amount you plan to spend on this annual expense. [Record Costs and Split Them Across Cost Centers](/Help/V1?guide=entering-costs). | A nonnegative scalar amount in your workspace currency, rounded to cents. Omit or leave blank on PATCH to keep it; null resets it to zero. Cost center allocations apply to the actual cost, not this planned amount. | | cost | Number or cost object | No | The full cost, as a number or an object with amount and/or cost_center_breakdown. [Record Costs and Split Them Across Cost Centers](/Help/V1?guide=entering-costs). | Optional; defaults to zero. | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` | Declared schema for `cost` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "anyOf": [ { "type": "number", "minimum": 0, "description": "Shorthand for an object with amount. The amount is rounded to cents before the supported storage range is checked.", "nullable": true }, { "type": "object", "additionalProperties": false, "properties": { "amount": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 }, "cost_center_breakdown": { "type": "array", "items": { "type": "object", "additionalProperties": false, "properties": { "cost_center_id": { "type": "integer", "format": "int64", "nullable": true }, "charge": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 }, "cost_center": { "type": "string", "description": "Optional and read-only: the cost center name a read returns, so a cost can be sent back unchanged. It is ignored; the line is saved by cost_center_id, and a name that doesn't match that cost center is explained in a warning.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "required": [ "charge" ] }, "maxItems": 2147483647 } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "anyOf": [ { "required": [ "amount" ] }, { "required": [ "cost_center_breakdown" ] } ], "nullable": true } ], "x-numeric-shorthand": "A number is equivalent to {amount:number}.", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": { "amount": 125.50 } } ``` #### Working with annual expenses These expenses appear under Annual Budgets and belong to a budget year, such as annual materials storage. The planned amount is your estimate; cost records the actual amount and its cost center breakdown. The id returned by /v1/financials/misc_annual_expense_costs identifies the same expense and can be used with these methods. Example — curl: ```bash curl -X POST "https://api.exhibitday.com/v1/financials/misc_annual_expenses" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"budget_year\":2030,\"description\":\"Sample description\",\"planned_amount\":100,\"cost\":{\"amount\":125.50}}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/financials/misc_annual_expenses", { method: "POST", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "budget_year": 2030, "description": "Sample description", "planned_amount": 100, "cost": {"amount":125.50} }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests import json response = requests.post( "https://api.exhibitday.com/v1/financials/misc_annual_expenses", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"budget_year": 2030, "description": "Sample description", "planned_amount": 100, "cost": json.loads("{\"amount\":125.50}")}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Text.Json; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PostAsync("https://api.exhibitday.com/v1/financials/misc_annual_expenses", JsonContent.Create(new { budget_year = 2030, description = "Sample description", planned_amount = 100, cost = JsonDocument.Parse("{\"amount\":125.50}").RootElement.Clone() })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/financials/misc_annual_expenses")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("POST", HttpRequest.BodyPublishers.ofString("{\"budget_year\":2030,\"description\":\"Sample description\",\"planned_amount\":100,\"cost\":{\"amount\":125.50}}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"budget_year":2030,"description":"Sample description","planned_amount":100,"cost":{"amount":125.50}}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/financials/misc_annual_expenses') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"budget_year":2030,"description":"Sample description","planned_amount":100,"cost":{"amount":125.50}}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/financials/misc_annual_expenses", strings.NewReader("{\"budget_year\":2030,\"description\":\"Sample description\",\"planned_amount\":100,\"cost\":{\"amount\":125.50}}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): POST /v1/financials/misc_annual_expenses - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "id": 23456, "budget_year": 2030, "description": "Sample description", "planned_amount": 100.00, "cost": { "amount": 125.50, "cost_center_breakdown": [ { "cost_center_id": null, "cost_center": "Not Specified", "charge": 125.50 } ] } } ``` ### Update an Annual Miscellaneous Expense `PATCH https://api.exhibitday.com/v1/financials/misc_annual_expenses` Documentation: https://api.exhibitday.com/Help/V1?epf=4&topic=misc-annual-expenses-credits#patch-v1-financials-misc_annual_expenses Updates an Annual Miscellaneous Expense. Include only the fields you want to change. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The id of the annual miscellaneous expense you would like to retrieve or change. Use the id returned for this expense. | | | budget_year | Number | No | Optionally confirm the budget year for this expense. If supplied, it must match the current year; an existing expense cannot be moved to another budget year. | | | description | String | No | The description shown under Annual Budgets, up to 500 characters. Omit it or send a blank value to keep the current description. Send `null` to use Misc. Expense. | Max length: 500. | | planned_amount | Number | No | The amount you plan to spend on this annual expense. [Record Costs and Split Them Across Cost Centers](/Help/V1?guide=entering-costs). | A nonnegative scalar amount in your workspace currency, rounded to cents. Omit or leave blank on PATCH to keep it; null resets it to zero. Cost center allocations apply to the actual cost, not this planned amount. | | cost | Number or cost object | No | The full cost, as a number or an object with amount and/or cost_center_breakdown. [Record Costs and Split Them Across Cost Centers](/Help/V1?guide=entering-costs). | Omit to keep the saved cost. A supplied value replaces its full allocation. | | expected_revision | String | No | The record_revision returned when you retrieved this record. Include it to avoid overwriting someone else's changes. Omit it to skip this check. | | Declared schema for `cost` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "anyOf": [ { "type": "number", "minimum": 0, "description": "Shorthand for an object with amount. The amount is rounded to cents before the supported storage range is checked.", "nullable": true }, { "type": "object", "additionalProperties": false, "properties": { "amount": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 }, "cost_center_breakdown": { "type": "array", "items": { "type": "object", "additionalProperties": false, "properties": { "cost_center_id": { "type": "integer", "format": "int64", "nullable": true }, "charge": { "type": "number", "minimum": 0.0, "maximum": 79228162514264337593543950335.0 }, "cost_center": { "type": "string", "description": "Optional and read-only: the cost center name a read returns, so a cost can be sent back unchanged. It is ignored; the line is saved by cost_center_id, and a name that doesn't match that cost center is explained in a warning.", "nullable": true } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "required": [ "charge" ] }, "maxItems": 2147483647 } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "anyOf": [ { "required": [ "amount" ] }, { "required": [ "cost_center_breakdown" ] } ], "nullable": true } ], "x-numeric-shorthand": "A number is equivalent to {amount:number}.", "nullable": true, "x-maximum-depth": 3, "x-empty-create-means-omitted": true, "example": { "amount": 125.50 } } ``` #### Working with annual expenses These expenses appear under Annual Budgets and belong to a budget year, such as annual materials storage. The planned amount is your estimate; cost records the actual amount and its cost center breakdown. The id returned by /v1/financials/misc_annual_expense_costs identifies the same expense and can be used with these methods. Example — curl: ```bash curl -X PATCH "https://api.exhibitday.com/v1/financials/misc_annual_expenses" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"id\":12345,\"description\":\"Updated description\"}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/financials/misc_annual_expenses", { method: "PATCH", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "id": 12345, "description": "Updated description" }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.patch( "https://api.exhibitday.com/v1/financials/misc_annual_expenses", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"id": 12345, "description": "Updated description"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PatchAsync("https://api.exhibitday.com/v1/financials/misc_annual_expenses", JsonContent.Create(new { id = 12345, description = "Updated description" })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/financials/misc_annual_expenses")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("PATCH", HttpRequest.BodyPublishers.ofString("{\"id\":12345,\"description\":\"Updated description\"}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"id":12345,"description":"Updated description"}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/financials/misc_annual_expenses') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"id":12345,"description":"Updated description"}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/financials/misc_annual_expenses", strings.NewReader("{\"id\":12345,\"description\":\"Updated description\"}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): PATCH /v1/financials/misc_annual_expenses - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Annual expense updated.", "errors": [] } ``` ### Delete an Annual Miscellaneous Expense `DELETE https://api.exhibitday.com/v1/financials/misc_annual_expenses` Documentation: https://api.exhibitday.com/Help/V1?epf=4&topic=misc-annual-expenses-credits#delete-v1-financials-misc_annual_expenses Permanently removes an Annual Miscellaneous Expense and its recorded cost. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The id of the annual miscellaneous expense you would like to retrieve or change. Use the id returned for this expense. | | #### Working with annual expenses These expenses appear under Annual Budgets and belong to a budget year, such as annual materials storage. The planned amount is your estimate; cost records the actual amount and its cost center breakdown. The id returned by /v1/financials/misc_annual_expense_costs identifies the same expense and can be used with these methods. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/financials/misc_annual_expenses?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/financials/misc_annual_expenses?" + new URLSearchParams({ "id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/financials/misc_annual_expenses", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/financials/misc_annual_expenses?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/financials/misc_annual_expenses?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/financials/misc_annual_expenses?id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/financials/misc_annual_expenses?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/financials/misc_annual_expenses - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Annual expense removed.", "errors": [] } ``` ### Retrieve Miscellaneous Annual Expense Costs `GET https://api.exhibitday.com/v1/financials/misc_annual_expense_costs` Documentation: https://api.exhibitday.com/Help/V1?epf=4&topic=misc-annual-expenses-credits#get-v1-financials-misc_annual_expense_costs If a specific Budget Year is passed in (using the "filter_by_budget_year" parameter, e.g. 2026), then only the miscellaneous annual expense costs for that budget year are returned. Otherwise, all miscellaneous annual expense costs for all budget years are returned. Every miscellaneous annual expense is listed, including one with a planned amount and no cost recorded yet (its actual_amount is 0 and its actual_amount_cost_center_breakdown is empty). Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | filter_by_budget_year | Number | No | Only return the miscellaneous annual expense costs of this budget year, for example 2030. Omit it (or send all) for every year. budget_year is an older name for this parameter and is still accepted; send one of them. | | | $limit | Number | No | The most cost records to return (a whole number of 1 or more). Use it with $offset to read a long list in pages: total_records in the response counts every matching cost record and has_more is true while more pages follow (the X-Total-Count header carries the total too). Without $limit, every matching cost record is returned. | | | $offset | Number | No | How many cost records to skip before the first one returned (a whole number; 0 by default). For the next page, add the number of cost records you received to $offset. | | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | | $on_error_return_empty_result | Boolean | No | For invalid filter_by_budget_year (or budget_year) or paging values, return HTTP 200 with no matching records in the selected result format. Authentication, rate-limit and unexpected server errors keep their normal HTTP status. | Default: false. | Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/financials/misc_annual_expense_costs" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/financials/misc_annual_expense_costs", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/financials/misc_annual_expense_costs", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/financials/misc_annual_expense_costs"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/financials/misc_annual_expense_costs")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/financials/misc_annual_expense_costs') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/financials/misc_annual_expense_costs", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/financials/misc_annual_expense_costs - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "misc_annual_expense_cost", "list_data": [ { "id": 12345, "budget_year": 2026, "description": "Sample annual expense", "planned_amount": 150.00, "cost": { "amount": 125.50, "cost_center_breakdown": [ { "cost_center_id": null, "cost_center": "Not Specified", "charge": 125.50 } ] }, "actual_amount": 125.50, "actual_amount_cost_center_breakdown": [ { "cost_center_id": null, "cost_center": "Not Specified", "charge": 125.50 } ] } ] } ``` ## References Lookup lists such as cost centers, custom fields, tags, types, statuses, and users and resources. Documentation page: https://api.exhibitday.com/Help/V1?epf=3 ### Workspace Info `GET https://api.exhibitday.com/v1/references/workspace_info` Documentation: https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-workspace_info Returns the workspace ID and name, plus its Event, Task and Asset counts. Use it to check that your API key works and which workspace it accesses. Parameters: None. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/references/workspace_info" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/references/workspace_info", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/references/workspace_info", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/references/workspace_info"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/references/workspace_info")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/references/workspace_info') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/references/workspace_info", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/references/workspace_info - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "id": 98765, "name": "Sample Workspace", "num_events": 1, "num_tasks": 1, "num_assets": 1 } ``` ### Related Item Types `GET https://api.exhibitday.com/v1/references/related_item_types` Documentation: https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-related_item_types Lists the related item types, their IDs and names, and the types each can be linked to, following ExhibitDay's linking rules. Use these type IDs when you link records with /v1/related_items. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | $result_format | String | No | By default, the response is an object containing `list_data`, `records_found` and `list_type`. Send `array` to get just a JSON array of the records. | Allowed values: `array` | Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/references/related_item_types" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/references/related_item_types", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/references/related_item_types", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/references/related_item_types"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/references/related_item_types")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/references/related_item_types') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/references/related_item_types", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/references/related_item_types - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "records_found": 10, "list_type": "related_item_type", "list_data": [ { "id": 1, "name": "Task", "uses_asset_type_id": false, "can_link_to_type_ids": [ 2, 3, 4, 5, 6, 7, 8, 9 ] }, { "id": 2, "name": "Playbook Activity", "uses_asset_type_id": false, "can_link_to_type_ids": [ 1, 3, 4, 5, 6, 7, 8, 9 ] }, { "id": 3, "name": "Booth Service", "uses_asset_type_id": false, "can_link_to_type_ids": [ 1, 2, 4, 5, 6, 7, 8, 9 ] }, { "id": 4, "name": "Shipment", "uses_asset_type_id": false, "can_link_to_type_ids": [ 1, 2, 3, 5, 6, 7, 8, 9 ] }, { "id": 5, "name": "Asset Reservation", "uses_asset_type_id": true, "can_link_to_type_ids": [ 1, 2, 3, 4, 6, 7, 8, 9 ] }, { "id": 6, "name": "Giveaway", "uses_asset_type_id": false, "can_link_to_type_ids": [ 1, 2, 3, 4, 5, 7, 8, 9 ] }, { "id": 7, "name": "Sponsorship", "uses_asset_type_id": false, "can_link_to_type_ids": [ 1, 2, 3, 4, 5, 6, 8, 9 ] }, { "id": 8, "name": "Misc. Expense / Credit", "uses_asset_type_id": false, "can_link_to_type_ids": [ 1, 2, 3, 4, 5, 6, 7, 9 ] }, { "id": 9, "name": "Travel Reservation", "uses_asset_type_id": false, "can_link_to_type_ids": [ 1, 2, 3, 4, 5, 6, 7, 8 ] }, { "id": 10, "name": "Attendee / Registration", "uses_asset_type_id": false, "can_link_to_type_ids": [ 1 ] } ] } ``` ### Users and Resources `GET https://api.exhibitday.com/v1/references/users_and_resources` Documentation: https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-users_and_resources Returns a list of users and resources in your ExhibitDay workspace. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | filter_by_can_have_tasks_assigned | Boolean | No | Pass in true to only include the users who can have tasks assigned to them (resources, and users who can't be assigned tasks, are left out). | Default: false. | | $result_format | String | No | By default, the response is an object containing `list_data`, `records_found` and `list_type`. Send `array` to get just a JSON array of the records. | Allowed values: `array` | Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/references/users_and_resources" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/references/users_and_resources", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/references/users_and_resources", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/references/users_and_resources"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/references/users_and_resources")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/references/users_and_resources') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/references/users_and_resources", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/references/users_and_resources - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "records_found": 1, "list_type": "user", "list_data": [ { "id": "11111111-2222-4333-8444-555555555555", "type": "User", "role": "Admin", "can_have_tasks_assigned": true, "display_name": "Jane Smith", "last_name": "Smith", "first_name": "Jane", "email": "jane@example.invalid", "phone_number": "", "organization": "", "title": "", "admin_notes": "" } ] } ``` ### Event Tags `GET https://api.exhibitday.com/v1/references/event_tags` Documentation: https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-event_tags Returns a list of all distinct event tags in your workspace. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | $result_format | String | No | By default, the response is an object containing `list_data`, `records_found` and `list_type`. Send `array` to get just a JSON array of the records. | Allowed values: `array` | Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/references/event_tags" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/references/event_tags", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/references/event_tags", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/references/event_tags"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/references/event_tags")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/references/event_tags') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/references/event_tags", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/references/event_tags - HTTP 200 Illustrative response. ```json { "records_found": 1, "list_type": "string", "list_data": [ "Sample tag" ] } ``` ### Event Participation Types `GET https://api.exhibitday.com/v1/references/event_participation_types` Documentation: https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-event_participation_types Returns a list of available event participation types (i.e., Committed, Considering, Not Going, etc.) which can be used when creating or updating an event. If you have created custom event participation types in your ExhibitDay workspace, they will also get returned. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | $result_format | String | No | By default, the response is an object containing `list_data`, `records_found` and `list_type`. Send `array` to get just a JSON array of the records. | Allowed values: `array` | Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/references/event_participation_types" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/references/event_participation_types", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/references/event_participation_types", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/references/event_participation_types"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/references/event_participation_types")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/references/event_participation_types') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/references/event_participation_types", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/references/event_participation_types - HTTP 200 Illustrative response. ```json { "records_found": 3, "list_type": "event_participation_type", "list_data": [ { "id": 1, "name": "Committed" }, { "id": 2, "name": "Considering" }, { "id": 3, "name": "Not Going" } ] } ``` ### Event Start Date Categories `GET https://api.exhibitday.com/v1/references/event_start_date_categories` Documentation: https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-event_start_date_categories Lists the categories accepted by `filter_by_event_start_date_category` on `GET /v1/events` and `GET /v1/financials/event_costs`. Each entry has an ID and a value. The choices are `all`, `upcoming`, `past`, and one category per year that has Events in your workspace, newest year first. Send the ID. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | $result_format | String | No | By default, the response is a JSON array of the records. Send `object` to get an object containing `list_data`, `records_found` and `list_type`. | Allowed values: `object` | Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/references/event_start_date_categories" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/references/event_start_date_categories", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/references/event_start_date_categories", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/references/event_start_date_categories"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/references/event_start_date_categories")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/references/event_start_date_categories') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/references/event_start_date_categories", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/references/event_start_date_categories - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json [ { "id": "all", "value": "All Events" }, { "id": "upcoming", "value": "Upcoming Events" }, { "id": "past", "value": "Past Events" }, { "id": "2026", "value": "2026 Events" } ] ``` ### Event Custom Fields `GET https://api.exhibitday.com/v1/references/event_custom_fields` Documentation: https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-event_custom_fields Lists custom Event fields in your workspace. File fields are left out by default: set `hydrate_file_fields=true` to include them with the field_name you use on the custom File methods (`/v1/events/custom_fields/file_attachment`). `GET /v1/events/info` returns the Event's `custom_fields` collection. With `GET /v1/events`, set `hydrate_custom_fields=true` to include it. Event Lite results (`$return_event_lites=true`) omit this collection. Hidden fields are disabled fields that are not shown on Event pages. Event reads omit their values, and Event PATCH refuses updates to them. Set `include_hidden_fields=false` to omit hidden definitions, including hidden File fields when `hydrate_file_fields=true`. When access permits, the dedicated custom File methods can still select a known hidden File field. The list also includes labels and dividers. They have an empty `field_type` and hold no value. Dropdown fields list their configured choices in `options` (null for other field types); send one of them as the field's value. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | $result_format | String | No | By default, the response is an object containing `list_data`, `records_found` and `list_type`. Send `array` to get just a JSON array of the records. | Allowed values: `array` | | hydrate_file_fields | Boolean | No | Set true to also include custom File fields and their field_name values. Omit this option or use false for the existing list. The option returns definitions only, without saved field values, attachment ids or file contents. Matching copies count once. Cookie-only options are refused. Blank or JSON null uses the default false. | Default: false. | | include_hidden_fields | Boolean | No | Set to false to omit hidden custom fields. | Default: true. Blank or JSON null uses the default. Matching copies count once. | Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/references/event_custom_fields" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/references/event_custom_fields", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/references/event_custom_fields", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/references/event_custom_fields"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/references/event_custom_fields")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/references/event_custom_fields') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/references/event_custom_fields", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/references/event_custom_fields - HTTP 200 Illustrative response. ```json { "records_found": 2, "list_type": "event_custom_field", "list_data": [ { "field_name": "custom_67890", "event_tab": "Event Information", "field_type": "Text (Single-line)", "field_label": "Illustrative setup instructions", "options": null, "is_hidden": false }, { "field_name": "custom_67891", "event_tab": "Booth", "field_type": "Dropdown", "field_label": "Illustrative booth tier", "options": [ "Gold", "Silver" ], "is_hidden": false } ] } ``` ### Filterable Event Custom Fields `GET https://api.exhibitday.com/v1/references/filterable_event_custom_fields` Documentation: https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-filterable_event_custom_fields Lists the custom Event fields you can filter by. Each entry has an ID and a value. The value names the Custom Text or Custom Dropdown field and its Event tab. Send the ID as `filter_by_custom_field_value_setting_id` on `GET /v1/events`. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | $result_format | String | No | By default, the response is a JSON array of the records. Send `object` to get an object containing `list_data`, `records_found` and `list_type`. | Allowed values: `object` | Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/references/filterable_event_custom_fields" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/references/filterable_event_custom_fields", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/references/filterable_event_custom_fields", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/references/filterable_event_custom_fields"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/references/filterable_event_custom_fields")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/references/filterable_event_custom_fields') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/references/filterable_event_custom_fields", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/references/filterable_event_custom_fields - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json [ { "id": "67890", "value": "Info Tab > Integration status" } ] ``` ### Event Attendee Roles `GET https://api.exhibitday.com/v1/references/event_attendee_roles` Documentation: https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-event_attendee_roles Returns the built-in Staff roles and the enabled custom roles configured in your workspace, ordered by id. Use the id to identify a role; a custom role keeps its id when its display name changes. Blank custom roles are left out. This lists role choices only, not people, Event assignments or email addresses, and sends no notifications. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | $result_format | String | No | By default, the response is an object containing `list_data`, `records_found` and `list_type`. Send `array` to get just a JSON array of the records. | Allowed values: `array` | Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/references/event_attendee_roles" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/references/event_attendee_roles", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/references/event_attendee_roles", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/references/event_attendee_roles"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/references/event_attendee_roles")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/references/event_attendee_roles') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/references/event_attendee_roles", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/references/event_attendee_roles - HTTP 200 Illustrative response. Assume the workspace has the nine built-in Staff roles and one custom role named Illustrative custom role. The built-in IDs and names are real; the custom caption is illustrative. Unnamed custom slots are not listed. No people or assignments are included. No query or body parameters are sent. ```json { "records_found": 10, "list_type": "event_attendee_role", "list_data": [ { "id": 1, "name": "Attendee", "is_custom": false }, { "id": 2, "name": "Team Lead", "is_custom": false }, { "id": 3, "name": "Set-up/Dismantle Crew", "is_custom": false }, { "id": 4, "name": "Sales Representative", "is_custom": false }, { "id": 5, "name": "Speaker", "is_custom": false }, { "id": 6, "name": "Planner", "is_custom": false }, { "id": 7, "name": "Host", "is_custom": false }, { "id": 8, "name": "Presenter", "is_custom": false }, { "id": 9, "name": "Demonstrator", "is_custom": false }, { "id": 100, "name": "Illustrative custom role", "is_custom": true } ] } ``` ### Booth Service Types `GET https://api.exhibitday.com/v1/references/booth_service_types` Documentation: https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-booth_service_types Returns the current Booth Service types, including each id, name, description and Details-tab caption, ordered by id. Use these ids to identify service types. This list contains the available choices, not the services booked for an Event, and does not change budget categories. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | $result_format | String | No | By default, the response is an object containing `list_data`, `records_found` and `list_type`. Send `array` to get just a JSON array of the records. | Allowed values: `array` | Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/references/booth_service_types" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/references/booth_service_types", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/references/booth_service_types", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/references/booth_service_types"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/references/booth_service_types")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/references/booth_service_types') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/references/booth_service_types", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/references/booth_service_types - HTTP 200 Illustrative response. Assume the lookup has the rows shown. IDs, names, descriptions, grouping and captions are illustrative. Get the current choices from this endpoint before using an ID in a write. Custom Objective slots use fixed slot IDs and appear only when named in the workspace. No query or body parameters are sent. ```json { "records_found": 1, "list_type": "booth_service_type", "list_data": [ { "id": 54321, "name": "Illustrative service", "description": "Illustrative picker description", "details_tab_name": "Illustrative Details caption" } ] } ``` ### Playbook Activity Types `GET https://api.exhibitday.com/v1/references/playbook_activity_types` Documentation: https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-playbook_activity_types Returns the Playbook activity types available in ExhibitDay, including each type id, name, description and category. For example, use this list to identify the activity type you need in another request. Types are ordered by their category display order and then their own display order, with ids breaking ties. This list contains choices only, not activities, planning details or costs, and does not grant permission to create or edit an activity. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | $result_format | String | No | By default, the response is an object containing `list_data`, `records_found` and `list_type`. Send `array` to get just a JSON array of the records. | Allowed values: `array` | Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/references/playbook_activity_types" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/references/playbook_activity_types", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/references/playbook_activity_types", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/references/playbook_activity_types"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/references/playbook_activity_types")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/references/playbook_activity_types') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/references/playbook_activity_types", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/references/playbook_activity_types - HTTP 200 Illustrative response. Assume the lookup has the rows shown. IDs, names, descriptions, grouping and captions are illustrative. Get the current choices from this endpoint before using an ID in a write. Custom Objective slots use fixed slot IDs and appear only when named in the workspace. No query or body parameters are sent. ```json { "records_found": 1, "list_type": "playbook_activity_type", "list_data": [ { "id": 54321, "name": "Illustrative activity", "description": "Illustrative activity description", "category_id": 54320, "category": "Illustrative category", "display_rank": 1 } ] } ``` ### Travel Reservation Types `GET https://api.exhibitday.com/v1/references/travel_reservation_types` Documentation: https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-travel_reservation_types Returns the standard Travel Reservation types (IDs 1 through 8) and the group each belongs to, with ids and names. Results are ordered by group id and then type id. This list contains choices only; it does not include travelers, reservations or contact information. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | $result_format | String | No | By default, the response is an object containing `list_data`, `records_found` and `list_type`. Send `array` to get just a JSON array of the records. | Allowed values: `array` | Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/references/travel_reservation_types" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/references/travel_reservation_types", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/references/travel_reservation_types", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/references/travel_reservation_types"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/references/travel_reservation_types")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/references/travel_reservation_types') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/references/travel_reservation_types", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/references/travel_reservation_types - HTTP 200 Illustrative response. Assume the lookup has the rows shown. IDs, names, descriptions, grouping and captions are illustrative. Get the current choices from this endpoint before using an ID in a write. Custom Objective slots use fixed slot IDs and appear only when named in the workspace. No query or body parameters are sent. ```json { "records_found": 2, "list_type": "travel_reservation_type", "list_data": [ { "id": 1, "name": "Illustrative Flight", "group_id": 1, "group": "Illustrative Transportation" }, { "id": 6, "name": "Illustrative Hotel", "group_id": 2, "group": "Illustrative Lodging" } ] } ``` ### Shipment Carriers `GET https://api.exhibitday.com/v1/references/shipment_carriers` Documentation: https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-shipment_carriers Returns the shipment carriers shown in the Shipment editor, ordered by name, display order and id. The list includes inactive carriers because the editor still shows them; is_active tells you their current status. display_name includes an alternate name when one is configured. For `POST /v1/events/shipments` and `PATCH /v1/events/shipments`, only the Other carrier accepts an `other_carrier_name`. Follow the length limit shown for that field. Private integration settings, tracking templates and contact details are not included. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | $result_format | String | No | By default, the response is an object containing `list_data`, `records_found` and `list_type`. Send `array` to get just a JSON array of the records. | Allowed values: `array` | Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/references/shipment_carriers" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/references/shipment_carriers", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/references/shipment_carriers", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/references/shipment_carriers"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/references/shipment_carriers")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/references/shipment_carriers') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/references/shipment_carriers", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/references/shipment_carriers - HTTP 200 Illustrative response. Assume the carrier lookup contains exactly these two rows. The carrier ID 54321, its caption, alternate name, active flag and sort order are illustrative. The Other carrier ID and the 200-character carrier name limit are real. Inactive rows are still listed, matching the carrier picker. No query or body parameters are sent. ```json { "records_found": 2, "list_type": "shipment_carrier", "list_data": [ { "id": 54321, "name": "Illustrative carrier", "display_name": "Illustrative carrier (Sample alternate name)", "is_active": false, "display_rank": 2, "allows_carrier_name": false, "carrier_name_max_length": null }, { "id": 1, "name": "Other", "display_name": "Other", "is_active": true, "display_rank": 1, "allows_carrier_name": true, "carrier_name_max_length": 200 } ] } ``` ### Shipment Component Types `GET https://api.exhibitday.com/v1/references/shipment_component_types` Documentation: https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-shipment_component_types Returns the Shipment component types, ordered by id, with each id and name. The website calls them Shipment Item Types. Use an id as components[].component_type_id in `POST /v1/events/shipments` and `PATCH /v1/events/shipments`; Shipment reads return the name as components[].component_type. This list contains choices only, not Shipments or their components. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | $result_format | String | No | By default, the response is an object containing `list_data`, `records_found` and `list_type`. Send `array` to get just a JSON array of the records. | Allowed values: `array` | Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/references/shipment_component_types" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/references/shipment_component_types", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/references/shipment_component_types", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/references/shipment_component_types"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/references/shipment_component_types")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/references/shipment_component_types') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/references/shipment_component_types", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/references/shipment_component_types - HTTP 200 Illustrative response. These three rows are real Shipment component types (IDs and names); the full list has more. No query or body parameters are sent. ```json { "records_found": 3, "list_type": "shipment_component_type", "list_data": [ { "id": 2, "name": "Pallet" }, { "id": 3, "name": "Crate" }, { "id": 100, "name": "Other" } ] } ``` ### Event Tabs `GET https://api.exhibitday.com/v1/references/event_tabs` Documentation: https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-event_tabs Returns the Event tab ids you can use as filter_by_event_tab_id on the log reads, such as GET /v1/events/logs, with each tab's name, ordered by id. A customer-specific tab is listed only in a workspace that has it. This list contains tab choices only, not Events or log entries. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | $result_format | String | No | By default, the response is an object containing `list_data`, `records_found` and `list_type`. Send `array` to get just a JSON array of the records. | Allowed values: `array` | Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/references/event_tabs" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/references/event_tabs", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/references/event_tabs", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/references/event_tabs"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/references/event_tabs")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/references/event_tabs') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/references/event_tabs", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/references/event_tabs - HTTP 200 Illustrative response. These three rows are real Event tab ids and names; the full list has more. No query or body parameters are sent. ```json { "records_found": 3, "list_type": "event_tab", "list_data": [ { "id": 1, "name": "Info" }, { "id": 2, "name": "Booth" }, { "id": 8, "name": "Tasks" } ] } ``` ### Objective Types `GET https://api.exhibitday.com/v1/references/objective_types` Documentation: https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-objective_types Returns the built-in Objective types and any named custom Objective types configured in your workspace, using the same choices as ExhibitDay. Blank custom choices are left out. Names are listed in the normal application sort order, with id breaking ties. This gives you the available types, not any Event objective, target or result, and does not change permission to edit Objectives. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | $result_format | String | No | By default, the response is an object containing `list_data`, `records_found` and `list_type`. Send `array` to get just a JSON array of the records. | Allowed values: `array` | Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/references/objective_types" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/references/objective_types", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/references/objective_types", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/references/objective_types"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/references/objective_types")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/references/objective_types') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/references/objective_types", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/references/objective_types - HTTP 200 Illustrative response. Assume the lookup has the rows shown. IDs, names, descriptions, grouping and captions are illustrative. Get the current choices from this endpoint before using an ID in a write. Custom Objective slots use fixed slot IDs and appear only when named in the workspace. No query or body parameters are sent. ```json { "records_found": 2, "list_type": "objective_type", "list_data": [ { "id": 1, "name": "Illustrative built-in objective", "is_custom": false }, { "id": 1001, "name": "Illustrative custom objective", "is_custom": true } ] } ``` ### Event Cost Types `GET https://api.exhibitday.com/v1/references/event_cost_types` Documentation: https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-event_cost_types Returns a list of event cost types. Type 9 is Event Activities and represents costs recorded under Playbook activities. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | $result_format | String | No | By default, the response is an object containing `list_data`, `records_found` and `list_type`. Send `array` to get just a JSON array of the records. | Allowed values: `array` | Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/references/event_cost_types" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/references/event_cost_types", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/references/event_cost_types", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/references/event_cost_types"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/references/event_cost_types")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/references/event_cost_types') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/references/event_cost_types", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/references/event_cost_types - HTTP 200 Illustrative response. ```json { "records_found": 9, "list_type": "event_cost_type", "list_data": [ { "id": 1, "name": "Booth Reservation" }, { "id": 2, "name": "Booth Service" }, { "id": 3, "name": "Travel" }, { "id": 4, "name": "Shipment" }, { "id": 5, "name": "Sponsorship" }, { "id": 6, "name": "Miscellaneous Expense/Credit" }, { "id": 7, "name": "Attendee Registration" }, { "id": 8, "name": "Giveaway" }, { "id": 9, "name": "Event Activities" } ] } ``` ### Cost Centers `GET https://api.exhibitday.com/v1/references/cost_centers` Documentation: https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-cost_centers Returns a list of cost centers that are configured in your ExhibitDay workspace. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | $result_format | String | No | By default, the response is a JSON array of the records. Send `object` to get an object containing `list_data`, `records_found` and `list_type`. | Allowed values: `object` | Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/references/cost_centers" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/references/cost_centers", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/references/cost_centers", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/references/cost_centers"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/references/cost_centers")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/references/cost_centers') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/references/cost_centers", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/references/cost_centers - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json [ { "id": 12345, "name": "Marketing" } ] ``` ### Budget Years `GET https://api.exhibitday.com/v1/references/budget_years` Documentation: https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-budget_years Lists the years that have a saved Annual Budget, most recent first. Each entry has an ID and a value. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | $result_format | String | No | By default, the response is a JSON array of the records. Send `object` to get an object containing `list_data`, `records_found` and `list_type`. | Allowed values: `object` | Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/references/budget_years" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/references/budget_years", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/references/budget_years", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/references/budget_years"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/references/budget_years")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/references/budget_years') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/references/budget_years", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/references/budget_years - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json [ { "id": "2026", "value": "2026" } ] ``` ### Payment Statuses `GET https://api.exhibitday.com/v1/references/payment_statuses` Documentation: https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-payment_statuses Lists the payment statuses and their IDs. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | $result_format | String | No | By default, the response is an object containing `list_data`, `records_found` and `list_type`. Send `array` to get just a JSON array of the records. | Allowed values: `array` | Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/references/payment_statuses" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/references/payment_statuses", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/references/payment_statuses", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/references/payment_statuses"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/references/payment_statuses")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/references/payment_statuses') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/references/payment_statuses", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/references/payment_statuses - HTTP 200 Illustrative response. ```json { "records_found": 4, "list_type": "payment_status", "list_data": [ { "id": 0, "name": "Not Specified" }, { "id": 1, "name": "Paid in Full" }, { "id": 2, "name": "Partially Paid" }, { "id": 3, "name": "Not Paid Yet" } ] } ``` ### Asset Custom Fields `GET https://api.exhibitday.com/v1/references/asset_custom_fields` Documentation: https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-asset_custom_fields Lists custom fields configured for Assets in your workspace, in display order with ID breaking ties. Each definition identifies its type and whether it is hidden. Hidden fields are disabled fields that are not shown on Asset pages. Set `include_hidden_fields=false` to omit hidden definitions. Asset reads omit hidden field values, and Asset writes refuse hidden fields. When access permits, the dedicated custom File methods can still select a known hidden File field. The response contains definitions rather than values saved on individual Assets. Existing definitions can be read without permission to customize them. The options field is null for a field that is not a dropdown, and [] for a dropdown with no choices. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | $result_format | String | No | By default, the response is an object containing `list_data`, `records_found` and `list_type`. Send `array` to get just a JSON array of the records. | Allowed values: `array` | | include_hidden_fields | Boolean | No | Set to false to omit hidden custom fields. | Default: true. Blank or JSON null uses the default. Matching copies count once. | Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/references/asset_custom_fields" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/references/asset_custom_fields", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/references/asset_custom_fields", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/references/asset_custom_fields"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/references/asset_custom_fields")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/references/asset_custom_fields') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/references/asset_custom_fields", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/references/asset_custom_fields - HTTP 200 Illustrative response. Assume the workspace has these three supported Asset definitions, including one hidden field returned by default. Set include_hidden_fields=false to omit that definition. Definition IDs, captions, type labels and dropdown choices are illustrative; the numeric type IDs are real. A text field has options null; a configured dropdown lists its choices; an empty dropdown has options []. No query or body parameters are sent. ```json { "records_found": 3, "list_type": "asset_custom_field", "list_data": [ { "id": 67890, "field_type_id": 1000000, "field_type": "Illustrative text type", "name": "Illustrative Asset description", "is_multi_line": false, "display_rank": 1, "options": null, "is_hidden": false }, { "id": 67891, "field_type_id": 3000000, "field_type": "Illustrative dropdown type", "name": "Illustrative tier", "is_multi_line": false, "display_rank": 2, "options": [ "Tier ", "R&D © \"quoted\"" ], "is_hidden": false }, { "id": 67892, "field_type_id": 3000000, "field_type": "Illustrative dropdown type", "name": "Illustrative empty dropdown", "is_multi_line": false, "display_rank": 3, "options": [], "is_hidden": true } ] } ``` ### Permissions and Content Restrictions `GET https://api.exhibitday.com/v1/references/permissions_and_content_restrictions` Documentation: https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-permissions_and_content_restrictions Lists the permissions and content restrictions you can set when you invite a Team Member or Guest with POST /v1/workspace_settings/users/invitations, with each role's default. These are the same choices, defaults and rules as the invitation dialog in ExhibitDay for your workspace: a permission that your workspace doesn't use isn't listed. Rows with type permission give the IDs for permission_denial_ids; rows with type content_restriction give the names for content_restrictions. roles shows, for each role, whether you can set the row (can_be_set) and what the role gets when you leave it out (default). requires_permission_ids lists the permissions a row needs: if one of them is denied, the permission is denied too, and a content restriction can't be turned on. allowed_with_permission_ids lists permissions that also allow this one. turns_on lists the content restrictions that turning this one on also turns on. Admins always have every permission and no content restrictions, so they aren't listed. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | $result_format | String | No | By default, the response is an object containing `list_data`, `records_found` and `list_type`. Send `array` to get just a JSON array of the records. | Allowed values: `array` | Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/references/permissions_and_content_restrictions" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/references/permissions_and_content_restrictions", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/references/permissions_and_content_restrictions", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/references/permissions_and_content_restrictions"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/references/permissions_and_content_restrictions")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/references/permissions_and_content_restrictions') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/references/permissions_and_content_restrictions", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/references/permissions_and_content_restrictions - HTTP 200 Illustrative response. These four rows are real (IDs, names, rules and defaults for a workspace with the standard sections); the full list has every permission and all five content restrictions. No query or body parameters are sent. ```json { "records_found": 4, "list_type": "permission_or_content_restriction", "list_data": [ { "type": "permission", "permission_id": 8, "name": "Can update event booth information (under the event Booth tab)", "requires_permission_ids": [ 16 ], "allowed_with_permission_ids": [], "roles": [ { "workspace_role_id": 2, "workspace_role": "Team Member", "can_be_set": true, "default": "allowed" }, { "workspace_role_id": 3, "workspace_role": "Guest", "can_be_set": false, "default": "denied" } ] }, { "type": "permission", "permission_id": 11, "name": "Can add/update/delete tasks assigned only to self (this user)", "requires_permission_ids": [ 18 ], "allowed_with_permission_ids": [ 10 ], "roles": [ { "workspace_role_id": 2, "workspace_role": "Team Member", "can_be_set": true, "default": "allowed" }, { "workspace_role_id": 3, "workspace_role": "Guest", "can_be_set": false, "default": "denied" } ] }, { "type": "permission", "permission_id": 16, "name": "Has access to view event Booth tab", "requires_permission_ids": [], "allowed_with_permission_ids": [], "roles": [ { "workspace_role_id": 2, "workspace_role": "Team Member", "can_be_set": true, "default": "allowed" }, { "workspace_role_id": 3, "workspace_role": "Guest", "can_be_set": true, "default": "allowed" } ] }, { "type": "content_restriction", "content_restriction": "only_my_travel", "name": "User can only see Travel Reservations that the user either created, or is tagged in", "requires_permission_ids": [ 17 ], "turns_on": [ "only_my_activity" ], "roles": [ { "workspace_role_id": 2, "workspace_role": "Team Member", "can_be_set": true, "default": "off" }, { "workspace_role_id": 3, "workspace_role": "Guest", "can_be_set": true, "default": "off" } ] } ] } ``` ## Users & Resources Workspace users and resources, their Event involvements and their activity. Documentation page: https://api.exhibitday.com/Help/V1?epf=6&topic=users ### Retrieve a Single Workspace User or Resource by ID `GET https://api.exhibitday.com/v1/workspace_settings/users/info` Documentation: https://api.exhibitday.com/Help/V1?epf=6&topic=users#get-v1-workspace_settings-users-info Retrieves one active user or Resource listed under Users & Permissions in your workspace. Use its id from the workspace member list. The response includes contact details, a profile photo link, workspace role, this workspace's Admin Notes, default Event Attendee Role, and the user's effective permissions and content restrictions. Default role id 1 means No Default Attendee Role; this setting is separate from a role already assigned for an Event. Custom role names come from your workspace, and a disabled custom role has state=unavailable. A Resource has its recorded contact email and permissions=null. The plan determines whether permissions can be customized; it does not remove existing effective permissions on Lite. Personal email, calendar and grid preferences, sign-in credentials, security settings and other workspaces are excluded. This read changes no member information and returns no edit revision. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | String | Yes | The user id of the active user or Resource in this workspace. Use the value from /v1/workspace_settings/users and treat it as text. | Max length: 128. | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` | Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/workspace_settings/users/info?id=11111111-2222-4333-8444-555555555555" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/workspace_settings/users/info?" + new URLSearchParams({ "id": "11111111-2222-4333-8444-555555555555" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/workspace_settings/users/info", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": "11111111-2222-4333-8444-555555555555"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/workspace_settings/users/info?id=11111111-2222-4333-8444-555555555555"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/workspace_settings/users/info?id=11111111-2222-4333-8444-555555555555")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/workspace_settings/users/info?id=11111111-2222-4333-8444-555555555555') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/workspace_settings/users/info?id=11111111-2222-4333-8444-555555555555", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/workspace_settings/users/info - HTTP 200 Illustrative response. Assume the workspace has one active member with the contact and role details shown. IDs, labels, contact details and Admin Notes are illustrative. Info grants follow the workspace's Admin role rules; role ID 1 means No Default Attendee Role only in the default attendee role field. Invitations, personal preferences and account security details are not shown. Request inputs: {"id":"11111111-2222-4333-8444-555555555555"}. ```json { "id": "11111111-2222-4333-8444-555555555555", "is_resource": false, "first_name": "Illustrative", "last_name": "Member", "email": "member@example.invalid", "organization": null, "title": null, "phone_number": null, "profile_photo_url": "https://www.exhibitday.com/Images/Generic-User-Icon.png", "workspace_role_id": 1, "workspace_role": "Admin", "workspace_member_joined_timestamp": null, "permissions": { "is_customization_available": true, "grants": [ { "id": 1, "name": "Illustrative WorkspaceManagement_Can_Edit_Workspace_Settings", "is_allowed": true }, { "id": 2, "name": "Illustrative WorkspaceManagement_Can_Manage_Billing_And_Licensing", "is_allowed": true }, { "id": 3, "name": "Illustrative WorkspaceManagement_Can_Manage_Users_and_Permissions", "is_allowed": true }, { "id": 4, "name": "Illustrative EventManagement_Can_Add_Remove_Events", "is_allowed": true }, { "id": 5, "name": "Illustrative EventManagement_Can_Update_Event_Names_and_Dates_and_Basic_Info", "is_allowed": true }, { "id": 6, "name": "Illustrative EventManagement_Update_Event_Attendance_Status", "is_allowed": true }, { "id": 8, "name": "Illustrative EventManagement_Update_Event_Booth_Tab", "is_allowed": true }, { "id": 9, "name": "Illustrative EventManagement_Update_Event_Travel_Tab", "is_allowed": true }, { "id": 10, "name": "Illustrative EventManagement_Manage_Tasks_for_Any_Team_Member", "is_allowed": true }, { "id": 11, "name": "Illustrative EventManagement_Add_Update_Tasks_Only_For_Self", "is_allowed": true }, { "id": 12, "name": "Illustrative Budgeting_Can_Edit_Budgets", "is_allowed": true }, { "id": 13, "name": "Illustrative EventManagement_Has_Access_To_Booth_Invoices", "is_allowed": true }, { "id": 14, "name": "Illustrative EventManagement_Manage_Event_Attendees", "is_allowed": true }, { "id": 15, "name": "Illustrative EventManagement_Has_Access_To_Travel_Invoices", "is_allowed": true }, { "id": 16, "name": "Illustrative EventManagement_Has_Access_To_View_Event_Booth_Tab", "is_allowed": true }, { "id": 17, "name": "Illustrative EventManagement_Has_Access_To_View_Travel_Tab", "is_allowed": true }, { "id": 18, "name": "Illustrative EventManagement_Has_Access_To_View_Event_Tasks_And_Task_Board", "is_allowed": true }, { "id": 19, "name": "Illustrative Budgeting_Can_View_Budgets", "is_allowed": true }, { "id": 20, "name": "Illustrative EventManagement_Has_Access_To_View_Sponsorship_Tab", "is_allowed": true }, { "id": 21, "name": "Illustrative EventManagement_Has_Access_To_Update_Sponsorship_Tab", "is_allowed": true }, { "id": 22, "name": "Illustrative EventManagement_Has_Access_To_Sponsorship_Invoices", "is_allowed": true }, { "id": 23, "name": "Illustrative EventManagement_Has_Access_To_View_Other_Expenses_Tab", "is_allowed": true }, { "id": 24, "name": "Illustrative EventManagement_Has_Access_To_Update_Other_Expenses_Tab", "is_allowed": true }, { "id": 25, "name": "Illustrative EventManagement_Has_Access_To_Other_Expenses_Invoices", "is_allowed": true }, { "id": 26, "name": "Illustrative EventManagement_Has_Access_To_View_Shipment_Tab", "is_allowed": true }, { "id": 27, "name": "Illustrative EventManagement_Has_Access_To_Update_Shipment_Tab", "is_allowed": true }, { "id": 28, "name": "Illustrative EventManagement_Has_Access_To_Shipment_Invoices", "is_allowed": true }, { "id": 29, "name": "Illustrative EventManagement_Has_Access_To_Update_PlayBook_Tab", "is_allowed": true }, { "id": 30, "name": "Illustrative EventManagement_Has_Access_To_View_PlayBook_Tab", "is_allowed": true }, { "id": 31, "name": "Illustrative AssetManagement_Has_Access_To_View_Assets_Area", "is_allowed": true }, { "id": 32, "name": "Illustrative AssetManagement_Has_Access_To_Edit_Assets", "is_allowed": true }, { "id": 33, "name": "Illustrative EventManagement_Has_Access_To_Event_Assets_Tab", "is_allowed": true }, { "id": 34, "name": "Illustrative EventManagement_Has_Access_To_Update_Event_Assets_Tab", "is_allowed": true }, { "id": 35, "name": "Illustrative EventManagement_Has_Access_To_View_Event_Logs", "is_allowed": true }, { "id": 38, "name": "Illustrative EventManagement_Has_Access_To_Registration_Invoices", "is_allowed": true }, { "id": 39, "name": "Illustrative EventManagement_Has_Access_To_View_Giveaway_Tab", "is_allowed": true }, { "id": 40, "name": "Illustrative EventManagement_Has_Access_To_Update_Giveaway_Tab", "is_allowed": true }, { "id": 41, "name": "Illustrative EventManagement_Has_Access_To_Giveaway_Invoices", "is_allowed": true }, { "id": 42, "name": "Illustrative EventManagement_Has_Access_To_View_Special_Tab", "is_allowed": true }, { "id": 43, "name": "Illustrative EventManagement_Has_Access_To_Update_Special_Tab", "is_allowed": true }, { "id": 44, "name": "Illustrative AIChatBot_Access_To_AI_Bot", "is_allowed": true }, { "id": 45, "name": "Illustrative EventManagement_Has_Access_To_Update_Event_Settings_Tab", "is_allowed": true }, { "id": 46, "name": "Illustrative EventManagement_Has_Access_To_Playbook_Activity_Invoices", "is_allowed": true } ], "content_restrictions": { "only_my_events": false, "only_my_travel": false, "only_my_playbook": false, "only_my_activity": false, "only_accessible_related_items": false } }, "admin_notes": "Illustrative workspace-only Admin Notes", "default_event_attendee_role": { "id": 1, "name": "No Default Attendee Role", "state": "none" } } ``` ### Retrieve Workspace Users and Resources `GET https://api.exhibitday.com/v1/workspace_settings/users` Documentation: https://api.exhibitday.com/Help/V1?epf=6&topic=users#get-v1-workspace_settings-users Returns the active users and Resources listed under Users & Permissions in your workspace. A Resource is a non-login contact or item, rather than a person who signs in; its email is its recorded contact email. Invitations and inactive or deactivated members are excluded. The response includes contact and workspace-role information. is_resource is true for a Resource and false for a user who can sign in. Pass hydrate_permissions=true to also include the effective permissions and content restrictions currently assigned to each user. Resources always have permissions=null. The ability to customize permissions is reported separately from the permissions a user actually has. Profile photo links use the normal ExhibitDay web page and its authentication; they are not API file-download links. Counts and pages can change if membership is edited while you are reading. Other workspaces and private account settings are not included. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | | filter_by_user_ids | String or JSON array | No | Only return the matching active users or Resources. Send one ID or an array of IDs from this workspace's Users list. Omit or send [] for no ID filter. Each ID allows up to 128 characters. IDs are case-sensitive text, not numbers. No matches returns an empty list. | | | filter_by_is_resource | Boolean | No | Pass true to return only Resources, or false to return only users who can sign in. Leave it out to include both. | | | hydrate_permissions | Boolean | No | Pass true to include each user's current effective permissions and all five content restrictions. The default is false, which leaves permissions=null for users. Resources always have permissions=null. | | | $limit | Number | No | The most matching records to return (a whole number of 1 or more). Leave it out to return all remaining matching records. | | | $offset | Number | No | How many matching records to skip (a whole number of 0 or more; 0 by default). Use this with $limit to read the next page. | | | $result_sort | String | No | Order workspace members by their opaque user IDs. Omit for ascending order; membership ID breaks ties. Unsupported values are refused. Use the values exactly as shown (lowercase). | Allowed values: `id_asc` \| `id_desc` | Declared schema for `filter_by_user_ids` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "oneOf": [ { "type": "string", "minLength": 1, "maxLength": 128, "pattern": "\\S" }, { "type": "array", "items": { "type": "string", "minLength": 1, "maxLength": 128, "pattern": "\\S" } } ], "x-normalization": "one string becomes a one-item array; trimmed distinct IDs; no record-count cap", "nullable": false, "x-maximum-depth": 1, "x-empty-create-means-omitted": false, "example": [ "user-id" ] } ``` Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/workspace_settings/users" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/workspace_settings/users", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/workspace_settings/users", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/workspace_settings/users"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/workspace_settings/users")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/workspace_settings/users') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/workspace_settings/users", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/workspace_settings/users - HTTP 200 Illustrative response. IDs and contact details are illustrative. is_resource is true for a non-login Resource and false for a user. Resources always have permissions=null. For users, pass hydrate_permissions=true to include permission details. No query or body parameters are sent. ```json { "records_found": 2, "total_records": 2, "has_more": false, "list_type": "workspace_member", "list_data": [ { "id": "11111111-2222-4333-8444-555555555555", "is_resource": false, "first_name": "Illustrative", "last_name": "Member", "email": "member@example.invalid", "organization": null, "title": null, "phone_number": null, "profile_photo_url": "https://www.exhibitday.com/Images/Generic-User-Icon.png", "workspace_role_id": 1, "workspace_role": "Admin", "workspace_member_joined_timestamp": null, "permissions": null }, { "id": "66666666-7777-4888-8999-000000000000", "is_resource": true, "first_name": "Illustrative Resource", "last_name": "", "email": "resource@example.invalid", "organization": "Illustrative supplier", "title": "Display equipment", "phone_number": "+1 202-555-0146", "profile_photo_url": "https://www.exhibitday.com/Images/Associate-Profile-5.png", "workspace_role_id": 4, "workspace_role": "Resource", "workspace_member_joined_timestamp": "2026-01-02T13:00:00Z", "permissions": null } ] } ``` ### Retrieve a User's Event Involvements `GET https://api.exhibitday.com/v1/workspace_settings/users/involvements` Documentation: https://api.exhibitday.com/Help/V1?epf=6&topic=users#get-v1-workspace_settings-users-involvements Retrieves the Events a workspace user or Resource is involved in. Each Event appears once, with all of the member's involvements and the complete Event Lite summary. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | user_id | String | Yes | The user id of the active user or Resource in this workspace. Use the value from /v1/workspace_settings/users and treat it as text. | Max length: 128. | | filter_by_involvement | String | No | Only return Events where the member has this involvement. Leave it out to match any involvement. Use the exact lower-case value. | Allowed values: `creator` \| `attendee` \| `travel_tag` \| `playbook_tag` \| `misc_expense_tag` \| `task_assignee` \| `task_contributor` | | filter_by_event_date_category | String | No | Only include Events that have ended, or Events that are upcoming or in progress. Leave it out for both. This uses the full Event date range and your workspace time zone. Surrounding spaces and letter case are ignored. Sending JSON null is the same as leaving this filter out. | Allowed values: `past` \| `upcoming` | | $limit | Number | No | The most matching records to return (a whole number of 1 or more). Leave it out to return all remaining matching records. | | | $offset | Number | No | How many matching records to skip (a whole number of 0 or more; 0 by default). Use this with $limit to read the next page. | | | $result_sort | String | No | Sort by Event start date. If you omit this option, past Events sort newest first and other results sort oldest first. Event ID breaks ties in the same direction. | Allowed values: `start_date_asc` \| `start_date_desc` | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | #### Involvements Each row contains involvements first, then event with the shared Event Lite fields. A member can have several involvements in the same Event. The involvement filter selects matching Events. The returned involvements array still contains all of the member's real, visible involvements in each Event. Attendee, travel, Playbook and Miscellaneous Expense or Credit involvements are left out when the Event hides that tab. An Event appears only when at least one involvement remains. Task involvements are included even when the Tasks tab is hidden. - "creator": Created the Event. - "attendee": Is listed as an Event attendee. - "travel_tag": Is tagged in a Travel Reservation (types 1 through 8). - "playbook_tag": Is tagged in a scheduled Playbook Activity. - "misc_expense_tag": Is tagged in a Miscellaneous Expense or Credit. - "task_assignee": Is assigned at least one Task for the Event. - "task_contributor": Is tagged as a contributor on at least one Task for the Event. #### Filtering and pages Use user_id from the workspace user list. This reads saved associations; it does not sign in as that member or infer time spent. The date and involvement filters are combined. Counts and paging apply to unique matching Events before their summaries are loaded. Omit $limit to return all remaining matches. Past uses Events whose end date is before today in your workspace. Upcoming also includes Events in progress. Counts and paging come from the first matching set. Each selected Event is then read with its current details and visible involvements. Events that no longer match are left out, so a page may contain fewer rows than requested, or be empty, while total_records and has_more still describe the first matching set. A shortened final page can still report has_more=true; the next request can return no rows. Event dates or involvements can also change between pages; this is not a snapshot. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/workspace_settings/users/involvements?user_id=11111111-2222-4333-8444-555555555555" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/workspace_settings/users/involvements?" + new URLSearchParams({ "user_id": "11111111-2222-4333-8444-555555555555" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/workspace_settings/users/involvements", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"user_id": "11111111-2222-4333-8444-555555555555"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/workspace_settings/users/involvements?user_id=11111111-2222-4333-8444-555555555555"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/workspace_settings/users/involvements?user_id=11111111-2222-4333-8444-555555555555")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/workspace_settings/users/involvements?user_id=11111111-2222-4333-8444-555555555555') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/workspace_settings/users/involvements?user_id=11111111-2222-4333-8444-555555555555", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/workspace_settings/users/involvements - HTTP 200 Illustrative response. Illustrative member involvements in two owned Events. Each Event appears once, with all shown associations and its complete Event Lite summary. Request inputs: {"user_id":"11111111-2222-4333-8444-555555555555"}. ```json { "records_found": 2, "total_records": 2, "has_more": false, "list_type": "workspace_member_involvement", "list_data": [ { "involvements": [ "creator", "attendee" ], "event": { "id": 12345, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=12345", "name": "Spring Trade Show", "start_date": "2026-01-10", "end_date": "2026-01-12", "participation_type_id": 1, "participation_type": "Going", "format_id": 1, "format": "In-Person", "star_rating": 3, "event_created_timestamp": "2019-11-05T14:00:00Z", "event_last_update_timestamp": "2026-01-02T15:30:00Z", "integration_metadata_field_1": "show-spring", "integration_metadata_field_2": "", "integration_metadata_field_3": "", "integration_metadata_field_4": "", "integration_metadata_field_5": "" } }, { "involvements": [ "travel_tag", "task_contributor" ], "event": { "id": 12346, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=12346", "name": "Regional Expo", "start_date": "2026-02-10", "end_date": "2026-02-12", "participation_type_id": 1, "participation_type": "Going", "format_id": 1, "format": "In-Person", "star_rating": 4, "event_created_timestamp": "2019-11-05T14:00:00Z", "event_last_update_timestamp": "2026-01-02T15:30:00Z", "integration_metadata_field_1": "show-regional", "integration_metadata_field_2": "", "integration_metadata_field_3": "", "integration_metadata_field_4": "", "integration_metadata_field_5": "" } } ] } ``` ### Retrieve a User's Workspace Logs `GET https://api.exhibitday.com/v1/workspace_settings/users/logs` Documentation: https://api.exhibitday.com/Help/V1?epf=6&topic=users#get-v1-workspace_settings-users-logs Retrieves workspace activity recorded by a selected user. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | user_id | String | Yes | The user id of the active workspace member whose authored entries you would like to retrieve. Treat it as text. Non-login Resources do not author this activity. | Max length: 128. | | $limit | Number | No | The most entries to return (a whole number of 1 or more). Leave it out to return all remaining matching entries. | | | $offset | Number | No | How many matching entries to skip (a whole number of 0 or more; 0 by default). Use this with $limit to read the next page. | | | $result_sort | String | No | Sort entries newest first (the default) or oldest first. The full saved timestamp is used, with the entry ID breaking ties in the same direction. Responses display whole seconds. Unsupported values are refused. Use the values exactly as shown (lowercase). | Allowed values: `create_timestamp_desc` (newest first) \| `create_timestamp_asc` (oldest first) | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | | filter_by_actor_user_id | String | No | Only include entries written by the user with this id. Treat the id as text. Older entries can match a former user without exposing their account information. | | | filter_by_log_entry_contains_text | String | No | Only include entries containing this text, up to 3,000 characters. The characters are matched as sent; they are not converted from HTML or treated as wildcards. | | | filter_by_create_timestamp_greater_than_or_equal_to | String | No | Include entries created at or after this timestamp. Filters use the whole seconds shown in responses, so a fractional lower bound starts at the next whole second. | | | filter_by_create_timestamp_smaller_than_or_equal_to | String | No | Include entries created at or before this timestamp, including every entry in its displayed second. It can't be earlier than the lower bound. | | | filter_by_event_id | Number | No | Only include entries filed under this Event id in your workspace history. | | | filter_by_event_tab_id | Number | No | Only include entries filed under this Event tab ID. GET /v1/references/event_tabs lists your workspace's tabs; the Presentations tab is accepted only where your workspace has it. | Allowed values: `1` (Info) \| `2` (Booth) \| `3` (Staff) \| `4` (Travel) \| `5` (Assets) \| `6` (Shipments) \| `7` (Sponsorships) \| `8` (Tasks) \| `9` (Playbook) \| `10` (Attachments) \| `11` (Misc. Expenses & Credits) \| `12` (Budget) \| `13` (ROI) \| `14` (Event Settings) \| `16` (Binder) \| `17` (Copy Event) \| `19` (Logs) \| `20` (Delete Event) \| `21` (Giveaways) \| `22` (Special Tab, shown under your workspace's name for it) | | filter_by_context_type | String | No | Only return entries associated with the selected context. Omit to include all contexts. Workspace means an entry with none of the other associations; an entry can belong to more than one other context. Unsupported values are refused. Values are case-insensitive. | Allowed values: `workspace` \| `event` \| `task` \| `asset` \| `storage_location` | #### What the history includes Includes user-visible business history, including changes that do not appear in the Activity Feed. Internal diagnostics, impersonation activity, IP addresses, device details and security information are not included. Each request reads the current history. Use these results to review activity; they are not a complete feed of record changes or deletions. #### Filtering entries When you supply several filters, an entry must match all of them. The total count and the returned page use those same filters. Text searches match the characters you enter literally, without wildcard matching. #### Reading dates and times Returned timestamps are in UTC and show whole seconds. Sorting uses the full saved timestamp, then the entry ID to break ties; entries showing the same second can still have a distinct order. Timestamp filters use the displayed whole-second precision. An upper bound includes all entries in that displayed second. A fractional lower bound starts at the next whole second. A filter value with a time-zone offset is converted to US Eastern time for comparison. A value without an offset is interpreted as US Eastern time. #### Reading the actor `actor_user_id` is the ID of the user who made the change. `actor_display_name` is the name saved with the entry at that time; it does not change if the user is renamed later. Entries recorded by the API have a null `actor_user_id` and show the label saved with them, such as `API`. #### Choosing a user Choose an active workspace member who can sign in, and supply their user_id as text. These are entries written by that person, rather than changes made to their account. Resources cannot write activity entries; selecting a Resource returns a validation error. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/workspace_settings/users/logs?user_id=11111111-2222-4333-8444-555555555555" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/workspace_settings/users/logs?" + new URLSearchParams({ "user_id": "11111111-2222-4333-8444-555555555555" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/workspace_settings/users/logs", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"user_id": "11111111-2222-4333-8444-555555555555"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/workspace_settings/users/logs?user_id=11111111-2222-4333-8444-555555555555"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/workspace_settings/users/logs?user_id=11111111-2222-4333-8444-555555555555")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/workspace_settings/users/logs?user_id=11111111-2222-4333-8444-555555555555') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/workspace_settings/users/logs?user_id=11111111-2222-4333-8444-555555555555", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/workspace_settings/users/logs - HTTP 200 Illustrative response. Assume the workspace has one visible history entry, written by the current user. IDs, the actor name and entry text are illustrative. This entry is not linked to an Event, Task, Asset or Storage Location. Request inputs: {"user_id":"11111111-2222-4333-8444-555555555555"}. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "workspace_log", "list_data": [ { "id": 67890, "log_entry_created_timestamp": "2026-01-02T08:04:05Z", "actor_user_id": "11111111-2222-4333-8444-555555555555", "actor_display_name": "Illustrative user", "log_entry": "Illustrative user updated a workspace setting.", "event_id": null, "event_name": null, "event_tab_id": 0, "task_id": null, "task_name": null, "asset_id": null, "asset_name": null, "storage_location_id": null, "storage_location_name": null } ] } ``` ## Workspace Settings - User Invitations Invite users to your workspace, and read, re-send or revoke open invitations. Documentation page: https://api.exhibitday.com/Help/V1?epf=6&topic=user-invitations ### Retrieve a Single Open Workspace Invitation by ID `GET https://api.exhibitday.com/v1/workspace_settings/users/invitations/info` Documentation: https://api.exhibitday.com/Help/V1?epf=6&topic=user-invitations#get-v1-workspace_settings-users-invitations-info Retrieves one open invitation, including its intended role, permissions and content restrictions. These are the invitation's saved settings; they do not change an existing workspace member's permissions. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The invitation ID from the open invitation list, Info response or creation receipt. | | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` \| `object` | | $include_record_revision | Boolean | No | Set to true to include record_revision. Use that value as expected_revision when revoking or re-sending this invitation. | Default: false. | | $ignore_params_with_empty_values | Boolean | No | Set to true to ignore optional blank values and JSON nulls. Required values still must be supplied; the text null is not ignored. | | #### Saved invitation settings Admin invitations have no effective permission denials or content restrictions. send_invitation_email shows the choice made when the invitation was created through the API. It is null for invitations sent from the web app (true after the API re-sent one whose inviter had left the workspace). It doesn't confirm that the email was delivered. A revoked, used, missing or other workspace's invitation returns HTTP 404. invited_by is the person who sent the invitation, as a User Lite object. For invitations created through the API it is the ExhibitDay API object (no id or email), as it is for a web app invitation the API re-sent after its inviter left the workspace. It is null when the person who sent the invitation is no longer an active member of this workspace. Email links, verification codes and proof tokens are never returned. #### Checking before revocation or Resend Include $include_record_revision=true, then send the returned record_revision as expected_revision to DELETE on the invitation list path, or to POST /v1/workspace_settings/users/invitations/resend. The check covers the recipient, intended access, status and saved notification preference. It grants no permission and is not an email verification link. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/workspace_settings/users/invitations/info?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/workspace_settings/users/invitations/info?" + new URLSearchParams({ "id": "12345" }), { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/workspace_settings/users/invitations/info", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/workspace_settings/users/invitations/info?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/workspace_settings/users/invitations/info?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/workspace_settings/users/invitations/info?id=12345') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/workspace_settings/users/invitations/info?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/workspace_settings/users/invitations/info - HTTP 200 Illustrative response. Illustrative open invitations in this workspace. No invitation is sent. Intended access settings are shown for Info; verification codes and links are excluded. Request inputs: {"id":12345}. ```json { "id": 12345, "email": "events-admin@example.invalid", "status_id": 1, "status": "Pending", "workspace_role_id": 1, "workspace_role": "Admin", "invited_by": { "id": null, "first_name": "ExhibitDay", "last_name": "API", "display_name": "ExhibitDay API", "email": null, "type": null, "workspace_role": null, "is_active": true }, "invitation_created_timestamp": "2030-01-15T12:00:00", "invitation_accepted_timestamp": null, "permission_denials": [], "content_restrictions": { "only_my_events": false, "only_my_travel": false, "only_my_playbook": false, "only_my_activity": false, "only_accessible_related_items": false }, "send_invitation_email": false } ``` ### Retrieve Open Workspace Invitations `GET https://api.exhibitday.com/v1/workspace_settings/users/invitations` Documentation: https://api.exhibitday.com/Help/V1?epf=6&topic=user-invitations#get-v1-workspace_settings-users-invitations Retrieves pending invitations and invitations accepted by people who have not yet joined your workspace. Invitations already used to join are excluded. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | filter_by_status | String | No | Select one open status. Leave it out for both. Accepted means the person accepted the invitation but has not yet joined. | Allowed values: `pending` \| `accepted` | | $limit | Number | No | The most invitations to return, as a positive whole number. Omit it for all remaining matching invitations. | | | $offset | Number | No | How many matching invitations to skip: 0 or more. The default is 0. | | | $result_sort | String | No | Order invitations by their IDs. Omit for oldest first; request descending order for newest first. Unsupported choices are refused. | Allowed values: `id_asc` \| `id_desc` | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | | $ignore_params_with_empty_values | Boolean | No | Set to true to ignore optional blank values and JSON nulls. Required values still must be supplied; the text null is not ignored. | | #### Invitation status Retrieving invitations sends no email and creates no account or workspace membership. Use Invitation Info to inspect an invitation's intended access. invited_by is the person who sent the invitation, as a User Lite object. For invitations created through the API it is the ExhibitDay API object (no id or email), as it is for a web app invitation the API re-sent after its inviter left the workspace. It is null when the person who sent the invitation is no longer an active member of this workspace. Verification codes, email links and proof tokens are never returned. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/workspace_settings/users/invitations" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/workspace_settings/users/invitations", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/workspace_settings/users/invitations", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/workspace_settings/users/invitations"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/workspace_settings/users/invitations")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/workspace_settings/users/invitations') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/workspace_settings/users/invitations", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/workspace_settings/users/invitations - HTTP 200 Illustrative response. Illustrative open invitations in this workspace. No invitation is sent. Intended access settings are shown for Info; verification codes and links are excluded. No query or body parameters are sent. ```json { "records_found": 2, "total_records": 2, "has_more": false, "list_type": "workspace_invitation", "list_data": [ { "id": 12345, "email": "events-admin@example.invalid", "status_id": 1, "status": "Pending", "workspace_role_id": 1, "workspace_role": "Admin", "invited_by": { "id": null, "first_name": "ExhibitDay", "last_name": "API", "display_name": "ExhibitDay API", "email": null, "type": null, "workspace_role": null, "is_active": true }, "invitation_created_timestamp": "2030-01-15T12:00:00", "invitation_accepted_timestamp": null }, { "id": 12346, "email": "events-team@example.invalid", "status_id": 2, "status": "Accepted, not yet joined", "workspace_role_id": 2, "workspace_role": "Team Member", "invited_by": { "id": null, "first_name": "ExhibitDay", "last_name": "API", "display_name": "ExhibitDay API", "email": null, "type": null, "workspace_role": null, "is_active": true }, "invitation_created_timestamp": "2030-01-15T12:00:00", "invitation_accepted_timestamp": "2030-01-16T13:00:00" } ] } ``` ### Invite a User to Your Workspace `POST https://api.exhibitday.com/v1/workspace_settings/users/invitations` Documentation: https://api.exhibitday.com/Help/V1?epf=6&topic=user-invitations#post-v1-workspace_settings-users-invitations Invites one person to your workspace and emails them the invitation right away. Set send_invitation_email to false to save the invitation without emailing it. The person joins after they accept the invitation and sign in or create an account; this request doesn't create an account or add them to the workspace. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | email | String | Yes | The email address of the person to invite. | Max length: 254. | | workspace_role_id | Number | Yes | Choose the intended workspace role. This choice is required. | Allowed values: `1` (Admin) \| `2` (Team Member) \| `3` (Guest) | | send_invitation_email | Boolean | No | Whether to email the invitation right away and send the automatic reminder. Default: true. Set it to false to save the invitation without those emails. You can still send it whenever you choose with Resend, through the API or in the web app; that sends the email without changing this preference. | Default: true. | | permission_denial_ids | JSON object/list | No | Team Member or Guest only. A JSON array of the permission IDs to deny. Get the IDs, each role's defaults and the rules from GET /v1/references/permissions_and_content_restrictions. Omit it to use the role's defaults. [] denies nothing the role can choose; a Guest still never gets permissions that the Guest role doesn't offer. | | | content_restrictions | JSON object/list | No | Team Member or Guest only. An object with any of only_my_events, only_my_travel, only_my_playbook, only_my_activity and only_accessible_related_items, each true or false. Leave a setting out for false. only_my_events, only_my_travel and only_my_playbook also turn on only_my_activity. only_my_travel and only_my_playbook need view access to Travel or Playbook. GET /v1/references/permissions_and_content_restrictions lists them with their rules. | | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` \| `object` | | $ignore_params_with_empty_values | Boolean | No | Set to true to ignore optional blank values and JSON nulls. Required values still must be supplied; the text null is not ignored. | | | $request_principal_name | String | No | Optional attribution label for API history, up to 122 characters. It does not impersonate a user or change the inviter. | | | Idempotency-Key | String | No | Optional request header. Reuse the same key and request to replay the original creation result instead of creating another invitation. | | Declared schema for `permission_denial_ids` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "array", "items": { "type": "integer", "format": "int32" }, "maxItems": 2147483647, "nullable": false, "x-maximum-depth": 1, "x-empty-create-means-omitted": false, "example": [ 1, 2, 3 ] } ``` Declared schema for `content_restrictions` (JSON body object/list; form/query alternatives use one JSON-text value; file parameters require multipart file parts): ```json { "type": "object", "additionalProperties": false, "properties": { "only_my_events": { "type": "boolean" }, "only_my_travel": { "type": "boolean" }, "only_my_playbook": { "type": "boolean" }, "only_my_activity": { "type": "boolean" }, "only_accessible_related_items": { "type": "boolean" } }, "x-member-name-comparison": "ordinal-ignore-case; duplicate case variants are rejected", "nullable": false, "x-maximum-depth": 1, "x-empty-create-means-omitted": false, "example": { "only_my_events": true } } ``` #### Choosing access Choose a role with workspace_role_id. Admins get every permission, so an Admin invitation can't include permission denials or content restrictions; [] and {} (or every setting false) are accepted because they restrict nothing. For a Team Member or Guest, get the choices from GET /v1/references/permissions_and_content_restrictions. It follows the same rules as the invitation dialog in ExhibitDay for your workspace. permission_denial_ids: omit it to use the role's defaults, send [] to deny nothing the role can choose, or send a list to deny exactly those permissions. A blank value or null is refused, unless $ignore_params_with_empty_values=true, which treats it as omitted. Leave content_restrictions out for no restrictions. Some choices depend on others, as in ExhibitDay: denying a permission also denies the permissions that need it, permission 11 (tasks assigned only to self) is allowed whenever permission 10 (tasks for any user) is allowed, and only_my_events, only_my_travel or only_my_playbook also turn on only_my_activity. When this changes your request, the invitation is still created and the X-API-Warnings response header lists each change. A request ExhibitDay wouldn't allow, such as denying a permission your workspace doesn't use, is refused with HTTP 400 and nothing is saved. Example: a Team Member with the role's defaults who also can't view Event Logs or the Activity Feed: {"email":"jordan@example.invalid","workspace_role_id":2,"permission_denial_ids":[1,2,3,12,19,31,32,35]}. Example: a Guest who sees only their own Travel Reservations: {"email":"jordan@example.invalid","workspace_role_id":3,"content_restrictions":{"only_my_travel":true,"only_my_activity":true}}. The current workspace plan, available invitation slots, existing active members, open invitations, blocked email rules and workspace email-domain rules are checked before the invitation is saved. If a check fails, no invitation is created. #### Email delivery send_invitation_email defaults to true. false saves the invitation without the invitation email or automatic reminders. You can send the email later with Resend, through the API (POST /v1/workspace_settings/users/invitations/resend) or in the web app. That doesn't change the saved automatic-email preference. The email is sent right away, as soon as the invitation is saved. If the invitation is saved but its email can't be sent, the request still succeeds and the X-API-Warnings response header says so; use Resend to send it again. A successful response doesn't confirm that the email was delivered. The response never includes the invitation link. #### Retrying a request If you can't tell whether the request succeeded, check the invitation list before you retry. Sending the same Idempotency-Key with the same request returns the original result instead of creating a second invitation. Example — curl: ```bash curl -X POST "https://api.exhibitday.com/v1/workspace_settings/users/invitations" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"email\":\"jordan@example.invalid\",\"workspace_role_id\":2,\"send_invitation_email\":false}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/workspace_settings/users/invitations", { method: "POST", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "email": "jordan@example.invalid", "workspace_role_id": 2, "send_invitation_email": false }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.post( "https://api.exhibitday.com/v1/workspace_settings/users/invitations", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"email": "jordan@example.invalid", "workspace_role_id": 2, "send_invitation_email": False}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PostAsync("https://api.exhibitday.com/v1/workspace_settings/users/invitations", JsonContent.Create(new { email = "jordan@example.invalid", workspace_role_id = 2, send_invitation_email = false })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/workspace_settings/users/invitations")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("POST", HttpRequest.BodyPublishers.ofString("{\"email\":\"jordan@example.invalid\",\"workspace_role_id\":2,\"send_invitation_email\":false}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"email":"jordan@example.invalid","workspace_role_id":2,"send_invitation_email":false}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/workspace_settings/users/invitations') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"email":"jordan@example.invalid","workspace_role_id":2,"send_invitation_email":false}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/workspace_settings/users/invitations", strings.NewReader("{\"email\":\"jordan@example.invalid\",\"workspace_role_id\":2,\"send_invitation_email\":false}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): POST /v1/workspace_settings/users/invitations - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "id": 12345, "email": "jordan@example.invalid", "status_id": 1, "status": "Pending", "workspace_role_id": 2, "workspace_role": "Team Member", "invited_by": { "id": null, "first_name": "ExhibitDay", "last_name": "API", "display_name": "ExhibitDay API", "email": null, "type": null, "workspace_role": null, "is_active": true }, "invitation_created_timestamp": "2030-01-15T12:00:00", "invitation_accepted_timestamp": null, "permission_denials": [ { "id": 1, "name": "Illustrative permission definition" }, { "id": 2, "name": "Illustrative permission definition" }, { "id": 3, "name": "Illustrative permission definition" }, { "id": 12, "name": "Illustrative permission definition" }, { "id": 19, "name": "Illustrative permission definition" }, { "id": 31, "name": "Illustrative permission definition" }, { "id": 32, "name": "Illustrative permission definition" } ], "content_restrictions": { "only_my_events": false, "only_my_travel": false, "only_my_playbook": false, "only_my_activity": false, "only_accessible_related_items": false }, "send_invitation_email": false, "record_revision": "r1:BLrTwWH3s2O3xSAKrlOoZLntkSOm1lCdxXTBpYiSg0g" } ``` ### Revoke a Pending Workspace Invitation `DELETE https://api.exhibitday.com/v1/workspace_settings/users/invitations` Documentation: https://api.exhibitday.com/Help/V1?epf=6&topic=user-invitations#delete-v1-workspace_settings-users-invitations Revokes a pending workspace invitation. To revoke an accepted invitation, use Users & Permissions in the web app. This operation does not remove an existing member or change their permissions. Inputs that do not apply to this operation, including the ignore-empty option, are ignored and reported in the X-API-Warnings response header. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The invitation ID from the open invitation list, Info response or creation receipt. | | | expected_revision | String | No | The record_revision from this invitation's Info response. Include it to revoke only if its recipient, intended access, status and notification preference still match that read. Omit it to skip this check. | Blank, null, malformed or conflicting copies return HTTP 400. A stale revision returns HTTP 409 and changes nothing. Successful removal returns no new revision because the invitation no longer exists. | | $request_principal_name | String | No | Optional attribution label for API history, up to 122 characters. It does not impersonate a user or change the inviter. | | #### Avoiding a stale revocation Optionally send the record_revision from the invitation's Info response or creation receipt as expected_revision. If the saved recipient, intended access or notification preference changed, the request returns HTTP 409 and changes nothing. If the invitation has since been accepted, the request returns HTTP 400; if it was used or revoked, it returns HTTP 404. An invitation that is missing, revoked, already used or belongs to another workspace is unavailable. Successful revocation returns no new revision because the invitation no longer exists. Revocation sends no invitation email. #### Retrying a request If you cannot confirm whether revocation succeeded, retrieve the open invitation list or Invitation Info before retrying. This endpoint does not accept an Idempotency-Key header; a request that sends one is refused with HTTP 400. Example — curl: ```bash curl -X DELETE "https://api.exhibitday.com/v1/workspace_settings/users/invitations?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/workspace_settings/users/invitations?" + new URLSearchParams({ "id": "12345" }), { method: "DELETE", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.delete( "https://api.exhibitday.com/v1/workspace_settings/users/invitations", headers={"Authorization": "Bearer YOUR_API_KEY"}, params={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.DeleteAsync("https://api.exhibitday.com/v1/workspace_settings/users/invitations?id=12345"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/workspace_settings/users/invitations?id=12345")) .header("Authorization", "Bearer YOUR_API_KEY") .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'DELETE', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/workspace_settings/users/invitations?id=12345') request = Net::HTTP::Delete.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("DELETE", "https://api.exhibitday.com/v1/workspace_settings/users/invitations?id=12345", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): DELETE /v1/workspace_settings/users/invitations - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Invitation revoked.", "errors": [] } ``` ### Re-send a Workspace Invitation `POST https://api.exhibitday.com/v1/workspace_settings/users/invitations/resend` Documentation: https://api.exhibitday.com/Help/V1?epf=6&topic=user-invitations#post-v1-workspace_settings-users-invitations-resend Emails an open workspace invitation again, the same way Resend works in the web app. Returns the invitation as Invitation Info does, with its record_revision. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | id | Number | Yes | The invitation ID from the open invitation list, Info response or creation receipt. | | | expected_revision | String | No | The record_revision from this invitation's Info response. Include it to re-send the invitation only if its recipient, intended access, status and notification preference still match that read. Omit it to skip this check. | Blank, null, malformed or conflicting copies return HTTP 400. A stale revision returns HTTP 409, and nothing is changed or sent. | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` \| `object` | | $ignore_params_with_empty_values | Boolean | No | Set to true to ignore optional blank values and JSON nulls. Required values still must be supplied; the text null is not ignored. | | | $request_principal_name | String | No | Optional attribution label for API history, up to 122 characters. It does not impersonate a user or change the inviter. | | #### Which invitations can be re-sent As in the web app, you can re-send a pending invitation or one the person accepted but hasn't yet used to join, whether it was created in the web app or through the API. If the invitation is missing, revoked, already used to join or belongs to another workspace, the request returns HTTP 404. Optionally send the record_revision from the invitation's Info response as expected_revision. If the saved recipient, intended access or notification preference changed since then, the request returns HTTP 409 and nothing is changed or sent. #### Email delivery The email is sent right away. It is the same kind of email the person first got: an invitation sent from the web app gets the web app's invitation email, which names the person who invited them; an invitation created through the API gets the API's invitation email, which names no one. Like Resend in the web app, it restarts the timing of the automatic reminder. It doesn't change the saved send_invitation_email preference (except as described below); when that is false, no automatic reminder follows. In the web app, when the person who sent an invitation is no longer an active member of the workspace, whoever re-sends it becomes its inviter. The API follows the same rule: the invitation becomes one sent by the ExhibitDay API, like an invitation created through the API. invited_by then returns the ExhibitDay API object, send_invitation_email returns true and the email names no one. If the email can't be sent, the request returns HTTP 500, the invitation is put back as it was (unless it changed again in the meantime) and nothing is added to the workspace history; try again later. A successful response doesn't confirm that the email was delivered. The response never includes the invitation link. #### Retrying a request Each successful request sends another email. If you can't tell whether a request succeeded, check the invitation's Info response before you retry. This endpoint does not accept an Idempotency-Key header; a request that sends one is refused with HTTP 400. Example — curl: ```bash curl -X POST "https://api.exhibitday.com/v1/workspace_settings/users/invitations/resend" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"id\":12345}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/workspace_settings/users/invitations/resend", { method: "POST", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "id": 12345 }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.post( "https://api.exhibitday.com/v1/workspace_settings/users/invitations/resend", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"id": 12345}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PostAsync("https://api.exhibitday.com/v1/workspace_settings/users/invitations/resend", JsonContent.Create(new { id = 12345 })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/workspace_settings/users/invitations/resend")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("POST", HttpRequest.BodyPublishers.ofString("{\"id\":12345}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'POST', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"id":12345}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/workspace_settings/users/invitations/resend') request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"id":12345}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("POST", "https://api.exhibitday.com/v1/workspace_settings/users/invitations/resend", strings.NewReader("{\"id\":12345}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): POST /v1/workspace_settings/users/invitations/resend - HTTP 200 Illustrative response. IDs are illustrative; use IDs from your workspace. ```json { "id": 12345, "email": "events-admin@example.invalid", "status_id": 1, "status": "Pending", "workspace_role_id": 1, "workspace_role": "Admin", "invited_by": { "id": null, "first_name": "ExhibitDay", "last_name": "API", "display_name": "ExhibitDay API", "email": null, "type": null, "workspace_role": null, "is_active": true }, "invitation_created_timestamp": "2030-01-15T12:00:00", "invitation_accepted_timestamp": null, "permission_denials": [], "content_restrictions": { "only_my_events": false, "only_my_travel": false, "only_my_playbook": false, "only_my_activity": false, "only_accessible_related_items": false }, "send_invitation_email": false, "record_revision": "r1:quAOUxQcrhS5HLeFZNDbOWCfDMNiZWoy8joJJuzxCqE" } ``` ## Workspace Logs The workspace's activity history. Documentation page: https://api.exhibitday.com/Help/V1?epf=6&topic=logs ### Retrieve Workspace Logs `GET https://api.exhibitday.com/v1/workspace_settings/logs` Documentation: https://api.exhibitday.com/Help/V1?epf=6&topic=logs#get-v1-workspace_settings-logs Retrieves your workspace activity history. Use filters to find the entries you need. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | $limit | Number | No | The most entries to return (a whole number of 1 or more). Leave it out to return all remaining matching entries. | | | $offset | Number | No | How many matching entries to skip (a whole number of 0 or more; 0 by default). Use this with $limit to read the next page. | | | $result_sort | String | No | Sort entries newest first (the default) or oldest first. The full saved timestamp is used, with the entry ID breaking ties in the same direction. Responses display whole seconds. Unsupported values are refused. Use the values exactly as shown (lowercase). | Allowed values: `create_timestamp_desc` (newest first) \| `create_timestamp_asc` (oldest first) | | $result_format | String | No | By default, the response is an object containing `list_data` and the paging totals (`records_found`, `total_records`, `has_more`). Send `array` to get just a JSON array of the records, or `wrapped_in_array` to get the default object inside a one-item array. | Allowed values: `array` \| `wrapped_in_array` | | filter_by_actor_user_id | String | No | Only include entries written by the user with this id. Treat the id as text. Older entries can match a former user without exposing their account information. | | | filter_by_log_entry_contains_text | String | No | Only include entries containing this text, up to 3,000 characters. The characters are matched as sent; they are not converted from HTML or treated as wildcards. | | | filter_by_create_timestamp_greater_than_or_equal_to | String | No | Include entries created at or after this timestamp. Filters use the whole seconds shown in responses, so a fractional lower bound starts at the next whole second. | | | filter_by_create_timestamp_smaller_than_or_equal_to | String | No | Include entries created at or before this timestamp, including every entry in its displayed second. It can't be earlier than the lower bound. | | | filter_by_event_id | Number | No | Only include entries filed under this Event id in your workspace history. | | | filter_by_event_tab_id | Number | No | Only include entries filed under this Event tab ID. GET /v1/references/event_tabs lists your workspace's tabs; the Presentations tab is accepted only where your workspace has it. | Allowed values: `1` (Info) \| `2` (Booth) \| `3` (Staff) \| `4` (Travel) \| `5` (Assets) \| `6` (Shipments) \| `7` (Sponsorships) \| `8` (Tasks) \| `9` (Playbook) \| `10` (Attachments) \| `11` (Misc. Expenses & Credits) \| `12` (Budget) \| `13` (ROI) \| `14` (Event Settings) \| `16` (Binder) \| `17` (Copy Event) \| `19` (Logs) \| `20` (Delete Event) \| `21` (Giveaways) \| `22` (Special Tab, shown under your workspace's name for it) | | filter_by_context_type | String | No | Only return entries associated with the selected context. Omit to include all contexts. Workspace means an entry with none of the other associations; an entry can belong to more than one other context. Unsupported values are refused. Values are case-insensitive. | Allowed values: `workspace` \| `event` \| `task` \| `asset` \| `storage_location` | | filter_by_asset_id | Number | No | Only include entries filed under this Asset id. Supply a positive whole number. | | | filter_by_storage_location_id | Number | No | Only include entries filed under this Storage Location id. Supply a positive whole number. | | | filter_by_task_id | Number | No | Only include entries filed under this Task id. Supply a positive whole number. | | #### What the history includes Includes user-visible business history, including changes that do not appear in the Activity Feed. Internal diagnostics, impersonation activity, IP addresses, device details and security information are not included. Each request reads the current history. Use these results to review activity; they are not a complete feed of record changes or deletions. #### Filtering entries When you supply several filters, an entry must match all of them. The total count and the returned page use those same filters. Text searches match the characters you enter literally, without wildcard matching. Asset, Storage Location and Task filters use the IDs saved with each history entry. You can combine them with the other filters. #### Reading dates and times Returned timestamps are in UTC and show whole seconds. Sorting uses the full saved timestamp, then the entry ID to break ties; entries showing the same second can still have a distinct order. Timestamp filters use the displayed whole-second precision. An upper bound includes all entries in that displayed second. A fractional lower bound starts at the next whole second. A filter value with a time-zone offset is converted to US Eastern time for comparison. A value without an offset is interpreted as US Eastern time. #### Reading the actor `actor_user_id` is the ID of the user who made the change. `actor_display_name` is the name saved with the entry at that time; it does not change if the user is renamed later. Entries recorded by the API have a null `actor_user_id` and show the label saved with them, such as `API`. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/workspace_settings/logs" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/workspace_settings/logs", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/workspace_settings/logs", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/workspace_settings/logs"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/workspace_settings/logs")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/workspace_settings/logs') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/workspace_settings/logs", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/workspace_settings/logs - HTTP 200 Illustrative response. Assume the workspace has one visible history entry, written by the current user. IDs, the actor name and entry text are illustrative. This entry is not linked to an Event, Task, Asset or Storage Location. No query or body parameters are sent. ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "workspace_log", "list_data": [ { "id": 67890, "log_entry_created_timestamp": "2026-01-02T08:04:05Z", "actor_user_id": "11111111-2222-4333-8444-555555555555", "actor_display_name": "Illustrative user", "log_entry": "Illustrative user updated a workspace setting.", "event_id": null, "event_name": null, "event_tab_id": 0, "task_id": null, "task_name": null, "asset_id": null, "asset_name": null, "storage_location_id": null, "storage_location_name": null } ] } ``` ## Workspace Settings Read and update the permitted workspace settings and workspace information. Documentation page: https://api.exhibitday.com/Help/V1?epf=6 ### Retrieve Workspace Settings `GET https://api.exhibitday.com/v1/workspace_settings` Documentation: https://api.exhibitday.com/Help/V1?epf=6#get-v1-workspace_settings Retrieves your workspace settings, including display preferences, units of measure, available features, currency and budget-year basis. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | include_available_options | Boolean | No | Include the available currency, time-zone and fiscal-year start-month choices. The default is false; available_options is null unless requested. | Default: false. | | $include_record_revision | Boolean | No | Set to true to include record_revision in the response. Send that value as expected_revision when updating to check for conflicting changes. | Default: false. | | $result_format | String | No | By default, the response is a single object. Send `array` to get it inside a one-item array. | Allowed values: `array` \| `object` | | $ignore_params_with_empty_values | Boolean | No | Set to true to ignore blank values and JSON null. Text null is not ignored. All supplied copies of this option must agree. | Default: false. | #### Available features and choices Unavailable Task Workflows and AI Assistant controls return null. This differs from an available control whose saved value is Disabled. Set include_available_options=true to retrieve accepted currencies, time zones and fiscal-year start months. Without this option, available_options is null. #### Updating settings workspace_currency_code and workspace_currency_symbol describe the currency currently used by this workspace. They are read-only. workspace_currency_id and workspace_fiscal_year_start_month can be changed with PATCH. Changing the currency changes the symbol shown on all amounts; the numbers are not converted. Changing the fiscal-year start month changes which budget year each cost belongs to. This affects Annual Budget and Metrics reports and API results grouped or filtered by budget year. GET /v1/references/workspace_info remains the separate simple workspace summary. 1. Retrieve these settings with $include_record_revision=true if you want to check for intervening changes. 2. Send PATCH to this same URL with the fields you want to change and, optionally, that expected_revision. Example — curl: ```bash curl -X GET "https://api.exhibitday.com/v1/workspace_settings" -H "Authorization: Bearer YOUR_API_KEY" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/workspace_settings", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.get( "https://api.exhibitday.com/v1/workspace_settings", headers={"Authorization": "Bearer YOUR_API_KEY"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.GetAsync("https://api.exhibitday.com/v1/workspace_settings"); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/workspace_settings")) .header("Authorization", "Bearer YOUR_API_KEY") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY'], ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/workspace_settings') request = Net::HTTP::Get.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://api.exhibitday.com/v1/workspace_settings", nil) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): GET /v1/workspace_settings - HTTP 200 Illustrative response. ```json { "name": "Sample Events Team", "timezone_id": "UTC", "workspace_currency_id": 1, "workspace_currency_code": "USD", "workspace_currency_symbol": "$", "user_display_name_format_id": 1, "attendee_double_book_warning_mode_id": 1, "is_activity_feed_enabled": true, "is_event_id_display_enabled": false, "event_cards_view_mode_id": 1, "task_workflows_mode_id": 1, "user_permission_denial_behavior_type_id": 1, "related_items_summary_mode_id": 1, "asset_weight_unit_type_id": 1, "asset_dimensions_unit_type_id": 1, "workspace_fiscal_year_start_month": 1, "ai_chatbot_availability_type_id": 1, "available_options": null, "exhibitday_url": "https://www.exhibitday.com/Workspace/Settings/98765" } ``` ### Update Workspace Settings `PATCH https://api.exhibitday.com/v1/workspace_settings` Documentation: https://api.exhibitday.com/Help/V1?epf=6#patch-v1-workspace_settings Updates the workspace settings you supply. Omitted settings keep their saved values. Parameters: | Name | Type | Required? | Description | Details | | --- | --- | --- | --- | --- | | name | String | No | The workspace name. A changed name must have 1 to 30 characters, excluding surrounding spaces. Some emoji count as more than one character. A blank name keeps the current name and returns a warning; your other changes are still saved. | Max length: 30. | | timezone_id | String | No | The ID of a time zone in available_options.timezones. IDs are matched without regard to case or surrounding spaces and saved with the listed spelling. | | | workspace_currency_id | Number | No | The currency used to display workspace amounts. Choose an ID from available_options.currencies. Changing the currency changes the symbol shown on all amounts; the numbers are not converted. | | | user_display_name_format_id | Number | No | Choose First Last to show the given name before the family name, or Last, First to show the family name first. | Allowed values: `1` (First Last) \| `2` (Last, First) | | attendee_double_book_warning_mode_id | Number | No | Smart considers each Event's Participation Status before warning about overlapping attendee bookings. Strict warns for all such overlaps. Disabled turns these warnings off. | Allowed values: `1` (Smart) \| `2` (Strict) \| `3` (Disabled) | | is_activity_feed_enabled | Boolean | No | Whether the Recent Activity Feed is enabled. | | | is_event_id_display_enabled | Boolean | No | Whether Event IDs are displayed. | | | event_cards_view_mode_id | Number | No | Choose Compact for smaller Event cards or Expanded for larger cards. | Allowed values: `1` (Compact) \| `2` (Expanded) | | task_workflows_mode_id | Number | No | Task Workflows define actions that run when a task is complete. Enhanced can also prompt users to create a relevant task, such as reserving an Event booth. Choose Enhanced, Enabled or Disabled. Send a different value only when GET returns a number for this field. null means this feature is unavailable in your workspace. | Allowed values: `1` (Enhanced) \| `2` (Enabled) \| `3` (Disabled) | | user_permission_denial_behavior_type_id | Number | No | For Team Members and Guests, show an Access Denied message when an area is unavailable, or hide the unavailable area. | Allowed values: `1` (show an Access Denied message) \| `2` (hide unavailable areas) | | related_items_summary_mode_id | Number | No | Hide Summary Details keeps linked-item summaries hidden from users who cannot view the item. Show Limited Summaries lets them see a brief summary without granting access to the full item. | Allowed values: `1` (Hide Summary Details) \| `2` (Show Limited Summaries) | | asset_weight_unit_type_id | Number | No | Choose Pounds or Kilograms for weight. Changing this preference does not rescale stored measurements. | Allowed values: `1` (Pounds) \| `2` (Kilograms) | | asset_dimensions_unit_type_id | Number | No | Choose Inches / Cubic Feet or Centimeters / Cubic Meters for dimensions and volume. Changing this preference does not rescale stored measurements. | Allowed values: `1` (Inches / Cubic Feet) \| `2` (Centimeters / Cubic Meters) | | workspace_fiscal_year_start_month | Number | No | The month in which the budget year starts. Changing it changes which budget year each cost belongs to. This affects Annual Budget and Metrics reports and API results grouped or filtered by budget year. | Allowed values: `1` (calendar year, January through December) \| `2` (February) \| `3` (March) \| `4` (April) \| `5` (May) \| `6` (June) \| `7` (July) \| `8` (August) \| `9` (September) \| `10` (October) \| `11` (November) \| `12` (December) | | ai_chatbot_availability_type_id | Number | No | This setting is for Planna (ExhibitDay's AI Assistant / Chatbot). Data-restricted answers questions about ExhibitDay features. Data-enabled can use workspace data. Disabled turns the AI Assistant off. Send a different value only when GET returns a number for this field. null means this feature is unavailable in your workspace. | Allowed values: `1` (Data-restricted: answers about ExhibitDay features only) \| `2` (Data-enabled: can use your workspace data) \| `3` (Disabled) | | expected_revision | String | No | The record_revision returned when you retrieved this record. Include it to avoid overwriting someone else's changes. Omit it to skip this check. | | | $ignore_params_with_empty_values | Boolean | No | Set to true to ignore blank values and JSON null. Text null is not ignored. All supplied copies of this option must agree. | Default: false. | #### Saving changes Send the settings you want to change. Omitted settings, blank Boolean settings and a blank name keep their saved values; a blank name returns a warning. A supplied value that equals the saved value is a no-op, including an unchanged legacy name over 30 characters and an unavailable feature's saved mode or returned null. You may send back unchanged workspace_currency_code, workspace_currency_symbol, record_revision and available_options values from GET. They are read-only; a different value is refused. Omit them if you do not need to echo the full response. An available_options value of null matches the default GET response. Blank values, JSON null and the text null cannot clear settings. With $ignore_params_with_empty_values=true, blank values and JSON null are ignored; the text null is still refused for a changed setting. An unchanged unavailable feature's returned null remains a no-op. All actual changes are validated before anything is saved. A changed name must have 1 to 30 characters, excluding surrounding spaces. Some emoji count as more than one character. An unavailable feature cannot be changed. A request that changes nothing leaves the settings timestamp, history and notifications unchanged. A successful response includes the current record_revision. The revision changes when a writable setting or feature availability changes. It excludes the saved modes of unavailable features. Use expected_revision to refuse a save when the available settings have changed since your read. Without it, the last save wins. The Workspace Settings page in ExhibitDay also uses the last saved values. Changing the currency changes the symbol shown on all amounts; the numbers are not converted. Changing the fiscal-year start month changes which budget year each cost belongs to. This affects Annual Budget and Metrics reports and API results grouped or filtered by budget year. Changing measurement units does not rescale existing measurements. #### History and AI Assistant notices Committed changes are recorded with API attribution. Workspace name changes appear in the activity feed; other settings history does not. Changing the AI Assistant to Data-enabled or Disabled also notifies ExhibitDay by e-mail. A history or notice-delivery failure does not undo a committed setting change. Example — curl: ```bash curl -X PATCH "https://api.exhibitday.com/v1/workspace_settings" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"name\":\"Sample Events Team Updated\"}" ``` Example — Node.js: ```javascript const response = await fetch("https://api.exhibitday.com/v1/workspace_settings", { method: "PATCH", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "name": "Sample Events Team Updated" }) }); const data = await response.json(); console.log(response.status, data); ``` Example — Python: ```python import requests response = requests.patch( "https://api.exhibitday.com/v1/workspace_settings", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"name": "Sample Events Team Updated"}, ) print(response.status_code, response.json()) ``` Example — C#: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PatchAsync("https://api.exhibitday.com/v1/workspace_settings", JsonContent.Create(new { name = "Sample Events Team Updated" })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` Example — Java: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/workspace_settings")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("PATCH", HttpRequest.BodyPublishers.ofString("{\"name\":\"Sample Events Team Updated\"}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` Example — PHP: ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"name":"Sample Events Team Updated"}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` Example — Ruby: ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/workspace_settings') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"name":"Sample Events Team Updated"}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` Example — Go: ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/workspace_settings", strings.NewReader("{\"name\":\"Sample Events Team Updated\"}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` Example HTTP response body (JSON): PATCH /v1/workspace_settings - HTTP 200 Illustrative response. ```json { "status_code": 200, "status": "OK", "message": "Workspace Settings updated.", "errors": [], "record_revision": "r1:52vvEXb8Ed14e4vKiq5ZIdK3BgVmu0aXtmUBC-kueMk" } ``` ## Guides ### Create or Update Events from Your CRM Guide page: https://api.exhibitday.com/Help/V1?guide=event-setup-crm Create an Event from a CRM record (for example Salesforce, HubSpot or Zoho CRM), or update the Event already linked to it. Example use case Your CRM has a confirmed show. You want to set up its planning section and Exhibit Hall schedule, then keep the linked Event's name and main dates in sync. What you'll end up with A verified link to one ExhibitDay Event and its planning section, plus the saved Exhibit Hall schedule. Before you start Have an API key that can read the workspace and perform the setup changes, a stable CRM key, and the complete Exhibit Hall schedule you want to save. This guide stores your system's ID for each Event in integration_metadata_field_1, one of five API-only text fields on each Event. If another integration already uses field 1, choose a free field (1 to 5) and use it consistently. Good to know This works with any CRM that can call a web API or use an automation tool (like Zapier, Make or Pipedream); no special connector is needed. #### At a glance Time to try About 20 minutes Effect on your data Creates and updates Endpoints 10 The program may create an Event or Task Section, update a linked Event's name or main dates, and replace the Exhibit Hall Dates group. It also writes a private local journal. - [`GET /v1/references/workspace_info`](https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-workspace_info) - [`GET /v1/events`](https://api.exhibitday.com/Help/V1?epf=1#get-v1-events) - [`POST /v1/events`](https://api.exhibitday.com/Help/V1?epf=1#post-v1-events) - [`GET /v1/events/info`](https://api.exhibitday.com/Help/V1?epf=1#get-v1-events-info) - [`PATCH /v1/events`](https://api.exhibitday.com/Help/V1?epf=1#patch-v1-events) - [`GET /v1/tasks/sections`](https://api.exhibitday.com/Help/V1?epf=2#get-v1-tasks-sections) - [`POST /v1/tasks/sections`](https://api.exhibitday.com/Help/V1?epf=2#post-v1-tasks-sections) - [`GET /v1/tasks/sections/info`](https://api.exhibitday.com/Help/V1?epf=2#get-v1-tasks-sections-info) - [`GET /v1/events/dates`](https://api.exhibitday.com/Help/V1?epf=1#get-v1-events-dates) - [`PATCH /v1/events/dates`](https://api.exhibitday.com/Help/V1?epf=1#patch-v1-events-dates) #### How it works 1. Each show in your CRM has a stable ID. If the search finds no match, the program creates the Event and saves that ID in integration_metadata_field_1. 2. On later runs, it looks up the Event by that ID, so renaming the show keeps the records linked. 3. If the CRM name or main dates differ, it updates only those fields after checking the Event's revision. 4. It finds or creates the planning Task Section and saves the complete Exhibit Hall schedule if it differs. 5. It records save attempts in a private local journal and checks what happened before continuing a stopped run. #### Set up the Event The examples below follow an Event that already exists. Step 3 applies only when the Event search finds no match. Step 8 applies only when the Task Section search finds no match. #### Step 1: Confirm the workspace Read the workspace summary to check where the key will make changes. ```bash curl -X GET "https://api.exhibitday.com/v1/references/workspace_info" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "id": 98765 } ``` **Check:** Confirm id belongs to the workspace you intended to use. #### Step 2: Find the linked Event Search Events by integration_metadata_field_1, the field where your CRM ID is stored, so a name change will not break the link. ```bash curl -X GET "https://api.exhibitday.com/v1/events?filter_by_integration_metadata_field_1=crm%3Aevent%3Aspring-expo-2030&%24limit=100&%24offset=0" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_data": [ { "id": 5001, "name": "Spring Expo", "integration_metadata_field_1": "crm:event:spring-expo-2030" } ] } ``` **Check:** Read every page and compare the saved key exactly. Continue with one distinct match, create with zero, or stop and investigate if there are several. #### Step 3: Create the Event if the search found none Send the CRM values and external key to create the first linked Event. ```bash curl -X POST "https://api.exhibitday.com/v1/events" -H "Authorization: Bearer YOUR_API_KEY" -H "Idempotency-Key: YOUR_EVENT_CREATE_KEY" -H "Content-Type: application/json" --data-binary "{\"name\":\"Spring Expo 2030\",\"start_date\":\"2030-01-14\",\"end_date\":\"2030-01-16\",\"integration_metadata_field_1\":\"crm:event:spring-expo-2030\"}" ``` Example response (shortened) ```json { "id": 5001, "name": "Spring Expo 2030", "start_date": "2030-01-14", "end_date": "2030-01-16", "integration_metadata_field_1": "crm:event:spring-expo-2030" } ``` **Check:** Keep the returned id and confirm the key, name and dates. The program saves the create key in its journal before sending the request. #### Step 4: Read the Event and its revision Read the selected Event by ID so you can check the exact link and compare its current values. ```bash curl -X GET "https://api.exhibitday.com/v1/events/info?id=5001&%24include_record_revision=true" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "id": 5001, "name": "Spring Expo", "start_date": "2030-01-14", "end_date": "2030-01-15", "integration_metadata_field_1": "crm:event:spring-expo-2030", "record_revision": "COPY_EVENT_REVISION_FROM_YOUR_READ" } ``` **Check:** Compare the ID and key. Save record_revision for the next request if an update is needed. The revision below is a placeholder. #### Step 5: Update the linked Event if values differ For an existing linked Event, send only the changed values and the revision from the previous read. ```bash curl -X PATCH "https://api.exhibitday.com/v1/events" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" --data-binary "{\"id\":5001,\"name\":\"Spring Expo 2030\",\"end_date\":\"2030-01-16\",\"expected_revision\":\"COPY_EVENT_REVISION_FROM_YOUR_READ\"}" ``` Example response (shortened) ```json { "status_code": 200, "status": "OK", "message": "Event Update Successful. Event properties that were changed: name, end_date", "record_revision": "NEW_EVENT_REVISION" } ``` **Check:** In this example, name and end_date changed, so start_date is omitted. A successful conditional update returns a new record_revision. #### Step 6: Verify the Event before continuing Read the Event again so the setup only continues when the actual values match the CRM values. ```bash curl -X GET "https://api.exhibitday.com/v1/events/info?id=5001" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "id": 5001, "name": "Spring Expo 2030", "start_date": "2030-01-14", "end_date": "2030-01-16", "integration_metadata_field_1": "crm:event:spring-expo-2030" } ``` **Check:** Check the ID, integration key, name, start date and end date. The example also checks these values if no update was needed. #### Step 7: Find the planning section Read this Event's Task Sections and look for the exact section name. ```bash curl -X GET "https://api.exhibitday.com/v1/tasks/sections?filter_by_event_id=5001&%24limit=100&%24offset=0" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_data": [ { "id": 6001, "event_id": 5001, "name": "Pre-event planning" } ] } ``` **Check:** Read all matching pages. Use one exact match, create with zero, or stop if there are several. #### Step 8: Create the section if none matched Send the section name with the saved Event ID to add it to this Event. ```bash curl -X POST "https://api.exhibitday.com/v1/tasks/sections" -H "Authorization: Bearer YOUR_API_KEY" -H "Idempotency-Key: YOUR_SECTION_CREATE_KEY" -H "Content-Type: application/json" --data-binary "{\"event_id\":5001,\"name\":\"Pre-event planning\"}" ``` Example response (shortened) ```json { "id": 6001, "event_id": 5001, "name": "Pre-event planning" } ``` **Check:** Keep the section id and confirm event_id. The section create uses its own saved idempotency key. #### Step 9: Verify the section Read the selected Task Section by ID to confirm its saved details. ```bash curl -X GET "https://api.exhibitday.com/v1/tasks/sections/info?id=6001" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "id": 6001, "event_id": 5001, "name": "Pre-event planning" } ``` **Check:** Check the section ID, Event ID and name before continuing. #### Step 10: Read the complete Exhibit Hall Dates group Read date type 1 with its revision so the program can replace that specific group safely. ```bash curl -X GET "https://api.exhibitday.com/v1/events/dates?event_id=5001&filter_by_date_type_id=1&%24include_record_revision=true" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_data": [ { "event_id": 5001, "date_type_id": 1, "dates": [ { "date": "2030-01-15", "start_time": "09:00:00", "end_time": "15:00:00", "timezone": "America/New_York", "description": "Earlier exhibit schedule" } ], "record_revision": "COPY_DATES_REVISION_FROM_YOUR_READ" } ] } ``` **Check:** Confirm the Event and date type in the one returned group. Use that group's record_revision for the Dates update. The revision below is a placeholder. #### Step 11: Save the complete Exhibit Hall schedule Replace the group with every date and time you want to keep, using the Dates revision. ```bash curl -X PATCH "https://api.exhibitday.com/v1/events/dates" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" --data-binary "{\"event_id\":5001,\"date_type_id\":1,\"dates\":[{\"date\":\"2030-01-15\",\"start_time\":\"09:00:00\",\"end_time\":\"17:00:00\",\"timezone\":\"America/New_York\",\"description\":\"Exhibit hours\"},{\"date\":\"2030-01-16\",\"start_time\":\"09:00:00\",\"end_time\":\"16:00:00\",\"timezone\":\"America/New_York\",\"description\":\"Final exhibit day\"}],\"expected_revision\":\"COPY_DATES_REVISION_FROM_YOUR_READ\"}" ``` Example response (shortened) ```json { "status_code": 200, "status": "OK", "message": "Event Dates updated.", "record_revision": "NEW_DATES_REVISION" } ``` **Check:** Look for the saved record_revision. Dates you leave out are removed from this group, so include every date you want to keep. #### Step 12: Verify the saved schedule Read the group again to check that the complete saved schedule matches what you sent. ```bash curl -X GET "https://api.exhibitday.com/v1/events/dates?event_id=5001&filter_by_date_type_id=1" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_data": [ { "event_id": 5001, "date_type_id": 1, "dates": [ { "date": "2030-01-15", "start_time": "09:00:00", "end_time": "17:00:00", "timezone": "America/New_York", "description": "Exhibit hours" }, { "date": "2030-01-16", "start_time": "09:00:00", "end_time": "16:00:00", "timezone": "America/New_York", "description": "Final exhibit day" } ] } ] } ``` **Check:** Compare each date, local time, time-zone label and description in the order the API returns them. #### Step 13: Confirm the final Event setup Read the Event again to verify its CRM link and planning section after the separate saves. ```bash curl -X GET "https://api.exhibitday.com/v1/events/info?id=5001" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "id": 5001, "name": "Spring Expo 2030", "start_date": "2030-01-14", "end_date": "2030-01-16", "integration_metadata_field_1": "crm:event:spring-expo-2030", "task_sections": [ { "id": 6001, "name": "Pre-event planning", "display_rank": 0 }, { "id": 6002, "name": "Onsite follow-up", "display_rank": 1 } ] } ``` **Check:** Confirm the ID, key, name and dates, and find the saved section ID in task_sections. #### Try it #### Before running the example | Variable | What to put in it | Required? | | --- | --- | --- | | `EXHIBITDAY_API_KEY` | Your workspace API key. | Yes | | `EXHIBITDAY_EXTERNAL_EVENT_KEY` | A stable CRM key, up to 3,000 UTF-16 code units. Leave no whitespace at either end. | Yes | | `EXHIBITDAY_EVENT_NAME` | The Event name, up to 500 UTF-16 code units. Use plain, single-line text with no surrounding whitespace. | Yes | | `EXHIBITDAY_START_DATE` | The main start date in YYYY-MM-DD format. | Yes | | `EXHIBITDAY_END_DATE` | The main end date in YYYY-MM-DD format, on or after the start date. | Yes | | `EXHIBITDAY_EXHIBIT_DATES_JSON` | The entire desired Exhibit Hall Dates array. Use all five fields per entry, including normalized times such as 09:00:00, in the order returned by the API. | Yes | | `EXHIBITDAY_JOURNAL` | A private local journal path for this setup. | Yes | | `EXHIBITDAY_JOB_ID` | A stable ID for this setup. Keep it for a resume. | Yes | | `EXHIBITDAY_TASK_SECTION_NAME` | The exact name to find or create. The default is Pre-event planning. | No | | `EXHIBITDAY_PAGE_SIZE` | The page size for the searches. The default is 100. | No | | `EXHIBITDAY_JOB_MODE` | Use new for a new job or resume for the existing journal. The default is resume. | No | **Careful.** This example changes data in your workspace. Use a test Event. #### Bash ``` export EXHIBITDAY_API_KEY='YOUR_API_KEY' export EXHIBITDAY_EXTERNAL_EVENT_KEY='crm:event:spring-expo-2030' export EXHIBITDAY_EVENT_NAME='Spring Expo 2030' export EXHIBITDAY_START_DATE='2030-01-14' export EXHIBITDAY_END_DATE='2030-01-16' export EXHIBITDAY_EXHIBIT_DATES_JSON='[{"date":"2030-01-15","start_time":"09:00:00","end_time":"17:00:00","timezone":"America/New_York","description":"Exhibit hours"},{"date":"2030-01-16","start_time":"09:00:00","end_time":"16:00:00","timezone":"America/New_York","description":"Final exhibit day"}]' ``` #### PowerShell ``` $env:EXHIBITDAY_API_KEY = 'YOUR_API_KEY' $env:EXHIBITDAY_EXTERNAL_EVENT_KEY = 'crm:event:spring-expo-2030' $env:EXHIBITDAY_EVENT_NAME = 'Spring Expo 2030' $env:EXHIBITDAY_START_DATE = '2030-01-14' $env:EXHIBITDAY_END_DATE = '2030-01-16' $env:EXHIBITDAY_EXHIBIT_DATES_JSON = '[{"date":"2030-01-15","start_time":"09:00:00","end_time":"17:00:00","timezone":"America/New_York","description":"Exhibit hours"},{"date":"2030-01-16","start_time":"09:00:00","end_time":"16:00:00","timezone":"America/New_York","description":"Final exhibit day"}]' ``` Set a private journal path and a stable job ID. For the first run, set `EXHIBITDAY_JOB_MODE=new`. Then copy and run the complete example in your language. #### Complete example program Code Samples ```bash #!/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\"},\"find_existing\":{\"method\":\"GET\",\"path\":\"/events\"},\"create_event\":{\"method\":\"POST\",\"path\":\"/events\"},\"confirm_event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"update_event\":{\"method\":\"PATCH\",\"path\":\"/events\"},\"verify_event_update\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"find_section\":{\"method\":\"GET\",\"path\":\"/tasks/sections\"},\"create_section\":{\"method\":\"POST\",\"path\":\"/tasks/sections\"},\"confirm_section\":{\"method\":\"GET\",\"path\":\"/tasks/sections/info\"},\"read_dates\":{\"method\":\"GET\",\"path\":\"/events/dates\"},\"save_dates\":{\"method\":\"PATCH\",\"path\":\"/events/dates\"},\"verify_dates\":{\"method\":\"GET\",\"path\":\"/events/dates\"},\"event_readback\":{\"method\":\"GET\",\"path\":\"/events/info\"}}}") API_KEY = os.environ["EXHIBITDAY_API_KEY"] if any(ord(char) < 32 or ord(char) > 126 for char in API_KEY): raise RuntimeError("Use the API key as one ASCII header value without control characters") if not API_KEY.strip(): raise RuntimeError("Set EXHIBITDAY_API_KEY") def decode_json(text): if SPEC["preserveNumbers"]: # Quote JSON NUMBER tokens, never text inside a JSON string, to keep CSV decimals exact. text = re.sub(r'"(?:\\.|[^"\\])*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?', lambda m: m[0] if m[0].startswith('"') else json.dumps(m[0]), text) return json.loads(text) from pathlib import Path # This terminal version uses curl for HTTP and Python's standard library for JSON/CSV. import subprocess import tempfile def transport(method, url, headers, data): with tempfile.TemporaryDirectory(prefix="exhibitday-guide-") as directory: folder = Path(directory) # curl may leave no output file for a valid bodyless304 response. (folder / "body").write_bytes(b"") command = ["curl", "--disable", "--silent", "--show-error", "--request", method, "--url", url, "--max-time", "30", "--dump-header", str(folder / "headers"), "--output", str(folder / "body"), "--write-out", "%{http_code}"] for name, value in headers.items(): command += ["--header", name + ": " + value] if data is not None: (folder / "request").write_bytes(data) command += ["--data-binary", "@" + str(folder / "request")] result = subprocess.run(command, capture_output=True, text=True) if result.returncode: raise urllib.error.URLError(result.stderr.strip()) response_headers = {} blocks = (folder / "headers").read_text(encoding="iso-8859-1").replace("\r\n", "\n").strip().split("\n\n") for line in blocks[-1].splitlines()[1:]: name, separator, value = line.partition(":") if separator: response_headers[name] = value.strip() return int(result.stdout), (folder / "body").read_bytes(), response_headers class ApiError(RuntimeError): """An API error response. Branch on error_code (and status), never on the message text. uncertain is True when a PATCH or DELETE got no response or a server error: it may or may not have been applied.""" def __init__(self, status, body, uncertain=False): self.status = status self.uncertain = uncertain self.error_code = body.get("error_code") if isinstance(body, dict) else None super().__init__(f"{body.get('error_code')} {body.get('error_params')}: {body.get('errors')} (request {body.get('request_id')})" if isinstance(body, dict) else "HTTP " + str(status) if status else "No response") def call(name, params=None, body=None, key=None): route = SPEC["requests"][name] headers = {"Authorization": "Bearer " + API_KEY, "Accept": "application/json"} if route["method"] == "POST": if not key: raise RuntimeError("Persist a logical create key before sending POST") headers["Idempotency-Key"] = key data = None if body is None else json.dumps(body).encode("utf-8") if data is not None: headers["Content-Type"] = "application/json" query = urllib.parse.urlencode(params or {}) url = BASE + route["path"] + ("?" + query if query else "") # Only GET has automatic retries in this workflow. A PATCH or DELETE that got no response or a # server error is never resent blindly: it may already have been applied, so the caller reads the record first. resend = route["method"] == "GET" for attempt in range(5): try: status, raw, response_headers = transport(route["method"], url, headers, data) except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException): if not resend: raise ApiError(0, None, uncertain=True) if attempt == 4: raise time.sleep(2 ** attempt) continue response_headers = {k.lower(): v for k, v in response_headers.items()} result = None if status != 304 and raw: try: result = decode_json(raw.decode("utf-8")) except (ValueError, UnicodeError): if status < 400: raise RuntimeError("Expected a JSON success response") if status >= 500 and not resend: raise ApiError(status, result, uncertain=True) retry = resend and (status == 429 or status >= 500) if retry: if attempt == 4: raise RuntimeError("Retry limit reached; check the request outcome before starting a new create") delay = response_headers.get("retry-after", str(2 ** attempt)) time.sleep(max(0, float(delay))) continue if status >= 400: raise ApiError(status, result) return {"status": status, "body": result, "headers": response_headers, "raw": raw} raise RuntimeError("Retry limit reached") def 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 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] 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 offsetlen(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)-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={};self.adopted_values={};self.order=[] 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);self.order.append(step);manifest.extend((step,method,route)) if not self.allowed:raise JournalRefusal('Only write workflows need a restart journal') self.header=['H','1',base,workspace,slug,job,input_fingerprint,digest(strings(manifest))] strings(self.header) try: self.fd=os.open(self.lock,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600);self.owned=True except FileExistsError:raise JournalRefusal('This journal is locked; do not run overlapping jobs or steal a stale lock') try: self.owner=secrets.token_hex(16);self.identity=os.fstat(self.fd) if os.write(self.fd,self.owner.encode('ascii'))!=len(self.owner):raise OSError('Incomplete lock identity write') os.fsync(self.fd) if self.path.is_symlink():raise JournalRefusal('Choose a private regular journal file') if mode=="resume" and not self.path.exists():raise JournalRefusal("Journal missing: stop and reconcile lost state before starting a new logical job") if mode=="new" and self.path.exists():raise JournalRefusal("A journal already exists; use resume for the same logical job") if mode=="new": with open(self.path,'xb',buffering=0)as target: target.write(PREAMBLE+frame(self.header));os.fsync(target.fileno()) records=decode(self.path.read_bytes()) if not records or records[0]!=self.header:raise JournalRefusal('Journal workspace/base/guide/job/input binding differs') for record in records[1:]:self.apply(record) if any(step not in self.saved_values for step in self.intents):raise JournalRefusal('A saved before-send intent lacks an ACK; stop and reconcile its outcome before retry') except BaseException: self.close();raise def apply(self,record): if not record:raise JournalRefusal('Empty journal record') if record[0]=='I': if len(record)!=6:raise JournalRefusal('Invalid intent shape') _,step,method,path,request_fingerprint,key=record if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.intents or step in self.adopted_values 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])) elif record[0]=='S': if len(record)<6:raise JournalRefusal('Invalid read-adoption shape') _,step,method,path,read_fingerprint,count,*pairs=record completed=set(self.saved_values)|set(self.adopted_values) if len(completed)>=len(self.order) or completed!=set(self.order[:len(completed)]) or step!=self.order[len(completed)] or any(name not in self.saved_values for name in self.intents):raise JournalRefusal('Adopt only the exact next setup action without any pending intent') target=self.allowed.get(step) expected='/v1/events/info'if (target==('POST','/v1/events') or step=='update_event' and target==('PATCH','/v1/events'))else '/v1/tasks/sections/info'if target==('POST','/v1/tasks/sections')else None if method!='GET' or expected is None or path!=expected:raise JournalRefusal('Adoption requires the exact source-bound single Event or section read') if not re.fullmatch('0|[1-9][0-9]*',count)or len(pairs)!=2*int(count):raise JournalRefusal('Invalid read-adoption field count') names=pairs[::2];fields=['id','integration_metadata_field_1']if expected=='/v1/events/info'else ['event_id','id','name'] if names!=fields:raise JournalRefusal('Read-adoption fields must match the exact source tuple') saved=dict(zip(names,pairs[1::2])) for name in ('id','event_id'): if name in saved and (not re.fullmatch('[1-9][0-9]*',saved[name])or int(saved[name])>9223372036854775807):raise JournalRefusal('Read-adoption IDs must be exact positive Int64 strings') if any(saved[name]==''for name in fields if name not in ('id','event_id'))or read_fingerprint!=fingerprint(saved):raise JournalRefusal('Read-adoption material must be complete and fingerprint-bound') self.adopted_values[step]=saved else:raise JournalRefusal('Unknown journal transition') def append(self,record): # The reader commits state only after complete length/digest recognition. # A torn append is retained and refused, never silently truncated. self.require_active();raw=frame(record) try: with open(self.path,'ab',buffering=0)as target: view=memoryview(raw) while view: written=target.write(view) if not written:raise OSError('Journal write did not advance') view=view[written:] os.fsync(target.fileno()) except BaseException: self.tainted=True;raise def require_active(self): if not self.owned or self.fd is None or self.identity is None or self.tainted:raise JournalRefusal('The journal scope is closed or its IO outcome needs reconciliation') current=self.lock.stat(follow_symlinks=False) if current.st_dev!=self.identity.st_dev or current.st_ino!=self.identity.st_ino or self.lock.read_text(encoding='ascii')!=self.owner:raise JournalRefusal('The journal lock was replaced; stop without deleting it') def acknowledged(self,step): self.require_active();return step in self.saved_values def saved(self,step): self.require_active() if step not in self.saved_values:raise JournalRefusal('No acknowledged state exists for this step') return dict(self.saved_values[step]) def completed(self,step): self.require_active();return step in self.saved_values or step in self.adopted_values def recorded(self,step): self.require_active() if step in self.saved_values:return dict(self.saved_values[step]) if step in self.adopted_values:return dict(self.adopted_values[step]) raise JournalRefusal('No completed write or read-adoption exists') def adopted(self,step): self.require_active();return step in self.adopted_values def adopt(self,step,source_method,source_path,saved): self.require_active() record=['S',step,source_method,source_path,fingerprint(saved),str(len(saved))] for name,value in sorted(saved.items()):record.extend((name,value)) old={name:dict(value)for name,value in self.adopted_values.items()} try:self.apply(record);strings(record) finally:self.adopted_values=old self.append(record);self.apply(record) 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_adopt(job,step,method,path,saved):job.adopt(step,method,path,journal_values(saved)) def journal_begin(job, step, method, path, request_fingerprint): return job.begin(step,method,path,request_fingerprint) def journal_completed(job,step):return job.completed(step) def journal_fingerprint(value): return fingerprint(journal_values(value)) def journal_recorded(job,step):return job.recorded(step) 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 page_size(value): if not re.fullmatch(r"[1-9][0-9]*", value) or int(value) > 2147483647: raise RuntimeError("Page size must be a positive int32") return value def parse_json(value): import math def pairs(values): result={} for key,item in values: if key in result:raise ValueError('Duplicate JSON input property') result[key]=item return result def number(value): result=float(value) if not math.isfinite(result):raise ValueError('Use finite JSON numbers') return result def invalid(value):raise ValueError('Use standard JSON values') return json.loads(value,object_pairs_hook=pairs,parse_float=number,parse_constant=invalid) def positive_id(value): if not re.fullmatch(r"[1-9][0-9]*", value) or int(value) > 9223372036854775807: raise RuntimeError("Use a positive record ID") return value def print_value(value): print(value if isinstance(value, str) else json.dumps(value, ensure_ascii=False)) def require_condition(value, message): if value is not True: raise RuntimeError(message) def required(name): value = os.environ.get(name) if value is None or not value.strip(): raise RuntimeError("Set " + name) return value def response_status(value): return str(value["status"]) def 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 validate_crm_event_inputs(key, name, start, end): from datetime import date spaces = '\u0009\u000A\u000B\u000C\u000D\u0020\u0085\u00A0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u2028\u2029\u202F\u205F\u3000' for value, label, limit in ((name, 'EXHIBITDAY_EVENT_NAME', 500), (key, 'EXHIBITDAY_EXTERNAL_EVENT_KEY', 3000)): utf8(value) if not value or value != value.strip(spaces): raise JournalRefusal('Remove whitespace at the start or end of ' + label) if len(value.encode('utf-16-le')) // 2 > limit: raise JournalRefusal(label + ' exceeds ' + str(limit) + ' UTF-16 code units') if any(ch in name for ch in '<>\r\n') or name.lower() == 'null': raise JournalRefusal('Use plain, single-line EXHIBITDAY_EVENT_NAME text other than null') for value, label in ((start, 'EXHIBITDAY_START_DATE'), (end, 'EXHIBITDAY_END_DATE')): try: valid = re.fullmatch(r'[0-9]{4}-[0-9]{2}-[0-9]{2}', value) and date.fromisoformat(value).year >= 1753 except ValueError: valid = False if not valid: raise JournalRefusal(label + ' must be a calendar date in YYYY-MM-DD on or after 1753-01-01') if end < start: raise JournalRefusal('EXHIBITDAY_END_DATE must be on or after EXHIBITDAY_START_DATE') def main(): external_event_key = required("EXHIBITDAY_EXTERNAL_EVENT_KEY") desired_event_name = required("EXHIBITDAY_EVENT_NAME") desired_start_date = required("EXHIBITDAY_START_DATE") desired_end_date = required("EXHIBITDAY_END_DATE") desired_dates_json = required("EXHIBITDAY_EXHIBIT_DATES_JSON") desired_section_name = optional("EXHIBITDAY_TASK_SECTION_NAME", "Pre-event planning") setup_page_size = page_size(optional("EXHIBITDAY_PAGE_SIZE", "100")) desired_setup_dates = items(parse_json(desired_dates_json)) validate_crm_event_inputs(external_event_key, desired_event_name, desired_start_date, desired_end_date) journal_path = required("EXHIBITDAY_JOURNAL") stable_job_id = required("EXHIBITDAY_JOB_ID") job_mode = optional("EXHIBITDAY_JOB_MODE", "resume") setup_workspace_response = call("workspace_binding", {}, None, None) require_condition(equal(response_status(setup_workspace_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") setup_workspace = setup_workspace_response["body"] owned_workspace_id = positive_id(text(field(setup_workspace, "id"))) setup_input_fingerprint = journal_fingerprint({"workflow_contract_sha256": "19097A09AE2D22C1AF56F5D4FBD9B72F524E5EC195434BC315834CC8C2417C32", "external_event_key": external_event_key, "name": desired_event_name, "start_date": desired_start_date, "end_date": desired_end_date, "section_name": desired_section_name, "dates": desired_dates_json}) setup_job = open_journal(journal_path, "https://api.exhibitday.com/v1", owned_workspace_id, "event-setup-crm", stable_job_id, setup_input_fingerprint, [["create_event", "POST", "/v1/events"], ["update_event", "PATCH", "/v1/events"], ["create_section", "POST", "/v1/tasks/sections"], ["save_dates", "PATCH", "/v1/events/dates"]], job_mode) try: setup_event_id = "" setup_section_id = "" recorded_section_name = desired_section_name if journal_completed(setup_job, "create_event"): recorded_event = journal_recorded(setup_job, "create_event") setup_event_id = positive_id(text(field(recorded_event, "id"))) require_condition(equal(text(field(recorded_event, "integration_metadata_field_1")), external_event_key), "The journal's completed Event differs from this external key.") else: event_search_offset = "0" event_search_query = {"filter_by_integration_metadata_field_1": external_event_key, "$limit": setup_page_size} while True: event_search_query["$offset"] = event_search_offset event_search_response = call("find_existing", event_search_query, None, None) require_condition(equal(response_status(event_search_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") event_search_page = event_search_response["body"] event_search_rows = items(field(event_search_page, "list_data")) require_condition(equal(text(field(event_search_page, "records_found")), text(count(event_search_rows))), "records_found differs from this complete page's rows.") require_condition(is_present(text(field(event_search_page, "total_records"))), "The search wrapper needs total_records.") require_condition(either(equal(field(event_search_page, "has_more"), True), equal(field(event_search_page, "has_more"), False)), "Expected a Boolean has_more value.") for event_search_row in items(event_search_rows): if equal(text(field(event_search_row, "integration_metadata_field_1")), external_event_key): event_search_candidate_id = positive_id(text(field(event_search_row, "id"))) if is_present(setup_event_id): require_condition(equal(setup_event_id, event_search_candidate_id), "More than one matching record exists. Reconcile the ambiguity instead of selecting one or creating another.") setup_event_id = event_search_candidate_id if equal(field(event_search_page, "has_more"), False): break require_condition(not_value(is_empty(event_search_rows)), "An empty search page has has_more=true. Stop and reconcile the search.") event_search_offset = add_offset(event_search_offset, count(event_search_rows)) if not_value(is_present(setup_event_id)): event_write_fingerprint = journal_fingerprint({"name": desired_event_name, "start_date": desired_start_date, "end_date": desired_end_date, "integration_metadata_field_1": external_event_key}) event_intent = journal_begin(setup_job, "create_event", "POST", "/v1/events", event_write_fingerprint) event_create_response = call("create_event", {}, {"name": desired_event_name, "start_date": desired_start_date, "end_date": desired_end_date, "integration_metadata_field_1": external_event_key}, text(field(event_intent, "idempotency_key"))) require_condition(equal(response_status(event_create_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") created_event = event_create_response["body"] setup_event_id = positive_id(text(field(created_event, "id"))) require_condition(equal(text(field(created_event, "integration_metadata_field_1")), external_event_key), "The created Event's external key differs; preserve the pending intent and reconcile.") require_condition(both(is_present(text(field(created_event, "name"))), both(is_present(text(field(created_event, "start_date"))), is_present(text(field(created_event, "end_date"))))), "The Event acknowledgement omitted its saved name or main dates.") journal_acknowledge(setup_job, "create_event", {"id": setup_event_id, "integration_metadata_field_1": external_event_key}) event_confirmation_response = call("confirm_event", {"id": setup_event_id, "$include_record_revision": "true"}, None, None) require_condition(equal(response_status(event_confirmation_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") confirmed_setup_event = event_confirmation_response["body"] require_condition(both(equal(text(field(confirmed_setup_event, "id")), setup_event_id), equal(text(field(confirmed_setup_event, "integration_metadata_field_1")), external_event_key)), "The captured Event is missing or rebound; stop instead of searching for or creating a replacement.") if not_value(journal_completed(setup_job, "create_event")): journal_adopt(setup_job, "create_event", "GET", "/v1/events/info", {"id": text(field(confirmed_setup_event, "id")), "integration_metadata_field_1": text(field(confirmed_setup_event, "integration_metadata_field_1"))}) setup_event_revision = text(field(confirmed_setup_event, "record_revision")) require_condition(is_present(setup_event_revision), "Read the selected Event with its revision before comparing or updating it.") require_condition(both(both(is_present(text(field(confirmed_setup_event, "name"))), is_present(text(field(confirmed_setup_event, "start_date")))), is_present(text(field(confirmed_setup_event, "end_date")))), "The selected Event must return its current name, start date and end date.") if journal_completed(setup_job, "update_event"): recorded_event_update = journal_recorded(setup_job, "update_event") require_condition(both(equal(text(field(recorded_event_update, "id")), setup_event_id), equal(text(field(recorded_event_update, "integration_metadata_field_1")), external_event_key)), "The recorded Event update has a different identity. Stop and reconcile.") require_condition(both(both(equal(text(field(confirmed_setup_event, "name")), desired_event_name), equal(text(field(confirmed_setup_event, "start_date")), desired_start_date)), equal(text(field(confirmed_setup_event, "end_date")), desired_end_date)), "The Event name or main dates changed after this job checked them. Review the current Event before writing again.") else: if both(both(equal(text(field(confirmed_setup_event, "name")), desired_event_name), equal(text(field(confirmed_setup_event, "start_date")), desired_start_date)), equal(text(field(confirmed_setup_event, "end_date")), desired_end_date)): journal_adopt(setup_job, "update_event", "GET", "/v1/events/info", {"id": setup_event_id, "integration_metadata_field_1": external_event_key}) else: require_condition(not_value(journal_acknowledged(setup_job, "create_event")), "The Event created by this job differs from the requested values. Inspect the saved Event before starting another update.") event_update_body = {"id": setup_event_id, "expected_revision": setup_event_revision} if not_value(equal(text(field(confirmed_setup_event, "name")), desired_event_name)): event_update_body["name"] = desired_event_name if not_value(equal(text(field(confirmed_setup_event, "start_date")), desired_start_date)): event_update_body["start_date"] = desired_start_date if not_value(equal(text(field(confirmed_setup_event, "end_date")), desired_end_date)): event_update_body["end_date"] = desired_end_date event_update_fingerprint = journal_fingerprint(event_update_body) journal_begin(setup_job, "update_event", "PATCH", "/v1/events", event_update_fingerprint) event_update_response = call("update_event", {}, event_update_body, None) require_condition(equal(response_status(event_update_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") event_update_ack = event_update_response["body"] event_updated_revision = text(field(event_update_ack, "record_revision")) require_condition(is_present(event_updated_revision), "The conditional Event update needs its returned revision. Reconcile the pending request before continuing.") journal_acknowledge(setup_job, "update_event", {"id": setup_event_id, "integration_metadata_field_1": external_event_key, "record_revision": event_updated_revision}) event_update_verify_response = call("verify_event_update", {"id": setup_event_id}, None, None) require_condition(equal(response_status(event_update_verify_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") verified_setup_event = event_update_verify_response["body"] require_condition(both(both(equal(text(field(verified_setup_event, "id")), setup_event_id), equal(text(field(verified_setup_event, "integration_metadata_field_1")), external_event_key)), both(both(equal(text(field(verified_setup_event, "name")), desired_event_name), equal(text(field(verified_setup_event, "start_date")), desired_start_date)), equal(text(field(verified_setup_event, "end_date")), desired_end_date))), "The Event's current identity, name or main dates differ. Inspect the Event before continuing with setup.") if journal_completed(setup_job, "create_section"): recorded_section = journal_recorded(setup_job, "create_section") setup_section_id = positive_id(text(field(recorded_section, "id"))) require_condition(equal(text(field(recorded_section, "event_id")), setup_event_id), "The recorded Task Section belongs to a different Event.") recorded_section_name = text(field(recorded_section, "name")) else: section_search_offset = "0" section_search_query = {"filter_by_event_id": setup_event_id, "$limit": setup_page_size} while True: section_search_query["$offset"] = section_search_offset section_search_response = call("find_section", section_search_query, None, None) require_condition(equal(response_status(section_search_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") section_search_page = section_search_response["body"] section_search_rows = items(field(section_search_page, "list_data")) require_condition(equal(text(field(section_search_page, "records_found")), text(count(section_search_rows))), "records_found differs from this complete page's rows.") require_condition(is_present(text(field(section_search_page, "total_records"))), "The search wrapper needs total_records.") require_condition(either(equal(field(section_search_page, "has_more"), True), equal(field(section_search_page, "has_more"), False)), "Expected a Boolean has_more value.") for section_search_row in items(section_search_rows): require_condition(equal(text(field(section_search_row, "event_id")), setup_event_id), "A section search row belongs to a different Event; stop before adopting or creating anything.") if equal(text(field(section_search_row, "name")), desired_section_name): section_search_candidate_id = positive_id(text(field(section_search_row, "id"))) if is_present(setup_section_id): require_condition(equal(setup_section_id, section_search_candidate_id), "More than one matching record exists. Reconcile the ambiguity instead of selecting one or creating another.") setup_section_id = section_search_candidate_id if equal(field(section_search_page, "has_more"), False): break require_condition(not_value(is_empty(section_search_rows)), "An empty search page has has_more=true. Stop and reconcile the search.") section_search_offset = add_offset(section_search_offset, count(section_search_rows)) if not_value(is_present(setup_section_id)): section_write_fingerprint = journal_fingerprint({"event_id": setup_event_id, "name": desired_section_name}) section_intent = journal_begin(setup_job, "create_section", "POST", "/v1/tasks/sections", section_write_fingerprint) section_create_response = call("create_section", {}, {"event_id": setup_event_id, "name": desired_section_name}, text(field(section_intent, "idempotency_key"))) require_condition(equal(response_status(section_create_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") created_section = section_create_response["body"] setup_section_id = positive_id(text(field(created_section, "id"))) require_condition(equal(text(field(created_section, "event_id")), setup_event_id), "The created Task Section belongs to a different Event; preserve the pending intent.") recorded_section_name = text(field(created_section, "name")) require_condition(is_present(recorded_section_name), "The Task Section acknowledgement needs its actual saved name.") journal_acknowledge(setup_job, "create_section", {"id": setup_section_id, "event_id": setup_event_id, "name": recorded_section_name}) section_confirmation_response = call("confirm_section", {"id": setup_section_id}, None, None) require_condition(equal(response_status(section_confirmation_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") confirmed_setup_section = section_confirmation_response["body"] require_condition(both(equal(text(field(confirmed_setup_section, "id")), setup_section_id), both(equal(text(field(confirmed_setup_section, "event_id")), setup_event_id), equal(text(field(confirmed_setup_section, "name")), recorded_section_name))), "The captured Task Section is missing, renamed or rebound; stop instead of creating a replacement.") if not_value(journal_completed(setup_job, "create_section")): journal_adopt(setup_job, "create_section", "GET", "/v1/tasks/sections/info", {"event_id": text(field(confirmed_setup_section, "event_id")), "id": text(field(confirmed_setup_section, "id")), "name": text(field(confirmed_setup_section, "name"))}) setup_dates_response = call("read_dates", {"event_id": setup_event_id, "filter_by_date_type_id": "1", "$include_record_revision": "true"}, None, None) require_condition(equal(response_status(setup_dates_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") setup_dates_page = setup_dates_response["body"] require_condition(both(equal(text(field(setup_dates_page, "records_found")), "1"), both(equal(text(field(setup_dates_page, "total_records")), "1"), equal(field(setup_dates_page, "has_more"), False))), "Expected one complete selected Dates group, without another page.") setup_dates_group = single(field(setup_dates_page, "list_data")) require_condition(both(equal(text(field(setup_dates_group, "event_id")), setup_event_id), equal(text(field(setup_dates_group, "date_type_id")), "1")), "The Dates group belongs to another Event or type.") setup_dates_revision = text(field(setup_dates_group, "record_revision")) require_condition(is_present(setup_dates_revision), "Read the actual selected group revision before replacing it.") if journal_completed(setup_job, "save_dates"): recorded_dates = journal_recorded(setup_job, "save_dates") require_condition(both(equal(text(field(recorded_dates, "event_id")), setup_event_id), equal(text(field(recorded_dates, "date_type_id")), "1")), "The recorded Dates acknowledgement belongs to another Event or group.") else: setup_dates_fingerprint = journal_fingerprint({"event_id": setup_event_id, "date_type_id": "1", "dates": desired_dates_json, "expected_revision": setup_dates_revision}) journal_begin(setup_job, "save_dates", "PATCH", "/v1/events/dates", setup_dates_fingerprint) setup_dates_save_response = call("save_dates", {}, {"event_id": setup_event_id, "date_type_id": "1", "dates": desired_setup_dates, "expected_revision": setup_dates_revision}, None) require_condition(equal(response_status(setup_dates_save_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") setup_dates_ack = setup_dates_save_response["body"] setup_dates_saved_revision = text(field(setup_dates_ack, "record_revision")) require_condition(is_present(setup_dates_saved_revision), "The checked Dates save needs its actual returned revision.") journal_acknowledge(setup_job, "save_dates", {"event_id": setup_event_id, "date_type_id": "1", "record_revision": setup_dates_saved_revision}) setup_dates_verify_response = call("verify_dates", {"event_id": setup_event_id, "filter_by_date_type_id": "1"}, None, None) require_condition(equal(response_status(setup_dates_verify_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") setup_dates_verify_page = setup_dates_verify_response["body"] require_condition(both(equal(text(field(setup_dates_verify_page, "records_found")), "1"), both(equal(text(field(setup_dates_verify_page, "total_records")), "1"), equal(field(setup_dates_verify_page, "has_more"), False))), "Expected one complete selected Dates group, without another page.") setup_dates_verify_group = single(field(setup_dates_verify_page, "list_data")) require_condition(both(equal(text(field(setup_dates_verify_group, "event_id")), setup_event_id), equal(text(field(setup_dates_verify_group, "date_type_id")), "1")), "The Dates group belongs to another Event or type.") require_condition(deep_equal(field(setup_dates_verify_group, "dates"), desired_setup_dates), "The saved normalized Dates list differs from the supplied canonical list. Inspect it; do not automatically restore or repeat the update.") setup_event_readback_response = call("event_readback", {"id": setup_event_id}, None, None) require_condition(equal(response_status(setup_event_readback_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") setup_event_readback = setup_event_readback_response["body"] require_condition(both(equal(text(field(setup_event_readback, "id")), setup_event_id), equal(text(field(setup_event_readback, "integration_metadata_field_1")), external_event_key)), "Final Event readback is missing or rebound; earlier steps remain saved.") require_condition(both(both(equal(text(field(setup_event_readback, "name")), desired_event_name), equal(text(field(setup_event_readback, "start_date")), desired_start_date)), equal(text(field(setup_event_readback, "end_date")), desired_end_date)), "The Event name or main dates changed before final readback. Inspect the Event before starting another update.") planning_section_present = False for setup_event_section in items(items(field(setup_event_readback, "task_sections"))): if equal(text(field(setup_event_section, "id")), setup_section_id): planning_section_present = True require_condition(planning_section_present, "The Event's current Task Sections do not include the recorded section; inspect it rather than creating another.") print_value({"event_id": setup_event_id, "task_section_id": setup_section_id, "dates_verified": "true"}) finally: setup_job.close() if __name__ == "__main__": main() EXHIBITDAY_PY ``` ```javascript // Server-side Node.js with fetch; built-in modules only. Set EXHIBITDAY_API_KEY. const BASE = "https://api.exhibitday.com/v1"; const SPEC = JSON.parse("{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"find_existing\":{\"method\":\"GET\",\"path\":\"/events\"},\"create_event\":{\"method\":\"POST\",\"path\":\"/events\"},\"confirm_event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"update_event\":{\"method\":\"PATCH\",\"path\":\"/events\"},\"verify_event_update\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"find_section\":{\"method\":\"GET\",\"path\":\"/tasks/sections\"},\"create_section\":{\"method\":\"POST\",\"path\":\"/tasks/sections\"},\"confirm_section\":{\"method\":\"GET\",\"path\":\"/tasks/sections/info\"},\"read_dates\":{\"method\":\"GET\",\"path\":\"/events/dates\"},\"save_dates\":{\"method\":\"PATCH\",\"path\":\"/events/dates\"},\"verify_dates\":{\"method\":\"GET\",\"path\":\"/events/dates\"},\"event_readback\":{\"method\":\"GET\",\"path\":\"/events/info\"}}}"); const API_KEY = process.env.EXHIBITDAY_API_KEY; if (!API_KEY || !API_KEY.trim()) throw new Error("Set EXHIBITDAY_API_KEY"); if (/[^\x20-\x7e]/.test(API_KEY)) throw new Error("Use the API key as one ASCII header value without control characters"); 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, errors: result.errors, error_params: result.error_params, 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, key = null) { const route = SPEC.requests[name]; const headers = { Authorization: "Bearer " + API_KEY, Accept: "application/json" }; if (route.method === "POST") { if (!key) throw new Error("Persist a logical create key before sending POST"); headers["Idempotency-Key"] = key; } 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 : ""); // 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. const resend = route.method === "GET"; 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 = resend && (response.status === 429 || response.status >= 500); 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, raw }; } throw new Error("Retry limit reached"); } function add_offset(offset, received) { const result = BigInt(offset) + received; if (received <= 0n || result > 2147483647n) throw new Error("Cannot advance this int32 offset; reconcile the query"); return result.toString(); } function both(left,right) { return left && right; } function items(value) { if (!Array.isArray(value)) throw new Error("Expected a JSON array"); return value; } function count(value) { return BigInt(items(value).length); } function deep_equal(left,right) { if(left===null||right===null)return left===right; if(typeof left!==typeof right||Array.isArray(left)!==Array.isArray(right))return false; if(typeof left!=='object')return left===right; const a=Object.keys(left).sort(),b=Object.keys(right).sort();return a.length===b.length&&a.every((k,i)=>k===b[i]&&deep_equal(left[k],right[k])); } function either(left, right) { if (typeof left !== "boolean" || typeof right !== "boolean") throw new Error("Expected Boolean criteria"); return left || right; } function equal(left, right) { return typeof left === typeof right && left === right; } function field(value, name) { if (!value || Array.isArray(value) || typeof value !== "object" || !Object.hasOwn(value, name)) throw new Error("Missing response field: " + name); return value[name]; } function is_empty(value) { return count(value) === 0n; } function is_present(value) { return value !== null && value !== undefined && value !== ""; } 'use strict'; // Private client restart state. No HTTP or application dependency. const fs = require('node:fs'); const crypto = require('node:crypto'); const PREAMBLE = Buffer.from('EXHIBITDAY-GUIDE-JOURNAL 1\n', 'ascii'); class JournalRefusal extends Error {} function ascii(raw) { if (raw.some(value => value > 127)) throw new JournalRefusal('Journal framing must be canonical ASCII'); return raw.toString('ascii'); } function utf8(value) { if (typeof value !== 'string') throw new JournalRefusal('Journal fields are exact strings'); for (const unit of value) if (unit.length === 1 && unit.charCodeAt(0) >= 0xd800 && unit.charCodeAt(0) <= 0xdfff) throw new JournalRefusal('Invalid Unicode journal field'); return Buffer.from(value, 'utf8'); } function strings(values) { const parts = []; for (const value of values) { const raw = utf8(value); parts.push(Buffer.from(String(raw.length) + ':', 'ascii'), raw); } return Buffer.concat(parts); } function readStrings(raw) { const values = []; let offset = 0; while (offset < raw.length) { const end = raw.indexOf(58, offset); if (end < 0) throw new JournalRefusal('Incomplete journal string length'); const length = ascii(raw.subarray(offset, end)); if (!/^(0|[1-9][0-9]*)$/.test(length)) throw new JournalRefusal('Noncanonical journal string length'); const size = BigInt(length); offset = end + 1; if (size > BigInt(raw.length - offset)) throw new JournalRefusal('Incomplete journal string'); const count = Number(size); values.push(new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(raw.subarray(offset, offset + count))); offset += count; } return values; } function digest(raw) { return crypto.createHash('sha256').update(raw).digest('hex').toUpperCase(); } function fingerprint(pairs) { const values = []; for (const name of Object.keys(pairs).sort()) { if (!/^[A-Za-z0-9_.-]+$/.test(name) || ['api_key', 'exhibitday_api_key'].includes(name.toLowerCase())) throw new JournalRefusal('Use explicit secret-free fingerprint field names'); values.push(name, pairs[name]); } return digest(strings(values)); } function frame(values) { const raw = strings(values); return Buffer.concat([Buffer.from(String(raw.length) + ' ' + digest(raw) + '\n', 'ascii'), raw, Buffer.from('\n')]); } function decode(raw) { if (!raw.subarray(0, PREAMBLE.length).equals(PREAMBLE)) throw new JournalRefusal('Unknown or incomplete journal version'); let offset = PREAMBLE.length; const records = []; while (offset < raw.length) { const end = raw.indexOf(10, offset); if (end < 0) throw new JournalRefusal('Incomplete journal frame header; reconcile before retry'); const match = /^(0|[1-9][0-9]*) ([0-9A-F]{64})$/.exec(ascii(raw.subarray(offset, end))); if (!match) throw new JournalRefusal('Invalid journal frame header'); const size = BigInt(match[1]); offset = end + 1; if (size >= BigInt(raw.length - offset)) throw new JournalRefusal('Incomplete journal frame; reconcile before retry'); const count = Number(size), payload = raw.subarray(offset, offset + count); offset += count; if (raw[offset] !== 10 || digest(payload) !== match[2]) throw new JournalRefusal('Journal integrity check failed; reconcile before retry'); records.push(readStrings(payload)); offset++; } return records; } function writeAll(fd, raw) { let offset = 0; while (offset < raw.length) { const count = fs.writeSync(fd, raw, offset, raw.length - offset); if (!count) throw new Error('Journal write did not advance'); offset += count; } } function same(left, right) { return left.length === right.length && left.every((value, index) => value === right[index]); } class Journal { constructor(path, base, workspace, slug, job, inputFingerprint, writes, mode = 'resume') { this.path = path; this.lock = path + '.lock'; this.fd = null; this.owned = false; this.identity = null; this.tainted = false; this.intents = new Map(); this.savedValues = new Map(); this.adoptedValues = new Map(); this.allowed = new Map(); if (!['new', 'resume'].includes(mode)) throw new JournalRefusal('Choose new or resume for this local job'); const address = new URL(base); if (!['https:', 'http:'].includes(address.protocol) || !address.hostname || address.username || address.password || address.search || address.hash || !/^[a-z][a-z0-9-]*$/.test(slug)) throw new JournalRefusal('Use the actual API base and closed guide slug'); if (!job.trim() || !/^[1-9][0-9]*$/.test(workspace) || !/^[0-9A-F]{64}$/.test(inputFingerprint)) throw new JournalRefusal('Use an actual workspace, stable explicit job ID and exact input fingerprint'); const manifest = []; for (const [step, method, route] of writes) { if (!/^[a-z][a-z0-9_-]*$/.test(step) || this.allowed.has(step) || !['POST', 'PATCH', 'DELETE'].includes(method) || !/^\/v1\/[A-Za-z0-9_/-]+$/.test(route) || route.includes('//')) throw new JournalRefusal('Use a closed unique write manifest'); this.allowed.set(step, [method, route]); manifest.push(step, method, route); } if (!this.allowed.size) throw new JournalRefusal('Only write workflows need a restart journal'); this.header = ['H', '1', base, workspace, slug, job, inputFingerprint, digest(strings(manifest))]; strings(this.header); try { this.fd = fs.openSync(this.lock, 'wx', 0o600); this.owned = true; } catch (error) { if (error.code === 'EEXIST') throw new JournalRefusal('This journal is locked; do not overlap jobs or steal a stale lock'); throw error; } try { this.owner = crypto.randomBytes(16).toString('hex'); this.identity = fs.fstatSync(this.fd, { bigint: true }); writeAll(this.fd, Buffer.from(this.owner, 'ascii')); fs.fsyncSync(this.fd); let exists = true; try { if (fs.lstatSync(path).isSymbolicLink()) throw new JournalRefusal('Choose a private regular journal file'); } catch (error) { if (error.code === 'ENOENT') exists = false; else throw error; } if (mode === 'resume' && !exists) throw new JournalRefusal('Journal missing: stop and reconcile lost state before starting a new logical job'); if (mode === 'new' && exists) throw new JournalRefusal('Journal already exists; use resume for the same logical job'); if (mode === 'new') { const target = fs.openSync(path, 'wx', 0o600); try { writeAll(target, Buffer.concat([PREAMBLE, frame(this.header)])); fs.fsyncSync(target); } finally { fs.closeSync(target); } } const records = decode(fs.readFileSync(path)); if (!records.length || !same(records[0], this.header)) throw new JournalRefusal('Journal workspace/base/guide/job/input binding differs'); for (const record of records.slice(1)) this.apply(record); if ([...this.intents.keys()].some(step => !this.savedValues.has(step))) throw new JournalRefusal('Saved before-send intent lacks ACK; stop and reconcile before retry'); } catch (error) { this.close(); throw error; } } apply(record) { if (record[0] === 'I') { if (record.length !== 6) throw new JournalRefusal('Invalid intent shape'); const [, step, method, path, requestFingerprint, key] = record; if (!/^[a-z][a-z0-9_-]*$/.test(step) || this.intents.has(step) || this.adoptedValues.has(step) || !this.allowed.has(step) || !same(this.allowed.get(step), [method, path]) || !/^[0-9A-F]{64}$/.test(requestFingerprint) || [...this.intents.keys()].some(name => !this.savedValues.has(name))) throw new JournalRefusal('Invalid, future or repeated intent'); if ((method === 'POST' && !/^[0-9a-f]{32}$/.test(key)) || (method !== 'POST' && key !== '')) throw new JournalRefusal('Invalid persisted action key'); this.intents.set(step, { method, path, request_fingerprint: requestFingerprint, idempotency_key: key }); } else if (record[0] === 'A') { const [, step, count, ...pairs] = record; if (record.length < 3 || !/^(0|[1-9][0-9]*)$/.test(count) || BigInt(pairs.length) !== 2n * BigInt(count) || !this.intents.has(step) || this.savedValues.has(step)) throw new JournalRefusal('ACK without exactly one prior intent'); const names = pairs.filter((_, index) => index % 2 === 0); if (!same(names, [...new Set(names)].sort()) || names.some(name => !/^[a-z][a-z0-9_]*$/.test(name) || ['api_key', 'exhibitday_api_key'].includes(name))) throw new JournalRefusal('ACK fields must be unique sorted secret-free identifiers'); this.savedValues.set(step, Object.fromEntries(names.map((name, index) => [name, pairs[index * 2 + 1]]))); } else if (record[0] === 'S') { if (record.length < 6) throw new JournalRefusal('Invalid read-adoption shape'); const [,step,method,path,readFingerprint,count,...pairs] = record; const completed = new Set([...this.savedValues.keys(),...this.adoptedValues.keys()]), order = [...this.allowed.keys()]; if (completed.size >= order.length || order.slice(0,completed.size).some(name=>!completed.has(name)) || step !== order[completed.size] || [...this.intents.keys()].some(name=>!this.savedValues.has(name))) throw new JournalRefusal('Adopt only the exact next setup action without any pending intent'); const target = this.allowed.get(step), expected = (same(target,['POST','/v1/events']) || step==='update_event' && same(target,['PATCH','/v1/events'])) ? '/v1/events/info' : same(target,['POST','/v1/tasks/sections']) ? '/v1/tasks/sections/info' : null; if (method !== 'GET' || expected === null || path !== expected) throw new JournalRefusal('Adoption requires the exact source-bound single Event or section read'); if (!/^(0|[1-9][0-9]*)$/.test(count) || BigInt(pairs.length) !== 2n*BigInt(count)) throw new JournalRefusal('Invalid read-adoption field count'); const names=pairs.filter((_,i)=>i%2===0), fields=expected==='/v1/events/info'?['id','integration_metadata_field_1']:['event_id','id','name']; if (!same(names,fields)) throw new JournalRefusal('Read-adoption fields must match the exact source tuple'); const saved=Object.fromEntries(names.map((name,i)=>[name,pairs[2*i+1]])); for (const name of ['id','event_id']) if (Object.hasOwn(saved,name) && (!/^[1-9][0-9]*$/.test(saved[name]) || BigInt(saved[name])>9223372036854775807n)) throw new JournalRefusal('Read-adoption IDs must be exact positive Int64 strings'); if (fields.some(name=>!['id','event_id'].includes(name)&&saved[name]==='') || readFingerprint!==fingerprint(saved)) throw new JournalRefusal('Read-adoption material must be complete and fingerprint-bound'); this.adoptedValues.set(step,saved); } else throw new JournalRefusal('Unknown journal transition'); } requireActive() { if (!this.owned || this.fd === null || this.identity === null || this.tainted) throw new JournalRefusal('Journal is closed or its IO outcome needs reconciliation'); const current = fs.lstatSync(this.lock, { bigint: true }); if (current.dev !== this.identity.dev || current.ino !== this.identity.ino || ascii(fs.readFileSync(this.lock)) !== this.owner) throw new JournalRefusal('Journal lock was replaced; stop without deleting it'); } append(record) { this.requireActive(); const raw = frame(record); let target; try { target = fs.openSync(this.path, 'a'); writeAll(target, raw); fs.fsyncSync(target); } catch (error) { this.tainted = true; throw error; } finally { if (target !== undefined) fs.closeSync(target); } } acknowledged(step) { this.requireActive(); return this.savedValues.has(step); } saved(step) { this.requireActive(); if (!this.savedValues.has(step)) throw new JournalRefusal('No acknowledged state exists'); return { ...this.savedValues.get(step) }; } completed(step) { this.requireActive(); return this.savedValues.has(step)||this.adoptedValues.has(step); } adopted(step) { this.requireActive(); return this.adoptedValues.has(step); } recorded(step) { this.requireActive(); if(!this.completed(step))throw new JournalRefusal('No completed write or read-adoption exists');return {...(this.savedValues.get(step)||this.adoptedValues.get(step))}; } adopt(step,method,path,saved) { this.requireActive(); const names=Object.keys(saved).sort(),record=['S',step,method,path,fingerprint(saved),String(names.length)]; for(const name of names)record.push(name,saved[name]); const old=new Map(this.adoptedValues);try{this.apply(record);strings(record);}finally{this.adoptedValues=old;} this.append(record);this.apply(record); } begin(step, method, path, requestFingerprint) { this.requireActive(); if (this.intents.has(step)) throw new JournalRefusal('Never blindly repeat an existing action'); const key = method === 'POST' ? crypto.randomBytes(16).toString('hex') : '', record = ['I', step, method, path, requestFingerprint, key]; const old = new Map(this.intents); try { this.apply(record); } finally { this.intents = old; } this.append(record); this.apply(record); return { ...this.intents.get(step) }; } acknowledge(step, saved) { this.requireActive(); const names = Object.keys(saved).sort(), record = ['A', step, String(names.length)]; for (const name of names) record.push(name, saved[name]); const old = new Map(this.savedValues); try { this.apply(record); strings(record); } finally { this.savedValues = old; } this.append(record); this.apply(record); } close() { if (!this.owned) return; if (this.tainted) { fs.closeSync(this.fd); this.fd = null; this.owned = false; return; } try { this.requireActive(); } catch (error) { fs.closeSync(this.fd); this.fd = null; this.owned = false; throw error; } fs.closeSync(this.fd); this.fd = null; this.owned = false; fs.unlinkSync(this.lock); } } function journal_values(value) { if (!value || typeof value !== 'object' || Array.isArray(value) || Object.values(value).some(item=>typeof item!=='string')) throw new JournalRefusal('Saved/fingerprint values must be exact strings'); return {...value}; } function journal_acknowledge(job,step,saved) { job.acknowledge(step,journal_values(saved)); } function journal_acknowledged(job,step) { return job.acknowledged(step); } function journal_adopt(job,step,method,path,saved){job.adopt(step,method,path,journal_values(saved));} function journal_begin(job,step,method,path,requestFingerprint) { return job.begin(step,method,path,requestFingerprint); } function journal_completed(job,step){return job.completed(step);} function journal_fingerprint(value) { return fingerprint(journal_values(value)); } function journal_recorded(job,step){return job.recorded(step);} function not_value(value) { if (typeof value !== "boolean") throw new Error("Expected a Boolean"); return !value; } function open_journal(path,base,workspace,slug,job,inputFingerprint,writes,mode) { return new Journal(path,base,workspace,slug,job,inputFingerprint,writes,mode); } function optional(name, fallback) { const value = process.env[name]; return value === undefined || value === "" ? fallback : value; } function page_size(value) { if (!/^[1-9][0-9]*$/.test(value) || BigInt(value) > 2147483647n) throw new Error("Page size must be a positive int32"); return value; } function parse_json(value){ const result=JSON.parse(value),stack=[]; for(const match of value.matchAll(/"(?:\\.|[^"\\])*"|[{}\[\],]/gs)){ const token=match[0]; if(token==='{')stack.push({object:true,key:true,names:new Set()}); else if(token==='[')stack.push({object:false}); else if(token==='}'||token===']')stack.pop(); else if(token===','){if(stack.length&&stack.at(-1).object)stack.at(-1).key=true;} else if(stack.length&&stack.at(-1).object&&stack.at(-1).key){const frame=stack.at(-1),name=JSON.parse(token);if(frame.names.has(name))throw new Error('Duplicate JSON input property');frame.names.add(name);frame.key=false;} } function finite(node){if(typeof node==='number'&&!Number.isFinite(node))throw new Error('Use finite JSON numbers');if(node&&typeof node==='object')for(const item of Object.values(node))finite(item);} finite(result);return result; } function positive_id(value) { if (!/^[1-9][0-9]*$/.test(value) || BigInt(value) > 9223372036854775807n) throw new Error("Use a positive record ID"); return value; } function print_value(value) { console.log(typeof value === "string" ? value : JSON.stringify(value)); } function require_condition(value, message) { if (value !== true) throw new Error(message); } function required(name) { const value = process.env[name]; if (value === undefined || !value.trim()) throw new Error("Set " + name); return value; } function response_status(value) { return String(value.status); } function single(value){const rows=items(value);if(rows.length!==1)throw new Error('Expected exactly one selected record');return rows[0];} function text(value) { if (value === null || value === undefined) return ""; if (["string", "boolean", "bigint"].includes(typeof value)) return String(value); throw new Error("Expected a scalar response value"); } function validate_crm_event_inputs(key, name, start, end) { const boundary = /^[\u0009-\u000D\u0020\u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]|[\u0009-\u000D\u0020\u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]$/; for (const [value,label,limit] of [[name,'EXHIBITDAY_EVENT_NAME',500],[key,'EXHIBITDAY_EXTERNAL_EVENT_KEY',3000]]) { utf8(value); if (!value || boundary.test(value)) throw new JournalRefusal('Remove whitespace at the start or end of ' + label); if (value.length > limit) throw new JournalRefusal(label + ' exceeds ' + limit + ' UTF-16 code units'); } if (/[<>\r\n]/.test(name) || name.toLowerCase() === 'null') throw new JournalRefusal('Use plain, single-line EXHIBITDAY_EVENT_NAME text other than null'); for (const [value,label] of [[start,'EXHIBITDAY_START_DATE'],[end,'EXHIBITDAY_END_DATE']]) { const time = new Date(value + 'T00:00:00Z'); if (value.length !== 10 || !/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test(value) || value < '1753-01-01' || Number.isNaN(time.getTime()) || time.toISOString().slice(0,10) !== value) throw new JournalRefusal(label + ' must be a calendar date in YYYY-MM-DD on or after 1753-01-01'); } if (end < start) throw new JournalRefusal('EXHIBITDAY_END_DATE must be on or after EXHIBITDAY_START_DATE'); } async function main() { let external_event_key = required("EXHIBITDAY_EXTERNAL_EVENT_KEY"); let desired_event_name = required("EXHIBITDAY_EVENT_NAME"); let desired_start_date = required("EXHIBITDAY_START_DATE"); let desired_end_date = required("EXHIBITDAY_END_DATE"); let desired_dates_json = required("EXHIBITDAY_EXHIBIT_DATES_JSON"); let desired_section_name = optional("EXHIBITDAY_TASK_SECTION_NAME", "Pre-event planning"); let setup_page_size = page_size(optional("EXHIBITDAY_PAGE_SIZE", "100")); let desired_setup_dates = items(parse_json(desired_dates_json)); validate_crm_event_inputs(external_event_key, desired_event_name, desired_start_date, desired_end_date); let journal_path = required("EXHIBITDAY_JOURNAL"); let stable_job_id = required("EXHIBITDAY_JOB_ID"); let job_mode = optional("EXHIBITDAY_JOB_MODE", "resume"); let setup_workspace_response = await call("workspace_binding", {}, null, null); require_condition(equal(response_status(setup_workspace_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); let setup_workspace = setup_workspace_response.body; let owned_workspace_id = positive_id(text(field(setup_workspace, "id"))); let setup_input_fingerprint = journal_fingerprint({"workflow_contract_sha256": "19097A09AE2D22C1AF56F5D4FBD9B72F524E5EC195434BC315834CC8C2417C32", "external_event_key": external_event_key, "name": desired_event_name, "start_date": desired_start_date, "end_date": desired_end_date, "section_name": desired_section_name, "dates": desired_dates_json}); let setup_job = open_journal(journal_path, "https://api.exhibitday.com/v1", owned_workspace_id, "event-setup-crm", stable_job_id, setup_input_fingerprint, [["create_event", "POST", "/v1/events"], ["update_event", "PATCH", "/v1/events"], ["create_section", "POST", "/v1/tasks/sections"], ["save_dates", "PATCH", "/v1/events/dates"]], job_mode); try { let setup_event_id = ""; let setup_section_id = ""; let recorded_section_name = desired_section_name; if (journal_completed(setup_job, "create_event")) { let recorded_event = journal_recorded(setup_job, "create_event"); setup_event_id = positive_id(text(field(recorded_event, "id"))); require_condition(equal(text(field(recorded_event, "integration_metadata_field_1")), external_event_key), "The journal's completed Event differs from this external key."); } else { let event_search_offset = "0"; let event_search_query = {"filter_by_integration_metadata_field_1": external_event_key, "$limit": setup_page_size}; while (true) { event_search_query["$offset"] = event_search_offset; let event_search_response = await call("find_existing", event_search_query, null, null); require_condition(equal(response_status(event_search_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); let event_search_page = event_search_response.body; let event_search_rows = items(field(event_search_page, "list_data")); require_condition(equal(text(field(event_search_page, "records_found")), text(count(event_search_rows))), "records_found differs from this complete page's rows."); require_condition(is_present(text(field(event_search_page, "total_records"))), "The search wrapper needs total_records."); require_condition(either(equal(field(event_search_page, "has_more"), true), equal(field(event_search_page, "has_more"), false)), "Expected a Boolean has_more value."); for (const event_search_row of items(event_search_rows)) { if (equal(text(field(event_search_row, "integration_metadata_field_1")), external_event_key)) { let event_search_candidate_id = positive_id(text(field(event_search_row, "id"))); if (is_present(setup_event_id)) { require_condition(equal(setup_event_id, event_search_candidate_id), "More than one matching record exists. Reconcile the ambiguity instead of selecting one or creating another."); } setup_event_id = event_search_candidate_id; } } if (equal(field(event_search_page, "has_more"), false)) { break; } require_condition(not_value(is_empty(event_search_rows)), "An empty search page has has_more=true. Stop and reconcile the search."); event_search_offset = add_offset(event_search_offset, count(event_search_rows)); } if (not_value(is_present(setup_event_id))) { let event_write_fingerprint = journal_fingerprint({"name": desired_event_name, "start_date": desired_start_date, "end_date": desired_end_date, "integration_metadata_field_1": external_event_key}); let event_intent = journal_begin(setup_job, "create_event", "POST", "/v1/events", event_write_fingerprint); let event_create_response = await call("create_event", {}, {"name": desired_event_name, "start_date": desired_start_date, "end_date": desired_end_date, "integration_metadata_field_1": external_event_key}, text(field(event_intent, "idempotency_key"))); require_condition(equal(response_status(event_create_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); let created_event = event_create_response.body; setup_event_id = positive_id(text(field(created_event, "id"))); require_condition(equal(text(field(created_event, "integration_metadata_field_1")), external_event_key), "The created Event's external key differs; preserve the pending intent and reconcile."); require_condition(both(is_present(text(field(created_event, "name"))), both(is_present(text(field(created_event, "start_date"))), is_present(text(field(created_event, "end_date"))))), "The Event acknowledgement omitted its saved name or main dates."); journal_acknowledge(setup_job, "create_event", {"id": setup_event_id, "integration_metadata_field_1": external_event_key}); } } let event_confirmation_response = await call("confirm_event", {"id": setup_event_id, "$include_record_revision": "true"}, null, null); require_condition(equal(response_status(event_confirmation_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); let confirmed_setup_event = event_confirmation_response.body; require_condition(both(equal(text(field(confirmed_setup_event, "id")), setup_event_id), equal(text(field(confirmed_setup_event, "integration_metadata_field_1")), external_event_key)), "The captured Event is missing or rebound; stop instead of searching for or creating a replacement."); if (not_value(journal_completed(setup_job, "create_event"))) { journal_adopt(setup_job, "create_event", "GET", "/v1/events/info", {"id": text(field(confirmed_setup_event, "id")), "integration_metadata_field_1": text(field(confirmed_setup_event, "integration_metadata_field_1"))}); } let setup_event_revision = text(field(confirmed_setup_event, "record_revision")); require_condition(is_present(setup_event_revision), "Read the selected Event with its revision before comparing or updating it."); require_condition(both(both(is_present(text(field(confirmed_setup_event, "name"))), is_present(text(field(confirmed_setup_event, "start_date")))), is_present(text(field(confirmed_setup_event, "end_date")))), "The selected Event must return its current name, start date and end date."); if (journal_completed(setup_job, "update_event")) { let recorded_event_update = journal_recorded(setup_job, "update_event"); require_condition(both(equal(text(field(recorded_event_update, "id")), setup_event_id), equal(text(field(recorded_event_update, "integration_metadata_field_1")), external_event_key)), "The recorded Event update has a different identity. Stop and reconcile."); require_condition(both(both(equal(text(field(confirmed_setup_event, "name")), desired_event_name), equal(text(field(confirmed_setup_event, "start_date")), desired_start_date)), equal(text(field(confirmed_setup_event, "end_date")), desired_end_date)), "The Event name or main dates changed after this job checked them. Review the current Event before writing again."); } else { if (both(both(equal(text(field(confirmed_setup_event, "name")), desired_event_name), equal(text(field(confirmed_setup_event, "start_date")), desired_start_date)), equal(text(field(confirmed_setup_event, "end_date")), desired_end_date))) { journal_adopt(setup_job, "update_event", "GET", "/v1/events/info", {"id": setup_event_id, "integration_metadata_field_1": external_event_key}); } else { require_condition(not_value(journal_acknowledged(setup_job, "create_event")), "The Event created by this job differs from the requested values. Inspect the saved Event before starting another update."); let event_update_body = {"id": setup_event_id, "expected_revision": setup_event_revision}; if (not_value(equal(text(field(confirmed_setup_event, "name")), desired_event_name))) { event_update_body["name"] = desired_event_name; } if (not_value(equal(text(field(confirmed_setup_event, "start_date")), desired_start_date))) { event_update_body["start_date"] = desired_start_date; } if (not_value(equal(text(field(confirmed_setup_event, "end_date")), desired_end_date))) { event_update_body["end_date"] = desired_end_date; } let event_update_fingerprint = journal_fingerprint(event_update_body); journal_begin(setup_job, "update_event", "PATCH", "/v1/events", event_update_fingerprint); let event_update_response = await call("update_event", {}, event_update_body, null); require_condition(equal(response_status(event_update_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); let event_update_ack = event_update_response.body; let event_updated_revision = text(field(event_update_ack, "record_revision")); require_condition(is_present(event_updated_revision), "The conditional Event update needs its returned revision. Reconcile the pending request before continuing."); journal_acknowledge(setup_job, "update_event", {"id": setup_event_id, "integration_metadata_field_1": external_event_key, "record_revision": event_updated_revision}); } } let event_update_verify_response = await call("verify_event_update", {"id": setup_event_id}, null, null); require_condition(equal(response_status(event_update_verify_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); let verified_setup_event = event_update_verify_response.body; require_condition(both(both(equal(text(field(verified_setup_event, "id")), setup_event_id), equal(text(field(verified_setup_event, "integration_metadata_field_1")), external_event_key)), both(both(equal(text(field(verified_setup_event, "name")), desired_event_name), equal(text(field(verified_setup_event, "start_date")), desired_start_date)), equal(text(field(verified_setup_event, "end_date")), desired_end_date))), "The Event's current identity, name or main dates differ. Inspect the Event before continuing with setup."); if (journal_completed(setup_job, "create_section")) { let recorded_section = journal_recorded(setup_job, "create_section"); setup_section_id = positive_id(text(field(recorded_section, "id"))); require_condition(equal(text(field(recorded_section, "event_id")), setup_event_id), "The recorded Task Section belongs to a different Event."); recorded_section_name = text(field(recorded_section, "name")); } else { let section_search_offset = "0"; let section_search_query = {"filter_by_event_id": setup_event_id, "$limit": setup_page_size}; while (true) { section_search_query["$offset"] = section_search_offset; let section_search_response = await call("find_section", section_search_query, null, null); require_condition(equal(response_status(section_search_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); let section_search_page = section_search_response.body; let section_search_rows = items(field(section_search_page, "list_data")); require_condition(equal(text(field(section_search_page, "records_found")), text(count(section_search_rows))), "records_found differs from this complete page's rows."); require_condition(is_present(text(field(section_search_page, "total_records"))), "The search wrapper needs total_records."); require_condition(either(equal(field(section_search_page, "has_more"), true), equal(field(section_search_page, "has_more"), false)), "Expected a Boolean has_more value."); for (const section_search_row of items(section_search_rows)) { require_condition(equal(text(field(section_search_row, "event_id")), setup_event_id), "A section search row belongs to a different Event; stop before adopting or creating anything."); if (equal(text(field(section_search_row, "name")), desired_section_name)) { let section_search_candidate_id = positive_id(text(field(section_search_row, "id"))); if (is_present(setup_section_id)) { require_condition(equal(setup_section_id, section_search_candidate_id), "More than one matching record exists. Reconcile the ambiguity instead of selecting one or creating another."); } setup_section_id = section_search_candidate_id; } } if (equal(field(section_search_page, "has_more"), false)) { break; } require_condition(not_value(is_empty(section_search_rows)), "An empty search page has has_more=true. Stop and reconcile the search."); section_search_offset = add_offset(section_search_offset, count(section_search_rows)); } if (not_value(is_present(setup_section_id))) { let section_write_fingerprint = journal_fingerprint({"event_id": setup_event_id, "name": desired_section_name}); let section_intent = journal_begin(setup_job, "create_section", "POST", "/v1/tasks/sections", section_write_fingerprint); let section_create_response = await call("create_section", {}, {"event_id": setup_event_id, "name": desired_section_name}, text(field(section_intent, "idempotency_key"))); require_condition(equal(response_status(section_create_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); let created_section = section_create_response.body; setup_section_id = positive_id(text(field(created_section, "id"))); require_condition(equal(text(field(created_section, "event_id")), setup_event_id), "The created Task Section belongs to a different Event; preserve the pending intent."); recorded_section_name = text(field(created_section, "name")); require_condition(is_present(recorded_section_name), "The Task Section acknowledgement needs its actual saved name."); journal_acknowledge(setup_job, "create_section", {"id": setup_section_id, "event_id": setup_event_id, "name": recorded_section_name}); } } let section_confirmation_response = await call("confirm_section", {"id": setup_section_id}, null, null); require_condition(equal(response_status(section_confirmation_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); let confirmed_setup_section = section_confirmation_response.body; require_condition(both(equal(text(field(confirmed_setup_section, "id")), setup_section_id), both(equal(text(field(confirmed_setup_section, "event_id")), setup_event_id), equal(text(field(confirmed_setup_section, "name")), recorded_section_name))), "The captured Task Section is missing, renamed or rebound; stop instead of creating a replacement."); if (not_value(journal_completed(setup_job, "create_section"))) { journal_adopt(setup_job, "create_section", "GET", "/v1/tasks/sections/info", {"event_id": text(field(confirmed_setup_section, "event_id")), "id": text(field(confirmed_setup_section, "id")), "name": text(field(confirmed_setup_section, "name"))}); } let setup_dates_response = await call("read_dates", {"event_id": setup_event_id, "filter_by_date_type_id": "1", "$include_record_revision": "true"}, null, null); require_condition(equal(response_status(setup_dates_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); let setup_dates_page = setup_dates_response.body; require_condition(both(equal(text(field(setup_dates_page, "records_found")), "1"), both(equal(text(field(setup_dates_page, "total_records")), "1"), equal(field(setup_dates_page, "has_more"), false))), "Expected one complete selected Dates group, without another page."); let setup_dates_group = single(field(setup_dates_page, "list_data")); require_condition(both(equal(text(field(setup_dates_group, "event_id")), setup_event_id), equal(text(field(setup_dates_group, "date_type_id")), "1")), "The Dates group belongs to another Event or type."); let setup_dates_revision = text(field(setup_dates_group, "record_revision")); require_condition(is_present(setup_dates_revision), "Read the actual selected group revision before replacing it."); if (journal_completed(setup_job, "save_dates")) { let recorded_dates = journal_recorded(setup_job, "save_dates"); require_condition(both(equal(text(field(recorded_dates, "event_id")), setup_event_id), equal(text(field(recorded_dates, "date_type_id")), "1")), "The recorded Dates acknowledgement belongs to another Event or group."); } else { let setup_dates_fingerprint = journal_fingerprint({"event_id": setup_event_id, "date_type_id": "1", "dates": desired_dates_json, "expected_revision": setup_dates_revision}); journal_begin(setup_job, "save_dates", "PATCH", "/v1/events/dates", setup_dates_fingerprint); let setup_dates_save_response = await call("save_dates", {}, {"event_id": setup_event_id, "date_type_id": "1", "dates": desired_setup_dates, "expected_revision": setup_dates_revision}, null); require_condition(equal(response_status(setup_dates_save_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); let setup_dates_ack = setup_dates_save_response.body; let setup_dates_saved_revision = text(field(setup_dates_ack, "record_revision")); require_condition(is_present(setup_dates_saved_revision), "The checked Dates save needs its actual returned revision."); journal_acknowledge(setup_job, "save_dates", {"event_id": setup_event_id, "date_type_id": "1", "record_revision": setup_dates_saved_revision}); } let setup_dates_verify_response = await call("verify_dates", {"event_id": setup_event_id, "filter_by_date_type_id": "1"}, null, null); require_condition(equal(response_status(setup_dates_verify_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); let setup_dates_verify_page = setup_dates_verify_response.body; require_condition(both(equal(text(field(setup_dates_verify_page, "records_found")), "1"), both(equal(text(field(setup_dates_verify_page, "total_records")), "1"), equal(field(setup_dates_verify_page, "has_more"), false))), "Expected one complete selected Dates group, without another page."); let setup_dates_verify_group = single(field(setup_dates_verify_page, "list_data")); require_condition(both(equal(text(field(setup_dates_verify_group, "event_id")), setup_event_id), equal(text(field(setup_dates_verify_group, "date_type_id")), "1")), "The Dates group belongs to another Event or type."); require_condition(deep_equal(field(setup_dates_verify_group, "dates"), desired_setup_dates), "The saved normalized Dates list differs from the supplied canonical list. Inspect it; do not automatically restore or repeat the update."); let setup_event_readback_response = await call("event_readback", {"id": setup_event_id}, null, null); require_condition(equal(response_status(setup_event_readback_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); let setup_event_readback = setup_event_readback_response.body; require_condition(both(equal(text(field(setup_event_readback, "id")), setup_event_id), equal(text(field(setup_event_readback, "integration_metadata_field_1")), external_event_key)), "Final Event readback is missing or rebound; earlier steps remain saved."); require_condition(both(both(equal(text(field(setup_event_readback, "name")), desired_event_name), equal(text(field(setup_event_readback, "start_date")), desired_start_date)), equal(text(field(setup_event_readback, "end_date")), desired_end_date)), "The Event name or main dates changed before final readback. Inspect the Event before starting another update."); let planning_section_present = false; for (const setup_event_section of items(items(field(setup_event_readback, "task_sections")))) { if (equal(text(field(setup_event_section, "id")), setup_section_id)) { planning_section_present = true; } } require_condition(planning_section_present, "The Event's current Task Sections do not include the recorded section; inspect it rather than creating another."); print_value({"event_id": setup_event_id, "task_section_id": setup_section_id, "dates_verified": "true"}); } finally { setup_job.close(); } } if (require.main === module) main().catch(error => { console.error(error.message); process.exitCode = 1; }); module.exports = { main }; ``` ```python # 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\"},\"find_existing\":{\"method\":\"GET\",\"path\":\"/events\"},\"create_event\":{\"method\":\"POST\",\"path\":\"/events\"},\"confirm_event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"update_event\":{\"method\":\"PATCH\",\"path\":\"/events\"},\"verify_event_update\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"find_section\":{\"method\":\"GET\",\"path\":\"/tasks/sections\"},\"create_section\":{\"method\":\"POST\",\"path\":\"/tasks/sections\"},\"confirm_section\":{\"method\":\"GET\",\"path\":\"/tasks/sections/info\"},\"read_dates\":{\"method\":\"GET\",\"path\":\"/events/dates\"},\"save_dates\":{\"method\":\"PATCH\",\"path\":\"/events/dates\"},\"verify_dates\":{\"method\":\"GET\",\"path\":\"/events/dates\"},\"event_readback\":{\"method\":\"GET\",\"path\":\"/events/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) 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, key=None): route = SPEC["requests"][name] headers = {"Authorization": "Bearer " + API_KEY, "Accept": "application/json"} if route["method"] == "POST": if not key: raise RuntimeError("Persist a logical create key before sending POST") headers["Idempotency-Key"] = key data = None if body is None else json.dumps(body).encode("utf-8") if data is not None: headers["Content-Type"] = "application/json" query = urllib.parse.urlencode(params or {}) url = BASE + route["path"] + ("?" + query if query else "") # Only GET has automatic retries in this workflow. A PATCH or DELETE that got no response or a # server error is never resent blindly: it may already have been applied, so the caller reads the record first. resend = route["method"] == "GET" for attempt in range(5): try: status, raw, response_headers = transport(route["method"], url, headers, data) except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException): if not resend: raise ApiError(0, None, uncertain=True) if attempt == 4: raise time.sleep(2 ** attempt) continue response_headers = {k.lower(): v for k, v in response_headers.items()} result = None if status != 304 and raw: try: result = decode_json(raw.decode("utf-8")) except (ValueError, UnicodeError): if status < 400: raise RuntimeError("Expected a JSON success response") if status >= 500 and not resend: raise ApiError(status, result, uncertain=True) retry = resend and (status == 429 or status >= 500) if retry: if attempt == 4: raise RuntimeError("Retry limit reached; check the request outcome before starting a new create") delay = response_headers.get("retry-after", str(2 ** attempt)) time.sleep(max(0, float(delay))) continue if status >= 400: raise ApiError(status, result) return {"status": status, "body": result, "headers": response_headers, "raw": raw} raise RuntimeError("Retry limit reached") def 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 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] 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 offsetlen(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)-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={};self.adopted_values={};self.order=[] 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);self.order.append(step);manifest.extend((step,method,route)) if not self.allowed:raise JournalRefusal('Only write workflows need a restart journal') self.header=['H','1',base,workspace,slug,job,input_fingerprint,digest(strings(manifest))] strings(self.header) try: self.fd=os.open(self.lock,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600);self.owned=True except FileExistsError:raise JournalRefusal('This journal is locked; do not run overlapping jobs or steal a stale lock') try: self.owner=secrets.token_hex(16);self.identity=os.fstat(self.fd) if os.write(self.fd,self.owner.encode('ascii'))!=len(self.owner):raise OSError('Incomplete lock identity write') os.fsync(self.fd) if self.path.is_symlink():raise JournalRefusal('Choose a private regular journal file') if mode=="resume" and not self.path.exists():raise JournalRefusal("Journal missing: stop and reconcile lost state before starting a new logical job") if mode=="new" and self.path.exists():raise JournalRefusal("A journal already exists; use resume for the same logical job") if mode=="new": with open(self.path,'xb',buffering=0)as target: target.write(PREAMBLE+frame(self.header));os.fsync(target.fileno()) records=decode(self.path.read_bytes()) if not records or records[0]!=self.header:raise JournalRefusal('Journal workspace/base/guide/job/input binding differs') for record in records[1:]:self.apply(record) if any(step not in self.saved_values for step in self.intents):raise JournalRefusal('A saved before-send intent lacks an ACK; stop and reconcile its outcome before retry') except BaseException: self.close();raise def apply(self,record): if not record:raise JournalRefusal('Empty journal record') if record[0]=='I': if len(record)!=6:raise JournalRefusal('Invalid intent shape') _,step,method,path,request_fingerprint,key=record if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.intents or step in self.adopted_values 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])) elif record[0]=='S': if len(record)<6:raise JournalRefusal('Invalid read-adoption shape') _,step,method,path,read_fingerprint,count,*pairs=record completed=set(self.saved_values)|set(self.adopted_values) if len(completed)>=len(self.order) or completed!=set(self.order[:len(completed)]) or step!=self.order[len(completed)] or any(name not in self.saved_values for name in self.intents):raise JournalRefusal('Adopt only the exact next setup action without any pending intent') target=self.allowed.get(step) expected='/v1/events/info'if (target==('POST','/v1/events') or step=='update_event' and target==('PATCH','/v1/events'))else '/v1/tasks/sections/info'if target==('POST','/v1/tasks/sections')else None if method!='GET' or expected is None or path!=expected:raise JournalRefusal('Adoption requires the exact source-bound single Event or section read') if not re.fullmatch('0|[1-9][0-9]*',count)or len(pairs)!=2*int(count):raise JournalRefusal('Invalid read-adoption field count') names=pairs[::2];fields=['id','integration_metadata_field_1']if expected=='/v1/events/info'else ['event_id','id','name'] if names!=fields:raise JournalRefusal('Read-adoption fields must match the exact source tuple') saved=dict(zip(names,pairs[1::2])) for name in ('id','event_id'): if name in saved and (not re.fullmatch('[1-9][0-9]*',saved[name])or int(saved[name])>9223372036854775807):raise JournalRefusal('Read-adoption IDs must be exact positive Int64 strings') if any(saved[name]==''for name in fields if name not in ('id','event_id'))or read_fingerprint!=fingerprint(saved):raise JournalRefusal('Read-adoption material must be complete and fingerprint-bound') self.adopted_values[step]=saved else:raise JournalRefusal('Unknown journal transition') def append(self,record): # The reader commits state only after complete length/digest recognition. # A torn append is retained and refused, never silently truncated. self.require_active();raw=frame(record) try: with open(self.path,'ab',buffering=0)as target: view=memoryview(raw) while view: written=target.write(view) if not written:raise OSError('Journal write did not advance') view=view[written:] os.fsync(target.fileno()) except BaseException: self.tainted=True;raise def require_active(self): if not self.owned or self.fd is None or self.identity is None or self.tainted:raise JournalRefusal('The journal scope is closed or its IO outcome needs reconciliation') current=self.lock.stat(follow_symlinks=False) if current.st_dev!=self.identity.st_dev or current.st_ino!=self.identity.st_ino or self.lock.read_text(encoding='ascii')!=self.owner:raise JournalRefusal('The journal lock was replaced; stop without deleting it') def acknowledged(self,step): self.require_active();return step in self.saved_values def saved(self,step): self.require_active() if step not in self.saved_values:raise JournalRefusal('No acknowledged state exists for this step') return dict(self.saved_values[step]) def completed(self,step): self.require_active();return step in self.saved_values or step in self.adopted_values def recorded(self,step): self.require_active() if step in self.saved_values:return dict(self.saved_values[step]) if step in self.adopted_values:return dict(self.adopted_values[step]) raise JournalRefusal('No completed write or read-adoption exists') def adopted(self,step): self.require_active();return step in self.adopted_values def adopt(self,step,source_method,source_path,saved): self.require_active() record=['S',step,source_method,source_path,fingerprint(saved),str(len(saved))] for name,value in sorted(saved.items()):record.extend((name,value)) old={name:dict(value)for name,value in self.adopted_values.items()} try:self.apply(record);strings(record) finally:self.adopted_values=old self.append(record);self.apply(record) 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_adopt(job,step,method,path,saved):job.adopt(step,method,path,journal_values(saved)) def journal_begin(job, step, method, path, request_fingerprint): return job.begin(step,method,path,request_fingerprint) def journal_completed(job,step):return job.completed(step) def journal_fingerprint(value): return fingerprint(journal_values(value)) def journal_recorded(job,step):return job.recorded(step) 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 page_size(value): if not re.fullmatch(r"[1-9][0-9]*", value) or int(value) > 2147483647: raise RuntimeError("Page size must be a positive int32") return value def parse_json(value): import math def pairs(values): result={} for key,item in values: if key in result:raise ValueError('Duplicate JSON input property') result[key]=item return result def number(value): result=float(value) if not math.isfinite(result):raise ValueError('Use finite JSON numbers') return result def invalid(value):raise ValueError('Use standard JSON values') return json.loads(value,object_pairs_hook=pairs,parse_float=number,parse_constant=invalid) def positive_id(value): if not re.fullmatch(r"[1-9][0-9]*", value) or int(value) > 9223372036854775807: raise RuntimeError("Use a positive record ID") return value def print_value(value): print(value if isinstance(value, str) else json.dumps(value, ensure_ascii=False)) def require_condition(value, message): if value is not True: raise RuntimeError(message) def required(name): value = os.environ.get(name) if value is None or not value.strip(): raise RuntimeError("Set " + name) return value def response_status(value): return str(value["status"]) def 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 validate_crm_event_inputs(key, name, start, end): from datetime import date spaces = '\u0009\u000A\u000B\u000C\u000D\u0020\u0085\u00A0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u2028\u2029\u202F\u205F\u3000' for value, label, limit in ((name, 'EXHIBITDAY_EVENT_NAME', 500), (key, 'EXHIBITDAY_EXTERNAL_EVENT_KEY', 3000)): utf8(value) if not value or value != value.strip(spaces): raise JournalRefusal('Remove whitespace at the start or end of ' + label) if len(value.encode('utf-16-le')) // 2 > limit: raise JournalRefusal(label + ' exceeds ' + str(limit) + ' UTF-16 code units') if any(ch in name for ch in '<>\r\n') or name.lower() == 'null': raise JournalRefusal('Use plain, single-line EXHIBITDAY_EVENT_NAME text other than null') for value, label in ((start, 'EXHIBITDAY_START_DATE'), (end, 'EXHIBITDAY_END_DATE')): try: valid = re.fullmatch(r'[0-9]{4}-[0-9]{2}-[0-9]{2}', value) and date.fromisoformat(value).year >= 1753 except ValueError: valid = False if not valid: raise JournalRefusal(label + ' must be a calendar date in YYYY-MM-DD on or after 1753-01-01') if end < start: raise JournalRefusal('EXHIBITDAY_END_DATE must be on or after EXHIBITDAY_START_DATE') def main(): external_event_key = required("EXHIBITDAY_EXTERNAL_EVENT_KEY") desired_event_name = required("EXHIBITDAY_EVENT_NAME") desired_start_date = required("EXHIBITDAY_START_DATE") desired_end_date = required("EXHIBITDAY_END_DATE") desired_dates_json = required("EXHIBITDAY_EXHIBIT_DATES_JSON") desired_section_name = optional("EXHIBITDAY_TASK_SECTION_NAME", "Pre-event planning") setup_page_size = page_size(optional("EXHIBITDAY_PAGE_SIZE", "100")) desired_setup_dates = items(parse_json(desired_dates_json)) validate_crm_event_inputs(external_event_key, desired_event_name, desired_start_date, desired_end_date) journal_path = required("EXHIBITDAY_JOURNAL") stable_job_id = required("EXHIBITDAY_JOB_ID") job_mode = optional("EXHIBITDAY_JOB_MODE", "resume") setup_workspace_response = call("workspace_binding", {}, None, None) require_condition(equal(response_status(setup_workspace_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") setup_workspace = setup_workspace_response["body"] owned_workspace_id = positive_id(text(field(setup_workspace, "id"))) setup_input_fingerprint = journal_fingerprint({"workflow_contract_sha256": "19097A09AE2D22C1AF56F5D4FBD9B72F524E5EC195434BC315834CC8C2417C32", "external_event_key": external_event_key, "name": desired_event_name, "start_date": desired_start_date, "end_date": desired_end_date, "section_name": desired_section_name, "dates": desired_dates_json}) setup_job = open_journal(journal_path, "https://api.exhibitday.com/v1", owned_workspace_id, "event-setup-crm", stable_job_id, setup_input_fingerprint, [["create_event", "POST", "/v1/events"], ["update_event", "PATCH", "/v1/events"], ["create_section", "POST", "/v1/tasks/sections"], ["save_dates", "PATCH", "/v1/events/dates"]], job_mode) try: setup_event_id = "" setup_section_id = "" recorded_section_name = desired_section_name if journal_completed(setup_job, "create_event"): recorded_event = journal_recorded(setup_job, "create_event") setup_event_id = positive_id(text(field(recorded_event, "id"))) require_condition(equal(text(field(recorded_event, "integration_metadata_field_1")), external_event_key), "The journal's completed Event differs from this external key.") else: event_search_offset = "0" event_search_query = {"filter_by_integration_metadata_field_1": external_event_key, "$limit": setup_page_size} while True: event_search_query["$offset"] = event_search_offset event_search_response = call("find_existing", event_search_query, None, None) require_condition(equal(response_status(event_search_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") event_search_page = event_search_response["body"] event_search_rows = items(field(event_search_page, "list_data")) require_condition(equal(text(field(event_search_page, "records_found")), text(count(event_search_rows))), "records_found differs from this complete page's rows.") require_condition(is_present(text(field(event_search_page, "total_records"))), "The search wrapper needs total_records.") require_condition(either(equal(field(event_search_page, "has_more"), True), equal(field(event_search_page, "has_more"), False)), "Expected a Boolean has_more value.") for event_search_row in items(event_search_rows): if equal(text(field(event_search_row, "integration_metadata_field_1")), external_event_key): event_search_candidate_id = positive_id(text(field(event_search_row, "id"))) if is_present(setup_event_id): require_condition(equal(setup_event_id, event_search_candidate_id), "More than one matching record exists. Reconcile the ambiguity instead of selecting one or creating another.") setup_event_id = event_search_candidate_id if equal(field(event_search_page, "has_more"), False): break require_condition(not_value(is_empty(event_search_rows)), "An empty search page has has_more=true. Stop and reconcile the search.") event_search_offset = add_offset(event_search_offset, count(event_search_rows)) if not_value(is_present(setup_event_id)): event_write_fingerprint = journal_fingerprint({"name": desired_event_name, "start_date": desired_start_date, "end_date": desired_end_date, "integration_metadata_field_1": external_event_key}) event_intent = journal_begin(setup_job, "create_event", "POST", "/v1/events", event_write_fingerprint) event_create_response = call("create_event", {}, {"name": desired_event_name, "start_date": desired_start_date, "end_date": desired_end_date, "integration_metadata_field_1": external_event_key}, text(field(event_intent, "idempotency_key"))) require_condition(equal(response_status(event_create_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") created_event = event_create_response["body"] setup_event_id = positive_id(text(field(created_event, "id"))) require_condition(equal(text(field(created_event, "integration_metadata_field_1")), external_event_key), "The created Event's external key differs; preserve the pending intent and reconcile.") require_condition(both(is_present(text(field(created_event, "name"))), both(is_present(text(field(created_event, "start_date"))), is_present(text(field(created_event, "end_date"))))), "The Event acknowledgement omitted its saved name or main dates.") journal_acknowledge(setup_job, "create_event", {"id": setup_event_id, "integration_metadata_field_1": external_event_key}) event_confirmation_response = call("confirm_event", {"id": setup_event_id, "$include_record_revision": "true"}, None, None) require_condition(equal(response_status(event_confirmation_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") confirmed_setup_event = event_confirmation_response["body"] require_condition(both(equal(text(field(confirmed_setup_event, "id")), setup_event_id), equal(text(field(confirmed_setup_event, "integration_metadata_field_1")), external_event_key)), "The captured Event is missing or rebound; stop instead of searching for or creating a replacement.") if not_value(journal_completed(setup_job, "create_event")): journal_adopt(setup_job, "create_event", "GET", "/v1/events/info", {"id": text(field(confirmed_setup_event, "id")), "integration_metadata_field_1": text(field(confirmed_setup_event, "integration_metadata_field_1"))}) setup_event_revision = text(field(confirmed_setup_event, "record_revision")) require_condition(is_present(setup_event_revision), "Read the selected Event with its revision before comparing or updating it.") require_condition(both(both(is_present(text(field(confirmed_setup_event, "name"))), is_present(text(field(confirmed_setup_event, "start_date")))), is_present(text(field(confirmed_setup_event, "end_date")))), "The selected Event must return its current name, start date and end date.") if journal_completed(setup_job, "update_event"): recorded_event_update = journal_recorded(setup_job, "update_event") require_condition(both(equal(text(field(recorded_event_update, "id")), setup_event_id), equal(text(field(recorded_event_update, "integration_metadata_field_1")), external_event_key)), "The recorded Event update has a different identity. Stop and reconcile.") require_condition(both(both(equal(text(field(confirmed_setup_event, "name")), desired_event_name), equal(text(field(confirmed_setup_event, "start_date")), desired_start_date)), equal(text(field(confirmed_setup_event, "end_date")), desired_end_date)), "The Event name or main dates changed after this job checked them. Review the current Event before writing again.") else: if both(both(equal(text(field(confirmed_setup_event, "name")), desired_event_name), equal(text(field(confirmed_setup_event, "start_date")), desired_start_date)), equal(text(field(confirmed_setup_event, "end_date")), desired_end_date)): journal_adopt(setup_job, "update_event", "GET", "/v1/events/info", {"id": setup_event_id, "integration_metadata_field_1": external_event_key}) else: require_condition(not_value(journal_acknowledged(setup_job, "create_event")), "The Event created by this job differs from the requested values. Inspect the saved Event before starting another update.") event_update_body = {"id": setup_event_id, "expected_revision": setup_event_revision} if not_value(equal(text(field(confirmed_setup_event, "name")), desired_event_name)): event_update_body["name"] = desired_event_name if not_value(equal(text(field(confirmed_setup_event, "start_date")), desired_start_date)): event_update_body["start_date"] = desired_start_date if not_value(equal(text(field(confirmed_setup_event, "end_date")), desired_end_date)): event_update_body["end_date"] = desired_end_date event_update_fingerprint = journal_fingerprint(event_update_body) journal_begin(setup_job, "update_event", "PATCH", "/v1/events", event_update_fingerprint) event_update_response = call("update_event", {}, event_update_body, None) require_condition(equal(response_status(event_update_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") event_update_ack = event_update_response["body"] event_updated_revision = text(field(event_update_ack, "record_revision")) require_condition(is_present(event_updated_revision), "The conditional Event update needs its returned revision. Reconcile the pending request before continuing.") journal_acknowledge(setup_job, "update_event", {"id": setup_event_id, "integration_metadata_field_1": external_event_key, "record_revision": event_updated_revision}) event_update_verify_response = call("verify_event_update", {"id": setup_event_id}, None, None) require_condition(equal(response_status(event_update_verify_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") verified_setup_event = event_update_verify_response["body"] require_condition(both(both(equal(text(field(verified_setup_event, "id")), setup_event_id), equal(text(field(verified_setup_event, "integration_metadata_field_1")), external_event_key)), both(both(equal(text(field(verified_setup_event, "name")), desired_event_name), equal(text(field(verified_setup_event, "start_date")), desired_start_date)), equal(text(field(verified_setup_event, "end_date")), desired_end_date))), "The Event's current identity, name or main dates differ. Inspect the Event before continuing with setup.") if journal_completed(setup_job, "create_section"): recorded_section = journal_recorded(setup_job, "create_section") setup_section_id = positive_id(text(field(recorded_section, "id"))) require_condition(equal(text(field(recorded_section, "event_id")), setup_event_id), "The recorded Task Section belongs to a different Event.") recorded_section_name = text(field(recorded_section, "name")) else: section_search_offset = "0" section_search_query = {"filter_by_event_id": setup_event_id, "$limit": setup_page_size} while True: section_search_query["$offset"] = section_search_offset section_search_response = call("find_section", section_search_query, None, None) require_condition(equal(response_status(section_search_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") section_search_page = section_search_response["body"] section_search_rows = items(field(section_search_page, "list_data")) require_condition(equal(text(field(section_search_page, "records_found")), text(count(section_search_rows))), "records_found differs from this complete page's rows.") require_condition(is_present(text(field(section_search_page, "total_records"))), "The search wrapper needs total_records.") require_condition(either(equal(field(section_search_page, "has_more"), True), equal(field(section_search_page, "has_more"), False)), "Expected a Boolean has_more value.") for section_search_row in items(section_search_rows): require_condition(equal(text(field(section_search_row, "event_id")), setup_event_id), "A section search row belongs to a different Event; stop before adopting or creating anything.") if equal(text(field(section_search_row, "name")), desired_section_name): section_search_candidate_id = positive_id(text(field(section_search_row, "id"))) if is_present(setup_section_id): require_condition(equal(setup_section_id, section_search_candidate_id), "More than one matching record exists. Reconcile the ambiguity instead of selecting one or creating another.") setup_section_id = section_search_candidate_id if equal(field(section_search_page, "has_more"), False): break require_condition(not_value(is_empty(section_search_rows)), "An empty search page has has_more=true. Stop and reconcile the search.") section_search_offset = add_offset(section_search_offset, count(section_search_rows)) if not_value(is_present(setup_section_id)): section_write_fingerprint = journal_fingerprint({"event_id": setup_event_id, "name": desired_section_name}) section_intent = journal_begin(setup_job, "create_section", "POST", "/v1/tasks/sections", section_write_fingerprint) section_create_response = call("create_section", {}, {"event_id": setup_event_id, "name": desired_section_name}, text(field(section_intent, "idempotency_key"))) require_condition(equal(response_status(section_create_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") created_section = section_create_response["body"] setup_section_id = positive_id(text(field(created_section, "id"))) require_condition(equal(text(field(created_section, "event_id")), setup_event_id), "The created Task Section belongs to a different Event; preserve the pending intent.") recorded_section_name = text(field(created_section, "name")) require_condition(is_present(recorded_section_name), "The Task Section acknowledgement needs its actual saved name.") journal_acknowledge(setup_job, "create_section", {"id": setup_section_id, "event_id": setup_event_id, "name": recorded_section_name}) section_confirmation_response = call("confirm_section", {"id": setup_section_id}, None, None) require_condition(equal(response_status(section_confirmation_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") confirmed_setup_section = section_confirmation_response["body"] require_condition(both(equal(text(field(confirmed_setup_section, "id")), setup_section_id), both(equal(text(field(confirmed_setup_section, "event_id")), setup_event_id), equal(text(field(confirmed_setup_section, "name")), recorded_section_name))), "The captured Task Section is missing, renamed or rebound; stop instead of creating a replacement.") if not_value(journal_completed(setup_job, "create_section")): journal_adopt(setup_job, "create_section", "GET", "/v1/tasks/sections/info", {"event_id": text(field(confirmed_setup_section, "event_id")), "id": text(field(confirmed_setup_section, "id")), "name": text(field(confirmed_setup_section, "name"))}) setup_dates_response = call("read_dates", {"event_id": setup_event_id, "filter_by_date_type_id": "1", "$include_record_revision": "true"}, None, None) require_condition(equal(response_status(setup_dates_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") setup_dates_page = setup_dates_response["body"] require_condition(both(equal(text(field(setup_dates_page, "records_found")), "1"), both(equal(text(field(setup_dates_page, "total_records")), "1"), equal(field(setup_dates_page, "has_more"), False))), "Expected one complete selected Dates group, without another page.") setup_dates_group = single(field(setup_dates_page, "list_data")) require_condition(both(equal(text(field(setup_dates_group, "event_id")), setup_event_id), equal(text(field(setup_dates_group, "date_type_id")), "1")), "The Dates group belongs to another Event or type.") setup_dates_revision = text(field(setup_dates_group, "record_revision")) require_condition(is_present(setup_dates_revision), "Read the actual selected group revision before replacing it.") if journal_completed(setup_job, "save_dates"): recorded_dates = journal_recorded(setup_job, "save_dates") require_condition(both(equal(text(field(recorded_dates, "event_id")), setup_event_id), equal(text(field(recorded_dates, "date_type_id")), "1")), "The recorded Dates acknowledgement belongs to another Event or group.") else: setup_dates_fingerprint = journal_fingerprint({"event_id": setup_event_id, "date_type_id": "1", "dates": desired_dates_json, "expected_revision": setup_dates_revision}) journal_begin(setup_job, "save_dates", "PATCH", "/v1/events/dates", setup_dates_fingerprint) setup_dates_save_response = call("save_dates", {}, {"event_id": setup_event_id, "date_type_id": "1", "dates": desired_setup_dates, "expected_revision": setup_dates_revision}, None) require_condition(equal(response_status(setup_dates_save_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") setup_dates_ack = setup_dates_save_response["body"] setup_dates_saved_revision = text(field(setup_dates_ack, "record_revision")) require_condition(is_present(setup_dates_saved_revision), "The checked Dates save needs its actual returned revision.") journal_acknowledge(setup_job, "save_dates", {"event_id": setup_event_id, "date_type_id": "1", "record_revision": setup_dates_saved_revision}) setup_dates_verify_response = call("verify_dates", {"event_id": setup_event_id, "filter_by_date_type_id": "1"}, None, None) require_condition(equal(response_status(setup_dates_verify_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") setup_dates_verify_page = setup_dates_verify_response["body"] require_condition(both(equal(text(field(setup_dates_verify_page, "records_found")), "1"), both(equal(text(field(setup_dates_verify_page, "total_records")), "1"), equal(field(setup_dates_verify_page, "has_more"), False))), "Expected one complete selected Dates group, without another page.") setup_dates_verify_group = single(field(setup_dates_verify_page, "list_data")) require_condition(both(equal(text(field(setup_dates_verify_group, "event_id")), setup_event_id), equal(text(field(setup_dates_verify_group, "date_type_id")), "1")), "The Dates group belongs to another Event or type.") require_condition(deep_equal(field(setup_dates_verify_group, "dates"), desired_setup_dates), "The saved normalized Dates list differs from the supplied canonical list. Inspect it; do not automatically restore or repeat the update.") setup_event_readback_response = call("event_readback", {"id": setup_event_id}, None, None) require_condition(equal(response_status(setup_event_readback_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") setup_event_readback = setup_event_readback_response["body"] require_condition(both(equal(text(field(setup_event_readback, "id")), setup_event_id), equal(text(field(setup_event_readback, "integration_metadata_field_1")), external_event_key)), "Final Event readback is missing or rebound; earlier steps remain saved.") require_condition(both(both(equal(text(field(setup_event_readback, "name")), desired_event_name), equal(text(field(setup_event_readback, "start_date")), desired_start_date)), equal(text(field(setup_event_readback, "end_date")), desired_end_date)), "The Event name or main dates changed before final readback. Inspect the Event before starting another update.") planning_section_present = False for setup_event_section in items(items(field(setup_event_readback, "task_sections"))): if equal(text(field(setup_event_section, "id")), setup_section_id): planning_section_present = True require_condition(planning_section_present, "The Event's current Task Sections do not include the recorded section; inspect it rather than creating another.") print_value({"event_id": setup_event_id, "task_section_id": setup_section_id, "dates_verified": "true"}) finally: setup_job.close() if __name__ == "__main__": main() ``` ```csharp // .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\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"find_existing\":{\"method\":\"GET\",\"path\":\"/events\"},\"create_event\":{\"method\":\"POST\",\"path\":\"/events\"},\"confirm_event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"update_event\":{\"method\":\"PATCH\",\"path\":\"/events\"},\"verify_event_update\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"find_section\":{\"method\":\"GET\",\"path\":\"/tasks/sections\"},\"create_section\":{\"method\":\"POST\",\"path\":\"/tasks/sections\"},\"confirm_section\":{\"method\":\"GET\",\"path\":\"/tasks/sections/info\"},\"read_dates\":{\"method\":\"GET\",\"path\":\"/events/dates\"},\"save_dates\":{\"method\":\"PATCH\",\"path\":\"/events/dates\"},\"verify_dates\":{\"method\":\"GET\",\"path\":\"/events/dates\"},\"event_readback\":{\"method\":\"GET\",\"path\":\"/events/info\"}}}"); static readonly string ApiKey = HeaderKey(Required("EXHIBITDAY_API_KEY")); static string HeaderKey(string value) { if(value.Any(c=>c<32||c>126))throw new Exception("Use the API key as one ASCII header value without control characters");return value; } static readonly HttpClient Client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false }) { Timeout = TimeSpan.FromSeconds(30) }; internal static Func> Send = request => Client.SendAsync(request); sealed class Result { public int Status; public JsonNode Body; public Dictionary Headers; public string Raw; } // 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(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 Call(string name, JsonObject query = null, JsonNode body = null, string key = null) { var route = Spec["requests"][name]; var method = Text(route["method"]); var headers = new Dictionary(StringComparer.OrdinalIgnoreCase) { ["Authorization"] = "Bearer " + ApiKey, ["Accept"] = "application/json" }; if (method == "POST") { if (string.IsNullOrEmpty(key)) throw new Exception("Persist a logical create key before sending POST"); headers["Idempotency-Key"] = key; } 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); // 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. var resend = method == "GET"; 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 Send(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 = resend && (status == 429 || status >= 500); 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, Raw = raw }; } } throw new Exception("Retry limit reached"); } static string AddOffset(string offset,long received) { var result=checked(long.Parse(offset,CultureInfo.InvariantCulture)+received);if(received<=0||result>int.MaxValue)throw new Exception("Cannot advance this int32 offset; reconcile the query");return result.ToString(CultureInfo.InvariantCulture); } static bool Both(bool left,bool right)=>left&&right; static JsonNode CopyNode(JsonNode value) => value?.DeepClone(); static JsonArray Items(JsonNode value) => value as JsonArray ?? throw new Exception("Expected a JSON array"); static long Count(JsonNode value) => Items(value).Count; static bool DeepEqual(JsonNode left,JsonNode right)=>JsonNode.DeepEquals(left,right); static bool Either(bool left,bool right) => left || right; static object Scalar(object value) { if(value is JsonValue json){if(json.TryGetValue(out var boolean))return boolean;if(json.TryGetValue(out var text))return text;return json.ToJsonString();}return value; } static bool Equal(object left,object right) => object.Equals(Scalar(left),Scalar(right)); static JsonNode Field(JsonNode value,string name) { if(value is not JsonObject obj || !obj.TryGetPropertyValue(name,out var item))throw new Exception("Missing response field: "+name);return item; } static bool IsEmpty(JsonNode value) => Count(value)==0; static bool IsPresent(string value) => value!=null && value!=""; public sealed class JournalRefusal : Exception { public JournalRefusal(string message) : base(message) {} } public static class JournalProtocol { public static readonly byte[] Preamble = Encoding.ASCII.GetBytes("EXHIBITDAY-GUIDE-JOURNAL 1\n"); static readonly UTF8Encoding Utf8 = new UTF8Encoding(false, true); static bool Match(string value,string pattern) => value != null && System.Text.RegularExpressions.Regex.IsMatch(value,"\\A(?:"+pattern+")\\z",System.Text.RegularExpressions.RegexOptions.CultureInvariant); public static bool Valid(string value,string pattern) => Match(value,pattern); static string Ascii(byte[] raw,int start,int count) { for(var i=start;i127)throw new JournalRefusal("Journal framing must be canonical ASCII");return Encoding.ASCII.GetString(raw,start,count); } public static byte[] Strings(IEnumerable values) { using var data=new MemoryStream(); foreach(var value in values){if(value==null)throw new JournalRefusal("Journal fields are exact strings");var item=Utf8.GetBytes(value);var prefix=Encoding.ASCII.GetBytes(item.Length.ToString(CultureInfo.InvariantCulture)+":");data.Write(prefix);data.Write(item);} return data.ToArray(); } public static List ReadStrings(byte[] raw) { var values=new List();var offset=0; while(offsetraw.Length-offset)throw new JournalRefusal("Incomplete journal string");values.Add(Utf8.GetString(raw,offset,(int)size));offset+=(int)size;} return values; } public static string Digest(byte[] raw)=>Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(raw)); public static string Fingerprint(IReadOnlyDictionary pairs) { var values=new List();foreach(var name in pairs.Keys.OrderBy(n=>n,StringComparer.Ordinal)){ if(!Match(name,"[A-Za-z0-9_.-]+")||new[]{"api_key","exhibitday_api_key"}.Contains(name.ToLowerInvariant()))throw new JournalRefusal("Use explicit secret-free fingerprint names");values.Add(name);values.Add(pairs[name]);} return Digest(Strings(values)); } public static byte[] Frame(IEnumerable values) { var payload=Strings(values);var header=Encoding.ASCII.GetBytes(payload.Length.ToString(CultureInfo.InvariantCulture)+" "+Digest(payload)+"\n"); using var data=new MemoryStream();data.Write(header);data.Write(payload);data.WriteByte(10);return data.ToArray(); } public static List> Decode(byte[] raw) { if(raw.Length>(); while(offset=raw.Length-offset)throw new JournalRefusal("Incomplete frame; reconcile before retry");var payload=raw.AsSpan(offset,(int)size).ToArray();offset+=(int)size; if(raw[offset]!=10||Digest(payload)!=split[1])throw new JournalRefusal("Journal integrity failed; reconcile before retry");records.Add(ReadStrings(payload));offset++;} return records; } } public sealed class Journal : IDisposable { readonly string path,lockPath,owner;readonly List header; readonly Dictionary allowed=new Dictionary(StringComparer.Ordinal); Dictionary> intents=new Dictionary>(StringComparer.Ordinal),savedValues=new Dictionary>(StringComparer.Ordinal); Dictionary> adoptedValues=new Dictionary>(StringComparer.Ordinal);readonly List order=new List(); FileStream lockStream;bool owned,tainted;DateTime creation; static FileStream CreatePrivate(string target,FileAccess access,FileShare share) { var options=new FileStreamOptions{Mode=FileMode.CreateNew,Access=access,Share=share}; if(!OperatingSystem.IsWindows())options.UnixCreateMode=UnixFileMode.UserRead|UnixFileMode.UserWrite; return new FileStream(target,options); } public Journal(string path,string apiBase,string workspace,string slug,string job,string inputFingerprint,IEnumerable<(string Step,string Method,string Path)> writes,string mode="resume") { this.path=path;lockPath=path+".lock";owner=Convert.ToHexString(System.Security.Cryptography.RandomNumberGenerator.GetBytes(16)).ToLowerInvariant(); if(!Uri.TryCreate(apiBase,UriKind.Absolute,out var address)||address.Scheme!="https"&&address.Scheme!="http"||address.UserInfo.Length!=0||address.Query.Length!=0||address.Fragment.Length!=0||!JournalProtocol.Valid(slug,"[a-z][a-z0-9-]*"))throw new JournalRefusal("Use the actual API base and closed guide slug"); if(string.IsNullOrWhiteSpace(job)||!JournalProtocol.Valid(workspace,"[1-9][0-9]*")||!JournalProtocol.Valid(inputFingerprint,"[0-9A-F]{64}"))throw new JournalRefusal("Use actual workspace, stable explicit job ID and exact fingerprint"); if(mode!="new"&&mode!="resume")throw new JournalRefusal("Choose new or resume for this local job"); var manifest=new List();foreach(var write in writes){ if(!JournalProtocol.Valid(write.Step,"[a-z][a-z0-9_-]*")||allowed.ContainsKey(write.Step)||!new[]{"POST","PATCH","DELETE"}.Contains(write.Method)||!JournalProtocol.Valid(write.Path,"/v1/[A-Za-z0-9_/-]+")||write.Path.Contains("//"))throw new JournalRefusal("Use a closed unique write manifest"); allowed.Add(write.Step,(write.Method,write.Path));order.Add(write.Step);manifest.AddRange(new[]{write.Step,write.Method,write.Path});} if(allowed.Count==0)throw new JournalRefusal("Only write workflows need a restart journal"); header=new List{"H","1",apiBase,workspace,slug,job,inputFingerprint,JournalProtocol.Digest(JournalProtocol.Strings(manifest))};JournalProtocol.Strings(header); try{lockStream=CreatePrivate(lockPath,FileAccess.ReadWrite,FileShare.Read);owned=true;} catch(IOException)when(File.Exists(lockPath)){throw new JournalRefusal("This journal is locked; do not overlap jobs or steal a stale lock");} try{ var token=Encoding.ASCII.GetBytes(owner);lockStream.Write(token);lockStream.Flush(true);creation=File.GetCreationTimeUtc(lockPath); if(File.Exists(path)&&(File.GetAttributes(path)&FileAttributes.ReparsePoint)!=0)throw new JournalRefusal("Choose a private regular journal file"); if(mode=="resume"&&!File.Exists(path))throw new JournalRefusal("Journal missing: stop and reconcile lost state before starting a new logical job"); if(mode=="new"&&File.Exists(path))throw new JournalRefusal("Journal exists; use resume for the same logical job"); if(mode=="new"){using var output=CreatePrivate(path,FileAccess.Write,FileShare.None);output.Write(JournalProtocol.Preamble);output.Write(JournalProtocol.Frame(header));output.Flush(true);} var records=JournalProtocol.Decode(File.ReadAllBytes(path));if(records.Count==0||!records[0].SequenceEqual(header))throw new JournalRefusal("Journal workspace/base/guide/job/input binding differs"); foreach(var record in records.Skip(1))Apply(record);if(intents.Keys.Any(step=>!savedValues.ContainsKey(step)))throw new JournalRefusal("Saved intent lacks ACK; stop and reconcile before retry"); }catch{Dispose();throw;} } void Apply(IReadOnlyList record) { if(record.Count==0)throw new JournalRefusal("Empty journal record"); if(record[0]=="I"){ if(record.Count!=6)throw new JournalRefusal("Invalid intent shape");var step=record[1];var method=record[2];var route=record[3];var fingerprint=record[4];var key=record[5]; if(!JournalProtocol.Valid(step,"[a-z][a-z0-9_-]*")||intents.ContainsKey(step)||adoptedValues.ContainsKey(step)||!allowed.TryGetValue(step,out var expected)||expected!=(method,route)||!JournalProtocol.Valid(fingerprint,"[0-9A-F]{64}")||intents.Keys.Any(name=>!savedValues.ContainsKey(name)))throw new JournalRefusal("Invalid, future or repeated intent"); if(method=="POST"&&!JournalProtocol.Valid(key,"[0-9a-f]{32}")||method!="POST"&&key!="")throw new JournalRefusal("Invalid persisted action key"); intents.Add(step,new Dictionary{{"method",method},{"path",route},{"request_fingerprint",fingerprint},{"idempotency_key",key}}); }else if(record[0]=="A"){ if(record.Count<3||!JournalProtocol.Valid(record[2],"0|[1-9][0-9]*")||!long.TryParse(record[2],NumberStyles.None,CultureInfo.InvariantCulture,out var count)||count!=(record.Count-3L)/2||record.Count%2!=1||!intents.ContainsKey(record[1])||savedValues.ContainsKey(record[1]))throw new JournalRefusal("ACK without exactly one prior intent"); var names=record.Skip(3).Where((_,index)=>index%2==0).ToArray(); if(!names.SequenceEqual(names.Distinct(StringComparer.Ordinal).OrderBy(name=>name,StringComparer.Ordinal))||names.Any(name=>!JournalProtocol.Valid(name,"[a-z][a-z0-9_]*")||name=="api_key"||name=="exhibitday_api_key"))throw new JournalRefusal("ACK fields must be unique sorted secret-free identifiers"); var saved=new Dictionary(StringComparer.Ordinal);for(var i=0;i(savedValues.Keys.Concat(adoptedValues.Keys),StringComparer.Ordinal); if(completed.Count>=order.Count||!completed.SetEquals(order.Take(completed.Count))||step!=order[completed.Count]||intents.Keys.Any(name=>!savedValues.ContainsKey(name)))throw new JournalRefusal("Adopt only the exact next setup action without any pending intent"); var target=allowed[step];var expected=(target==("POST","/v1/events")||step=="update_event"&&target==("PATCH","/v1/events"))?"/v1/events/info":target==("POST","/v1/tasks/sections")?"/v1/tasks/sections/info":null; if(method!="GET"||expected==null||route!=expected)throw new JournalRefusal("Adoption requires the exact source-bound single Event or section read"); if(!JournalProtocol.Valid(record[5],"0|[1-9][0-9]*")||!long.TryParse(record[5],NumberStyles.None,CultureInfo.InvariantCulture,out var count)||count!=(record.Count-6L)/2||record.Count%2!=0)throw new JournalRefusal("Invalid read-adoption field count"); var names=record.Skip(6).Where((_,index)=>index%2==0).ToArray();var fields=expected=="/v1/events/info"?new[]{"id","integration_metadata_field_1"}:new[]{"event_id","id","name"}; if(!names.SequenceEqual(fields))throw new JournalRefusal("Read-adoption fields must match the exact source tuple"); var saved=new Dictionary(StringComparer.Ordinal);for(int i=0;iname!="id"&&name!="event_id"&&string.IsNullOrEmpty(saved[name]))||readFingerprint!=JournalProtocol.Fingerprint(saved))throw new JournalRefusal("Read-adoption material must be complete and fingerprint-bound"); adoptedValues.Add(step,saved); }else throw new JournalRefusal("Unknown journal transition"); } void RequireActive() { if(!owned||lockStream==null||tainted)throw new JournalRefusal("Journal is closed or IO outcome needs reconciliation"); // FileShare.Read denies write/delete sharing on Windows while this handle // is held. Token + creation witness guards cooperative ownership. Manual // replacement during a run is outside the portable compare/unlink claim. var position=lockStream.Position;lockStream.Position=0;var token=new byte[owner.Length];var count=lockStream.Read(token);lockStream.Position=position; if(!File.Exists(lockPath)||File.GetCreationTimeUtc(lockPath)!=creation||lockStream.Length!=owner.Length||count!=owner.Length||!token.SequenceEqual(Encoding.ASCII.GetBytes(owner)))throw new JournalRefusal("Journal lock was replaced; stop without deleting it"); } void Append(IReadOnlyList record) { RequireActive();var raw=JournalProtocol.Frame(record); try{using var output=new FileStream(path,FileMode.Append,FileAccess.Write,FileShare.None);output.Write(raw);output.Flush(true);} catch{tainted=true;throw;} } public bool Acknowledged(string step){RequireActive();return savedValues.ContainsKey(step);} public Dictionary Saved(string step){RequireActive();if(!savedValues.ContainsKey(step))throw new JournalRefusal("No acknowledged state exists");return new Dictionary(savedValues[step],StringComparer.Ordinal);} public bool Completed(string step){RequireActive();return savedValues.ContainsKey(step)||adoptedValues.ContainsKey(step);} public bool Adopted(string step){RequireActive();return adoptedValues.ContainsKey(step);} public Dictionary Recorded(string step){RequireActive();if(!Completed(step))throw new JournalRefusal("No completed write or read-adoption exists");return new Dictionary(savedValues.ContainsKey(step)?savedValues[step]:adoptedValues[step],StringComparer.Ordinal);} public void Adopt(string step,string method,string route,IReadOnlyDictionary saved){RequireActive();var record=new List{"S",step,method,route,JournalProtocol.Fingerprint(saved),saved.Count.ToString(CultureInfo.InvariantCulture)};foreach(var name in saved.Keys.OrderBy(name=>name,StringComparer.Ordinal))record.AddRange(new[]{name,saved[name]});var previous=new Dictionary>(adoptedValues,StringComparer.Ordinal);try{Apply(record);JournalProtocol.Strings(record);}finally{adoptedValues=previous;}Append(record);Apply(record);} public Dictionary Begin(string step,string method,string route,string requestFingerprint) { RequireActive();if(intents.ContainsKey(step))throw new JournalRefusal("Never blindly repeat an existing action"); var key=method=="POST"?Convert.ToHexString(System.Security.Cryptography.RandomNumberGenerator.GetBytes(16)).ToLowerInvariant():""; var record=new[]{"I",step,method,route,requestFingerprint,key};var previous=new Dictionary>(intents,StringComparer.Ordinal);try{Apply(record);}finally{intents=previous;} Append(record);Apply(record);return new Dictionary(intents[step],StringComparer.Ordinal); } public void Acknowledge(string step,IReadOnlyDictionary saved) { RequireActive();var record=new List{"A",step,saved.Count.ToString(CultureInfo.InvariantCulture)};foreach(var name in saved.Keys.OrderBy(name=>name,StringComparer.Ordinal))record.AddRange(new[]{name,saved[name]}); var previous=new Dictionary>(savedValues,StringComparer.Ordinal);try{Apply(record);JournalProtocol.Strings(record);}finally{savedValues=previous;} Append(record);Apply(record); } public void Dispose() { if(!owned)return;if(tainted){lockStream.Dispose();lockStream=null;owned=false;return;} try{RequireActive();}catch{lockStream.Dispose();lockStream=null;owned=false;throw;} lockStream.Dispose();lockStream=null;owned=false;File.Delete(lockPath); } } static Dictionary JournalValues(JsonNode value) { if(value is not JsonObject fields)throw new JournalRefusal("Saved/fingerprint values need an explicit object"); var result=new Dictionary(StringComparer.Ordinal); foreach(var field in fields){if(field.Value is not JsonValue item || !item.TryGetValue(out var text) || text==null)throw new JournalRefusal("Saved/fingerprint values must be exact strings");result.Add(field.Key,text);}return result; } static JsonObject JournalObject(IReadOnlyDictionary fields){var result=new JsonObject();foreach(var field in fields)result.Add(field.Key,JsonValue.Create(field.Value));return result;} static void JournalAcknowledge(Journal job,string step,JsonNode saved)=>job.Acknowledge(step,JournalValues(saved)); static bool JournalAcknowledged(Journal job,string step)=>job.Acknowledged(step); static void JournalAdopt(Journal job,string step,string method,string path,JsonNode saved)=>job.Adopt(step,method,path,JournalValues(saved)); static JsonNode JournalBegin(Journal job,string step,string method,string path,string requestFingerprint)=>JournalObject(job.Begin(step,method,path,requestFingerprint)); static bool JournalCompleted(Journal job,string step)=>job.Completed(step); static string JournalFingerprint(JsonNode value)=>JournalProtocol.Fingerprint(JournalValues(value)); static JsonObject JournalRecorded(Journal job,string step)=>JournalObject(job.Recorded(step)); static bool NotValue(bool value) => !value; static Journal OpenJournal(string path,string apiBase,string workspace,string slug,string job,string inputFingerprint,JsonNode manifest,string mode) { if(manifest is not JsonArray rows)throw new JournalRefusal("A closed write manifest is required");var writes=new List<(string,string,string)>(); foreach(var row in rows){if(row is not JsonArray fields || fields.Count!=3)throw new JournalRefusal("Each write must bind its step/method/path");var values=fields.Select(value=>value is JsonValue item&&item.TryGetValue(out var text)&&text!=null?text:throw new JournalRefusal("Manifest values are exact strings")).ToArray();writes.Add((values[0],values[1],values[2]));} return new Journal(path,apiBase,workspace,slug,job,inputFingerprint,writes,mode); } static string Optional(string name,string fallback) { var value=Environment.GetEnvironmentVariable(name);return value==null||value==""?fallback:value; } static string PageSize(string value) { if(string.IsNullOrEmpty(value)||value[0]=='0'||!value.All(c=>c>='0'&&c<='9')||!int.TryParse(value,NumberStyles.None,CultureInfo.InvariantCulture,out var limit)||limit<=0)throw new Exception("Page size must be a positive int32");return value; } static JsonNode ParseJson(string value){ using var document=System.Text.Json.JsonDocument.Parse(value); void Check(System.Text.Json.JsonElement node){ if(node.ValueKind==System.Text.Json.JsonValueKind.Object){var names=new HashSet(StringComparer.Ordinal);foreach(var field in node.EnumerateObject()){if(!names.Add(field.Name))throw new Exception("Duplicate JSON input property");Check(field.Value);}} else if(node.ValueKind==System.Text.Json.JsonValueKind.Array)foreach(var item in node.EnumerateArray())Check(item); } Check(document.RootElement);return JsonNode.Parse(value); } static string PositiveId(string value) { if(string.IsNullOrEmpty(value)||value[0]=='0'||!value.All(c=>c>='0'&&c<='9')||!long.TryParse(value,NumberStyles.None,CultureInfo.InvariantCulture,out var id)||id<=0)throw new Exception("Use a positive record ID");return value; } static void PrintValue(object value) => Console.WriteLine(value is string text ? text : JsonSerializer.Serialize(value)); static void RequireCondition(bool value,string message) { if(!value)throw new Exception(message); } static string ResponseStatus(Result value)=>value.Status.ToString(CultureInfo.InvariantCulture); static JsonNode Single(JsonNode value){var rows=Items(value);if(rows.Count!=1)throw new Exception("Expected exactly one selected record");return rows[0];} static string Text(object value) => value==null?"":value is JsonNode node?Text(node):Convert.ToString(value,CultureInfo.InvariantCulture); static void ValidateCrmEventInputs(string key, string name, string start, string end) { void TextInput(string value, string label, int limit) { JournalProtocol.Strings(new[] { value }); if (value.Length == 0 || value != value.Trim()) throw new JournalRefusal("Remove whitespace at the start or end of " + label); if (value.Length > limit) throw new JournalRefusal(label + " exceeds " + limit + " UTF-16 code units"); } void DateInput(string value, string label) { if (!DateTime.TryParseExact(value, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date) || value != date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) || date.Year < 1753) throw new JournalRefusal(label + " must be a calendar date in YYYY-MM-DD on or after 1753-01-01"); } TextInput(name, "EXHIBITDAY_EVENT_NAME", 500); TextInput(key, "EXHIBITDAY_EXTERNAL_EVENT_KEY", 3000); if (name.IndexOfAny(new[] { '<', '>', '\r', '\n' }) >= 0 || name.Equals("null", StringComparison.OrdinalIgnoreCase)) throw new JournalRefusal("Use plain, single-line EXHIBITDAY_EVENT_NAME text other than null"); DateInput(start, "EXHIBITDAY_START_DATE"); DateInput(end, "EXHIBITDAY_END_DATE"); if (string.CompareOrdinal(end, start) < 0) throw new JournalRefusal("EXHIBITDAY_END_DATE must be on or after EXHIBITDAY_START_DATE"); } internal static async Task Run() { var external_event_key = Required("EXHIBITDAY_EXTERNAL_EVENT_KEY"); var desired_event_name = Required("EXHIBITDAY_EVENT_NAME"); var desired_start_date = Required("EXHIBITDAY_START_DATE"); var desired_end_date = Required("EXHIBITDAY_END_DATE"); var desired_dates_json = Required("EXHIBITDAY_EXHIBIT_DATES_JSON"); var desired_section_name = Optional("EXHIBITDAY_TASK_SECTION_NAME", "Pre-event planning"); var setup_page_size = PageSize(Optional("EXHIBITDAY_PAGE_SIZE", "100")); var desired_setup_dates = Items(ParseJson(desired_dates_json)); ValidateCrmEventInputs(external_event_key, desired_event_name, desired_start_date, desired_end_date); var journal_path = Required("EXHIBITDAY_JOURNAL"); var stable_job_id = Required("EXHIBITDAY_JOB_ID"); var job_mode = Optional("EXHIBITDAY_JOB_MODE", "resume"); var setup_workspace_response = await Call("workspace_binding", new JsonObject { }, null, null); RequireCondition(Equal(ResponseStatus(setup_workspace_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); var setup_workspace = setup_workspace_response.Body; var owned_workspace_id = PositiveId(Text(Field(setup_workspace, "id"))); var setup_input_fingerprint = JournalFingerprint(new JsonObject { ["workflow_contract_sha256"] = "19097A09AE2D22C1AF56F5D4FBD9B72F524E5EC195434BC315834CC8C2417C32", ["external_event_key"] = external_event_key, ["name"] = desired_event_name, ["start_date"] = desired_start_date, ["end_date"] = desired_end_date, ["section_name"] = desired_section_name, ["dates"] = desired_dates_json }); using (var setup_job = OpenJournal(journal_path, "https://api.exhibitday.com/v1", owned_workspace_id, "event-setup-crm", stable_job_id, setup_input_fingerprint, new JsonArray(new JsonArray("create_event", "POST", "/v1/events"), new JsonArray("update_event", "PATCH", "/v1/events"), new JsonArray("create_section", "POST", "/v1/tasks/sections"), new JsonArray("save_dates", "PATCH", "/v1/events/dates")), job_mode)) { var setup_event_id = ""; var setup_section_id = ""; var recorded_section_name = desired_section_name; if (JournalCompleted(setup_job, "create_event")) { var recorded_event = JournalRecorded(setup_job, "create_event"); setup_event_id = PositiveId(Text(Field(recorded_event, "id"))); RequireCondition(Equal(Text(Field(recorded_event, "integration_metadata_field_1")), external_event_key), "The journal's completed Event differs from this external key."); } else { var event_search_offset = "0"; var event_search_query = new JsonObject { ["filter_by_integration_metadata_field_1"] = external_event_key, ["$limit"] = setup_page_size }; while (true) { event_search_query["$offset"] = event_search_offset; var event_search_response = await Call("find_existing", event_search_query, null, null); RequireCondition(Equal(ResponseStatus(event_search_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); var event_search_page = event_search_response.Body; var event_search_rows = Items(Field(event_search_page, "list_data")); RequireCondition(Equal(Text(Field(event_search_page, "records_found")), Text(Count(event_search_rows))), "records_found differs from this complete page's rows."); RequireCondition(IsPresent(Text(Field(event_search_page, "total_records"))), "The search wrapper needs total_records."); RequireCondition(Either(Equal(Field(event_search_page, "has_more"), true), Equal(Field(event_search_page, "has_more"), false)), "Expected a Boolean has_more value."); foreach (var event_search_row in Items(event_search_rows)) { if (Equal(Text(Field(event_search_row, "integration_metadata_field_1")), external_event_key)) { var event_search_candidate_id = PositiveId(Text(Field(event_search_row, "id"))); if (IsPresent(setup_event_id)) { RequireCondition(Equal(setup_event_id, event_search_candidate_id), "More than one matching record exists. Reconcile the ambiguity instead of selecting one or creating another."); } setup_event_id = event_search_candidate_id; } } if (Equal(Field(event_search_page, "has_more"), false)) { break; } RequireCondition(NotValue(IsEmpty(event_search_rows)), "An empty search page has has_more=true. Stop and reconcile the search."); event_search_offset = AddOffset(event_search_offset, Count(event_search_rows)); } if (NotValue(IsPresent(setup_event_id))) { var event_write_fingerprint = JournalFingerprint(new JsonObject { ["name"] = desired_event_name, ["start_date"] = desired_start_date, ["end_date"] = desired_end_date, ["integration_metadata_field_1"] = external_event_key }); var event_intent = JournalBegin(setup_job, "create_event", "POST", "/v1/events", event_write_fingerprint); var event_create_response = await Call("create_event", new JsonObject { }, new JsonObject { ["name"] = desired_event_name, ["start_date"] = desired_start_date, ["end_date"] = desired_end_date, ["integration_metadata_field_1"] = external_event_key }, Text(Field(event_intent, "idempotency_key"))); RequireCondition(Equal(ResponseStatus(event_create_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); var created_event = event_create_response.Body; setup_event_id = PositiveId(Text(Field(created_event, "id"))); RequireCondition(Equal(Text(Field(created_event, "integration_metadata_field_1")), external_event_key), "The created Event's external key differs; preserve the pending intent and reconcile."); RequireCondition(Both(IsPresent(Text(Field(created_event, "name"))), Both(IsPresent(Text(Field(created_event, "start_date"))), IsPresent(Text(Field(created_event, "end_date"))))), "The Event acknowledgement omitted its saved name or main dates."); JournalAcknowledge(setup_job, "create_event", new JsonObject { ["id"] = setup_event_id, ["integration_metadata_field_1"] = external_event_key }); } } var event_confirmation_response = await Call("confirm_event", new JsonObject { ["id"] = setup_event_id, ["$include_record_revision"] = "true" }, null, null); RequireCondition(Equal(ResponseStatus(event_confirmation_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); var confirmed_setup_event = event_confirmation_response.Body; RequireCondition(Both(Equal(Text(Field(confirmed_setup_event, "id")), setup_event_id), Equal(Text(Field(confirmed_setup_event, "integration_metadata_field_1")), external_event_key)), "The captured Event is missing or rebound; stop instead of searching for or creating a replacement."); if (NotValue(JournalCompleted(setup_job, "create_event"))) { JournalAdopt(setup_job, "create_event", "GET", "/v1/events/info", new JsonObject { ["id"] = Text(Field(confirmed_setup_event, "id")), ["integration_metadata_field_1"] = Text(Field(confirmed_setup_event, "integration_metadata_field_1")) }); } var setup_event_revision = Text(Field(confirmed_setup_event, "record_revision")); RequireCondition(IsPresent(setup_event_revision), "Read the selected Event with its revision before comparing or updating it."); RequireCondition(Both(Both(IsPresent(Text(Field(confirmed_setup_event, "name"))), IsPresent(Text(Field(confirmed_setup_event, "start_date")))), IsPresent(Text(Field(confirmed_setup_event, "end_date")))), "The selected Event must return its current name, start date and end date."); if (JournalCompleted(setup_job, "update_event")) { var recorded_event_update = JournalRecorded(setup_job, "update_event"); RequireCondition(Both(Equal(Text(Field(recorded_event_update, "id")), setup_event_id), Equal(Text(Field(recorded_event_update, "integration_metadata_field_1")), external_event_key)), "The recorded Event update has a different identity. Stop and reconcile."); RequireCondition(Both(Both(Equal(Text(Field(confirmed_setup_event, "name")), desired_event_name), Equal(Text(Field(confirmed_setup_event, "start_date")), desired_start_date)), Equal(Text(Field(confirmed_setup_event, "end_date")), desired_end_date)), "The Event name or main dates changed after this job checked them. Review the current Event before writing again."); } else { if (Both(Both(Equal(Text(Field(confirmed_setup_event, "name")), desired_event_name), Equal(Text(Field(confirmed_setup_event, "start_date")), desired_start_date)), Equal(Text(Field(confirmed_setup_event, "end_date")), desired_end_date))) { JournalAdopt(setup_job, "update_event", "GET", "/v1/events/info", new JsonObject { ["id"] = setup_event_id, ["integration_metadata_field_1"] = external_event_key }); } else { RequireCondition(NotValue(JournalAcknowledged(setup_job, "create_event")), "The Event created by this job differs from the requested values. Inspect the saved Event before starting another update."); var event_update_body = new JsonObject { ["id"] = setup_event_id, ["expected_revision"] = setup_event_revision }; if (NotValue(Equal(Text(Field(confirmed_setup_event, "name")), desired_event_name))) { event_update_body["name"] = desired_event_name; } if (NotValue(Equal(Text(Field(confirmed_setup_event, "start_date")), desired_start_date))) { event_update_body["start_date"] = desired_start_date; } if (NotValue(Equal(Text(Field(confirmed_setup_event, "end_date")), desired_end_date))) { event_update_body["end_date"] = desired_end_date; } var event_update_fingerprint = JournalFingerprint(event_update_body); JournalBegin(setup_job, "update_event", "PATCH", "/v1/events", event_update_fingerprint); var event_update_response = await Call("update_event", new JsonObject { }, event_update_body, null); RequireCondition(Equal(ResponseStatus(event_update_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); var event_update_ack = event_update_response.Body; var event_updated_revision = Text(Field(event_update_ack, "record_revision")); RequireCondition(IsPresent(event_updated_revision), "The conditional Event update needs its returned revision. Reconcile the pending request before continuing."); JournalAcknowledge(setup_job, "update_event", new JsonObject { ["id"] = setup_event_id, ["integration_metadata_field_1"] = external_event_key, ["record_revision"] = event_updated_revision }); } } var event_update_verify_response = await Call("verify_event_update", new JsonObject { ["id"] = setup_event_id }, null, null); RequireCondition(Equal(ResponseStatus(event_update_verify_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); var verified_setup_event = event_update_verify_response.Body; RequireCondition(Both(Both(Equal(Text(Field(verified_setup_event, "id")), setup_event_id), Equal(Text(Field(verified_setup_event, "integration_metadata_field_1")), external_event_key)), Both(Both(Equal(Text(Field(verified_setup_event, "name")), desired_event_name), Equal(Text(Field(verified_setup_event, "start_date")), desired_start_date)), Equal(Text(Field(verified_setup_event, "end_date")), desired_end_date))), "The Event's current identity, name or main dates differ. Inspect the Event before continuing with setup."); if (JournalCompleted(setup_job, "create_section")) { var recorded_section = JournalRecorded(setup_job, "create_section"); setup_section_id = PositiveId(Text(Field(recorded_section, "id"))); RequireCondition(Equal(Text(Field(recorded_section, "event_id")), setup_event_id), "The recorded Task Section belongs to a different Event."); recorded_section_name = Text(Field(recorded_section, "name")); } else { var section_search_offset = "0"; var section_search_query = new JsonObject { ["filter_by_event_id"] = setup_event_id, ["$limit"] = setup_page_size }; while (true) { section_search_query["$offset"] = section_search_offset; var section_search_response = await Call("find_section", section_search_query, null, null); RequireCondition(Equal(ResponseStatus(section_search_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); var section_search_page = section_search_response.Body; var section_search_rows = Items(Field(section_search_page, "list_data")); RequireCondition(Equal(Text(Field(section_search_page, "records_found")), Text(Count(section_search_rows))), "records_found differs from this complete page's rows."); RequireCondition(IsPresent(Text(Field(section_search_page, "total_records"))), "The search wrapper needs total_records."); RequireCondition(Either(Equal(Field(section_search_page, "has_more"), true), Equal(Field(section_search_page, "has_more"), false)), "Expected a Boolean has_more value."); foreach (var section_search_row in Items(section_search_rows)) { RequireCondition(Equal(Text(Field(section_search_row, "event_id")), setup_event_id), "A section search row belongs to a different Event; stop before adopting or creating anything."); if (Equal(Text(Field(section_search_row, "name")), desired_section_name)) { var section_search_candidate_id = PositiveId(Text(Field(section_search_row, "id"))); if (IsPresent(setup_section_id)) { RequireCondition(Equal(setup_section_id, section_search_candidate_id), "More than one matching record exists. Reconcile the ambiguity instead of selecting one or creating another."); } setup_section_id = section_search_candidate_id; } } if (Equal(Field(section_search_page, "has_more"), false)) { break; } RequireCondition(NotValue(IsEmpty(section_search_rows)), "An empty search page has has_more=true. Stop and reconcile the search."); section_search_offset = AddOffset(section_search_offset, Count(section_search_rows)); } if (NotValue(IsPresent(setup_section_id))) { var section_write_fingerprint = JournalFingerprint(new JsonObject { ["event_id"] = setup_event_id, ["name"] = desired_section_name }); var section_intent = JournalBegin(setup_job, "create_section", "POST", "/v1/tasks/sections", section_write_fingerprint); var section_create_response = await Call("create_section", new JsonObject { }, new JsonObject { ["event_id"] = setup_event_id, ["name"] = desired_section_name }, Text(Field(section_intent, "idempotency_key"))); RequireCondition(Equal(ResponseStatus(section_create_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); var created_section = section_create_response.Body; setup_section_id = PositiveId(Text(Field(created_section, "id"))); RequireCondition(Equal(Text(Field(created_section, "event_id")), setup_event_id), "The created Task Section belongs to a different Event; preserve the pending intent."); recorded_section_name = Text(Field(created_section, "name")); RequireCondition(IsPresent(recorded_section_name), "The Task Section acknowledgement needs its actual saved name."); JournalAcknowledge(setup_job, "create_section", new JsonObject { ["id"] = setup_section_id, ["event_id"] = setup_event_id, ["name"] = recorded_section_name }); } } var section_confirmation_response = await Call("confirm_section", new JsonObject { ["id"] = setup_section_id }, null, null); RequireCondition(Equal(ResponseStatus(section_confirmation_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); var confirmed_setup_section = section_confirmation_response.Body; RequireCondition(Both(Equal(Text(Field(confirmed_setup_section, "id")), setup_section_id), Both(Equal(Text(Field(confirmed_setup_section, "event_id")), setup_event_id), Equal(Text(Field(confirmed_setup_section, "name")), recorded_section_name))), "The captured Task Section is missing, renamed or rebound; stop instead of creating a replacement."); if (NotValue(JournalCompleted(setup_job, "create_section"))) { JournalAdopt(setup_job, "create_section", "GET", "/v1/tasks/sections/info", new JsonObject { ["event_id"] = Text(Field(confirmed_setup_section, "event_id")), ["id"] = Text(Field(confirmed_setup_section, "id")), ["name"] = Text(Field(confirmed_setup_section, "name")) }); } var setup_dates_response = await Call("read_dates", new JsonObject { ["event_id"] = setup_event_id, ["filter_by_date_type_id"] = "1", ["$include_record_revision"] = "true" }, null, null); RequireCondition(Equal(ResponseStatus(setup_dates_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); var setup_dates_page = setup_dates_response.Body; RequireCondition(Both(Equal(Text(Field(setup_dates_page, "records_found")), "1"), Both(Equal(Text(Field(setup_dates_page, "total_records")), "1"), Equal(Field(setup_dates_page, "has_more"), false))), "Expected one complete selected Dates group, without another page."); var setup_dates_group = Single(Field(setup_dates_page, "list_data")); RequireCondition(Both(Equal(Text(Field(setup_dates_group, "event_id")), setup_event_id), Equal(Text(Field(setup_dates_group, "date_type_id")), "1")), "The Dates group belongs to another Event or type."); var setup_dates_revision = Text(Field(setup_dates_group, "record_revision")); RequireCondition(IsPresent(setup_dates_revision), "Read the actual selected group revision before replacing it."); if (JournalCompleted(setup_job, "save_dates")) { var recorded_dates = JournalRecorded(setup_job, "save_dates"); RequireCondition(Both(Equal(Text(Field(recorded_dates, "event_id")), setup_event_id), Equal(Text(Field(recorded_dates, "date_type_id")), "1")), "The recorded Dates acknowledgement belongs to another Event or group."); } else { var setup_dates_fingerprint = JournalFingerprint(new JsonObject { ["event_id"] = setup_event_id, ["date_type_id"] = "1", ["dates"] = desired_dates_json, ["expected_revision"] = setup_dates_revision }); JournalBegin(setup_job, "save_dates", "PATCH", "/v1/events/dates", setup_dates_fingerprint); var setup_dates_save_response = await Call("save_dates", new JsonObject { }, new JsonObject { ["event_id"] = setup_event_id, ["date_type_id"] = "1", ["dates"] = CopyNode(desired_setup_dates), ["expected_revision"] = setup_dates_revision }, null); RequireCondition(Equal(ResponseStatus(setup_dates_save_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); var setup_dates_ack = setup_dates_save_response.Body; var setup_dates_saved_revision = Text(Field(setup_dates_ack, "record_revision")); RequireCondition(IsPresent(setup_dates_saved_revision), "The checked Dates save needs its actual returned revision."); JournalAcknowledge(setup_job, "save_dates", new JsonObject { ["event_id"] = setup_event_id, ["date_type_id"] = "1", ["record_revision"] = setup_dates_saved_revision }); } var setup_dates_verify_response = await Call("verify_dates", new JsonObject { ["event_id"] = setup_event_id, ["filter_by_date_type_id"] = "1" }, null, null); RequireCondition(Equal(ResponseStatus(setup_dates_verify_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); var setup_dates_verify_page = setup_dates_verify_response.Body; RequireCondition(Both(Equal(Text(Field(setup_dates_verify_page, "records_found")), "1"), Both(Equal(Text(Field(setup_dates_verify_page, "total_records")), "1"), Equal(Field(setup_dates_verify_page, "has_more"), false))), "Expected one complete selected Dates group, without another page."); var setup_dates_verify_group = Single(Field(setup_dates_verify_page, "list_data")); RequireCondition(Both(Equal(Text(Field(setup_dates_verify_group, "event_id")), setup_event_id), Equal(Text(Field(setup_dates_verify_group, "date_type_id")), "1")), "The Dates group belongs to another Event or type."); RequireCondition(DeepEqual(Field(setup_dates_verify_group, "dates"), desired_setup_dates), "The saved normalized Dates list differs from the supplied canonical list. Inspect it; do not automatically restore or repeat the update."); var setup_event_readback_response = await Call("event_readback", new JsonObject { ["id"] = setup_event_id }, null, null); RequireCondition(Equal(ResponseStatus(setup_event_readback_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); var setup_event_readback = setup_event_readback_response.Body; RequireCondition(Both(Equal(Text(Field(setup_event_readback, "id")), setup_event_id), Equal(Text(Field(setup_event_readback, "integration_metadata_field_1")), external_event_key)), "Final Event readback is missing or rebound; earlier steps remain saved."); RequireCondition(Both(Both(Equal(Text(Field(setup_event_readback, "name")), desired_event_name), Equal(Text(Field(setup_event_readback, "start_date")), desired_start_date)), Equal(Text(Field(setup_event_readback, "end_date")), desired_end_date)), "The Event name or main dates changed before final readback. Inspect the Event before starting another update."); var planning_section_present = false; foreach (var setup_event_section in Items(Items(Field(setup_event_readback, "task_sections")))) { if (Equal(Text(Field(setup_event_section, "id")), setup_section_id)) { planning_section_present = true; } } RequireCondition(planning_section_present, "The Event's current Task Sections do not include the recorded section; inspect it rather than creating another."); PrintValue(new JsonObject { ["event_id"] = setup_event_id, ["task_section_id"] = setup_section_id, ["dates_verified"] = "true" }); } } static Task Main() => Run(); } ``` ```java // 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 SPEC = JSON.fromJson("{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"find_existing\":{\"method\":\"GET\",\"path\":\"/events\"},\"create_event\":{\"method\":\"POST\",\"path\":\"/events\"},\"confirm_event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"update_event\":{\"method\":\"PATCH\",\"path\":\"/events\"},\"verify_event_update\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"find_section\":{\"method\":\"GET\",\"path\":\"/tasks/sections\"},\"create_section\":{\"method\":\"POST\",\"path\":\"/tasks/sections\"},\"confirm_section\":{\"method\":\"GET\",\"path\":\"/tasks/sections/info\"},\"read_dates\":{\"method\":\"GET\",\"path\":\"/events/dates\"},\"save_dates\":{\"method\":\"PATCH\",\"path\":\"/events/dates\"},\"verify_dates\":{\"method\":\"GET\",\"path\":\"/events/dates\"},\"event_readback\":{\"method\":\"GET\",\"path\":\"/events/info\"}}}", Map.class); static final String API_KEY = headerKey(required("EXHIBITDAY_API_KEY")); static String headerKey(String value){if(value.chars().anyMatch(c->c<32||c>126))throw new IllegalArgumentException("Use the API key as one ASCII header value without control characters");return value;} static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).followRedirects(HttpClient.Redirect.NEVER).build(); interface RequestSender { HttpResponse send(HttpRequest request)throws IOException,InterruptedException; } static RequestSender SEND=request->CLIENT.send(request,HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); static class Result { int status; Object body; Map headers; String raw; Result(int s, Object b, Map h,String r) {status=s;body=b;headers=h;raw=r;} } // 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 obj(Object value) {return value==null?new LinkedHashMap<>(): (Map)value;} @SuppressWarnings("unchecked") static List list(Object value) {return value==null?Collections.emptyList():(List)value;} static Map map(Object... pairs) {Map result=new LinkedHashMap<>();for(int i=0;i query,Object body,String key) { Map route=obj(obj(SPEC.get("requests")).get(name));String method=text(route.get("method")); Map headers=map("Authorization","Bearer " + API_KEY,"Accept","application/json"); if(method.equals("POST")){if(key==null||key.isEmpty())throw new IllegalArgumentException("Persist a logical create key before sending POST");headers.put("Idempotency-Key",key);} 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); // 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. boolean resend=method.equals("GET"); 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 response; try {response=SEND.send(request.build());} 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();Object parsed=null; if(status!=304&&!response.body().isEmpty()) { try {parsed=JSON.fromJson(response.body(),Object.class);} catch(RuntimeException error){if(status<400)throw new IllegalStateException("Expected a JSON success response",error);} } Map 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=resend&&(status==429||status>=500); 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,response.body()); } throw new IllegalStateException("Retry limit reached"); } static String add_offset(String offset,long received){long result=Math.addExact(Long.parseLong(offset),received);if(received<=0||result>Integer.MAX_VALUE)throw new IllegalStateException("Cannot advance this int32 offset; reconcile the query");return Long.toString(result);} static boolean both(boolean left,boolean right){return left&&right;} static List items(Object value){if(!(value instanceof List))throw new IllegalStateException("Expected a JSON array");return list(value);} static long count(Object value){return items(value).size();} static boolean deep_equal(Object left,Object right){return Objects.equals(left,right);} static boolean either(boolean left,boolean right){return left||right;} static boolean equal(Object left,Object right){return Objects.equals(left,right);} static Object field(Object value,String name){if(!(value instanceof Map)||!obj(value).containsKey(name))throw new IllegalStateException("Missing response field: "+name);return obj(value).get(name);} static boolean is_empty(Object value){return count(value)==0;} static boolean is_present(String value){return value!=null&&!value.isEmpty();} // Private client restart state only. No transport, application or JSON interpreter. static final class Journal implements AutoCloseable { public static final class Refusal extends IllegalStateException { Refusal(String message){super(message);} } public static final byte[] PREAMBLE="EXHIBITDAY-GUIDE-JOURNAL 1\n".getBytes(StandardCharsets.US_ASCII); static boolean valid(String value,String pattern){return value!=null&&value.matches(pattern);} static byte[] utf8(String value)throws java.nio.charset.CharacterCodingException { if(value==null)throw new Refusal("Journal fields are exact strings"); java.nio.ByteBuffer encoded=StandardCharsets.UTF_8.newEncoder().onMalformedInput(java.nio.charset.CodingErrorAction.REPORT).onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT).encode(java.nio.CharBuffer.wrap(value));byte[] raw=new byte[encoded.remaining()];encoded.get(raw);return raw; } static String ascii(byte[] raw,int start,int count){for(int i=start;i127)throw new Refusal("Journal framing must be canonical ASCII");return new String(raw,start,count,StandardCharsets.US_ASCII);} public static byte[] strings(Collection values)throws IOException { ByteArrayOutputStream output=new ByteArrayOutputStream();for(String value:values){byte[] raw=utf8(value);output.write((raw.length+":").getBytes(StandardCharsets.US_ASCII));output.write(raw);}return output.toByteArray(); } static int find(byte[] raw,int offset,int value){for(int i=offset;i readStrings(byte[] raw)throws IOException { List values=new ArrayList<>();int offset=0; while(offset0)throw new Refusal("Incomplete journal string");int count=size.intValueExact(); values.add(StandardCharsets.UTF_8.newDecoder().onMalformedInput(java.nio.charset.CodingErrorAction.REPORT).onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT).decode(java.nio.ByteBuffer.wrap(raw,offset,count)).toString());offset+=count;} return values; } public static String digest(byte[] raw){try{byte[] hash=java.security.MessageDigest.getInstance("SHA-256").digest(raw);StringBuilder text=new StringBuilder();for(byte item:hash)text.append(String.format(Locale.ROOT,"%02X",item&255));return text.toString();}catch(java.security.NoSuchAlgorithmException error){throw new IllegalStateException(error);}} public static String fingerprint(Map pairs)throws IOException { List values=new ArrayList<>();for(String name:new TreeSet<>(pairs.keySet())){if(!valid(name,"[A-Za-z0-9_.-]+")||Arrays.asList("api_key","exhibitday_api_key").contains(name.toLowerCase(Locale.ROOT)))throw new Refusal("Use explicit secret-free fingerprint names");values.add(name);values.add(pairs.get(name));}return digest(strings(values)); } public static byte[] frame(Collection values)throws IOException {byte[] payload=strings(values);ByteArrayOutputStream output=new ByteArrayOutputStream();output.write((payload.length+" "+digest(payload)+"\n").getBytes(StandardCharsets.US_ASCII));output.write(payload);output.write(10);return output.toByteArray();} public static List> decode(byte[] raw)throws IOException { if(raw.length> records=new ArrayList<>(); while(offset=0)throw new Refusal("Incomplete frame; reconcile before retry");int count=size.intValueExact();byte[] payload=Arrays.copyOfRange(raw,offset,offset+count);offset+=count; if(raw[offset]!=10||!digest(payload).equals(fields[1]))throw new Refusal("Journal integrity failed; reconcile before retry");records.add(readStrings(payload));offset++;}return records; } static void writeAll(java.nio.channels.FileChannel target,byte[] raw)throws IOException {java.nio.ByteBuffer data=java.nio.ByteBuffer.wrap(raw);while(data.hasRemaining())if(target.write(data)<=0)throw new IOException("Journal write did not advance");} static java.nio.channels.FileChannel createPrivate(Path path,OpenOption... options)throws IOException { java.nio.file.attribute.FileAttribute[] attributes=FileSystems.getDefault().supportedFileAttributeViews().contains("posix")?new java.nio.file.attribute.FileAttribute[]{java.nio.file.attribute.PosixFilePermissions.asFileAttribute(java.nio.file.attribute.PosixFilePermissions.fromString("rw-------"))}:new java.nio.file.attribute.FileAttribute[0]; return java.nio.channels.FileChannel.open(path,new HashSet<>(Arrays.asList(options)),attributes); } final Path path,lockPath;final String owner;final List header; final Map> allowed=new LinkedHashMap<>();Map> intents=new LinkedHashMap<>(),savedValues=new LinkedHashMap<>(); Map> adoptedValues=new LinkedHashMap<>(); java.nio.channels.FileChannel lock;boolean owned,tainted;Object fileKey;java.nio.file.attribute.FileTime creation; public Journal(Path path,String apiBase,String workspace,String slug,String job,String inputFingerprint,List> writes)throws IOException {this(path,apiBase,workspace,slug,job,inputFingerprint,writes,"resume");} public Journal(Path path,String apiBase,String workspace,String slug,String job,String inputFingerprint,List> writes,String mode)throws IOException { this.path=path;lockPath=Path.of(path.toString()+".lock");byte[] random=new byte[16];new java.security.SecureRandom().nextBytes(random);StringBuilder token=new StringBuilder();for(byte item:random)token.append(String.format(Locale.ROOT,"%02x",item&255));owner=token.toString(); URI address=URI.create(apiBase);if(!Arrays.asList("https","http").contains(address.getScheme())||address.getHost()==null||address.getUserInfo()!=null||address.getRawQuery()!=null||address.getRawFragment()!=null||!valid(slug,"[a-z][a-z0-9-]*"))throw new Refusal("Use actual API base and closed guide slug"); if(job==null||job.trim().isEmpty()||!valid(workspace,"[1-9][0-9]*")||!valid(inputFingerprint,"[0-9A-F]{64}"))throw new Refusal("Use actual workspace, stable explicit job ID and exact fingerprint"); if(!Arrays.asList("new","resume").contains(mode))throw new Refusal("Choose new or resume for this local job"); List manifest=new ArrayList<>();for(List item:writes){if(item.size()!=3)throw new Refusal("Invalid write manifest shape");String step=item.get(0),method=item.get(1),route=item.get(2); if(!valid(step,"[a-z][a-z0-9_-]*")||allowed.containsKey(step)||!Arrays.asList("POST","PATCH","DELETE").contains(method)||!valid(route,"/v1/[A-Za-z0-9_/-]+")||route.contains("//"))throw new Refusal("Use a closed unique write manifest");allowed.put(step,List.of(method,route));manifest.addAll(item);} if(allowed.isEmpty())throw new Refusal("Only write workflows need a restart journal");header=List.of("H","1",apiBase,workspace,slug,job,inputFingerprint,digest(strings(manifest)));strings(header); try{lock=createPrivate(lockPath,StandardOpenOption.CREATE_NEW,StandardOpenOption.READ,StandardOpenOption.WRITE);owned=true;}catch(FileAlreadyExistsException error){throw new Refusal("This journal is locked; do not overlap jobs or steal a stale lock");} try{writeAll(lock,owner.getBytes(StandardCharsets.US_ASCII));lock.force(true);java.nio.file.attribute.BasicFileAttributes identity=Files.readAttributes(lockPath,java.nio.file.attribute.BasicFileAttributes.class,LinkOption.NOFOLLOW_LINKS);fileKey=identity.fileKey();creation=identity.creationTime(); if(Files.isSymbolicLink(path))throw new Refusal("Choose a private regular journal file"); if(mode.equals("resume")&&!Files.exists(path))throw new Refusal("Journal missing: stop and reconcile lost state before starting a new logical job"); if(mode.equals("new")&&Files.exists(path))throw new Refusal("Journal exists; use resume for the same logical job"); if(mode.equals("new")){try(java.nio.channels.FileChannel target=createPrivate(path,StandardOpenOption.CREATE_NEW,StandardOpenOption.WRITE)){writeAll(target,PREAMBLE);writeAll(target,frame(header));target.force(true);}} List> records=decode(Files.readAllBytes(path));if(records.isEmpty()||!records.get(0).equals(header))throw new Refusal("Journal workspace/base/guide/job/input binding differs");for(List record:records.subList(1,records.size()))apply(record); if(intents.keySet().stream().anyMatch(step->!savedValues.containsKey(step)))throw new Refusal("Saved intent lacks ACK; stop and reconcile before retry"); }catch(IOException|RuntimeException error){close();throw error;} } void apply(List record)throws IOException { if(record.isEmpty())throw new Refusal("Empty journal record"); if(record.get(0).equals("I")){ if(record.size()!=6)throw new Refusal("Invalid intent shape");String step=record.get(1),method=record.get(2),route=record.get(3),fingerprint=record.get(4),key=record.get(5); if(!valid(step,"[a-z][a-z0-9_-]*")||intents.containsKey(step)||adoptedValues.containsKey(step)||!List.of(method,route).equals(allowed.get(step))||!valid(fingerprint,"[0-9A-F]{64}")||intents.keySet().stream().anyMatch(name->!savedValues.containsKey(name)))throw new Refusal("Invalid, future or repeated intent"); if(method.equals("POST")&&!valid(key,"[0-9a-f]{32}")||!method.equals("POST")&&!key.isEmpty())throw new Refusal("Invalid persisted action key");intents.put(step,new LinkedHashMap<>(Map.of("method",method,"path",route,"request_fingerprint",fingerprint,"idempotency_key",key))); }else if(record.get(0).equals("A")){ if(record.size()<3||!valid(record.get(2),"0|[1-9][0-9]*")||!new java.math.BigInteger(record.get(2)).multiply(java.math.BigInteger.TWO).equals(java.math.BigInteger.valueOf(record.size()-3))||!intents.containsKey(record.get(1))||savedValues.containsKey(record.get(1)))throw new Refusal("ACK without exactly one prior intent"); List names=new ArrayList<>();for(int i=3;i(new TreeSet<>(names)))||names.stream().anyMatch(name->!valid(name,"[a-z][a-z0-9_]*")||name.equals("api_key")||name.equals("exhibitday_api_key")))throw new Refusal("ACK fields must be unique sorted secret-free identifiers"); Map saved=new LinkedHashMap<>();for(int i=0;i completed=new HashSet<>(savedValues.keySet());completed.addAll(adoptedValues.keySet());List order=new ArrayList<>(allowed.keySet()); if(completed.size()>=order.size()||!completed.equals(new HashSet<>(order.subList(0,completed.size())))||!step.equals(order.get(completed.size()))||intents.keySet().stream().anyMatch(name->!savedValues.containsKey(name)))throw new Refusal("Adopt only the exact next setup action without any pending intent"); List target=allowed.get(step);String expected=(List.of("POST","/v1/events").equals(target)||step.equals("update_event")&&List.of("PATCH","/v1/events").equals(target))?"/v1/events/info":List.of("POST","/v1/tasks/sections").equals(target)?"/v1/tasks/sections/info":null; if(!method.equals("GET")||expected==null||!route.equals(expected))throw new Refusal("Adoption requires the exact source-bound single Event or section read"); if(!valid(record.get(5),"0|[1-9][0-9]*")||!new java.math.BigInteger(record.get(5)).multiply(java.math.BigInteger.TWO).equals(java.math.BigInteger.valueOf(record.size()-6)))throw new Refusal("Invalid read-adoption field count"); List names=new ArrayList<>();for(int i=6;i fields=expected.equals("/v1/events/info")?List.of("id","integration_metadata_field_1"):List.of("event_id","id","name");if(!names.equals(fields))throw new Refusal("Read-adoption fields must match the exact source tuple"); Map saved=new LinkedHashMap<>();for(int i=0;i0))throw new Refusal("Read-adoption IDs must be exact positive Int64 strings"); if(fields.stream().anyMatch(name->!List.of("id","event_id").contains(name)&&saved.get(name).isEmpty())||!readFingerprint.equals(fingerprint(saved)))throw new Refusal("Read-adoption material must be complete and fingerprint-bound");adoptedValues.put(step,saved); }else throw new Refusal("Unknown journal transition"); } void requireActive()throws IOException { if(!owned||lock==null||tainted)throw new Refusal("Journal is closed or IO outcome needs reconciliation");java.nio.file.attribute.BasicFileAttributes current=Files.readAttributes(lockPath,java.nio.file.attribute.BasicFileAttributes.class,LinkOption.NOFOLLOW_LINKS); if(!Objects.equals(fileKey,current.fileKey())||!creation.equals(current.creationTime())||!Arrays.equals(Files.readAllBytes(lockPath),owner.getBytes(StandardCharsets.US_ASCII)))throw new Refusal("Journal lock was replaced; stop without deleting it"); } void append(List record)throws IOException {requireActive();byte[] raw=frame(record);try(java.nio.channels.FileChannel target=java.nio.channels.FileChannel.open(path,StandardOpenOption.WRITE,StandardOpenOption.APPEND)){writeAll(target,raw);target.force(true);}catch(IOException|RuntimeException error){tainted=true;throw error;}} public boolean acknowledged(String step)throws IOException{requireActive();return savedValues.containsKey(step);} public Map saved(String step)throws IOException{requireActive();if(!savedValues.containsKey(step))throw new Refusal("No acknowledged state exists");return new LinkedHashMap<>(savedValues.get(step));} public boolean completed(String step)throws IOException{requireActive();return savedValues.containsKey(step)||adoptedValues.containsKey(step);} public boolean adopted(String step)throws IOException{requireActive();return adoptedValues.containsKey(step);} public Map recorded(String step)throws IOException{requireActive();if(!completed(step))throw new Refusal("No completed write or read-adoption exists");return new LinkedHashMap<>(savedValues.containsKey(step)?savedValues.get(step):adoptedValues.get(step));} public void adopt(String step,String method,String route,Map saved)throws IOException{requireActive();List record=new ArrayList<>(List.of("S",step,method,route,fingerprint(saved),Integer.toString(saved.size())));for(String name:new TreeSet<>(saved.keySet())){record.add(name);record.add(saved.get(name));}Map> previous=new LinkedHashMap<>(adoptedValues);try{apply(record);strings(record);}finally{adoptedValues=previous;}append(record);apply(record);} public Map begin(String step,String method,String route,String requestFingerprint)throws IOException { requireActive();if(intents.containsKey(step))throw new Refusal("Never blindly repeat an existing action");String key="";if(method.equals("POST")){byte[] bytes=new byte[16];new java.security.SecureRandom().nextBytes(bytes);StringBuilder text=new StringBuilder();for(byte item:bytes)text.append(String.format(Locale.ROOT,"%02x",item&255));key=text.toString();} List record=List.of("I",step,method,route,requestFingerprint,key);Map> previous=new LinkedHashMap<>(intents);try{apply(record);}finally{intents=previous;}append(record);apply(record);return new LinkedHashMap<>(intents.get(step)); } public void acknowledge(String step,Map saved)throws IOException { requireActive();List record=new ArrayList<>(List.of("A",step,Integer.toString(saved.size())));for(String name:new TreeSet<>(saved.keySet())){record.add(name);record.add(saved.get(name));} Map> previous=new LinkedHashMap<>(savedValues);try{apply(record);strings(record);}finally{savedValues=previous;}append(record);apply(record); } public void close()throws IOException { if(!owned)return;if(tainted){lock.close();lock=null;owned=false;return;} try{requireActive();}catch(IOException|RuntimeException error){lock.close();lock=null;owned=false;throw error;}lock.close();lock=null;owned=false;Files.delete(lockPath); } } static Map journal_values(Object value){if(!(value instanceof Map))throw new Journal.Refusal("Saved/fingerprint values need an explicit object");Map result=new LinkedHashMap<>();for(Map.Entry field:((Map)value).entrySet()){if(!(field.getKey() instanceof String)||!(field.getValue() instanceof String))throw new Journal.Refusal("Saved/fingerprint values must be exact strings");result.put((String)field.getKey(),(String)field.getValue());}return result;} static void journal_acknowledge(Journal job,String step,Object saved)throws IOException{job.acknowledge(step,journal_values(saved));} static boolean journal_acknowledged(Journal job,String step)throws IOException{return job.acknowledged(step);} static void journal_adopt(Journal job,String step,String method,String path,Object saved)throws IOException{job.adopt(step,method,path,journal_values(saved));} static Object journal_begin(Journal job,String step,String method,String path,String requestFingerprint)throws IOException{return new LinkedHashMap(job.begin(step,method,path,requestFingerprint));} static boolean journal_completed(Journal job,String step)throws IOException{return job.completed(step);} static String journal_fingerprint(Object value)throws IOException{return Journal.fingerprint(journal_values(value));} static Object journal_recorded(Journal job,String step)throws IOException{return new LinkedHashMap<>(job.recorded(step));} static boolean not_value(boolean value){return !value;} static Journal open_journal(String path,String base,String workspace,String slug,String job,String inputFingerprint,Object manifest,String mode)throws IOException { if(!(manifest instanceof List))throw new Journal.Refusal("A closed write manifest is required");List> writes=new ArrayList<>();for(Object row:(List)manifest){if(!(row instanceof List)||((List)row).size()!=3)throw new Journal.Refusal("Each write must bind step/method/path");List fields=new ArrayList<>();for(Object value:(List)row){if(!(value instanceof String))throw new Journal.Refusal("Manifest values are exact strings");fields.add((String)value);}writes.add(fields);}return new Journal(Path.of(path),base,workspace,slug,job,inputFingerprint,writes,mode); } static String optional(String name,String fallback){String value=System.getenv(name);return value==null||value.isEmpty()?fallback:value;} static String page_size(String value){try{if(value==null||!value.matches("[1-9][0-9]*")||Integer.parseInt(value)<=0)throw new IllegalArgumentException();return value;}catch(RuntimeException error){throw new IllegalArgumentException("Page size must be a positive int32");}} static Object parse_json(String value){ Object result=new GsonBuilder().setObjectToNumberStrategy(ToNumberPolicy.LAZILY_PARSED_NUMBER).setStrictness(com.google.gson.Strictness.STRICT).create().fromJson(value,Object.class); java.util.regex.Matcher tokens=java.util.regex.Pattern.compile("\"(?:\\\\.|[^\"\\\\])*\"|[{}\\[\\],]",java.util.regex.Pattern.DOTALL).matcher(value); List> stack=new ArrayList<>(); while(tokens.find()){ String token=tokens.group(); if(token.equals("{"))stack.add(map("object",true,"key",true,"names",new HashSet())); else if(token.equals("["))stack.add(map("object",false)); else if(token.equals("}")||token.equals("]"))stack.remove(stack.size()-1); else if(token.equals(",")){if(!stack.isEmpty()&&Boolean.TRUE.equals(stack.get(stack.size()-1).get("object")))stack.get(stack.size()-1).put("key",true);} else if(!stack.isEmpty()){ Map frame=stack.get(stack.size()-1); if(Boolean.TRUE.equals(frame.get("object"))&&Boolean.TRUE.equals(frame.get("key"))){String name=JSON.fromJson(token,String.class);@SuppressWarnings("unchecked") Set names=(Set)frame.get("names");if(!names.add(name))throw new IllegalArgumentException("Duplicate JSON input property");frame.put("key",false);} } } return result; } static String positive_id(String value){try{if(value==null||!value.matches("[1-9][0-9]*")||Long.parseLong(value)<=0)throw new IllegalArgumentException();return value;}catch(RuntimeException error){throw new IllegalArgumentException("Use a positive record ID");}} static void print_value(Object value){try{String text=value instanceof String?(String)value:JSON.toJson(value);System.out.write((text+"\n").getBytes(StandardCharsets.UTF_8));}catch(IOException error){throw new UncheckedIOException(error);}} static void require_condition(boolean value,String message){if(!value)throw new IllegalStateException(message);} static String response_status(Result value){return Integer.toString(value.status);} static Object single(Object value){List rows=items(value);if(rows.size()!=1)throw new IllegalStateException("Expected exactly one selected record");return rows.get(0);} static void validate_crm_event_inputs(String key, String name, String start, String end) throws IOException { crm_text(name, "EXHIBITDAY_EVENT_NAME", 500); crm_text(key, "EXHIBITDAY_EXTERNAL_EVENT_KEY", 3000); if (name.indexOf('<') >= 0 || name.indexOf('>') >= 0 || name.indexOf('\r') >= 0 || name.indexOf('\n') >= 0 || name.equalsIgnoreCase("null")) throw new Journal.Refusal("Use plain, single-line EXHIBITDAY_EVENT_NAME text other than null"); crm_date(start, "EXHIBITDAY_START_DATE"); crm_date(end, "EXHIBITDAY_END_DATE"); if (end.compareTo(start) < 0) throw new Journal.Refusal("EXHIBITDAY_END_DATE must be on or after EXHIBITDAY_START_DATE"); } static void crm_text(String value, String label, int limit) throws IOException { Journal.strings(List.of(value)); if (value.isEmpty() || crm_space(value.charAt(0)) || crm_space(value.charAt(value.length()-1))) throw new Journal.Refusal("Remove whitespace at the start or end of " + label); if (value.length() > limit) throw new Journal.Refusal(label + " exceeds " + limit + " UTF-16 code units"); } static boolean crm_space(char c) { return Character.isWhitespace(c) && !(c >= 0x1C && c <= 0x1F) || Character.isSpaceChar(c) || c == 0x85; } static void crm_date(String value, String label) { boolean valid; try { valid = value.matches("[0-9]{4}-[0-9]{2}-[0-9]{2}") && LocalDate.parse(value).getYear() >= 1753; } catch (java.time.format.DateTimeParseException error) { valid = false; } if (!valid) throw new Journal.Refusal(label + " must be a calendar date in YYYY-MM-DD on or after 1753-01-01"); } static void run()throws Exception { String external_event_key = required("EXHIBITDAY_EXTERNAL_EVENT_KEY"); String desired_event_name = required("EXHIBITDAY_EVENT_NAME"); String desired_start_date = required("EXHIBITDAY_START_DATE"); String desired_end_date = required("EXHIBITDAY_END_DATE"); String desired_dates_json = required("EXHIBITDAY_EXHIBIT_DATES_JSON"); String desired_section_name = optional("EXHIBITDAY_TASK_SECTION_NAME", "Pre-event planning"); String setup_page_size = page_size(optional("EXHIBITDAY_PAGE_SIZE", "100")); List desired_setup_dates = items(parse_json(desired_dates_json)); validate_crm_event_inputs(external_event_key, desired_event_name, desired_start_date, desired_end_date); String journal_path = required("EXHIBITDAY_JOURNAL"); String stable_job_id = required("EXHIBITDAY_JOB_ID"); String job_mode = optional("EXHIBITDAY_JOB_MODE", "resume"); Result setup_workspace_response = call("workspace_binding", map(), null, null); require_condition(equal(response_status(setup_workspace_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); Object setup_workspace = setup_workspace_response.body; String owned_workspace_id = positive_id(text(field(setup_workspace, "id"))); String setup_input_fingerprint = journal_fingerprint(map("workflow_contract_sha256", "19097A09AE2D22C1AF56F5D4FBD9B72F524E5EC195434BC315834CC8C2417C32", "external_event_key", external_event_key, "name", desired_event_name, "start_date", desired_start_date, "end_date", desired_end_date, "section_name", desired_section_name, "dates", desired_dates_json)); try (Journal setup_job = open_journal(journal_path, "https://api.exhibitday.com/v1", owned_workspace_id, "event-setup-crm", stable_job_id, setup_input_fingerprint, Arrays.asList(Arrays.asList("create_event", "POST", "/v1/events"), Arrays.asList("update_event", "PATCH", "/v1/events"), Arrays.asList("create_section", "POST", "/v1/tasks/sections"), Arrays.asList("save_dates", "PATCH", "/v1/events/dates")), job_mode)) { String setup_event_id = ""; String setup_section_id = ""; String recorded_section_name = desired_section_name; if (journal_completed(setup_job, "create_event")) { Object recorded_event = journal_recorded(setup_job, "create_event"); setup_event_id = positive_id(text(field(recorded_event, "id"))); require_condition(equal(text(field(recorded_event, "integration_metadata_field_1")), external_event_key), "The journal's completed Event differs from this external key."); } else { String event_search_offset = "0"; Map event_search_query = map("filter_by_integration_metadata_field_1", external_event_key, "$limit", setup_page_size); while (true) { event_search_query.put("$offset", event_search_offset); Result event_search_response = call("find_existing", event_search_query, null, null); require_condition(equal(response_status(event_search_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); Object event_search_page = event_search_response.body; List event_search_rows = items(field(event_search_page, "list_data")); require_condition(equal(text(field(event_search_page, "records_found")), text(count(event_search_rows))), "records_found differs from this complete page's rows."); require_condition(is_present(text(field(event_search_page, "total_records"))), "The search wrapper needs total_records."); require_condition(either(equal(field(event_search_page, "has_more"), true), equal(field(event_search_page, "has_more"), false)), "Expected a Boolean has_more value."); for (Object event_search_row : items(event_search_rows)) { if (equal(text(field(event_search_row, "integration_metadata_field_1")), external_event_key)) { String event_search_candidate_id = positive_id(text(field(event_search_row, "id"))); if (is_present(setup_event_id)) { require_condition(equal(setup_event_id, event_search_candidate_id), "More than one matching record exists. Reconcile the ambiguity instead of selecting one or creating another."); } setup_event_id = event_search_candidate_id; } } if (equal(field(event_search_page, "has_more"), false)) { break; } require_condition(not_value(is_empty(event_search_rows)), "An empty search page has has_more=true. Stop and reconcile the search."); event_search_offset = add_offset(event_search_offset, count(event_search_rows)); } if (not_value(is_present(setup_event_id))) { String event_write_fingerprint = journal_fingerprint(map("name", desired_event_name, "start_date", desired_start_date, "end_date", desired_end_date, "integration_metadata_field_1", external_event_key)); Object event_intent = journal_begin(setup_job, "create_event", "POST", "/v1/events", event_write_fingerprint); Result event_create_response = call("create_event", map(), map("name", desired_event_name, "start_date", desired_start_date, "end_date", desired_end_date, "integration_metadata_field_1", external_event_key), text(field(event_intent, "idempotency_key"))); require_condition(equal(response_status(event_create_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); Object created_event = event_create_response.body; setup_event_id = positive_id(text(field(created_event, "id"))); require_condition(equal(text(field(created_event, "integration_metadata_field_1")), external_event_key), "The created Event's external key differs; preserve the pending intent and reconcile."); require_condition(both(is_present(text(field(created_event, "name"))), both(is_present(text(field(created_event, "start_date"))), is_present(text(field(created_event, "end_date"))))), "The Event acknowledgement omitted its saved name or main dates."); journal_acknowledge(setup_job, "create_event", map("id", setup_event_id, "integration_metadata_field_1", external_event_key)); } } Result event_confirmation_response = call("confirm_event", map("id", setup_event_id, "$include_record_revision", "true"), null, null); require_condition(equal(response_status(event_confirmation_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); Object confirmed_setup_event = event_confirmation_response.body; require_condition(both(equal(text(field(confirmed_setup_event, "id")), setup_event_id), equal(text(field(confirmed_setup_event, "integration_metadata_field_1")), external_event_key)), "The captured Event is missing or rebound; stop instead of searching for or creating a replacement."); if (not_value(journal_completed(setup_job, "create_event"))) { journal_adopt(setup_job, "create_event", "GET", "/v1/events/info", map("id", text(field(confirmed_setup_event, "id")), "integration_metadata_field_1", text(field(confirmed_setup_event, "integration_metadata_field_1")))); } String setup_event_revision = text(field(confirmed_setup_event, "record_revision")); require_condition(is_present(setup_event_revision), "Read the selected Event with its revision before comparing or updating it."); require_condition(both(both(is_present(text(field(confirmed_setup_event, "name"))), is_present(text(field(confirmed_setup_event, "start_date")))), is_present(text(field(confirmed_setup_event, "end_date")))), "The selected Event must return its current name, start date and end date."); if (journal_completed(setup_job, "update_event")) { Object recorded_event_update = journal_recorded(setup_job, "update_event"); require_condition(both(equal(text(field(recorded_event_update, "id")), setup_event_id), equal(text(field(recorded_event_update, "integration_metadata_field_1")), external_event_key)), "The recorded Event update has a different identity. Stop and reconcile."); require_condition(both(both(equal(text(field(confirmed_setup_event, "name")), desired_event_name), equal(text(field(confirmed_setup_event, "start_date")), desired_start_date)), equal(text(field(confirmed_setup_event, "end_date")), desired_end_date)), "The Event name or main dates changed after this job checked them. Review the current Event before writing again."); } else { if (both(both(equal(text(field(confirmed_setup_event, "name")), desired_event_name), equal(text(field(confirmed_setup_event, "start_date")), desired_start_date)), equal(text(field(confirmed_setup_event, "end_date")), desired_end_date))) { journal_adopt(setup_job, "update_event", "GET", "/v1/events/info", map("id", setup_event_id, "integration_metadata_field_1", external_event_key)); } else { require_condition(not_value(journal_acknowledged(setup_job, "create_event")), "The Event created by this job differs from the requested values. Inspect the saved Event before starting another update."); Object event_update_body = map("id", setup_event_id, "expected_revision", setup_event_revision); if (not_value(equal(text(field(confirmed_setup_event, "name")), desired_event_name))) { ((Map)event_update_body).put("name", desired_event_name); } if (not_value(equal(text(field(confirmed_setup_event, "start_date")), desired_start_date))) { ((Map)event_update_body).put("start_date", desired_start_date); } if (not_value(equal(text(field(confirmed_setup_event, "end_date")), desired_end_date))) { ((Map)event_update_body).put("end_date", desired_end_date); } String event_update_fingerprint = journal_fingerprint(event_update_body); journal_begin(setup_job, "update_event", "PATCH", "/v1/events", event_update_fingerprint); Result event_update_response = call("update_event", map(), event_update_body, null); require_condition(equal(response_status(event_update_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); Object event_update_ack = event_update_response.body; String event_updated_revision = text(field(event_update_ack, "record_revision")); require_condition(is_present(event_updated_revision), "The conditional Event update needs its returned revision. Reconcile the pending request before continuing."); journal_acknowledge(setup_job, "update_event", map("id", setup_event_id, "integration_metadata_field_1", external_event_key, "record_revision", event_updated_revision)); } } Result event_update_verify_response = call("verify_event_update", map("id", setup_event_id), null, null); require_condition(equal(response_status(event_update_verify_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); Object verified_setup_event = event_update_verify_response.body; require_condition(both(both(equal(text(field(verified_setup_event, "id")), setup_event_id), equal(text(field(verified_setup_event, "integration_metadata_field_1")), external_event_key)), both(both(equal(text(field(verified_setup_event, "name")), desired_event_name), equal(text(field(verified_setup_event, "start_date")), desired_start_date)), equal(text(field(verified_setup_event, "end_date")), desired_end_date))), "The Event's current identity, name or main dates differ. Inspect the Event before continuing with setup."); if (journal_completed(setup_job, "create_section")) { Object recorded_section = journal_recorded(setup_job, "create_section"); setup_section_id = positive_id(text(field(recorded_section, "id"))); require_condition(equal(text(field(recorded_section, "event_id")), setup_event_id), "The recorded Task Section belongs to a different Event."); recorded_section_name = text(field(recorded_section, "name")); } else { String section_search_offset = "0"; Map section_search_query = map("filter_by_event_id", setup_event_id, "$limit", setup_page_size); while (true) { section_search_query.put("$offset", section_search_offset); Result section_search_response = call("find_section", section_search_query, null, null); require_condition(equal(response_status(section_search_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); Object section_search_page = section_search_response.body; List section_search_rows = items(field(section_search_page, "list_data")); require_condition(equal(text(field(section_search_page, "records_found")), text(count(section_search_rows))), "records_found differs from this complete page's rows."); require_condition(is_present(text(field(section_search_page, "total_records"))), "The search wrapper needs total_records."); require_condition(either(equal(field(section_search_page, "has_more"), true), equal(field(section_search_page, "has_more"), false)), "Expected a Boolean has_more value."); for (Object section_search_row : items(section_search_rows)) { require_condition(equal(text(field(section_search_row, "event_id")), setup_event_id), "A section search row belongs to a different Event; stop before adopting or creating anything."); if (equal(text(field(section_search_row, "name")), desired_section_name)) { String section_search_candidate_id = positive_id(text(field(section_search_row, "id"))); if (is_present(setup_section_id)) { require_condition(equal(setup_section_id, section_search_candidate_id), "More than one matching record exists. Reconcile the ambiguity instead of selecting one or creating another."); } setup_section_id = section_search_candidate_id; } } if (equal(field(section_search_page, "has_more"), false)) { break; } require_condition(not_value(is_empty(section_search_rows)), "An empty search page has has_more=true. Stop and reconcile the search."); section_search_offset = add_offset(section_search_offset, count(section_search_rows)); } if (not_value(is_present(setup_section_id))) { String section_write_fingerprint = journal_fingerprint(map("event_id", setup_event_id, "name", desired_section_name)); Object section_intent = journal_begin(setup_job, "create_section", "POST", "/v1/tasks/sections", section_write_fingerprint); Result section_create_response = call("create_section", map(), map("event_id", setup_event_id, "name", desired_section_name), text(field(section_intent, "idempotency_key"))); require_condition(equal(response_status(section_create_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); Object created_section = section_create_response.body; setup_section_id = positive_id(text(field(created_section, "id"))); require_condition(equal(text(field(created_section, "event_id")), setup_event_id), "The created Task Section belongs to a different Event; preserve the pending intent."); recorded_section_name = text(field(created_section, "name")); require_condition(is_present(recorded_section_name), "The Task Section acknowledgement needs its actual saved name."); journal_acknowledge(setup_job, "create_section", map("id", setup_section_id, "event_id", setup_event_id, "name", recorded_section_name)); } } Result section_confirmation_response = call("confirm_section", map("id", setup_section_id), null, null); require_condition(equal(response_status(section_confirmation_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); Object confirmed_setup_section = section_confirmation_response.body; require_condition(both(equal(text(field(confirmed_setup_section, "id")), setup_section_id), both(equal(text(field(confirmed_setup_section, "event_id")), setup_event_id), equal(text(field(confirmed_setup_section, "name")), recorded_section_name))), "The captured Task Section is missing, renamed or rebound; stop instead of creating a replacement."); if (not_value(journal_completed(setup_job, "create_section"))) { journal_adopt(setup_job, "create_section", "GET", "/v1/tasks/sections/info", map("event_id", text(field(confirmed_setup_section, "event_id")), "id", text(field(confirmed_setup_section, "id")), "name", text(field(confirmed_setup_section, "name")))); } Result setup_dates_response = call("read_dates", map("event_id", setup_event_id, "filter_by_date_type_id", "1", "$include_record_revision", "true"), null, null); require_condition(equal(response_status(setup_dates_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); Object setup_dates_page = setup_dates_response.body; require_condition(both(equal(text(field(setup_dates_page, "records_found")), "1"), both(equal(text(field(setup_dates_page, "total_records")), "1"), equal(field(setup_dates_page, "has_more"), false))), "Expected one complete selected Dates group, without another page."); Object setup_dates_group = single(field(setup_dates_page, "list_data")); require_condition(both(equal(text(field(setup_dates_group, "event_id")), setup_event_id), equal(text(field(setup_dates_group, "date_type_id")), "1")), "The Dates group belongs to another Event or type."); String setup_dates_revision = text(field(setup_dates_group, "record_revision")); require_condition(is_present(setup_dates_revision), "Read the actual selected group revision before replacing it."); if (journal_completed(setup_job, "save_dates")) { Object recorded_dates = journal_recorded(setup_job, "save_dates"); require_condition(both(equal(text(field(recorded_dates, "event_id")), setup_event_id), equal(text(field(recorded_dates, "date_type_id")), "1")), "The recorded Dates acknowledgement belongs to another Event or group."); } else { String setup_dates_fingerprint = journal_fingerprint(map("event_id", setup_event_id, "date_type_id", "1", "dates", desired_dates_json, "expected_revision", setup_dates_revision)); journal_begin(setup_job, "save_dates", "PATCH", "/v1/events/dates", setup_dates_fingerprint); Result setup_dates_save_response = call("save_dates", map(), map("event_id", setup_event_id, "date_type_id", "1", "dates", desired_setup_dates, "expected_revision", setup_dates_revision), null); require_condition(equal(response_status(setup_dates_save_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); Object setup_dates_ack = setup_dates_save_response.body; String setup_dates_saved_revision = text(field(setup_dates_ack, "record_revision")); require_condition(is_present(setup_dates_saved_revision), "The checked Dates save needs its actual returned revision."); journal_acknowledge(setup_job, "save_dates", map("event_id", setup_event_id, "date_type_id", "1", "record_revision", setup_dates_saved_revision)); } Result setup_dates_verify_response = call("verify_dates", map("event_id", setup_event_id, "filter_by_date_type_id", "1"), null, null); require_condition(equal(response_status(setup_dates_verify_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); Object setup_dates_verify_page = setup_dates_verify_response.body; require_condition(both(equal(text(field(setup_dates_verify_page, "records_found")), "1"), both(equal(text(field(setup_dates_verify_page, "total_records")), "1"), equal(field(setup_dates_verify_page, "has_more"), false))), "Expected one complete selected Dates group, without another page."); Object setup_dates_verify_group = single(field(setup_dates_verify_page, "list_data")); require_condition(both(equal(text(field(setup_dates_verify_group, "event_id")), setup_event_id), equal(text(field(setup_dates_verify_group, "date_type_id")), "1")), "The Dates group belongs to another Event or type."); require_condition(deep_equal(field(setup_dates_verify_group, "dates"), desired_setup_dates), "The saved normalized Dates list differs from the supplied canonical list. Inspect it; do not automatically restore or repeat the update."); Result setup_event_readback_response = call("event_readback", map("id", setup_event_id), null, null); require_condition(equal(response_status(setup_event_readback_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status."); Object setup_event_readback = setup_event_readback_response.body; require_condition(both(equal(text(field(setup_event_readback, "id")), setup_event_id), equal(text(field(setup_event_readback, "integration_metadata_field_1")), external_event_key)), "Final Event readback is missing or rebound; earlier steps remain saved."); require_condition(both(both(equal(text(field(setup_event_readback, "name")), desired_event_name), equal(text(field(setup_event_readback, "start_date")), desired_start_date)), equal(text(field(setup_event_readback, "end_date")), desired_end_date)), "The Event name or main dates changed before final readback. Inspect the Event before starting another update."); boolean planning_section_present = false; for (Object setup_event_section : items(items(field(setup_event_readback, "task_sections")))) { if (equal(text(field(setup_event_section, "id")), setup_section_id)) { planning_section_present = true; } } require_condition(planning_section_present, "The Event's current Task Sections do not include the recorded section; inspect it rather than creating another."); print_value(map("event_id", setup_event_id, "task_section_id", setup_section_id, "dates_verified", "true")); } } public static void main(String[] args)throws Exception {run();} } ``` ```php $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, ?string $key = null): array { global $spec, $apiKey, $transport; $route = $spec['requests'][$name]; $headers = ['Authorization' => 'Bearer ' . $apiKey, 'Accept' => 'application/json']; if ($route['method'] === 'POST') { if ($key === null || $key === '') throw new RuntimeException('Persist a logical create key before sending POST'); $headers['Idempotency-Key'] = $key; // 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); // 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 = 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 = $resend && ($status === 429 || $status >= 500); 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, 'raw' => $raw]; } throw new RuntimeException('Retry limit reached'); } $transport = Closure::fromCallable('nativeTransport'); function add_offset(string $offset,int $received):string{$result=(int)$offset+$received;if($received<=0||$result>2147483647)throw new RuntimeException("Cannot advance this int32 offset; reconcile the query");return (string)$result;} function both(bool $left,bool $right):bool{return $left&&$right;} function deep_equal(mixed $left,mixed $right):bool { if(is_object($left))$left=get_object_vars($left);if(is_object($right))$right=get_object_vars($right); if(gettype($left)!==gettype($right))return false; if(!is_array($left))return$left===$right; if(array_is_list($left)!==array_is_list($right)||count($left)!==count($right))return false; foreach($left as$key=>$value)if(!array_key_exists($key,$right)||!deep_equal($value,$right[$key]))return false; return true; } function either(bool $left,bool $right):bool{return $left||$right;} function equal(mixed $left,mixed $right):bool{return $left===$right;} function field(mixed $value,string $name):mixed{if(!is_array($value)||!array_key_exists($name,$value))throw new RuntimeException("Missing response field: ".$name);return $value[$name];} function items(mixed $value):array{if(!is_array($value)||!array_is_list($value))throw new RuntimeException("Expected a JSON array");return $value;} function is_empty(mixed $value):bool{return count(items($value))===0;} function is_present(?string $value):bool{return $value!==null&&$value!=="";} final class JournalRefusal extends RuntimeException {} final class JournalProtocol { public const PREAMBLE="EXHIBITDAY-GUIDE-JOURNAL 1\n"; public static function utf8(mixed $value):string {if(!is_string($value)||preg_match('//u',$value)!==1)throw new JournalRefusal('Journal fields must be exact valid UTF8 strings');return$value;} public static function strings(array $values):string {$raw='';foreach($values as$value){$item=self::utf8($value);$raw.=strlen($item).':'.$item;}return$raw;} private static function length(string $text,int $remaining):int {if(!preg_match('/\A(?:0|[1-9][0-9]*)\z/',$text))throw new JournalRefusal('Noncanonical string length');$maximum=(string)$remaining;if(strlen($text)>strlen($maximum)||(strlen($text)===strlen($maximum)&&strcmp($text,$maximum)>0))throw new JournalRefusal('Incomplete journal string/frame');return(int)$text;} public static function readStrings(string $raw):array {$values=[];$offset=0;while($offset=strlen($raw)-$offset)throw new JournalRefusal('Incomplete frame; reconcile before retry');$payload=substr($raw,$offset,$size);$offset+=$size;if($raw[$offset]!=="\n"||self::digest($payload)!==$match[2])throw new JournalRefusal('Journal integrity failed; reconcile before retry');$records[]=self::readStrings($payload);$offset++;}return$records;} public static function writeAll($file,string $raw):void {$offset=0;while($offsetpath=$path;$this->lockPath=$path.'.lock';$this->owner=bin2hex(random_bytes(16));$address=parse_url($base); if($address===false||!in_array($address['scheme']??null,['https','http'],true)||!isset($address['host'])||isset($address['user'])||isset($address['pass'])||isset($address['query'])||isset($address['fragment'])||!preg_match('/\A[a-z][a-z0-9-]*\z/',$slug))throw new JournalRefusal('Use actual API base and closed guide slug'); if(trim($job)===''||!preg_match('/\A[1-9][0-9]*\z/',$workspace)||!preg_match('/\A[0-9A-F]{64}\z/',$inputFingerprint))throw new JournalRefusal('Use actual workspace, stable explicit job ID and exact fingerprint'); if(!in_array($mode,['new','resume'],true))throw new JournalRefusal('Choose new or resume for this local job'); $manifest=[];foreach($writes as$write){if(!is_array($write)||!array_is_list($write)||count($write)!==3)throw new JournalRefusal('Invalid write manifest');[$step,$method,$route]=$write; if(!is_string($step)||!preg_match('/\A[a-z][a-z0-9_-]*\z/',$step)||isset($this->allowed[$step])||!in_array($method,['POST','PATCH','DELETE'],true)||!is_string($route)||!preg_match('~\A/v1/[A-Za-z0-9_/-]+\z~',$route)||str_contains($route,'//'))throw new JournalRefusal('Use a closed unique write manifest');$this->allowed[$step]=[$method,$route];array_push($manifest,$step,$method,$route);} if($this->allowed===[])throw new JournalRefusal('Only write workflows need restart journal');$this->header=['H','1',$base,$workspace,$slug,$job,$inputFingerprint,JournalProtocol::digest(JournalProtocol::strings($manifest))];JournalProtocol::strings($this->header); $this->file=JournalProtocol::createPrivate($this->lockPath);$this->owned=true; try{ JournalProtocol::writeAll($this->file,$this->owner);$identity=fstat($this->file);if($identity===false)throw new JournalRefusal('Cannot bind acquired lock identity');$this->identity=$identity; clearstatcache(true,$path);if(is_link($path))throw new JournalRefusal('Choose private regular journal file'); $exists=file_exists($path);if($mode==='resume'&&!$exists)throw new JournalRefusal('Journal missing: stop and reconcile lost state before starting a new logical job');if($mode==='new'&&$exists)throw new JournalRefusal('Journal exists; use resume for the same logical job'); if($mode==='new'){$target=JournalProtocol::createPrivate($path);try{JournalProtocol::writeAll($target,JournalProtocol::PREAMBLE.JournalProtocol::frame($this->header));}finally{fclose($target);}} $raw=file_get_contents($path);if($raw===false)throw new JournalRefusal('Cannot read journal');$records=JournalProtocol::decode($raw);if($records===[]||$records[0]!==$this->header)throw new JournalRefusal('Journal workspace/base/guide/job/input binding differs');foreach(array_slice($records,1)as$record)$this->apply($record); if(array_diff(array_keys($this->intents),array_keys($this->savedValues))!==[])throw new JournalRefusal('Saved intent lacks ACK; stop and reconcile before retry'); }catch(Throwable $error){$this->close();throw$error;} } private function apply(array $record):void { if(($record[0]??null)==='I'){ if(count($record)!==6)throw new JournalRefusal('Invalid intent shape');[,$step,$method,$route,$fingerprint,$key]=$record; if(!preg_match('/\A[a-z][a-z0-9_-]*\z/',$step)||isset($this->intents[$step])||isset($this->adoptedValues[$step])||($this->allowed[$step]??null)!==[$method,$route]||!preg_match('/\A[0-9A-F]{64}\z/',$fingerprint)||array_diff(array_keys($this->intents),array_keys($this->savedValues))!==[])throw new JournalRefusal('Invalid, future or repeated intent'); if(($method==='POST'&&!preg_match('/\A[0-9a-f]{32}\z/',$key))||($method!=='POST'&&$key!==''))throw new JournalRefusal('Invalid persisted action key');$this->intents[$step]=['method'=>$method,'path'=>$route,'request_fingerprint'=>$fingerprint,'idempotency_key'=>$key]; }elseif(($record[0]??null)==='A'){ if(count($record)<3)throw new JournalRefusal('Invalid ACK shape');[,$step,$count]=$record;$pairs=array_slice($record,3); if(!preg_match('/\A(?:0|[1-9][0-9]*)\z/',$count)||(string)intdiv(count($pairs),2)!==$count||count($pairs)%2!==0||!isset($this->intents[$step])||isset($this->savedValues[$step]))throw new JournalRefusal('ACK without exactly one prior intent'); $names=[];for($i=0;$i$name){if(!preg_match('/\A[a-z][a-z0-9_]*\z/',$name)||in_array($name,['api_key','exhibitday_api_key'],true))throw new JournalRefusal('Use secret-free ACK field names');$saved[$name]=$pairs[$i*2+1];}$this->savedValues[$step]=$saved; }elseif(($record[0]??null)==='S'){ if(count($record)<6)throw new JournalRefusal('Invalid read-adoption shape');[,$step,$method,$route,$readFingerprint,$count]=$record;$pairs=array_slice($record,6); $completed=array_unique(array_merge(array_keys($this->savedValues),array_keys($this->adoptedValues)),SORT_STRING);$order=array_keys($this->allowed);$prefix=array_slice($order,0,count($completed));$sorted=$completed;sort($sorted,SORT_STRING);sort($prefix,SORT_STRING); if(count($completed)>=count($order)||$sorted!==$prefix||$step!==$order[count($completed)]||array_diff(array_keys($this->intents),array_keys($this->savedValues))!==[])throw new JournalRefusal('Adopt only the exact next setup action without any pending intent'); $target=$this->allowed[$step];$expected=($target===['POST','/v1/events']||$step==='update_event'&&$target===['PATCH','/v1/events'])?'/v1/events/info':($target===['POST','/v1/tasks/sections']?'/v1/tasks/sections/info':null); if($method!=='GET'||$expected===null||$route!==$expected)throw new JournalRefusal('Adoption requires the exact source-bound single Event or section read'); if(!preg_match('/\A(?:0|[1-9][0-9]*)\z/',$count)||(string)intdiv(count($pairs),2)!==$count||count($pairs)%2!==0)throw new JournalRefusal('Invalid read-adoption field count'); $names=[];for($i=0;$i$name)$saved[$name]=$pairs[$i*2+1]; foreach(['id','event_id']as$name)if(isset($saved[$name])&&(!preg_match('/\A[1-9][0-9]*\z/',$saved[$name])||strlen($saved[$name])>19||(strlen($saved[$name])===19&&strcmp($saved[$name],'9223372036854775807')>0)))throw new JournalRefusal('Read-adoption IDs must be exact positive Int64 strings'); foreach($fields as$name)if(!in_array($name,['id','event_id'],true)&&$saved[$name]==='')throw new JournalRefusal('Read-adoption material must be complete and fingerprint-bound'); if($readFingerprint!==JournalProtocol::fingerprint($saved))throw new JournalRefusal('Read-adoption material must be complete and fingerprint-bound');$this->adoptedValues[$step]=$saved; }else throw new JournalRefusal('Unknown journal transition'); } private function requireActive():void { if(!$this->owned||$this->file===null||$this->tainted)throw new JournalRefusal('Journal closed or IO outcome needs reconciliation');clearstatcache(true,$this->lockPath);$current=@lstat($this->lockPath);$token=@file_get_contents($this->lockPath); if($current===false||($current['dev']??null)!==($this->identity['dev']??null)||($current['ino']??null)!==($this->identity['ino']??null)||$token!==$this->owner)throw new JournalRefusal('Journal lock replaced; stop without deleting it'); } private function append(array $record):void { $this->requireActive();$raw=JournalProtocol::frame($record);$target=null; try{$target=@fopen($this->path,'ab');if($target===false)throw new JournalRefusal('Cannot append journal; stop and reconcile');JournalProtocol::writeAll($target,$raw);}catch(Throwable $error){$this->tainted=true;throw$error;}finally{if(is_resource($target))fclose($target);} } public function acknowledged(string $step):bool{$this->requireActive();return isset($this->savedValues[$step]);} public function saved(string $step):array{$this->requireActive();if(!isset($this->savedValues[$step]))throw new JournalRefusal('No acknowledged state exists');return$this->savedValues[$step];} public function completed(string $step):bool{$this->requireActive();return isset($this->savedValues[$step])||isset($this->adoptedValues[$step]);} public function adopted(string $step):bool{$this->requireActive();return isset($this->adoptedValues[$step]);} public function recorded(string $step):array{$this->requireActive();if(!$this->completed($step))throw new JournalRefusal('No completed write or read-adoption exists');return$this->savedValues[$step]??$this->adoptedValues[$step];} public function adopt(string $step,string $method,string $route,array $saved):void{$this->requireActive();$record=['S',$step,$method,$route,JournalProtocol::fingerprint($saved),(string)count($saved)];$names=array_keys($saved);sort($names,SORT_STRING);foreach($names as$name){$record[]=$name;$record[]=$saved[$name];}$previous=$this->adoptedValues;try{$this->apply($record);JournalProtocol::strings($record);}finally{$this->adoptedValues=$previous;}$this->append($record);$this->apply($record);} public function beginAction(string $step,string $method,string $route,string $requestFingerprint):array { $this->requireActive();if(isset($this->intents[$step]))throw new JournalRefusal('Never blindly repeat an existing action');$key=$method==='POST'?bin2hex(random_bytes(16)):'';$record=['I',$step,$method,$route,$requestFingerprint,$key];$previous=$this->intents;try{$this->apply($record);}finally{$this->intents=$previous;}$this->append($record);$this->apply($record);return$this->intents[$step]; } public function acknowledge(string $step,array $saved):void { $this->requireActive();$record=['A',$step,(string)count($saved)];$names=array_keys($saved);sort($names,SORT_STRING);foreach($names as$name){$record[]=$name;$record[]=$saved[$name];}$previous=$this->savedValues;try{$this->apply($record);JournalProtocol::strings($record);}finally{$this->savedValues=$previous;}$this->append($record);$this->apply($record); } public function close():void { if(!$this->owned)return;if($this->tainted){fclose($this->file);$this->file=null;$this->owned=false;return;} try{$this->requireActive();}catch(Throwable $error){fclose($this->file);$this->file=null;$this->owned=false;throw$error;}fclose($this->file);$this->file=null;$this->owned=false;if(!unlink($this->lockPath))throw new JournalRefusal('Could not release owned journal lock'); } } function journal_values(mixed $value):array{if(!is_object($value))throw new JournalRefusal('Saved/fingerprint values need an explicit object');$result=get_object_vars($value);foreach($result as$name=>$item)if(!is_string($name)||!is_string($item))throw new JournalRefusal('Saved/fingerprint values must be exact strings');return$result;} function journal_acknowledge(GuideJournal $job,string $step,mixed $saved):void{$job->acknowledge($step,journal_values($saved));} function journal_acknowledged(GuideJournal $job,string $step):bool{return $job->acknowledged($step);} function journal_adopt(GuideJournal $job,string $step,string $method,string $path,mixed $saved):void{$job->adopt($step,$method,$path,journal_values($saved));} function journal_begin(GuideJournal $job,string $step,string $method,string $path,string $requestFingerprint):array{return $job->beginAction($step,$method,$path,$requestFingerprint);} function journal_completed(GuideJournal $job,string $step):bool{return$job->completed($step);} function journal_fingerprint(mixed $value):string{return JournalProtocol::fingerprint(journal_values($value));} function journal_recorded(GuideJournal $job,string $step):array{return$job->recorded($step);} function not_value(bool $value):bool{return !$value;} function open_journal(string $path,string $base,string $workspace,string $slug,string $job,string $inputFingerprint,array $writes,string $mode):GuideJournal{return new GuideJournal($path,$base,$workspace,$slug,$job,$inputFingerprint,$writes,$mode);} function page_size(string $value):string{if(!preg_match("/^[1-9][0-9]*$/D",$value)||strlen($value)>10||(strlen($value)===10&&strcmp($value,"2147483647")>0))throw new RuntimeException("Page size must be a positive int32");return $value;} function parse_json(string $value):mixed{ $result=json_decode($value,false,512,JSON_THROW_ON_ERROR);$stack=[]; if(preg_match_all('~"(?:\\\\.|[^"\\\\])*"|[{}\[\],]~s',$value,$matches)===false)throw new RuntimeException('JSON token validation failed'); foreach($matches[0]as$token){ if($token==='{')$stack[]=['object'=>true,'key'=>true,'names'=>[]]; elseif($token==='[')$stack[]=['object'=>false]; elseif($token==='}'||$token===']')array_pop($stack); elseif($token===','){if($stack!==[]&&$stack[count($stack)-1]['object'])$stack[count($stack)-1]['key']=true;} elseif($stack!==[]&&$stack[count($stack)-1]['object']&&$stack[count($stack)-1]['key']){$at=count($stack)-1;$name=json_decode($token,false,512,JSON_THROW_ON_ERROR);if(array_key_exists($name,$stack[$at]['names']))throw new RuntimeException('Duplicate JSON input property');$stack[$at]['names'][$name]=true;$stack[$at]['key']=false;} } $finite=function(mixed $node)use(&$finite):void{if(is_float($node)&&!is_finite($node))throw new RuntimeException('Use finite JSON numbers');if(is_object($node)||is_array($node))foreach($node as$item)$finite($item);};$finite($result);return$result; } function positive_id(string $value):string{if(!preg_match("/^[1-9][0-9]*$/D",$value)||strlen($value)>19||(strlen($value)===19&&strcmp($value,"9223372036854775807")>0))throw new RuntimeException("Use a positive record ID");return $value;} function print_value(mixed $value):void{echo (is_string($value)?$value:json_encode($value,JSON_THROW_ON_ERROR))."\n";} function require_condition(bool $value,string $message):void{if(!$value)throw new RuntimeException($message);} function response_status(array $value):string{return(string)$value["status"];} function single(mixed $value):mixed{$rows=items($value);if(count($rows)!==1)throw new RuntimeException('Expected exactly one selected record');return$rows[0];} function text(mixed $value):string{if($value===null)return "";if(is_string($value))return $value;if(is_bool($value))return $value?"true":"false";if(is_int($value))return (string)$value;throw new RuntimeException("Expected a scalar response value");} function validate_crm_event_inputs(string $key, string $name, string $start, string $end): void { $spaces = '[\x{0009}-\x{000D}\x{0020}\x{0085}\x{00A0}\x{1680}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]'; foreach ([[$name,'EXHIBITDAY_EVENT_NAME',500],[$key,'EXHIBITDAY_EXTERNAL_EVENT_KEY',3000]] as [$value,$label,$limit]) { JournalProtocol::utf8($value); if ($value === '' || preg_match('~\A'.$spaces.'|'.$spaces.'\z~u', $value)) throw new JournalRefusal('Remove whitespace at the start or end of '.$label); if (preg_match_all('/./us',$value) + preg_match_all('/[\x{10000}-\x{10FFFF}]/u',$value) > $limit) throw new JournalRefusal($label.' exceeds '.$limit.' UTF-16 code units'); } if (strpbrk($name, "<>\r\n") !== false || strtolower($name) === 'null') throw new JournalRefusal('Use plain, single-line EXHIBITDAY_EVENT_NAME text other than null'); foreach ([[$start,'EXHIBITDAY_START_DATE'],[$end,'EXHIBITDAY_END_DATE']] as [$value,$label]) { if (!preg_match('/\A([0-9]{4})-([0-9]{2})-([0-9]{2})\z/', $value, $match) || (int)$match[1] < 1753 || !checkdate((int)$match[2],(int)$match[3],(int)$match[1])) throw new JournalRefusal($label.' must be a calendar date in YYYY-MM-DD on or after 1753-01-01'); } if (strcmp($end,$start) < 0) throw new JournalRefusal('EXHIBITDAY_END_DATE must be on or after EXHIBITDAY_START_DATE'); } function main():void { $external_event_key = required('EXHIBITDAY_EXTERNAL_EVENT_KEY'); $desired_event_name = required('EXHIBITDAY_EVENT_NAME'); $desired_start_date = required('EXHIBITDAY_START_DATE'); $desired_end_date = required('EXHIBITDAY_END_DATE'); $desired_dates_json = required('EXHIBITDAY_EXHIBIT_DATES_JSON'); $desired_section_name = optional('EXHIBITDAY_TASK_SECTION_NAME', 'Pre-event planning'); $setup_page_size = page_size(optional('EXHIBITDAY_PAGE_SIZE', '100')); $desired_setup_dates = items(parse_json($desired_dates_json)); validate_crm_event_inputs($external_event_key, $desired_event_name, $desired_start_date, $desired_end_date); $journal_path = required('EXHIBITDAY_JOURNAL'); $stable_job_id = required('EXHIBITDAY_JOB_ID'); $job_mode = optional('EXHIBITDAY_JOB_MODE', 'resume'); $setup_workspace_response = call('workspace_binding', [], null, null); require_condition(equal(response_status($setup_workspace_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.'); $setup_workspace = $setup_workspace_response["body"]; $owned_workspace_id = positive_id(text(field($setup_workspace, 'id'))); $setup_input_fingerprint = journal_fingerprint((object)['workflow_contract_sha256' => '19097A09AE2D22C1AF56F5D4FBD9B72F524E5EC195434BC315834CC8C2417C32', 'external_event_key' => $external_event_key, 'name' => $desired_event_name, 'start_date' => $desired_start_date, 'end_date' => $desired_end_date, 'section_name' => $desired_section_name, 'dates' => $desired_dates_json]); $setup_job = open_journal($journal_path, 'https://api.exhibitday.com/v1', $owned_workspace_id, 'event-setup-crm', $stable_job_id, $setup_input_fingerprint, [['create_event', 'POST', '/v1/events'], ['update_event', 'PATCH', '/v1/events'], ['create_section', 'POST', '/v1/tasks/sections'], ['save_dates', 'PATCH', '/v1/events/dates']], $job_mode); try { $setup_event_id = ''; $setup_section_id = ''; $recorded_section_name = $desired_section_name; if (journal_completed($setup_job, 'create_event')) { $recorded_event = journal_recorded($setup_job, 'create_event'); $setup_event_id = positive_id(text(field($recorded_event, 'id'))); require_condition(equal(text(field($recorded_event, 'integration_metadata_field_1')), $external_event_key), 'The journal\'s completed Event differs from this external key.'); } else { $event_search_offset = '0'; $event_search_query = ['filter_by_integration_metadata_field_1' => $external_event_key, '$limit' => $setup_page_size]; while (true) { $event_search_query['$offset'] = $event_search_offset; $event_search_response = call('find_existing', $event_search_query, null, null); require_condition(equal(response_status($event_search_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.'); $event_search_page = $event_search_response["body"]; $event_search_rows = items(field($event_search_page, 'list_data')); require_condition(equal(text(field($event_search_page, 'records_found')), text(count($event_search_rows))), 'records_found differs from this complete page\'s rows.'); require_condition(is_present(text(field($event_search_page, 'total_records'))), 'The search wrapper needs total_records.'); require_condition(either(equal(field($event_search_page, 'has_more'), true), equal(field($event_search_page, 'has_more'), false)), 'Expected a Boolean has_more value.'); foreach (items($event_search_rows) as $event_search_row) { if (equal(text(field($event_search_row, 'integration_metadata_field_1')), $external_event_key)) { $event_search_candidate_id = positive_id(text(field($event_search_row, 'id'))); if (is_present($setup_event_id)) { require_condition(equal($setup_event_id, $event_search_candidate_id), 'More than one matching record exists. Reconcile the ambiguity instead of selecting one or creating another.'); } $setup_event_id = $event_search_candidate_id; } } if (equal(field($event_search_page, 'has_more'), false)) { break; } require_condition(not_value(is_empty($event_search_rows)), 'An empty search page has has_more=true. Stop and reconcile the search.'); $event_search_offset = add_offset($event_search_offset, count($event_search_rows)); } if (not_value(is_present($setup_event_id))) { $event_write_fingerprint = journal_fingerprint((object)['name' => $desired_event_name, 'start_date' => $desired_start_date, 'end_date' => $desired_end_date, 'integration_metadata_field_1' => $external_event_key]); $event_intent = journal_begin($setup_job, 'create_event', 'POST', '/v1/events', $event_write_fingerprint); $event_create_response = call('create_event', [], (object)['name' => $desired_event_name, 'start_date' => $desired_start_date, 'end_date' => $desired_end_date, 'integration_metadata_field_1' => $external_event_key], text(field($event_intent, 'idempotency_key'))); require_condition(equal(response_status($event_create_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.'); $created_event = $event_create_response["body"]; $setup_event_id = positive_id(text(field($created_event, 'id'))); require_condition(equal(text(field($created_event, 'integration_metadata_field_1')), $external_event_key), 'The created Event\'s external key differs; preserve the pending intent and reconcile.'); require_condition(both(is_present(text(field($created_event, 'name'))), both(is_present(text(field($created_event, 'start_date'))), is_present(text(field($created_event, 'end_date'))))), 'The Event acknowledgement omitted its saved name or main dates.'); journal_acknowledge($setup_job, 'create_event', (object)['id' => $setup_event_id, 'integration_metadata_field_1' => $external_event_key]); } } $event_confirmation_response = call('confirm_event', ['id' => $setup_event_id, '$include_record_revision' => 'true'], null, null); require_condition(equal(response_status($event_confirmation_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.'); $confirmed_setup_event = $event_confirmation_response["body"]; require_condition(both(equal(text(field($confirmed_setup_event, 'id')), $setup_event_id), equal(text(field($confirmed_setup_event, 'integration_metadata_field_1')), $external_event_key)), 'The captured Event is missing or rebound; stop instead of searching for or creating a replacement.'); if (not_value(journal_completed($setup_job, 'create_event'))) { journal_adopt($setup_job, 'create_event', 'GET', '/v1/events/info', (object)['id' => text(field($confirmed_setup_event, 'id')), 'integration_metadata_field_1' => text(field($confirmed_setup_event, 'integration_metadata_field_1'))]); } $setup_event_revision = text(field($confirmed_setup_event, 'record_revision')); require_condition(is_present($setup_event_revision), 'Read the selected Event with its revision before comparing or updating it.'); require_condition(both(both(is_present(text(field($confirmed_setup_event, 'name'))), is_present(text(field($confirmed_setup_event, 'start_date')))), is_present(text(field($confirmed_setup_event, 'end_date')))), 'The selected Event must return its current name, start date and end date.'); if (journal_completed($setup_job, 'update_event')) { $recorded_event_update = journal_recorded($setup_job, 'update_event'); require_condition(both(equal(text(field($recorded_event_update, 'id')), $setup_event_id), equal(text(field($recorded_event_update, 'integration_metadata_field_1')), $external_event_key)), 'The recorded Event update has a different identity. Stop and reconcile.'); require_condition(both(both(equal(text(field($confirmed_setup_event, 'name')), $desired_event_name), equal(text(field($confirmed_setup_event, 'start_date')), $desired_start_date)), equal(text(field($confirmed_setup_event, 'end_date')), $desired_end_date)), 'The Event name or main dates changed after this job checked them. Review the current Event before writing again.'); } else { if (both(both(equal(text(field($confirmed_setup_event, 'name')), $desired_event_name), equal(text(field($confirmed_setup_event, 'start_date')), $desired_start_date)), equal(text(field($confirmed_setup_event, 'end_date')), $desired_end_date))) { journal_adopt($setup_job, 'update_event', 'GET', '/v1/events/info', (object)['id' => $setup_event_id, 'integration_metadata_field_1' => $external_event_key]); } else { require_condition(not_value(journal_acknowledged($setup_job, 'create_event')), 'The Event created by this job differs from the requested values. Inspect the saved Event before starting another update.'); $event_update_body = (object)['id' => $setup_event_id, 'expected_revision' => $setup_event_revision]; if (not_value(equal(text(field($confirmed_setup_event, 'name')), $desired_event_name))) { $event_update_body->{'name'} = $desired_event_name; } if (not_value(equal(text(field($confirmed_setup_event, 'start_date')), $desired_start_date))) { $event_update_body->{'start_date'} = $desired_start_date; } if (not_value(equal(text(field($confirmed_setup_event, 'end_date')), $desired_end_date))) { $event_update_body->{'end_date'} = $desired_end_date; } $event_update_fingerprint = journal_fingerprint($event_update_body); journal_begin($setup_job, 'update_event', 'PATCH', '/v1/events', $event_update_fingerprint); $event_update_response = call('update_event', [], $event_update_body, null); require_condition(equal(response_status($event_update_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.'); $event_update_ack = $event_update_response["body"]; $event_updated_revision = text(field($event_update_ack, 'record_revision')); require_condition(is_present($event_updated_revision), 'The conditional Event update needs its returned revision. Reconcile the pending request before continuing.'); journal_acknowledge($setup_job, 'update_event', (object)['id' => $setup_event_id, 'integration_metadata_field_1' => $external_event_key, 'record_revision' => $event_updated_revision]); } } $event_update_verify_response = call('verify_event_update', ['id' => $setup_event_id], null, null); require_condition(equal(response_status($event_update_verify_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.'); $verified_setup_event = $event_update_verify_response["body"]; require_condition(both(both(equal(text(field($verified_setup_event, 'id')), $setup_event_id), equal(text(field($verified_setup_event, 'integration_metadata_field_1')), $external_event_key)), both(both(equal(text(field($verified_setup_event, 'name')), $desired_event_name), equal(text(field($verified_setup_event, 'start_date')), $desired_start_date)), equal(text(field($verified_setup_event, 'end_date')), $desired_end_date))), 'The Event\'s current identity, name or main dates differ. Inspect the Event before continuing with setup.'); if (journal_completed($setup_job, 'create_section')) { $recorded_section = journal_recorded($setup_job, 'create_section'); $setup_section_id = positive_id(text(field($recorded_section, 'id'))); require_condition(equal(text(field($recorded_section, 'event_id')), $setup_event_id), 'The recorded Task Section belongs to a different Event.'); $recorded_section_name = text(field($recorded_section, 'name')); } else { $section_search_offset = '0'; $section_search_query = ['filter_by_event_id' => $setup_event_id, '$limit' => $setup_page_size]; while (true) { $section_search_query['$offset'] = $section_search_offset; $section_search_response = call('find_section', $section_search_query, null, null); require_condition(equal(response_status($section_search_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.'); $section_search_page = $section_search_response["body"]; $section_search_rows = items(field($section_search_page, 'list_data')); require_condition(equal(text(field($section_search_page, 'records_found')), text(count($section_search_rows))), 'records_found differs from this complete page\'s rows.'); require_condition(is_present(text(field($section_search_page, 'total_records'))), 'The search wrapper needs total_records.'); require_condition(either(equal(field($section_search_page, 'has_more'), true), equal(field($section_search_page, 'has_more'), false)), 'Expected a Boolean has_more value.'); foreach (items($section_search_rows) as $section_search_row) { require_condition(equal(text(field($section_search_row, 'event_id')), $setup_event_id), 'A section search row belongs to a different Event; stop before adopting or creating anything.'); if (equal(text(field($section_search_row, 'name')), $desired_section_name)) { $section_search_candidate_id = positive_id(text(field($section_search_row, 'id'))); if (is_present($setup_section_id)) { require_condition(equal($setup_section_id, $section_search_candidate_id), 'More than one matching record exists. Reconcile the ambiguity instead of selecting one or creating another.'); } $setup_section_id = $section_search_candidate_id; } } if (equal(field($section_search_page, 'has_more'), false)) { break; } require_condition(not_value(is_empty($section_search_rows)), 'An empty search page has has_more=true. Stop and reconcile the search.'); $section_search_offset = add_offset($section_search_offset, count($section_search_rows)); } if (not_value(is_present($setup_section_id))) { $section_write_fingerprint = journal_fingerprint((object)['event_id' => $setup_event_id, 'name' => $desired_section_name]); $section_intent = journal_begin($setup_job, 'create_section', 'POST', '/v1/tasks/sections', $section_write_fingerprint); $section_create_response = call('create_section', [], (object)['event_id' => $setup_event_id, 'name' => $desired_section_name], text(field($section_intent, 'idempotency_key'))); require_condition(equal(response_status($section_create_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.'); $created_section = $section_create_response["body"]; $setup_section_id = positive_id(text(field($created_section, 'id'))); require_condition(equal(text(field($created_section, 'event_id')), $setup_event_id), 'The created Task Section belongs to a different Event; preserve the pending intent.'); $recorded_section_name = text(field($created_section, 'name')); require_condition(is_present($recorded_section_name), 'The Task Section acknowledgement needs its actual saved name.'); journal_acknowledge($setup_job, 'create_section', (object)['id' => $setup_section_id, 'event_id' => $setup_event_id, 'name' => $recorded_section_name]); } } $section_confirmation_response = call('confirm_section', ['id' => $setup_section_id], null, null); require_condition(equal(response_status($section_confirmation_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.'); $confirmed_setup_section = $section_confirmation_response["body"]; require_condition(both(equal(text(field($confirmed_setup_section, 'id')), $setup_section_id), both(equal(text(field($confirmed_setup_section, 'event_id')), $setup_event_id), equal(text(field($confirmed_setup_section, 'name')), $recorded_section_name))), 'The captured Task Section is missing, renamed or rebound; stop instead of creating a replacement.'); if (not_value(journal_completed($setup_job, 'create_section'))) { journal_adopt($setup_job, 'create_section', 'GET', '/v1/tasks/sections/info', (object)['event_id' => text(field($confirmed_setup_section, 'event_id')), 'id' => text(field($confirmed_setup_section, 'id')), 'name' => text(field($confirmed_setup_section, 'name'))]); } $setup_dates_response = call('read_dates', ['event_id' => $setup_event_id, 'filter_by_date_type_id' => '1', '$include_record_revision' => 'true'], null, null); require_condition(equal(response_status($setup_dates_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.'); $setup_dates_page = $setup_dates_response["body"]; require_condition(both(equal(text(field($setup_dates_page, 'records_found')), '1'), both(equal(text(field($setup_dates_page, 'total_records')), '1'), equal(field($setup_dates_page, 'has_more'), false))), 'Expected one complete selected Dates group, without another page.'); $setup_dates_group = single(field($setup_dates_page, 'list_data')); require_condition(both(equal(text(field($setup_dates_group, 'event_id')), $setup_event_id), equal(text(field($setup_dates_group, 'date_type_id')), '1')), 'The Dates group belongs to another Event or type.'); $setup_dates_revision = text(field($setup_dates_group, 'record_revision')); require_condition(is_present($setup_dates_revision), 'Read the actual selected group revision before replacing it.'); if (journal_completed($setup_job, 'save_dates')) { $recorded_dates = journal_recorded($setup_job, 'save_dates'); require_condition(both(equal(text(field($recorded_dates, 'event_id')), $setup_event_id), equal(text(field($recorded_dates, 'date_type_id')), '1')), 'The recorded Dates acknowledgement belongs to another Event or group.'); } else { $setup_dates_fingerprint = journal_fingerprint((object)['event_id' => $setup_event_id, 'date_type_id' => '1', 'dates' => $desired_dates_json, 'expected_revision' => $setup_dates_revision]); journal_begin($setup_job, 'save_dates', 'PATCH', '/v1/events/dates', $setup_dates_fingerprint); $setup_dates_save_response = call('save_dates', [], (object)['event_id' => $setup_event_id, 'date_type_id' => '1', 'dates' => $desired_setup_dates, 'expected_revision' => $setup_dates_revision], null); require_condition(equal(response_status($setup_dates_save_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.'); $setup_dates_ack = $setup_dates_save_response["body"]; $setup_dates_saved_revision = text(field($setup_dates_ack, 'record_revision')); require_condition(is_present($setup_dates_saved_revision), 'The checked Dates save needs its actual returned revision.'); journal_acknowledge($setup_job, 'save_dates', (object)['event_id' => $setup_event_id, 'date_type_id' => '1', 'record_revision' => $setup_dates_saved_revision]); } $setup_dates_verify_response = call('verify_dates', ['event_id' => $setup_event_id, 'filter_by_date_type_id' => '1'], null, null); require_condition(equal(response_status($setup_dates_verify_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.'); $setup_dates_verify_page = $setup_dates_verify_response["body"]; require_condition(both(equal(text(field($setup_dates_verify_page, 'records_found')), '1'), both(equal(text(field($setup_dates_verify_page, 'total_records')), '1'), equal(field($setup_dates_verify_page, 'has_more'), false))), 'Expected one complete selected Dates group, without another page.'); $setup_dates_verify_group = single(field($setup_dates_verify_page, 'list_data')); require_condition(both(equal(text(field($setup_dates_verify_group, 'event_id')), $setup_event_id), equal(text(field($setup_dates_verify_group, 'date_type_id')), '1')), 'The Dates group belongs to another Event or type.'); require_condition(deep_equal(field($setup_dates_verify_group, 'dates'), $desired_setup_dates), 'The saved normalized Dates list differs from the supplied canonical list. Inspect it; do not automatically restore or repeat the update.'); $setup_event_readback_response = call('event_readback', ['id' => $setup_event_id], null, null); require_condition(equal(response_status($setup_event_readback_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.'); $setup_event_readback = $setup_event_readback_response["body"]; require_condition(both(equal(text(field($setup_event_readback, 'id')), $setup_event_id), equal(text(field($setup_event_readback, 'integration_metadata_field_1')), $external_event_key)), 'Final Event readback is missing or rebound; earlier steps remain saved.'); require_condition(both(both(equal(text(field($setup_event_readback, 'name')), $desired_event_name), equal(text(field($setup_event_readback, 'start_date')), $desired_start_date)), equal(text(field($setup_event_readback, 'end_date')), $desired_end_date)), 'The Event name or main dates changed before final readback. Inspect the Event before starting another update.'); $planning_section_present = false; foreach (items(items(field($setup_event_readback, 'task_sections'))) as $setup_event_section) { if (equal(text(field($setup_event_section, 'id')), $setup_section_id)) { $planning_section_present = true; } } require_condition($planning_section_present, 'The Event\'s current Task Sections do not include the recorded section; inspect it rather than creating another.'); print_value((object)['event_id' => $setup_event_id, 'task_section_id' => $setup_section_id, 'dates_verified' => 'true']); } finally { $setup_job->close(); } } if (realpath($_SERVER['SCRIPT_FILENAME'] ?? '') === __FILE__) main(); ``` ```ruby # 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":true,"requests":{"workspace_binding":{"method":"GET","path":"/references/workspace_info"},"find_existing":{"method":"GET","path":"/events"},"create_event":{"method":"POST","path":"/events"},"confirm_event":{"method":"GET","path":"/events/info"},"update_event":{"method":"PATCH","path":"/events"},"verify_event_update":{"method":"GET","path":"/events/info"},"find_section":{"method":"GET","path":"/tasks/sections"},"create_section":{"method":"POST","path":"/tasks/sections"},"confirm_section":{"method":"GET","path":"/tasks/sections/info"},"read_dates":{"method":"GET","path":"/events/dates"},"save_dates":{"method":"PATCH","path":"/events/dates"},"verify_dates":{"method":"GET","path":"/events/dates"},"event_readback":{"method":"GET","path":"/events/info"}}}') API_KEY = ENV.fetch('EXHIBITDAY_API_KEY') raise 'Use the API key as one ASCII header value without control characters' if API_KEY.each_codepoint.any?{|point|point<32||point>126} 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, 'DELETE' => Net::HTTP::Delete }.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, key = nil) route = SPEC.fetch('requests').fetch(name) headers = { 'Authorization' => 'Bearer ' + API_KEY, 'Accept' => 'application/json' } if route.fetch('method') == 'POST' headers['Idempotency-Key'] = key || raise('Persist a logical create key before sending POST') # 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) # 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.fetch('method') == 'GET' 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 = resend && (status == 429 || (500..599).cover?(status)) 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, raw: raw } end raise 'Retry limit reached' end def add_offset(offset,received) result=Integer(offset)+received raise "Cannot advance this int32 offset; reconcile the query" if received<=0 || result>2147483647 result.to_s end def both(left,right);left&&right;end def items(value) raise "Expected a JSON array" unless value.is_a?(Array) value end def count(value) items(value).length end def deep_equal(left,right) return false unless left.class==right.class if left.is_a?(Hash) return left.keys.sort==right.keys.sort&&left.all?{|key,value|deep_equal(value,right[key])} end return left.length==right.length&&left.zip(right).all?{|a,b|deep_equal(a,b)} if left.is_a?(Array) left==right end def either(left,right) raise "Expected Boolean criteria" unless [true,false].include?(left) && [true,false].include?(right) left || right end def equal(left,right) left.class==right.class && left==right end def field(value,name) raise "Missing response field: #{name}" unless value.is_a?(Hash) && value.key?(name) value.fetch(name) end def is_empty(value) count(value)==0 end def is_present(value) !value.nil? && value!="" end require 'digest' require 'securerandom' require 'uri' # Private client restart state, with no transport or application dependency. module GuideJournalProtocol PREAMBLE="EXHIBITDAY-GUIDE-JOURNAL 1\n".b.freeze class Refusal < StandardError; end def self.utf8(value) raise Refusal,'Journal fields are exact strings' unless value.is_a?(String)&&value.valid_encoding? raw=value.encode(Encoding::UTF_8) raise Refusal,'Invalid UTF8 journal field' unless raw.valid_encoding? raw.b end def self.strings(values) values.map{|value|raw=utf8(value);raw.bytesize.to_s.b+':'.b+raw}.join.b end def self.read_strings(raw) values=[];offset=0 while offsetraw.bytesize-offset value=raw.byteslice(offset,size).dup.force_encoding(Encoding::UTF_8);raise Refusal,'Invalid UTF8 string' unless value.valid_encoding? values<=raw.bytesize-offset payload=raw.byteslice(offset,size);offset+=size raise Refusal,'Journal integrity failed; reconcile before retry' unless raw.getbyte(offset)==10&&digest(payload)==match[2] records<0 offset+=written end file.flush;file.fsync end end class GuideJournal P=GuideJournalProtocol def initialize(path,base,workspace,slug,job,input_fingerprint,writes,mode='resume') @path=path.dup;@lock_path=path+'.lock';@file=nil;@owned=false;@tainted=false;@intents={};@saved={};@adopted={};@allowed={} address=URI(base) raise P::Refusal,'Use actual API base and closed guide slug' unless ['https','http'].include?(address.scheme)&&address.host&&address.userinfo.nil?&&address.query.nil?&&address.fragment.nil?&&slug.match?(/\A[a-z][a-z0-9-]*\z/) raise P::Refusal,'Use actual workspace, stable explicit job ID and exact fingerprint' unless !job.strip.empty?&&workspace.match?(/\A[1-9][0-9]*\z/)&&input_fingerprint.match?(/\A[0-9A-F]{64}\z/) raise P::Refusal,'Choose new or resume for this local job' unless ['new','resume'].include?(mode) manifest=[] writes.each do|step,method,route| raise P::Refusal,'Use closed unique write manifest' unless step.match?(/\A[a-z][a-z0-9_-]*\z/)&&!@allowed.key?(step)&&['POST','PATCH','DELETE'].include?(method)&&route.match?(/\A\/v1\/[A-Za-z0-9_\/-]+\z/)&&!route.include?('//') @allowed[step.dup.freeze]=[method.dup.freeze,route.dup.freeze].freeze;manifest.concat([step,method,route]) end raise P::Refusal,'Only write workflows need a restart journal' if @allowed.empty? @header=['H','1',base,workspace,slug,job,input_fingerprint,P.digest(P.strings(manifest))].map{|value|value.dup.freeze}.freeze;P.strings(@header) begin @file=File.open(@lock_path,File::RDWR|File::CREAT|File::EXCL,0o600);@file.binmode;@owned=true rescue Errno::EEXIST raise P::Refusal,'This journal is locked; do not overlap jobs or steal a stale lock' end begin @owner=SecureRandom.hex(16).freeze;P.write_all(@file,@owner.b);@identity=@file.stat # Ruby's Windows fstat reports dev=0 while lstat reports the drive number. # Both expose the same exact inode. Retain it plus the initial path device; # compare like-for-like instead of treating the differing dev APIs as equal. named_identity=File.lstat(@lock_path);raise P::Refusal,'Lock identity did not bind' unless named_identity.ino==@identity.ino @path_device=named_identity.dev raise P::Refusal,'Choose a private regular journal file' if File.symlink?(@path) raise P::Refusal,'Journal missing: stop and reconcile lost state before starting a new logical job' if mode=='resume'&&!File.exist?(@path) raise P::Refusal,'Journal exists; use resume for the same logical job' if mode=='new'&&File.exist?(@path) if mode=='new' File.open(@path,File::WRONLY|File::CREAT|File::EXCL,0o600){|target|target.binmode;P.write_all(target,P::PREAMBLE+P.frame(@header))} end records=P.decode(File.binread(@path));raise P::Refusal,'Journal workspace/base/guide/job/input binding differs' if records.empty?||records[0]!=@header records.drop(1).each{|record|apply(record)} raise P::Refusal,'Saved intent lacks ACK; stop and reconcile before retry' if @intents.keys.any?{|step|!@saved.key?(step)} rescue Exception close;raise end end def apply(record) case record[0] when 'I' raise P::Refusal,'Invalid intent shape' unless record.length==6 _,step,method,route,fingerprint,key=record raise P::Refusal,'Invalid, future or repeated intent' unless step.match?(/\A[a-z][a-z0-9_-]*\z/)&&!@intents.key?(step)&&!@adopted.key?(step)&&@allowed[step]==[method,route]&&fingerprint.match?(/\A[0-9A-F]{64}\z/)&&!@intents.keys.any?{|name|!@saved.key?(name)} raise P::Refusal,'Invalid persisted action key' unless (method=='POST'&&key.match?(/\A[0-9a-f]{32}\z/))||(method!='POST'&&key=='') @intents[step.dup.freeze]={'method'=>method.dup.freeze,'path'=>route.dup.freeze,'request_fingerprint'=>fingerprint.dup.freeze,'idempotency_key'=>key.dup.freeze}.freeze when 'A' raise P::Refusal,'Invalid ACK shape' unless record.length>=3 _,step,count,*pairs=record raise P::Refusal,'ACK without exactly one prior intent' unless count.match?(/\A(?:0|[1-9][0-9]*)\z/)&&pairs.length==2*count.to_i&&@intents.key?(step)&&!@saved.key?(step) names=pairs.each_slice(2).map(&:first) raise P::Refusal,'ACK fields must be unique sorted secret-free identifiers' unless names==names.uniq.sort&&names.all?{|name|name.match?(/\A[a-z][a-z0-9_]*\z/)&&!['api_key','exhibitday_api_key'].include?(name)} @saved[step.dup.freeze]=pairs.each_slice(2).to_h.transform_values{|value|value.dup.freeze}.freeze when 'S' raise P::Refusal,'Invalid read-adoption shape' unless record.length>=6 _,step,method,route,read_fingerprint,count,*pairs=record completed=(@saved.keys+@adopted.keys).uniq;order=@allowed.keys raise P::Refusal,'Adopt only the exact next setup action without any pending intent' unless completed.length9223372036854775807)} raise P::Refusal,'Read-adoption material must be complete and fingerprint-bound' if fields.any?{|name|!['id','event_id'].include?(name)&&saved[name].empty?}||read_fingerprint!=P.fingerprint(saved) @adopted[step.dup.freeze]=saved.transform_values{|value|value.dup.freeze}.freeze else raise P::Refusal,'Unknown journal transition' end end def require_active raise P::Refusal,'Journal is closed or IO outcome needs reconciliation' unless @owned&&@file&&!@tainted current=File.lstat(@lock_path) raise P::Refusal,'Journal lock replaced; stop without deleting it' unless current.dev==@path_device&¤t.ino==@identity.ino&&File.binread(@lock_path)==@owner.b end def append(record) require_active;raw=P.frame(record) begin File.open(@path,'ab'){|target|P.write_all(target,raw)} rescue Exception @tainted=true;raise end end def acknowledged(step);require_active;@saved.key?(step);end def saved(step) require_active;raise P::Refusal,'No acknowledged state exists' unless @saved.key?(step) @saved.fetch(step).transform_values(&:dup) end def completed(step);require_active;@saved.key?(step)||@adopted.key?(step);end def adopted(step);require_active;@adopted.key?(step);end def recorded(step);require_active;raise P::Refusal,'No completed write or read-adoption exists' unless completed(step);(@saved[step]||@adopted[step]).transform_values(&:dup);end def adopt(step,method,route,saved) require_active;record=['S',step,method,route,P.fingerprint(saved),saved.length.to_s];saved.keys.sort.each{|name|record.concat([name,saved[name]])};previous=@adopted.dup begin;apply(record);P.strings(record);ensure;@adopted=previous;end append(record);apply(record) end def begin_action(step,method,route,request_fingerprint) require_active;raise P::Refusal,'Never blindly repeat an action' if @intents.key?(step) record=['I',step,method,route,request_fingerprint,method=='POST'?SecureRandom.hex(16):''] previous=@intents.dup;begin;apply(record);ensure;@intents=previous;end append(record);apply(record);@intents.fetch(step).transform_values(&:dup) end def acknowledge(step,saved) require_active;record=['A',step,saved.length.to_s];saved.keys.sort.each{|name|record.concat([name,saved.fetch(name)])} previous=@saved.dup;begin;apply(record);P.strings(record);ensure;@saved=previous;end append(record);apply(record) end def close return unless @owned if @tainted;@file.close;@file=nil;@owned=false;return;end begin;require_active;rescue Exception;@file.close;@file=nil;@owned=false;raise;end @file.close;@file=nil;@owned=false;File.unlink(@lock_path) end end def journal_values(value) raise GuideJournalProtocol::Refusal,'Saved/fingerprint values must be exact strings' unless value.is_a?(Hash)&&value.all?{|name,item|name.is_a?(String)&&item.is_a?(String)} value.transform_values(&:dup) end def journal_acknowledge(job,step,saved);job.acknowledge(step,journal_values(saved));end def journal_acknowledged(job,step);job.acknowledged(step);end def journal_adopt(job,step,method,path,saved);job.adopt(step,method,path,journal_values(saved));end def journal_begin(job,step,method,path,request_fingerprint);job.begin_action(step,method,path,request_fingerprint);end def journal_completed(job,step);job.completed(step);end def journal_fingerprint(value);GuideJournalProtocol.fingerprint(journal_values(value));end def journal_recorded(job,step);job.recorded(step);end def not_value(value) raise "Expected a Boolean" unless value==true || value==false !value end def open_journal(path,base,workspace,slug,job,input_fingerprint,writes,mode);GuideJournal.new(path,base,workspace,slug,job,input_fingerprint,writes,mode);end def optional(name,fallback) value=ENV[name] value.nil? || value.empty? ? fallback : value end def page_size(value) raise "Page size must be a positive int32" unless /\A[1-9][0-9]*\z/.match?(value) && Integer(value)<=2147483647 value end class WorkflowInputObject(node){case node;when Hash;node.each_with_object({}){|(key,item),memo|memo[key]=copy.call(item)};when Array;node.map{|item|copy.call(item)};when Float;raise'Use finite JSON numbers' unless node.finite?;node;else;node;end} copy.call(result) end def positive_id(value) raise "Use a positive record ID" unless /\A[1-9][0-9]*\z/.match?(value) && Integer(value)<=9223372036854775807 value end def print_value(value) STDOUT.binmode.write((value.is_a?(String)?value:JSON.generate(value))+"\n") end def require_condition(value,message) raise message unless value==true end def required(name) value=ENV[name] raise "Set #{name}" if value.nil? || value.strip.empty? value end def response_status(value);value.fetch(:status).to_s;end def single(value);rows=items(value);raise 'Expected exactly one selected record' unless rows.length==1;rows[0];end def text(value) return "" if value.nil? return value.to_s if value.is_a?(String)||value.is_a?(Integer)||value==true||value==false raise "Expected a scalar response value" end def validate_crm_event_inputs(key, name, start_date, end_date) boundary = /\A[\u0009-\u000D\u0020\u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]|[\u0009-\u000D\u0020\u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]\z/ [[name,'EXHIBITDAY_EVENT_NAME',500],[key,'EXHIBITDAY_EXTERNAL_EVENT_KEY',3000]].each do |value,label,limit| GuideJournalProtocol.utf8(value) raise GuideJournalProtocol::Refusal,'Remove whitespace at the start or end of '+label if value.empty? || boundary.match?(value) raise GuideJournalProtocol::Refusal,label+" exceeds #{limit} UTF-16 code units" if value.encode('UTF-16LE').bytesize / 2 > limit end if name.match?(/[<>\r\n]/) || name.downcase == 'null' raise GuideJournalProtocol::Refusal,'Use plain, single-line EXHIBITDAY_EVENT_NAME text other than null' end [[start_date,'EXHIBITDAY_START_DATE'],[end_date,'EXHIBITDAY_END_DATE']].each do |value,label| match = /\A([0-9]{4})-([0-9]{2})-([0-9]{2})\z/.match(value) unless match && match[1].to_i >= 1753 && Date.valid_date?(*match.captures.map(&:to_i)) raise GuideJournalProtocol::Refusal,label+' must be a calendar date in YYYY-MM-DD on or after 1753-01-01' end end raise GuideJournalProtocol::Refusal,'EXHIBITDAY_END_DATE must be on or after EXHIBITDAY_START_DATE' if end_date < start_date end def main external_event_key = required('EXHIBITDAY_EXTERNAL_EVENT_KEY') desired_event_name = required('EXHIBITDAY_EVENT_NAME') desired_start_date = required('EXHIBITDAY_START_DATE') desired_end_date = required('EXHIBITDAY_END_DATE') desired_dates_json = required('EXHIBITDAY_EXHIBIT_DATES_JSON') desired_section_name = optional('EXHIBITDAY_TASK_SECTION_NAME', 'Pre-event planning') setup_page_size = page_size(optional('EXHIBITDAY_PAGE_SIZE', '100')) desired_setup_dates = items(parse_json(desired_dates_json)) validate_crm_event_inputs(external_event_key, desired_event_name, desired_start_date, desired_end_date) journal_path = required('EXHIBITDAY_JOURNAL') stable_job_id = required('EXHIBITDAY_JOB_ID') job_mode = optional('EXHIBITDAY_JOB_MODE', 'resume') setup_workspace_response = call('workspace_binding', {}, nil, nil) require_condition(equal(response_status(setup_workspace_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.') setup_workspace = setup_workspace_response.fetch(:body) owned_workspace_id = positive_id(text(field(setup_workspace, 'id'))) setup_input_fingerprint = journal_fingerprint({'workflow_contract_sha256' => '19097A09AE2D22C1AF56F5D4FBD9B72F524E5EC195434BC315834CC8C2417C32', 'external_event_key' => external_event_key, 'name' => desired_event_name, 'start_date' => desired_start_date, 'end_date' => desired_end_date, 'section_name' => desired_section_name, 'dates' => desired_dates_json}) setup_job = open_journal(journal_path, 'https://api.exhibitday.com/v1', owned_workspace_id, 'event-setup-crm', stable_job_id, setup_input_fingerprint, [['create_event', 'POST', '/v1/events'], ['update_event', 'PATCH', '/v1/events'], ['create_section', 'POST', '/v1/tasks/sections'], ['save_dates', 'PATCH', '/v1/events/dates']], job_mode) begin setup_event_id = '' setup_section_id = '' recorded_section_name = desired_section_name if journal_completed(setup_job, 'create_event') recorded_event = journal_recorded(setup_job, 'create_event') setup_event_id = positive_id(text(field(recorded_event, 'id'))) require_condition(equal(text(field(recorded_event, 'integration_metadata_field_1')), external_event_key), 'The journal\'s completed Event differs from this external key.') else event_search_offset = '0' event_search_query = {'filter_by_integration_metadata_field_1' => external_event_key, '$limit' => setup_page_size} while true event_search_query['$offset'] = event_search_offset event_search_response = call('find_existing', event_search_query, nil, nil) require_condition(equal(response_status(event_search_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.') event_search_page = event_search_response.fetch(:body) event_search_rows = items(field(event_search_page, 'list_data')) require_condition(equal(text(field(event_search_page, 'records_found')), text(count(event_search_rows))), 'records_found differs from this complete page\'s rows.') require_condition(is_present(text(field(event_search_page, 'total_records'))), 'The search wrapper needs total_records.') require_condition(either(equal(field(event_search_page, 'has_more'), true), equal(field(event_search_page, 'has_more'), false)), 'Expected a Boolean has_more value.') items(event_search_rows).each do |event_search_row| if equal(text(field(event_search_row, 'integration_metadata_field_1')), external_event_key) event_search_candidate_id = positive_id(text(field(event_search_row, 'id'))) if is_present(setup_event_id) require_condition(equal(setup_event_id, event_search_candidate_id), 'More than one matching record exists. Reconcile the ambiguity instead of selecting one or creating another.') end setup_event_id = event_search_candidate_id end end if equal(field(event_search_page, 'has_more'), false) break end require_condition(not_value(is_empty(event_search_rows)), 'An empty search page has has_more=true. Stop and reconcile the search.') event_search_offset = add_offset(event_search_offset, count(event_search_rows)) end if not_value(is_present(setup_event_id)) event_write_fingerprint = journal_fingerprint({'name' => desired_event_name, 'start_date' => desired_start_date, 'end_date' => desired_end_date, 'integration_metadata_field_1' => external_event_key}) event_intent = journal_begin(setup_job, 'create_event', 'POST', '/v1/events', event_write_fingerprint) event_create_response = call('create_event', {}, {'name' => desired_event_name, 'start_date' => desired_start_date, 'end_date' => desired_end_date, 'integration_metadata_field_1' => external_event_key}, text(field(event_intent, 'idempotency_key'))) require_condition(equal(response_status(event_create_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.') created_event = event_create_response.fetch(:body) setup_event_id = positive_id(text(field(created_event, 'id'))) require_condition(equal(text(field(created_event, 'integration_metadata_field_1')), external_event_key), 'The created Event\'s external key differs; preserve the pending intent and reconcile.') require_condition(both(is_present(text(field(created_event, 'name'))), both(is_present(text(field(created_event, 'start_date'))), is_present(text(field(created_event, 'end_date'))))), 'The Event acknowledgement omitted its saved name or main dates.') journal_acknowledge(setup_job, 'create_event', {'id' => setup_event_id, 'integration_metadata_field_1' => external_event_key}) end end event_confirmation_response = call('confirm_event', {'id' => setup_event_id, '$include_record_revision' => 'true'}, nil, nil) require_condition(equal(response_status(event_confirmation_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.') confirmed_setup_event = event_confirmation_response.fetch(:body) require_condition(both(equal(text(field(confirmed_setup_event, 'id')), setup_event_id), equal(text(field(confirmed_setup_event, 'integration_metadata_field_1')), external_event_key)), 'The captured Event is missing or rebound; stop instead of searching for or creating a replacement.') if not_value(journal_completed(setup_job, 'create_event')) journal_adopt(setup_job, 'create_event', 'GET', '/v1/events/info', {'id' => text(field(confirmed_setup_event, 'id')), 'integration_metadata_field_1' => text(field(confirmed_setup_event, 'integration_metadata_field_1'))}) end setup_event_revision = text(field(confirmed_setup_event, 'record_revision')) require_condition(is_present(setup_event_revision), 'Read the selected Event with its revision before comparing or updating it.') require_condition(both(both(is_present(text(field(confirmed_setup_event, 'name'))), is_present(text(field(confirmed_setup_event, 'start_date')))), is_present(text(field(confirmed_setup_event, 'end_date')))), 'The selected Event must return its current name, start date and end date.') if journal_completed(setup_job, 'update_event') recorded_event_update = journal_recorded(setup_job, 'update_event') require_condition(both(equal(text(field(recorded_event_update, 'id')), setup_event_id), equal(text(field(recorded_event_update, 'integration_metadata_field_1')), external_event_key)), 'The recorded Event update has a different identity. Stop and reconcile.') require_condition(both(both(equal(text(field(confirmed_setup_event, 'name')), desired_event_name), equal(text(field(confirmed_setup_event, 'start_date')), desired_start_date)), equal(text(field(confirmed_setup_event, 'end_date')), desired_end_date)), 'The Event name or main dates changed after this job checked them. Review the current Event before writing again.') else if both(both(equal(text(field(confirmed_setup_event, 'name')), desired_event_name), equal(text(field(confirmed_setup_event, 'start_date')), desired_start_date)), equal(text(field(confirmed_setup_event, 'end_date')), desired_end_date)) journal_adopt(setup_job, 'update_event', 'GET', '/v1/events/info', {'id' => setup_event_id, 'integration_metadata_field_1' => external_event_key}) else require_condition(not_value(journal_acknowledged(setup_job, 'create_event')), 'The Event created by this job differs from the requested values. Inspect the saved Event before starting another update.') event_update_body = {'id' => setup_event_id, 'expected_revision' => setup_event_revision} if not_value(equal(text(field(confirmed_setup_event, 'name')), desired_event_name)) event_update_body['name'] = desired_event_name end if not_value(equal(text(field(confirmed_setup_event, 'start_date')), desired_start_date)) event_update_body['start_date'] = desired_start_date end if not_value(equal(text(field(confirmed_setup_event, 'end_date')), desired_end_date)) event_update_body['end_date'] = desired_end_date end event_update_fingerprint = journal_fingerprint(event_update_body) journal_begin(setup_job, 'update_event', 'PATCH', '/v1/events', event_update_fingerprint) event_update_response = call('update_event', {}, event_update_body, nil) require_condition(equal(response_status(event_update_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.') event_update_ack = event_update_response.fetch(:body) event_updated_revision = text(field(event_update_ack, 'record_revision')) require_condition(is_present(event_updated_revision), 'The conditional Event update needs its returned revision. Reconcile the pending request before continuing.') journal_acknowledge(setup_job, 'update_event', {'id' => setup_event_id, 'integration_metadata_field_1' => external_event_key, 'record_revision' => event_updated_revision}) end end event_update_verify_response = call('verify_event_update', {'id' => setup_event_id}, nil, nil) require_condition(equal(response_status(event_update_verify_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.') verified_setup_event = event_update_verify_response.fetch(:body) require_condition(both(both(equal(text(field(verified_setup_event, 'id')), setup_event_id), equal(text(field(verified_setup_event, 'integration_metadata_field_1')), external_event_key)), both(both(equal(text(field(verified_setup_event, 'name')), desired_event_name), equal(text(field(verified_setup_event, 'start_date')), desired_start_date)), equal(text(field(verified_setup_event, 'end_date')), desired_end_date))), 'The Event\'s current identity, name or main dates differ. Inspect the Event before continuing with setup.') if journal_completed(setup_job, 'create_section') recorded_section = journal_recorded(setup_job, 'create_section') setup_section_id = positive_id(text(field(recorded_section, 'id'))) require_condition(equal(text(field(recorded_section, 'event_id')), setup_event_id), 'The recorded Task Section belongs to a different Event.') recorded_section_name = text(field(recorded_section, 'name')) else section_search_offset = '0' section_search_query = {'filter_by_event_id' => setup_event_id, '$limit' => setup_page_size} while true section_search_query['$offset'] = section_search_offset section_search_response = call('find_section', section_search_query, nil, nil) require_condition(equal(response_status(section_search_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.') section_search_page = section_search_response.fetch(:body) section_search_rows = items(field(section_search_page, 'list_data')) require_condition(equal(text(field(section_search_page, 'records_found')), text(count(section_search_rows))), 'records_found differs from this complete page\'s rows.') require_condition(is_present(text(field(section_search_page, 'total_records'))), 'The search wrapper needs total_records.') require_condition(either(equal(field(section_search_page, 'has_more'), true), equal(field(section_search_page, 'has_more'), false)), 'Expected a Boolean has_more value.') items(section_search_rows).each do |section_search_row| require_condition(equal(text(field(section_search_row, 'event_id')), setup_event_id), 'A section search row belongs to a different Event; stop before adopting or creating anything.') if equal(text(field(section_search_row, 'name')), desired_section_name) section_search_candidate_id = positive_id(text(field(section_search_row, 'id'))) if is_present(setup_section_id) require_condition(equal(setup_section_id, section_search_candidate_id), 'More than one matching record exists. Reconcile the ambiguity instead of selecting one or creating another.') end setup_section_id = section_search_candidate_id end end if equal(field(section_search_page, 'has_more'), false) break end require_condition(not_value(is_empty(section_search_rows)), 'An empty search page has has_more=true. Stop and reconcile the search.') section_search_offset = add_offset(section_search_offset, count(section_search_rows)) end if not_value(is_present(setup_section_id)) section_write_fingerprint = journal_fingerprint({'event_id' => setup_event_id, 'name' => desired_section_name}) section_intent = journal_begin(setup_job, 'create_section', 'POST', '/v1/tasks/sections', section_write_fingerprint) section_create_response = call('create_section', {}, {'event_id' => setup_event_id, 'name' => desired_section_name}, text(field(section_intent, 'idempotency_key'))) require_condition(equal(response_status(section_create_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.') created_section = section_create_response.fetch(:body) setup_section_id = positive_id(text(field(created_section, 'id'))) require_condition(equal(text(field(created_section, 'event_id')), setup_event_id), 'The created Task Section belongs to a different Event; preserve the pending intent.') recorded_section_name = text(field(created_section, 'name')) require_condition(is_present(recorded_section_name), 'The Task Section acknowledgement needs its actual saved name.') journal_acknowledge(setup_job, 'create_section', {'id' => setup_section_id, 'event_id' => setup_event_id, 'name' => recorded_section_name}) end end section_confirmation_response = call('confirm_section', {'id' => setup_section_id}, nil, nil) require_condition(equal(response_status(section_confirmation_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.') confirmed_setup_section = section_confirmation_response.fetch(:body) require_condition(both(equal(text(field(confirmed_setup_section, 'id')), setup_section_id), both(equal(text(field(confirmed_setup_section, 'event_id')), setup_event_id), equal(text(field(confirmed_setup_section, 'name')), recorded_section_name))), 'The captured Task Section is missing, renamed or rebound; stop instead of creating a replacement.') if not_value(journal_completed(setup_job, 'create_section')) journal_adopt(setup_job, 'create_section', 'GET', '/v1/tasks/sections/info', {'event_id' => text(field(confirmed_setup_section, 'event_id')), 'id' => text(field(confirmed_setup_section, 'id')), 'name' => text(field(confirmed_setup_section, 'name'))}) end setup_dates_response = call('read_dates', {'event_id' => setup_event_id, 'filter_by_date_type_id' => '1', '$include_record_revision' => 'true'}, nil, nil) require_condition(equal(response_status(setup_dates_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.') setup_dates_page = setup_dates_response.fetch(:body) require_condition(both(equal(text(field(setup_dates_page, 'records_found')), '1'), both(equal(text(field(setup_dates_page, 'total_records')), '1'), equal(field(setup_dates_page, 'has_more'), false))), 'Expected one complete selected Dates group, without another page.') setup_dates_group = single(field(setup_dates_page, 'list_data')) require_condition(both(equal(text(field(setup_dates_group, 'event_id')), setup_event_id), equal(text(field(setup_dates_group, 'date_type_id')), '1')), 'The Dates group belongs to another Event or type.') setup_dates_revision = text(field(setup_dates_group, 'record_revision')) require_condition(is_present(setup_dates_revision), 'Read the actual selected group revision before replacing it.') if journal_completed(setup_job, 'save_dates') recorded_dates = journal_recorded(setup_job, 'save_dates') require_condition(both(equal(text(field(recorded_dates, 'event_id')), setup_event_id), equal(text(field(recorded_dates, 'date_type_id')), '1')), 'The recorded Dates acknowledgement belongs to another Event or group.') else setup_dates_fingerprint = journal_fingerprint({'event_id' => setup_event_id, 'date_type_id' => '1', 'dates' => desired_dates_json, 'expected_revision' => setup_dates_revision}) journal_begin(setup_job, 'save_dates', 'PATCH', '/v1/events/dates', setup_dates_fingerprint) setup_dates_save_response = call('save_dates', {}, {'event_id' => setup_event_id, 'date_type_id' => '1', 'dates' => desired_setup_dates, 'expected_revision' => setup_dates_revision}, nil) require_condition(equal(response_status(setup_dates_save_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.') setup_dates_ack = setup_dates_save_response.fetch(:body) setup_dates_saved_revision = text(field(setup_dates_ack, 'record_revision')) require_condition(is_present(setup_dates_saved_revision), 'The checked Dates save needs its actual returned revision.') journal_acknowledge(setup_job, 'save_dates', {'event_id' => setup_event_id, 'date_type_id' => '1', 'record_revision' => setup_dates_saved_revision}) end setup_dates_verify_response = call('verify_dates', {'event_id' => setup_event_id, 'filter_by_date_type_id' => '1'}, nil, nil) require_condition(equal(response_status(setup_dates_verify_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.') setup_dates_verify_page = setup_dates_verify_response.fetch(:body) require_condition(both(equal(text(field(setup_dates_verify_page, 'records_found')), '1'), both(equal(text(field(setup_dates_verify_page, 'total_records')), '1'), equal(field(setup_dates_verify_page, 'has_more'), false))), 'Expected one complete selected Dates group, without another page.') setup_dates_verify_group = single(field(setup_dates_verify_page, 'list_data')) require_condition(both(equal(text(field(setup_dates_verify_group, 'event_id')), setup_event_id), equal(text(field(setup_dates_verify_group, 'date_type_id')), '1')), 'The Dates group belongs to another Event or type.') require_condition(deep_equal(field(setup_dates_verify_group, 'dates'), desired_setup_dates), 'The saved normalized Dates list differs from the supplied canonical list. Inspect it; do not automatically restore or repeat the update.') setup_event_readback_response = call('event_readback', {'id' => setup_event_id}, nil, nil) require_condition(equal(response_status(setup_event_readback_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.') setup_event_readback = setup_event_readback_response.fetch(:body) require_condition(both(equal(text(field(setup_event_readback, 'id')), setup_event_id), equal(text(field(setup_event_readback, 'integration_metadata_field_1')), external_event_key)), 'Final Event readback is missing or rebound; earlier steps remain saved.') require_condition(both(both(equal(text(field(setup_event_readback, 'name')), desired_event_name), equal(text(field(setup_event_readback, 'start_date')), desired_start_date)), equal(text(field(setup_event_readback, 'end_date')), desired_end_date)), 'The Event name or main dates changed before final readback. Inspect the Event before starting another update.') planning_section_present = false items(items(field(setup_event_readback, 'task_sections'))).each do |setup_event_section| if equal(text(field(setup_event_section, 'id')), setup_section_id) planning_section_present = true end end require_condition(planning_section_present, 'The Event\'s current Task Sections do not include the recorded section; inspect it rather than creating another.') print_value({'event_id' => setup_event_id, 'task_section_id' => setup_section_id, 'dates_verified' => 'true'}) ensure setup_job.close() end end main if $PROGRAM_NAME == __FILE__ ``` ```go // Go 1.18+; standard library only. Set EXHIBITDAY_API_KEY. package main import ( "bytes" "crypto/rand" "crypto/sha256" "encoding/hex" "regexp" "sort" "unicode/utf8" "encoding/json" "fmt" "io" "net/http" "net/url" "os" "strconv" "strings" "time" ) const base = "https://api.exhibitday.com/v1" const specification = "{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"find_existing\":{\"method\":\"GET\",\"path\":\"/events\"},\"create_event\":{\"method\":\"POST\",\"path\":\"/events\"},\"confirm_event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"update_event\":{\"method\":\"PATCH\",\"path\":\"/events\"},\"verify_event_update\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"find_section\":{\"method\":\"GET\",\"path\":\"/tasks/sections\"},\"create_section\":{\"method\":\"POST\",\"path\":\"/tasks/sections\"},\"confirm_section\":{\"method\":\"GET\",\"path\":\"/tasks/sections/info\"},\"read_dates\":{\"method\":\"GET\",\"path\":\"/events/dates\"},\"save_dates\":{\"method\":\"PATCH\",\"path\":\"/events/dates\"},\"verify_dates\":{\"method\":\"GET\",\"path\":\"/events/dates\"},\"event_readback\":{\"method\":\"GET\",\"path\":\"/events/info\"}}}" 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 }} var send = client.Do type result struct { status int; body any; headers http.Header; raw []byte } // 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 call(name string, query map[string]string, body any, key string) result { route := object(object(spec["requests"])[name]); method := text(route["method"]) headers := map[string]string{"Authorization": "Bearer " + apiKey, "Accept": "application/json"} if method == "POST" { if key == "" { panic("Persist a logical create key before sending POST") }; 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() } // 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 := method == "GET" 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 := send(request) if err != nil { if !resend { panic(apiError{0, "", "No response", true}) }; if attempt == 4 { panic(err) }; time.Sleep(time.Second*time.Duration(1<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 := resend && (response.StatusCode == 429 || response.StatusCode >= 500) if retry { if attempt == 4 { panic("Retry limit reached; check the outcome before starting a new create") } seconds := float64(int64(1)<= 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, raw} } panic("Retry limit reached") } func add_offset(offset string,received int64)string{previous,err:=strconv.ParseInt(offset,10,32);if err!=nil||received<=0||received>2147483647-previous{panic("Cannot advance this int32 offset; reconcile the query")};return strconv.FormatInt(previous+received,10)} func both(left,right bool)bool{return left&&right} func items(value any)[]any{result,ok:=value.([]any);if !ok{panic("Expected a JSON array")};return result} func count(value any)int64{return int64(len(items(value)))} func deep_equal(left,right any)bool{a,e:=json.Marshal(left);if e!=nil{panic(e)};b,e:=json.Marshal(right);if e!=nil{panic(e)};return string(a)==string(b)} func either(left,right bool)bool{return left||right} func equal(left,right any)bool{switch a:=left.(type){case string:b,ok:=right.(string);return ok&&a==b;case bool:b,ok:=right.(bool);return ok&&a==b;case int64:b,ok:=right.(int64);return ok&&a==b};return left==nil&&right==nil} func field(value any,name string)any{obj,ok:=value.(map[string]any);if !ok{panic("Missing response object")};item,found:=obj[name];if !found{panic("Missing response field: "+name)};return item} func is_empty(value any)bool{return count(value)==0} func is_present(value string)bool{return value!=""} // Private client restart state only; no API transport or workflow interpreter. const journalPreamble = "EXHIBITDAY-GUIDE-JOURNAL 1\n" type journalRefusal struct{ message string } func (e journalRefusal) Error() string { return e.message } func journalNeed(ok bool, message string) { if !ok { panic(journalRefusal{message}) } } func journalMatch(value, pattern string) bool { return regexp.MustCompile("\\A(?:"+pattern+")\\z").MatchString(value) } func journalStrings(values []string) []byte { var output bytes.Buffer for _,value:=range values { journalNeed(utf8.ValidString(value),"Journal fields must be valid UTF8 strings"); output.WriteString(strconv.Itoa(len(value))+":");output.WriteString(value) } return output.Bytes() } func journalReadStrings(raw []byte) []string { values:=[]string{};offset:=0 for offset=0,"Incomplete journal string length");end:=offset+relative;text:=string(raw[offset:end]);journalNeed(journalMatch(text,"0|[1-9][0-9]*"),"Noncanonical journal string length");size,err:=strconv.ParseUint(text,10,64);offset=end+1;journalNeed(err==nil&&size<=uint64(len(raw)-offset),"Incomplete journal string");count:=int(size);value:=string(raw[offset:offset+count]);journalNeed(utf8.ValidString(value),"Invalid UTF8 journal field");values=append(values,value);offset+=count } return values } func journalDigest(raw []byte) string { hash:=sha256.Sum256(raw);return strings.ToUpper(hex.EncodeToString(hash[:])) } func journalFingerprint(pairs map[string]string) string { names:=make([]string,0,len(pairs));for name:=range pairs { names=append(names,name) };sort.Strings(names);values:=[]string{} for _,name:=range names { lower:=strings.ToLower(name);journalNeed(journalMatch(name,"[A-Za-z0-9_.-]+")&&lower!="api_key"&&lower!="exhibitday_api_key","Use explicit secret-free fingerprint names");values=append(values,name,pairs[name]) } return journalDigest(journalStrings(values)) } func journalFrame(values []string) []byte { raw:=journalStrings(values);header:=[]byte(strconv.Itoa(len(raw))+" "+journalDigest(raw)+"\n");result:=append(header,raw...);return append(result,'\n') } func journalDecode(raw []byte) [][]string { journalNeed(bytes.HasPrefix(raw,[]byte(journalPreamble)),"Unknown or incomplete journal version");offset:=len(journalPreamble);records:=[][]string{} for offset=0,"Incomplete frame header; reconcile before retry");end:=offset+relative;header:=string(raw[offset:end]);journalNeed(journalMatch(header,"(0|[1-9][0-9]*) [0-9A-F]{64}"),"Invalid frame header");fields:=strings.Split(header," ");size,err:=strconv.ParseUint(fields[0],10,64);offset=end+1;journalNeed(err==nil&&size0 { count,err:=file.Write(raw);if err!=nil{return err};if count<=0{return io.ErrShortWrite};raw=raw[count:] } return file.Sync() } func journalWriteFile(path string,flags int,raw []byte) (err error) { file,err:=os.OpenFile(path,flags,0600);if err!=nil{return err};defer func(){closed:=file.Close();if err==nil{err=closed}}();return journalWriteAll(file,raw) } func journalCopy(source map[string]string) map[string]string { copy:=map[string]string{};for name,value:=range source{copy[name]=value};return copy } func journalCopyStates(source map[string]map[string]string) map[string]map[string]string { copy:=map[string]map[string]string{};for name,value:=range source{copy[name]=journalCopy(value)};return copy } type guideJournal struct { path,lockPath,owner string header []string allowed map[string][2]string intents,savedValues,adoptedValues map[string]map[string]string order []string file *os.File identity os.FileInfo owned,tainted bool } func openGuideJournal(path,base,workspace,slug,job,inputFingerprint string,writes [][3]string,modes ...string) (result *guideJournal) { mode:="resume";journalNeed(len(modes)<=1,"Choose one local job mode");if len(modes)==1{mode=modes[0]};journalNeed(mode=="new"||mode=="resume","Choose new or resume for this local job") address,err:=url.Parse(base);journalNeed(err==nil&&address.Hostname()!=""&&(address.Scheme=="https"||address.Scheme=="http")&&address.User==nil&&address.RawQuery==""&&address.Fragment==""&&journalMatch(slug,"[a-z][a-z0-9-]*"),"Use actual API base and closed guide slug") journalNeed(strings.TrimSpace(job)!=""&&journalMatch(workspace,"[1-9][0-9]*")&&journalMatch(inputFingerprint,"[0-9A-F]{64}"),"Use actual workspace, stable explicit job ID and exact fingerprint") j:=&guideJournal{path:path,lockPath:path+".lock",allowed:map[string][2]string{},intents:map[string]map[string]string{},savedValues:map[string]map[string]string{},adoptedValues:map[string]map[string]string{}} manifest:=[]string{};for _,write:=range writes { step,method,route:=write[0],write[1],write[2];_,exists:=j.allowed[step];journalNeed(journalMatch(step,"[a-z][a-z0-9_-]*")&&!exists&&(method=="POST"||method=="PATCH"||method=="DELETE")&&journalMatch(route,"/v1/[A-Za-z0-9_/-]+")&&!strings.Contains(route,"//"),"Use a closed unique write manifest");j.allowed[step]=[2]string{method,route};j.order=append(j.order,step);manifest=append(manifest,step,method,route) } journalNeed(len(j.allowed)>0,"Only write workflows need a restart journal");j.header=[]string{"H","1",base,workspace,slug,job,inputFingerprint,journalDigest(journalStrings(manifest))};journalStrings(j.header) j.file,err=os.OpenFile(j.lockPath,os.O_RDWR|os.O_CREATE|os.O_EXCL,0600);if err!=nil { if os.IsExist(err){panic(journalRefusal{"This journal is locked; do not overlap jobs or steal a stale lock"})};panic(err) };j.owned=true defer func(){ if observed:=recover();observed!=nil { j.Close();panic(observed) } }() random:=make([]byte,16);if _,err=io.ReadFull(rand.Reader,random);err!=nil{panic(err)};j.owner=hex.EncodeToString(random);if err=journalWriteAll(j.file,[]byte(j.owner));err!=nil{panic(err)};j.identity,err=j.file.Stat();if err!=nil{panic(err)} info,err:=os.Lstat(path);if err!=nil&&!os.IsNotExist(err){panic(err)};exists:=err==nil;if exists{journalNeed(info.Mode()&os.ModeSymlink==0,"Choose a private regular journal file")};journalNeed(mode!="resume"||exists,"Journal missing: stop and reconcile lost state before starting a new logical job");journalNeed(mode!="new"||!exists,"Journal exists; use resume for the same logical job");if mode=="new"{raw:=append([]byte(journalPreamble),journalFrame(j.header)...);if err=journalWriteFile(path,os.O_WRONLY|os.O_CREATE|os.O_EXCL,raw);err!=nil{panic(err)}} raw,err:=os.ReadFile(path);if err!=nil{panic(err)};records:=journalDecode(raw);journalNeed(len(records)>0&&stringsEqual(records[0],j.header),"Journal workspace/base/guide/job/input binding differs");for _,record:=range records[1:]{j.apply(record)};for step:=range j.intents{_,ok:=j.savedValues[step];journalNeed(ok,"Saved intent lacks ACK; stop and reconcile before retry")};return j } func stringsEqual(left,right []string) bool { if len(left)!=len(right){return false};for i,value:=range left{if value!=right[i]{return false}};return true } func (j *guideJournal) apply(record []string) { journalNeed(len(record)>0,"Empty journal record") if record[0]=="I" { journalNeed(len(record)==6,"Invalid intent shape");step,method,route,fingerprint,key:=record[1],record[2],record[3],record[4],record[5];_,exists:=j.intents[step];expected,allowed:=j.allowed[step];_,adopted:=j.adoptedValues[step];pending:=false;for name:=range j.intents{if _,ok:=j.savedValues[name];!ok{pending=true}} journalNeed(journalMatch(step,"[a-z][a-z0-9_-]*")&&!exists&&!adopted&&allowed&&expected==[2]string{method,route}&&journalMatch(fingerprint,"[0-9A-F]{64}")&&!pending,"Invalid, future or repeated intent");journalNeed(method=="POST"&&journalMatch(key,"[0-9a-f]{32}")||method!="POST"&&key=="","Invalid persisted action key");j.intents[step]=map[string]string{"method":method,"path":route,"request_fingerprint":fingerprint,"idempotency_key":key} }else if record[0]=="A" { journalNeed(len(record)>=3,"Invalid ACK shape");step,text:=record[1],record[2];count,err:=strconv.ParseUint(text,10,64);_,prior:=j.intents[step];_,done:=j.savedValues[step];journalNeed(journalMatch(text,"0|[1-9][0-9]*")&&err==nil&&len(record)%2==1&&count==uint64((len(record)-3)/2)&&prior&&!done,"ACK without exactly one prior intent");names:=[]string{};for i:=3;i=6,"Invalid read-adoption shape");step,method,route,readFingerprint,text:=record[1],record[2],record[3],record[4],record[5];completed:=map[string]bool{};for name:=range j.savedValues{completed[name]=true};for name:=range j.adoptedValues{completed[name]=true};prefix:=len(completed)0,"Read-adoption IDs must be exact positive Int64 strings")}};for _,name:=range fields{journalNeed(name=="id"||name=="event_id"||saved[name]!="","Read-adoption material must be complete and fingerprint-bound")};journalNeed(readFingerprint==journalFingerprint(saved),"Read-adoption material must be complete and fingerprint-bound");j.adoptedValues[step]=saved }else{panic(journalRefusal{"Unknown journal transition"})} } func (j *guideJournal) requireActive() { journalNeed(j.owned&&j.file!=nil&&j.identity!=nil&&!j.tainted,"Journal is closed or IO outcome needs reconciliation");info,err:=os.Lstat(j.lockPath);if err!=nil{panic(err)};journalNeed(os.SameFile(j.identity,info),"Journal lock replaced; stop without deleting it");raw,err:=os.ReadFile(j.lockPath);if err!=nil{panic(err)};journalNeed(string(raw)==j.owner,"Journal lock token changed; stop without deleting it") } func (j *guideJournal) append(record []string) { j.requireActive();raw:=journalFrame(record);if err:=journalWriteFile(j.path,os.O_WRONLY|os.O_APPEND,raw);err!=nil{j.tainted=true;panic(err)} } func (j *guideJournal) Acknowledged(step string) bool {j.requireActive();_,ok:=j.savedValues[step];return ok} func (j *guideJournal) Saved(step string) map[string]string {j.requireActive();value,ok:=j.savedValues[step];journalNeed(ok,"No acknowledged state exists");return journalCopy(value)} func (j *guideJournal) Completed(step string) bool {j.requireActive();_,a:=j.savedValues[step];_,s:=j.adoptedValues[step];return a||s} func (j *guideJournal) Adopted(step string) bool {j.requireActive();_,ok:=j.adoptedValues[step];return ok} func (j *guideJournal) Recorded(step string) map[string]string {j.requireActive();if value,ok:=j.savedValues[step];ok{return journalCopy(value)};value,ok:=j.adoptedValues[step];journalNeed(ok,"No completed write or read-adoption exists");return journalCopy(value)} func (j *guideJournal) Adopt(step,method,route string,saved map[string]string) {j.requireActive();record:=[]string{"S",step,method,route,journalFingerprint(saved),strconv.Itoa(len(saved))};names:=[]string{};for name:=range saved{names=append(names,name)};sort.Strings(names);for _,name:=range names{record=append(record,name,saved[name])};previous:=journalCopyStates(j.adoptedValues);func(){defer func(){j.adoptedValues=previous}();j.apply(record);journalStrings(record)}();j.append(record);j.apply(record)} func (j *guideJournal) Begin(step,method,route,requestFingerprint string) map[string]string { j.requireActive();_,exists:=j.intents[step];journalNeed(!exists,"Never blindly repeat an existing action");key:="";if method=="POST"{raw:=make([]byte,16);if _,err:=io.ReadFull(rand.Reader,raw);err!=nil{panic(err)};key=hex.EncodeToString(raw)};record:=[]string{"I",step,method,route,requestFingerprint,key} previous:=journalCopyStates(j.intents);func(){defer func(){j.intents=previous}();j.apply(record)}();j.append(record);j.apply(record);return journalCopy(j.intents[step]) } func (j *guideJournal) Acknowledge(step string,saved map[string]string) { j.requireActive();record:=[]string{"A",step,strconv.Itoa(len(saved))};names:=make([]string,0,len(saved));for name:=range saved{names=append(names,name)};sort.Strings(names);for _,name:=range names{record=append(record,name,saved[name])};previous:=journalCopyStates(j.savedValues);func(){defer func(){j.savedValues=previous}();j.apply(record);journalStrings(record)}();j.append(record);j.apply(record) } func (j *guideJournal) Close() { if !j.owned{return};if j.tainted{err:=j.file.Close();j.file=nil;j.owned=false;if err!=nil{panic(err)};return} func(){defer func(){if observed:=recover();observed!=nil{j.file.Close();j.file=nil;j.owned=false;panic(observed)}}();j.requireActive()}();if err:=j.file.Close();err!=nil{j.file=nil;j.owned=false;panic(err)};j.file=nil;j.owned=false;if err:=os.Remove(j.lockPath);err!=nil{panic(err)} } func journal_values(value any)map[string]string{fields,ok:=value.(map[string]any);journalNeed(ok,"Saved/fingerprint values need an explicit object");result:=map[string]string{};for name,item:=range fields{text,valid:=item.(string);journalNeed(valid,"Saved/fingerprint values must be exact strings");result[name]=text};return result} func journal_object(fields map[string]string)any{result:=map[string]any{};for name,value:=range fields{result[name]=value};return result} func journal_acknowledge(job *guideJournal,step string,saved any){job.Acknowledge(step,journal_values(saved))} func journal_acknowledged(job *guideJournal,step string)bool{return job.Acknowledged(step)} func journal_adopt(job *guideJournal,step,method,path string,saved any){job.Adopt(step,method,path,journal_values(saved))} func journal_begin(job *guideJournal,step,method,path,requestFingerprint string)any{return journal_object(job.Begin(step,method,path,requestFingerprint))} func journal_completed(job *guideJournal,step string)bool{return job.Completed(step)} func journal_fingerprint(value any)string{return journalFingerprint(journal_values(value))} func journal_recorded(job *guideJournal,step string)any{return journal_object(job.Recorded(step))} func not_value(value bool)bool{return !value} func open_journal(path,base,workspace,slug,job,inputFingerprint string,manifest any,mode string)*guideJournal{rows,ok:=manifest.([]any);journalNeed(ok,"A closed write manifest is required");writes:=[][3]string{};for _,row:=range rows{fields,valid:=row.([]any);journalNeed(valid&&len(fields)==3,"Each write must bind step/method/path");var values [3]string;for index,item:=range fields{text,valid:=item.(string);journalNeed(valid,"Manifest values are exact strings");values[index]=text};writes=append(writes,values)};return openGuideJournal(path,base,workspace,slug,job,inputFingerprint,writes,mode)} func optional(name,fallback string)string{value:=os.Getenv(name);if value==""{return fallback};return value} func page_size(value string)string{valid:=len(value)>0&&value[0]!='0';for _,ch:=range value{valid=valid&&ch>='0'&&ch<='9'};size,err:=strconv.ParseInt(value,10,32);if !valid||err!=nil||size<=0{panic("Page size must be a positive int32")};return value} func parse_json(value string)any{ decoder:=json.NewDecoder(strings.NewReader(value));decoder.UseNumber();var read func()any read=func()any{token,err:=decoder.Token();if err!=nil{panic(err)};if delimiter,ok:=token.(json.Delim);ok{ if delimiter=='{'{result:=map[string]any{};for decoder.More(){key,err:=decoder.Token();if err!=nil{panic(err)};name,ok:=key.(string);if !ok{panic("Expected JSON property")};if _,exists:=result[name];exists{panic("Duplicate JSON input property")};result[name]=read()};end,err:=decoder.Token();if err!=nil||end!=json.Delim('}'){panic("Incomplete JSON object")};return result} if delimiter=='['{result:=[]any{};for decoder.More(){result=append(result,read())};end,err:=decoder.Token();if err!=nil||end!=json.Delim(']'){panic("Incomplete JSON array")};return result};panic("Unexpected JSON delimiter") };return token};result:=read();if _,err:=decoder.Token();err!=io.EOF{panic("Use one complete JSON input")};return result } func positive_id(value string)string{valid:=len(value)>0&&value[0]!='0';for _,ch:=range value{valid=valid&&ch>='0'&&ch<='9'};id,err:=strconv.ParseInt(value,10,64);if !valid||err!=nil||id<=0{panic("Use a positive record ID")};return value} func print_value(value any){if result,ok:=value.(string);ok{fmt.Println(result);return};raw,err:=json.Marshal(value);if err!=nil{panic(err)};fmt.Println(string(raw))} func require_condition(value bool,message string){if !value{panic(message)}} func response_status(value result)string{return strconv.Itoa(value.status)} func single(value any)any{rows:=items(value);if len(rows)!=1{panic("Expected exactly one selected record")};return rows[0]} func validate_crm_event_inputs(key, name, start, end string) { space := func(c rune) bool { return c >= 9 && c <= 13 || c == 32 || c == 0x85 || c == 0xA0 || c == 0x1680 || c >= 0x2000 && c <= 0x200A || c == 0x2028 || c == 0x2029 || c == 0x202F || c == 0x205F || c == 0x3000 } checkText := func(value, label string, limit int) { journalNeed(utf8.ValidString(value), "Use valid UTF-8 for "+label) journalNeed(value != "" && strings.TrimFunc(value,space) == value, "Remove whitespace at the start or end of "+label) units := 0 for _, character := range value { units++; if character > 0xFFFF { units++ } } journalNeed(units <= limit, fmt.Sprintf("%s exceeds %d UTF-16 code units",label,limit)) } checkDate := func(value,label string) { const format = "2006-01-02" date,err := time.Parse(format,value) journalNeed(err == nil && date.Format(format) == value && date.Year() >= 1753, label+" must be a calendar date in YYYY-MM-DD on or after 1753-01-01") } checkText(name,"EXHIBITDAY_EVENT_NAME",500) checkText(key,"EXHIBITDAY_EXTERNAL_EVENT_KEY",3000) journalNeed(!strings.ContainsAny(name,"<>\r\n") && !strings.EqualFold(name,"null"), "Use plain, single-line EXHIBITDAY_EVENT_NAME text other than null") checkDate(start,"EXHIBITDAY_START_DATE") checkDate(end,"EXHIBITDAY_END_DATE") journalNeed(end >= start,"EXHIBITDAY_END_DATE must be on or after EXHIBITDAY_START_DATE") } func workflow() { external_event_key := required("EXHIBITDAY_EXTERNAL_EVENT_KEY") desired_event_name := required("EXHIBITDAY_EVENT_NAME") desired_start_date := required("EXHIBITDAY_START_DATE") desired_end_date := required("EXHIBITDAY_END_DATE") desired_dates_json := required("EXHIBITDAY_EXHIBIT_DATES_JSON") desired_section_name := optional("EXHIBITDAY_TASK_SECTION_NAME", "Pre-event planning") setup_page_size := page_size(optional("EXHIBITDAY_PAGE_SIZE", "100")) desired_setup_dates := items(parse_json(desired_dates_json)) validate_crm_event_inputs(external_event_key, desired_event_name, desired_start_date, desired_end_date) journal_path := required("EXHIBITDAY_JOURNAL") stable_job_id := required("EXHIBITDAY_JOB_ID") job_mode := optional("EXHIBITDAY_JOB_MODE", "resume") setup_workspace_response := call("workspace_binding", map[string]string{}, nil, "") require_condition(equal(response_status(setup_workspace_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") setup_workspace := setup_workspace_response.body owned_workspace_id := positive_id(text(field(setup_workspace, "id"))) setup_input_fingerprint := journal_fingerprint(map[string]any{"workflow_contract_sha256": "19097A09AE2D22C1AF56F5D4FBD9B72F524E5EC195434BC315834CC8C2417C32", "external_event_key": external_event_key, "name": desired_event_name, "start_date": desired_start_date, "end_date": desired_end_date, "section_name": desired_section_name, "dates": desired_dates_json}) func() { setup_job := open_journal(journal_path, "https://api.exhibitday.com/v1", owned_workspace_id, "event-setup-crm", stable_job_id, setup_input_fingerprint, []any{[]any{"create_event", "POST", "/v1/events"}, []any{"update_event", "PATCH", "/v1/events"}, []any{"create_section", "POST", "/v1/tasks/sections"}, []any{"save_dates", "PATCH", "/v1/events/dates"}}, job_mode) defer setup_job.Close() setup_event_id := "" setup_section_id := "" recorded_section_name := desired_section_name if journal_completed(setup_job, "create_event") { recorded_event := journal_recorded(setup_job, "create_event") setup_event_id = positive_id(text(field(recorded_event, "id"))) require_condition(equal(text(field(recorded_event, "integration_metadata_field_1")), external_event_key), "The journal's completed Event differs from this external key.") } else { event_search_offset := "0" event_search_query := map[string]string{"filter_by_integration_metadata_field_1": external_event_key, "$limit": setup_page_size} for true { event_search_query["$offset"] = event_search_offset event_search_response := call("find_existing", event_search_query, nil, "") require_condition(equal(response_status(event_search_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") event_search_page := event_search_response.body event_search_rows := items(field(event_search_page, "list_data")) require_condition(equal(text(field(event_search_page, "records_found")), text(count(event_search_rows))), "records_found differs from this complete page's rows.") require_condition(is_present(text(field(event_search_page, "total_records"))), "The search wrapper needs total_records.") require_condition(either(equal(field(event_search_page, "has_more"), true), equal(field(event_search_page, "has_more"), false)), "Expected a Boolean has_more value.") for _, event_search_row := range items(event_search_rows) { if equal(text(field(event_search_row, "integration_metadata_field_1")), external_event_key) { event_search_candidate_id := positive_id(text(field(event_search_row, "id"))) if is_present(setup_event_id) { require_condition(equal(setup_event_id, event_search_candidate_id), "More than one matching record exists. Reconcile the ambiguity instead of selecting one or creating another.") } setup_event_id = event_search_candidate_id } } if equal(field(event_search_page, "has_more"), false) { break } require_condition(not_value(is_empty(event_search_rows)), "An empty search page has has_more=true. Stop and reconcile the search.") event_search_offset = add_offset(event_search_offset, count(event_search_rows)) } if not_value(is_present(setup_event_id)) { event_write_fingerprint := journal_fingerprint(map[string]any{"name": desired_event_name, "start_date": desired_start_date, "end_date": desired_end_date, "integration_metadata_field_1": external_event_key}) event_intent := journal_begin(setup_job, "create_event", "POST", "/v1/events", event_write_fingerprint) event_create_response := call("create_event", map[string]string{}, map[string]any{"name": desired_event_name, "start_date": desired_start_date, "end_date": desired_end_date, "integration_metadata_field_1": external_event_key}, text(field(event_intent, "idempotency_key"))) require_condition(equal(response_status(event_create_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") created_event := event_create_response.body setup_event_id = positive_id(text(field(created_event, "id"))) require_condition(equal(text(field(created_event, "integration_metadata_field_1")), external_event_key), "The created Event's external key differs; preserve the pending intent and reconcile.") require_condition(both(is_present(text(field(created_event, "name"))), both(is_present(text(field(created_event, "start_date"))), is_present(text(field(created_event, "end_date"))))), "The Event acknowledgement omitted its saved name or main dates.") journal_acknowledge(setup_job, "create_event", map[string]any{"id": setup_event_id, "integration_metadata_field_1": external_event_key}) } } event_confirmation_response := call("confirm_event", map[string]string{"id": setup_event_id, "$include_record_revision": "true"}, nil, "") require_condition(equal(response_status(event_confirmation_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") confirmed_setup_event := event_confirmation_response.body require_condition(both(equal(text(field(confirmed_setup_event, "id")), setup_event_id), equal(text(field(confirmed_setup_event, "integration_metadata_field_1")), external_event_key)), "The captured Event is missing or rebound; stop instead of searching for or creating a replacement.") if not_value(journal_completed(setup_job, "create_event")) { journal_adopt(setup_job, "create_event", "GET", "/v1/events/info", map[string]any{"id": text(field(confirmed_setup_event, "id")), "integration_metadata_field_1": text(field(confirmed_setup_event, "integration_metadata_field_1"))}) } setup_event_revision := text(field(confirmed_setup_event, "record_revision")) require_condition(is_present(setup_event_revision), "Read the selected Event with its revision before comparing or updating it.") require_condition(both(both(is_present(text(field(confirmed_setup_event, "name"))), is_present(text(field(confirmed_setup_event, "start_date")))), is_present(text(field(confirmed_setup_event, "end_date")))), "The selected Event must return its current name, start date and end date.") if journal_completed(setup_job, "update_event") { recorded_event_update := journal_recorded(setup_job, "update_event") require_condition(both(equal(text(field(recorded_event_update, "id")), setup_event_id), equal(text(field(recorded_event_update, "integration_metadata_field_1")), external_event_key)), "The recorded Event update has a different identity. Stop and reconcile.") require_condition(both(both(equal(text(field(confirmed_setup_event, "name")), desired_event_name), equal(text(field(confirmed_setup_event, "start_date")), desired_start_date)), equal(text(field(confirmed_setup_event, "end_date")), desired_end_date)), "The Event name or main dates changed after this job checked them. Review the current Event before writing again.") } else { if both(both(equal(text(field(confirmed_setup_event, "name")), desired_event_name), equal(text(field(confirmed_setup_event, "start_date")), desired_start_date)), equal(text(field(confirmed_setup_event, "end_date")), desired_end_date)) { journal_adopt(setup_job, "update_event", "GET", "/v1/events/info", map[string]any{"id": setup_event_id, "integration_metadata_field_1": external_event_key}) } else { require_condition(not_value(journal_acknowledged(setup_job, "create_event")), "The Event created by this job differs from the requested values. Inspect the saved Event before starting another update.") event_update_body := map[string]any{"id": setup_event_id, "expected_revision": setup_event_revision} if not_value(equal(text(field(confirmed_setup_event, "name")), desired_event_name)) { event_update_body["name"] = desired_event_name } if not_value(equal(text(field(confirmed_setup_event, "start_date")), desired_start_date)) { event_update_body["start_date"] = desired_start_date } if not_value(equal(text(field(confirmed_setup_event, "end_date")), desired_end_date)) { event_update_body["end_date"] = desired_end_date } event_update_fingerprint := journal_fingerprint(event_update_body) journal_begin(setup_job, "update_event", "PATCH", "/v1/events", event_update_fingerprint) event_update_response := call("update_event", map[string]string{}, event_update_body, "") require_condition(equal(response_status(event_update_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") event_update_ack := event_update_response.body event_updated_revision := text(field(event_update_ack, "record_revision")) require_condition(is_present(event_updated_revision), "The conditional Event update needs its returned revision. Reconcile the pending request before continuing.") journal_acknowledge(setup_job, "update_event", map[string]any{"id": setup_event_id, "integration_metadata_field_1": external_event_key, "record_revision": event_updated_revision}) } } event_update_verify_response := call("verify_event_update", map[string]string{"id": setup_event_id}, nil, "") require_condition(equal(response_status(event_update_verify_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") verified_setup_event := event_update_verify_response.body require_condition(both(both(equal(text(field(verified_setup_event, "id")), setup_event_id), equal(text(field(verified_setup_event, "integration_metadata_field_1")), external_event_key)), both(both(equal(text(field(verified_setup_event, "name")), desired_event_name), equal(text(field(verified_setup_event, "start_date")), desired_start_date)), equal(text(field(verified_setup_event, "end_date")), desired_end_date))), "The Event's current identity, name or main dates differ. Inspect the Event before continuing with setup.") if journal_completed(setup_job, "create_section") { recorded_section := journal_recorded(setup_job, "create_section") setup_section_id = positive_id(text(field(recorded_section, "id"))) require_condition(equal(text(field(recorded_section, "event_id")), setup_event_id), "The recorded Task Section belongs to a different Event.") recorded_section_name = text(field(recorded_section, "name")) } else { section_search_offset := "0" section_search_query := map[string]string{"filter_by_event_id": setup_event_id, "$limit": setup_page_size} for true { section_search_query["$offset"] = section_search_offset section_search_response := call("find_section", section_search_query, nil, "") require_condition(equal(response_status(section_search_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") section_search_page := section_search_response.body section_search_rows := items(field(section_search_page, "list_data")) require_condition(equal(text(field(section_search_page, "records_found")), text(count(section_search_rows))), "records_found differs from this complete page's rows.") require_condition(is_present(text(field(section_search_page, "total_records"))), "The search wrapper needs total_records.") require_condition(either(equal(field(section_search_page, "has_more"), true), equal(field(section_search_page, "has_more"), false)), "Expected a Boolean has_more value.") for _, section_search_row := range items(section_search_rows) { require_condition(equal(text(field(section_search_row, "event_id")), setup_event_id), "A section search row belongs to a different Event; stop before adopting or creating anything.") if equal(text(field(section_search_row, "name")), desired_section_name) { section_search_candidate_id := positive_id(text(field(section_search_row, "id"))) if is_present(setup_section_id) { require_condition(equal(setup_section_id, section_search_candidate_id), "More than one matching record exists. Reconcile the ambiguity instead of selecting one or creating another.") } setup_section_id = section_search_candidate_id } } if equal(field(section_search_page, "has_more"), false) { break } require_condition(not_value(is_empty(section_search_rows)), "An empty search page has has_more=true. Stop and reconcile the search.") section_search_offset = add_offset(section_search_offset, count(section_search_rows)) } if not_value(is_present(setup_section_id)) { section_write_fingerprint := journal_fingerprint(map[string]any{"event_id": setup_event_id, "name": desired_section_name}) section_intent := journal_begin(setup_job, "create_section", "POST", "/v1/tasks/sections", section_write_fingerprint) section_create_response := call("create_section", map[string]string{}, map[string]any{"event_id": setup_event_id, "name": desired_section_name}, text(field(section_intent, "idempotency_key"))) require_condition(equal(response_status(section_create_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") created_section := section_create_response.body setup_section_id = positive_id(text(field(created_section, "id"))) require_condition(equal(text(field(created_section, "event_id")), setup_event_id), "The created Task Section belongs to a different Event; preserve the pending intent.") recorded_section_name = text(field(created_section, "name")) require_condition(is_present(recorded_section_name), "The Task Section acknowledgement needs its actual saved name.") journal_acknowledge(setup_job, "create_section", map[string]any{"id": setup_section_id, "event_id": setup_event_id, "name": recorded_section_name}) } } section_confirmation_response := call("confirm_section", map[string]string{"id": setup_section_id}, nil, "") require_condition(equal(response_status(section_confirmation_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") confirmed_setup_section := section_confirmation_response.body require_condition(both(equal(text(field(confirmed_setup_section, "id")), setup_section_id), both(equal(text(field(confirmed_setup_section, "event_id")), setup_event_id), equal(text(field(confirmed_setup_section, "name")), recorded_section_name))), "The captured Task Section is missing, renamed or rebound; stop instead of creating a replacement.") if not_value(journal_completed(setup_job, "create_section")) { journal_adopt(setup_job, "create_section", "GET", "/v1/tasks/sections/info", map[string]any{"event_id": text(field(confirmed_setup_section, "event_id")), "id": text(field(confirmed_setup_section, "id")), "name": text(field(confirmed_setup_section, "name"))}) } setup_dates_response := call("read_dates", map[string]string{"event_id": setup_event_id, "filter_by_date_type_id": "1", "$include_record_revision": "true"}, nil, "") require_condition(equal(response_status(setup_dates_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") setup_dates_page := setup_dates_response.body require_condition(both(equal(text(field(setup_dates_page, "records_found")), "1"), both(equal(text(field(setup_dates_page, "total_records")), "1"), equal(field(setup_dates_page, "has_more"), false))), "Expected one complete selected Dates group, without another page.") setup_dates_group := single(field(setup_dates_page, "list_data")) require_condition(both(equal(text(field(setup_dates_group, "event_id")), setup_event_id), equal(text(field(setup_dates_group, "date_type_id")), "1")), "The Dates group belongs to another Event or type.") setup_dates_revision := text(field(setup_dates_group, "record_revision")) require_condition(is_present(setup_dates_revision), "Read the actual selected group revision before replacing it.") if journal_completed(setup_job, "save_dates") { recorded_dates := journal_recorded(setup_job, "save_dates") require_condition(both(equal(text(field(recorded_dates, "event_id")), setup_event_id), equal(text(field(recorded_dates, "date_type_id")), "1")), "The recorded Dates acknowledgement belongs to another Event or group.") } else { setup_dates_fingerprint := journal_fingerprint(map[string]any{"event_id": setup_event_id, "date_type_id": "1", "dates": desired_dates_json, "expected_revision": setup_dates_revision}) journal_begin(setup_job, "save_dates", "PATCH", "/v1/events/dates", setup_dates_fingerprint) setup_dates_save_response := call("save_dates", map[string]string{}, map[string]any{"event_id": setup_event_id, "date_type_id": "1", "dates": desired_setup_dates, "expected_revision": setup_dates_revision}, "") require_condition(equal(response_status(setup_dates_save_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") setup_dates_ack := setup_dates_save_response.body setup_dates_saved_revision := text(field(setup_dates_ack, "record_revision")) require_condition(is_present(setup_dates_saved_revision), "The checked Dates save needs its actual returned revision.") journal_acknowledge(setup_job, "save_dates", map[string]any{"event_id": setup_event_id, "date_type_id": "1", "record_revision": setup_dates_saved_revision}) } setup_dates_verify_response := call("verify_dates", map[string]string{"event_id": setup_event_id, "filter_by_date_type_id": "1"}, nil, "") require_condition(equal(response_status(setup_dates_verify_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") setup_dates_verify_page := setup_dates_verify_response.body require_condition(both(equal(text(field(setup_dates_verify_page, "records_found")), "1"), both(equal(text(field(setup_dates_verify_page, "total_records")), "1"), equal(field(setup_dates_verify_page, "has_more"), false))), "Expected one complete selected Dates group, without another page.") setup_dates_verify_group := single(field(setup_dates_verify_page, "list_data")) require_condition(both(equal(text(field(setup_dates_verify_group, "event_id")), setup_event_id), equal(text(field(setup_dates_verify_group, "date_type_id")), "1")), "The Dates group belongs to another Event or type.") require_condition(deep_equal(field(setup_dates_verify_group, "dates"), desired_setup_dates), "The saved normalized Dates list differs from the supplied canonical list. Inspect it; do not automatically restore or repeat the update.") setup_event_readback_response := call("event_readback", map[string]string{"id": setup_event_id}, nil, "") require_condition(equal(response_status(setup_event_readback_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.") setup_event_readback := setup_event_readback_response.body require_condition(both(equal(text(field(setup_event_readback, "id")), setup_event_id), equal(text(field(setup_event_readback, "integration_metadata_field_1")), external_event_key)), "Final Event readback is missing or rebound; earlier steps remain saved.") require_condition(both(both(equal(text(field(setup_event_readback, "name")), desired_event_name), equal(text(field(setup_event_readback, "start_date")), desired_start_date)), equal(text(field(setup_event_readback, "end_date")), desired_end_date)), "The Event name or main dates changed before final readback. Inspect the Event before starting another update.") planning_section_present := false for _, setup_event_section := range items(items(field(setup_event_readback, "task_sections"))) { if equal(text(field(setup_event_section, "id")), setup_section_id) { planning_section_present = true } } require_condition(planning_section_present, "The Event's current Task Sections do not include the recorded section; inspect it rather than creating another.") print_value(map[string]any{"event_id": setup_event_id, "task_section_id": setup_section_id, "dates_verified": "true"}) }() } func header_key(value string)string{for _,ch:=range value{if ch<32||ch>126{panic("Use the API key as one ASCII header value without control characters")}};return value} func main(){apiKey=header_key(required("EXHIBITDAY_API_KEY"));if err:=json.Unmarshal([]byte(specification),&spec);err!=nil{panic(err)};workflow()} ``` #### Example response Response 200 — OK 304 — Not Modified 400 — Bad Request 401 — Unauthorized 404 — Not Found 409 — Conflict 429 — Too Many Requests 500 — Internal Server Error Example Successful request ```json { "id": 5001, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=5001", "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", "star_rating": 0, "tags": [ "International", "Field Marketing" ], "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, "booth_reservation_cost": { "amount": 125.50, "cost_center_breakdown": [ { "cost_center_id": 34567, "cost_center": "Marketing", "charge": 75.50 }, { "cost_center_id": 34568, "cost_center": "Operations", "charge": 50.00 } ] }, "cost_booth_reservation": 125.50, "booth_reservation_payment_status_id": 0, "booth_reservation_payment_status": "", "booth_reservation_payment_due_date": null, "booth_reservation_next_payment_due_date": null, "booth_reservation_payment_notes": null, "booth_reservation_invoice_attachment": { "id": 175001, "filename": "booth-reservation-invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" }, "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": 100.50, "cost_sponsorships": 0.00, "total_sum_event_costs": 226.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, "roo_score": null, "event_created_timestamp": "2029-12-01T17:00:00Z", "event_last_update_timestamp": "2030-01-02T17:00:00Z", "event_created_by": null, "custom_fields": [ { "label": "Integration status", "value": "Ready", "notes": "", "field_name": "custom_67890", "field_type": "Text (Single-line)", "field_event_tab": "Info" }, { "label": "Setup instructions", "value": "Place the display beside the entrance.", "notes": "", "field_name": "custom_67891", "field_type": "Text (Single-line)", "field_event_tab": "Booth" } ], "task_sections": [ { "id": 6001, "name": "Pre-event planning", "display_rank": 0 }, { "id": 6002, "name": "Onsite follow-up", "display_rank": 1 } ], "tasks": [ { "id": 7002, "exhibitday_url": "https://www.exhibitday.com/Workspace/TaskView/98765?tid=7002", "event_task_section_id": 6001, "event_task_section": "Pre-event planning", "display_rank": 1, "name": "Confirm booth setup", "due_date": "2030-01-12", "assignee": { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, "is_completed": false, "task_completed_timestamp": null, "task_created_timestamp": "2029-12-01T17:01:00Z", "task_last_update_timestamp": "2029-12-01T17:01:00Z" }, { "id": 7003, "exhibitday_url": "https://www.exhibitday.com/Workspace/TaskView/98765?tid=7003", "event_task_section_id": 6002, "event_task_section": "Onsite follow-up", "display_rank": 2, "name": "Prepare the staff schedule", "due_date": "2030-01-13", "assignee": { "id": "66666666-7777-4888-8999-aaaaaaaaaaaa", "first_name": "Alex", "last_name": "Jordan", "display_name": "Alex Jordan", "email": "alex@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, "is_completed": false, "task_completed_timestamp": null, "task_created_timestamp": "2029-12-01T17:02:00Z", "task_last_update_timestamp": "2029-12-01T17:02:00Z" } ], "misc_expenses_credits": [ { "id": 8002, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=5001&riType=8&riSub=0&riId=8002", "description": "Conference meals", "is_credit": false, "cost": { "amount": 125.50, "cost_center_breakdown": [ { "cost_center_id": 34567, "cost_center": "Marketing", "charge": 75.50 }, { "cost_center_id": 34568, "cost_center": "Operations", "charge": 50.00 } ] }, "notes": "", "payment_due_date": null, "payment_status": { "id": 0, "name": "Not Specified" }, "next_payment_due_date": null, "next_partial_payment_due_date": null, "payment_notes": null, "invoice_attachment": { "id": 678002, "filename": "expense-invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" }, "event_misc_expense_credit_created_timestamp": "2029-12-01T17:00:00Z", "event_misc_expense_credit_last_update_timestamp": "2029-12-01T17:00:00Z" }, { "id": 8003, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=5001&riType=8&riSub=0&riId=8003", "description": "Supplier refund", "is_credit": true, "cost": { "amount": -25.00, "cost_center_breakdown": [ { "cost_center_id": 34567, "cost_center": "Marketing", "charge": -15.00 }, { "cost_center_id": 34568, "cost_center": "Operations", "charge": -10.00 } ] }, "notes": "", "payment_due_date": null, "payment_status": { "id": 0, "name": "Not Specified" }, "next_payment_due_date": null, "next_partial_payment_due_date": null, "payment_notes": null, "invoice_attachment": { "id": 678003, "filename": "expense-invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" }, "event_misc_expense_credit_created_timestamp": "2029-12-01T17:00:00Z", "event_misc_expense_credit_last_update_timestamp": "2029-12-01T17:00:00Z" } ], "integration_metadata_field_1": "crm:event:spring-expo-2030", "integration_metadata_field_2": null, "integration_metadata_field_3": null, "integration_metadata_field_4": null, "integration_metadata_field_5": null } ``` Note: Confirmed Event planning setup. The final Event read confirms the saved external key and planning section. The separate Dates read has already checked the complete Exhibit Hall schedule. Note: There is no response body. Keep using your cached response. ```json { "status_code": 400, "status": "Bad Request", "message": "HTTP method override is not supported.", "error_code": "invalid_request", "errors": [ "Send the documented HTTP method directly. X-HTTP-Method-Override cannot change a request's HTTP method." ], "error_params": [ "X-HTTP-Method-Override" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "No API key was provided. Send your key in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "missing_api_key", "errors": [ "Copy the key from Workspace Settings > API & Integrations > API Access in ExhibitDay." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "The API key is not valid. Check that you copied the whole key from Workspace Settings > API & Integrations > API Access, then send it in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "invalid_api_key", "errors": [ "Check that you sent the whole key. If it was regenerated, use the current key from Workspace Settings > API & Integrations > API Access." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "Access to the ExhibitDay API is not enabled for your workspace. Please contact support@exhibitday.com to enable API Access. Once access is enabled, send your key in the Authorization header as 'Bearer YOUR_API_KEY'.", "error_code": "api_access_disabled", "errors": [ "Nothing was read or changed." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 404, "status": "Not Found", "message": "Event not found. Invalid Event ID: 12345.", "error_code": "not_found", "errors": [ "Event not found. Invalid Event ID: 12345." ], "error_params": [ "id" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "The invoice attachment or its owning record changed or has conflicting saved information. Retrieve the current record before retrying.", "error_code": "record_changed", "errors": [ "The invoice attachment or its owning record changed or has conflicting saved information. Retrieve the current record before retrying." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "The Booth Reservation payment information changed or has an unsupported saved status. Retrieve the current Event before retrying.", "error_code": "record_changed", "errors": [ "The Booth Reservation payment information changed or has an unsupported saved status. Retrieve the current Event before retrying." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "The Event objective score changed or could not be read consistently. Retrieve the Event before retrying.", "error_code": "record_changed", "errors": [ "The Event objective score changed or could not be read consistently. Retrieve the Event before retrying." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "The record was being changed while it was read, so no record_revision could be issued. Read it again.", "error_code": "record_changed", "errors": [ "The record was being changed while it was read, so no record_revision could be issued. Read it again." ], "error_params": [ "$include_record_revision" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 429, "status": "Too Many Requests", "message": "Error 429 - Too Many Requests", "error_code": "rate_limited", "errors": [ "Error 429 - Too Many Requests" ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "An unexpected error occurred. Please try again later." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` Note: Use the request_id from your own response when contacting support. ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "Check whether your change was saved before trying again." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` #### Things to keep in mind - Use one CRM key per Event. ExhibitDay allows the same key on more than one Event. - If two runs could create the same Event, run them one at a time. - If the search finds more than one match, the program stops so you can check. - Enter Exhibit Hall times in the Event's local time. ExhibitDay saves the time-zone label you send and keeps the times as entered. - The Event and its Exhibit Hall dates are protected from overwrites separately. #### If a run stops - Each step saves on its own, so a stopped run may have saved some steps. - Keep the journal private. It records what the program tried to save and which saves it 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 save stopped with a conflict, a lost response or a missing revision, check what was saved in ExhibitDay before running the program again. - If you still need changes after checking the old run, set `EXHIBITDAY_JOB_MODE=new` with a new job ID and journal path. - Start a new job when your CRM sends new values. - Run only one copy per journal. - If a crash leaves a `.lock` file, make sure no copy using that journal is running or can start. Then remove the lock file and keep the journal. #### Related guides - [Link ExhibitDay Events to Your CRM or ERP Records](https://api.exhibitday.com/Help/V1?guide=match-records) - [Set an Event's Exhibit Hall Dates and Hours](https://api.exhibitday.com/Help/V1?guide=dates-times-time-zones) - [Handle Errors and Retry Failed Requests](https://api.exhibitday.com/Help/V1?guide=errors-and-retries) ### Get a Complete List of Attendees, Travel and More Guide page: https://api.exhibitday.com/Help/V1?guide=find-filter-page Pull a complete filtered list, such as everyone registered or traveling for a show, page by page. Example use case You need a report of everyone registered or traveling for a show and want to collect every matching record. What you'll end up with A list of Staff registrations and Travel Reservations for one Event or the whole workspace. You can also filter the Travel list by tagged people. Before you start Have a workspace API key. If you plan to filter by people, get their IDs from Users and Resources. Good to know Leave out the Event filter to search the whole workspace, or add it to focus on one show. #### At a glance Time to try About 5 minutes Effect on your data Read-only Endpoints 2 The program reads Staff registrations and Travel Reservations and prints their IDs. - [`GET /v1/events/staff`](https://api.exhibitday.com/Help/V1?epf=1&topic=staff#get-v1-events-staff) - [`GET /v1/events/travel_reservations`](https://api.exhibitday.com/Help/V1?epf=1&topic=travel-reservations#get-v1-events-travel_reservations) #### How it works 1. The program reads Staff registrations and Travel Reservations. An Event ID narrows both lists. 2. If you supply tagged people, it applies those filters to Travel and keeps the same filters on every page. 3. It follows the paging fields and prints each distinct record ID and Event ID. #### Read every matching record The examples below use the Staff and Travel lists. The program reads Staff first, then Travel, and continues each list when there are more records. **Careful.** Leave out `$result_format` so the response includes `has_more` and `total_records` for paging. #### Step 1: Read every page of attendees Read Staff registrations a page at a time, with an optional Event filter. ```bash curl -X GET "https://api.exhibitday.com/v1/events/staff?%24limit=2&%24offset=0" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "records_found": 2, "total_records": 3, "has_more": true, "list_data": [ { "id": 101, "event_id": 5001 }, { "id": 102, "event_id": 5002 } ] } ``` total_records is the number of matches across all pages. **Check:** While has_more is true, increase $offset by the number of rows returned and request the next page. #### Step 2: Read every page of travel reservations Read Travel Reservations a page at a time, with optional Event and tagged-people filters. ```bash curl -X GET "https://api.exhibitday.com/v1/events/travel_reservations?filter_by_tagged_user_ids=%5B%2211111111-2222-4333-8444-555555555555%22%2C%2266666666-7777-4888-8999-000000000000%22%5D&filter_by_tagged_user_ids_match_type=all&%24limit=2&%24offset=0" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "records_found": 2, "total_records": 3, "has_more": true, "list_data": [ { "id": 201, "event_id": 5001 }, { "id": 202, "event_id": 5002 } ] } ``` list_data[].id identifies a Travel Reservation. Keep each ID once, even if it appears on two pages. **Check:** Use the same filters on every page. Stop when has_more is false. #### Try it #### Before running the example | Variable | What to put in it | Required? | | --- | --- | --- | | `EXHIBITDAY_API_KEY` | Your workspace API key. | Yes | | `EXHIBITDAY_PAGE_SIZE` | A positive number of records per page. Defaults to 100. | No | | `EXHIBITDAY_EVENT_ID` | One Event ID to limit both lists. Leave it out for all readable Events in the workspace. | No | | `EXHIBITDAY_TAGGED_USER_IDS_JSON` | One person ID or a JSON array of IDs to filter Travel. | No | | `EXHIBITDAY_TAG_MATCH_TYPE` | Use any for at least one selected person, or all for every selected person. Defaults to any. | No | **Note.** This example only reads data. It prints each record ID and its Event ID once per collection. #### Bash ``` export EXHIBITDAY_API_KEY='YOUR_API_KEY' ``` #### PowerShell ``` $env:EXHIBITDAY_API_KEY = 'YOUR_API_KEY' ``` Then copy the complete example program below in your language and run it. #### Complete example program Code Samples ```bash #!/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\":{\"staff_pages\":{\"method\":\"GET\",\"path\":\"/events/staff\"},\"travel_pages\":{\"method\":\"GET\",\"path\":\"/events/travel_reservations\"}}}") API_KEY = os.environ["EXHIBITDAY_API_KEY"] if any(ord(char) < 32 or ord(char) > 126 for char in API_KEY): raise RuntimeError("Use the API key as one ASCII header value without control characters") if not API_KEY.strip(): raise RuntimeError("Set EXHIBITDAY_API_KEY") def decode_json(text): if SPEC["preserveNumbers"]: # Quote JSON NUMBER tokens, never text inside a JSON string, to keep CSV decimals exact. text = re.sub(r'"(?:\\.|[^"\\])*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?', lambda m: m[0] if m[0].startswith('"') else json.dumps(m[0]), text) return json.loads(text) from pathlib import Path # This terminal version uses curl for HTTP and Python's standard library for JSON/CSV. import subprocess import tempfile def transport(method, url, headers, data): with tempfile.TemporaryDirectory(prefix="exhibitday-guide-") as directory: folder = Path(directory) # curl may leave no output file for a valid bodyless304 response. (folder / "body").write_bytes(b"") command = ["curl", "--disable", "--silent", "--show-error", "--request", method, "--url", url, "--max-time", "30", "--dump-header", str(folder / "headers"), "--output", str(folder / "body"), "--write-out", "%{http_code}"] for name, value in headers.items(): command += ["--header", name + ": " + value] if data is not None: (folder / "request").write_bytes(data) command += ["--data-binary", "@" + str(folder / "request")] result = subprocess.run(command, capture_output=True, text=True) if result.returncode: raise urllib.error.URLError(result.stderr.strip()) response_headers = {} blocks = (folder / "headers").read_text(encoding="iso-8859-1").replace("\r\n", "\n").strip().split("\n\n") for line in blocks[-1].splitlines()[1:]: name, separator, value = line.partition(":") if separator: response_headers[name] = value.strip() return int(result.stdout), (folder / "body").read_bytes(), response_headers class ApiError(RuntimeError): """An API error response. Branch on error_code (and status), never on the message text. uncertain is True when a PATCH or DELETE got no response or a server error: it may or may not have been applied.""" def __init__(self, status, body, uncertain=False): self.status = status self.uncertain = uncertain self.error_code = body.get("error_code") if isinstance(body, dict) else None super().__init__(f"{body.get('error_code')} {body.get('error_params')}: {body.get('errors')} (request {body.get('request_id')})" if isinstance(body, dict) else "HTTP " + str(status) if status else "No response") def call(name, params=None, body=None, key=None): route = SPEC["requests"][name] headers = {"Authorization": "Bearer " + API_KEY, "Accept": "application/json"} if route["method"] == "POST": if not key: raise RuntimeError("Persist a logical create key before sending POST") headers["Idempotency-Key"] = key data = None if body is None else json.dumps(body).encode("utf-8") if data is not None: headers["Content-Type"] = "application/json" query = urllib.parse.urlencode(params or {}) url = BASE + route["path"] + ("?" + query if query else "") # Only GET has automatic retries in this workflow. A PATCH or DELETE that got no response or a # server error is never resent blindly: it may already have been applied, so the caller reads the record first. resend = route["method"] == "GET" for attempt in range(5): try: status, raw, response_headers = transport(route["method"], url, headers, data) except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException): if not resend: raise ApiError(0, None, uncertain=True) if attempt == 4: raise time.sleep(2 ** attempt) continue response_headers = {k.lower(): v for k, v in response_headers.items()} result = None if status != 304 and raw: try: result = decode_json(raw.decode("utf-8")) except (ValueError, UnicodeError): if status < 400: raise RuntimeError("Expected a JSON success response") if status >= 500 and not resend: raise ApiError(status, result, uncertain=True) retry = resend and (status == 429 or status >= 500) if retry: if attempt == 4: raise RuntimeError("Retry limit reached; check the request outcome before starting a new create") delay = response_headers.get("retry-after", str(2 ** attempt)) time.sleep(max(0, float(delay))) continue if status >= 400: raise ApiError(status, result) return {"status": status, "body": result, "headers": response_headers, "raw": raw} raise RuntimeError("Retry limit reached") def 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 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 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] def is_empty(value): return count(value) == 0 def is_present(value): return value is not None and value != "" def new_id_set(): return set() def not_value(value): if not isinstance(value, bool): raise RuntimeError("Expected a Boolean") return not value def optional(name, fallback): value = os.environ.get(name) return fallback if value is None or value == "" else value def page_size(value): if not re.fullmatch(r"[1-9][0-9]*", value) or int(value) > 2147483647: raise RuntimeError("Page size must be a positive int32") return 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 remember_id(seen, value): if value in seen: return False seen.add(value) return True def require_condition(value, message): if value is not True: raise RuntimeError(message) 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(): selected_page_size = page_size(optional("EXHIBITDAY_PAGE_SIZE", "100")) selected_event_id = optional("EXHIBITDAY_EVENT_ID", "") if is_present(selected_event_id): selected_event_id = positive_id(selected_event_id) tagged_user_filter = optional("EXHIBITDAY_TAGGED_USER_IDS_JSON", "") tag_match_type = optional("EXHIBITDAY_TAG_MATCH_TYPE", "any") require_condition(either(equal(tag_match_type, "any"), equal(tag_match_type, "all")), "Choose any or all for EXHIBITDAY_TAG_MATCH_TYPE.") staff_query = {"$limit": selected_page_size} if is_present(selected_event_id): staff_query["filter_by_event_id"] = selected_event_id staff_offset = "0" staff_seen_ids = new_id_set() print_value("Staff record ID\tEvent ID") while True: staff_query["$offset"] = staff_offset staff_response = call("staff_pages", staff_query, None, None) staff_page = staff_response["body"] staff_rows = items(field(staff_page, "list_data")) require_condition(equal(text(field(staff_page, "records_found")), text(count(staff_rows))), "records_found does not match this page's rows.") require_condition(is_present(text(field(staff_page, "total_records"))), "The collection wrapper needs total_records.") require_condition(either(equal(field(staff_page, "has_more"), True), equal(field(staff_page, "has_more"), False)), "Expected a Boolean has_more value.") for staff_record in items(staff_rows): staff_record_id = positive_id(text(field(staff_record, "id"))) staff_event_id = positive_id(text(field(staff_record, "event_id"))) if is_present(selected_event_id): require_condition(equal(staff_event_id, selected_event_id), "A returned row belongs to a different Event.") if remember_id(staff_seen_ids, staff_record_id): print_value(concat(staff_record_id, concat("\t", staff_event_id))) if equal(field(staff_page, "has_more"), False): break require_condition(not_value(is_empty(staff_rows)), "An empty page has has_more=true; stop and reconcile the query.") staff_offset = add_offset(staff_offset, count(staff_rows)) travel_query = {"$limit": selected_page_size} if is_present(selected_event_id): travel_query["filter_by_event_id"] = selected_event_id if is_present(tagged_user_filter): travel_query["filter_by_tagged_user_ids"] = tagged_user_filter travel_query["filter_by_tagged_user_ids_match_type"] = tag_match_type travel_offset = "0" travel_seen_ids = new_id_set() print_value("Travel record ID\tEvent ID") while True: travel_query["$offset"] = travel_offset travel_response = call("travel_pages", travel_query, None, None) travel_page = travel_response["body"] travel_rows = items(field(travel_page, "list_data")) require_condition(equal(text(field(travel_page, "records_found")), text(count(travel_rows))), "records_found does not match this page's rows.") require_condition(is_present(text(field(travel_page, "total_records"))), "The collection wrapper needs total_records.") require_condition(either(equal(field(travel_page, "has_more"), True), equal(field(travel_page, "has_more"), False)), "Expected a Boolean has_more value.") for travel_record in items(travel_rows): travel_record_id = positive_id(text(field(travel_record, "id"))) travel_event_id = positive_id(text(field(travel_record, "event_id"))) if is_present(selected_event_id): require_condition(equal(travel_event_id, selected_event_id), "A returned row belongs to a different Event.") if remember_id(travel_seen_ids, travel_record_id): print_value(concat(travel_record_id, concat("\t", travel_event_id))) if equal(field(travel_page, "has_more"), False): break require_condition(not_value(is_empty(travel_rows)), "An empty page has has_more=true; stop and reconcile the query.") travel_offset = add_offset(travel_offset, count(travel_rows)) if __name__ == "__main__": main() EXHIBITDAY_PY ``` ```javascript // Server-side Node.js with fetch; built-in modules only. Set EXHIBITDAY_API_KEY. const BASE = "https://api.exhibitday.com/v1"; const SPEC = JSON.parse("{\"preserveNumbers\":true,\"requests\":{\"staff_pages\":{\"method\":\"GET\",\"path\":\"/events/staff\"},\"travel_pages\":{\"method\":\"GET\",\"path\":\"/events/travel_reservations\"}}}"); const API_KEY = process.env.EXHIBITDAY_API_KEY; if (!API_KEY || !API_KEY.trim()) throw new Error("Set EXHIBITDAY_API_KEY"); if (/[^\x20-\x7e]/.test(API_KEY)) throw new Error("Use the API key as one ASCII header value without control characters"); 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, errors: result.errors, error_params: result.error_params, 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, key = null) { const route = SPEC.requests[name]; const headers = { Authorization: "Bearer " + API_KEY, Accept: "application/json" }; if (route.method === "POST") { if (!key) throw new Error("Persist a logical create key before sending POST"); headers["Idempotency-Key"] = key; } 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 : ""); // 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. const resend = route.method === "GET"; 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 = resend && (response.status === 429 || response.status >= 500); 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, raw }; } throw new Error("Retry limit reached"); } function add_offset(offset, received) { const result = BigInt(offset) + received; if (received <= 0n || result > 2147483647n) throw new Error("Cannot advance this int32 offset; reconcile the query"); return result.toString(); } function concat(left, right) { return left + right; } function items(value) { if (!Array.isArray(value)) throw new Error("Expected a JSON array"); return value; } function count(value) { return BigInt(items(value).length); } function either(left, right) { if (typeof left !== "boolean" || typeof right !== "boolean") throw new Error("Expected Boolean criteria"); return left || right; } function equal(left, right) { return typeof left === typeof right && left === right; } function field(value, name) { if (!value || Array.isArray(value) || typeof value !== "object" || !Object.hasOwn(value, name)) throw new Error("Missing response field: " + name); return value[name]; } function is_empty(value) { return count(value) === 0n; } function is_present(value) { return value !== null && value !== undefined && value !== ""; } function new_id_set() { return new Set(); } function not_value(value) { if (typeof value !== "boolean") throw new Error("Expected a Boolean"); return !value; } function optional(name, fallback) { const value = process.env[name]; return value === undefined || value === "" ? fallback : value; } function page_size(value) { if (!/^[1-9][0-9]*$/.test(value) || BigInt(value) > 2147483647n) throw new Error("Page size must be a positive int32"); return value; } function positive_id(value) { if (!/^[1-9][0-9]*$/.test(value) || BigInt(value) > 9223372036854775807n) throw new Error("Use a positive record ID"); return value; } function print_value(value) { console.log(typeof value === "string" ? value : JSON.stringify(value)); } function remember_id(seen, value) { if (seen.has(value)) return false; seen.add(value); return true; } function require_condition(value, message) { if (value !== true) throw new Error(message); } function text(value) { if (value === null || value === undefined) return ""; if (["string", "boolean", "bigint"].includes(typeof value)) return String(value); throw new Error("Expected a scalar response value"); } async function main() { let selected_page_size = page_size(optional("EXHIBITDAY_PAGE_SIZE", "100")); let selected_event_id = optional("EXHIBITDAY_EVENT_ID", ""); if (is_present(selected_event_id)) { selected_event_id = positive_id(selected_event_id); } let tagged_user_filter = optional("EXHIBITDAY_TAGGED_USER_IDS_JSON", ""); let tag_match_type = optional("EXHIBITDAY_TAG_MATCH_TYPE", "any"); require_condition(either(equal(tag_match_type, "any"), equal(tag_match_type, "all")), "Choose any or all for EXHIBITDAY_TAG_MATCH_TYPE."); let staff_query = {"$limit": selected_page_size}; if (is_present(selected_event_id)) { staff_query["filter_by_event_id"] = selected_event_id; } let staff_offset = "0"; let staff_seen_ids = new_id_set(); print_value("Staff record ID\tEvent ID"); while (true) { staff_query["$offset"] = staff_offset; let staff_response = await call("staff_pages", staff_query, null, null); let staff_page = staff_response.body; let staff_rows = items(field(staff_page, "list_data")); require_condition(equal(text(field(staff_page, "records_found")), text(count(staff_rows))), "records_found does not match this page's rows."); require_condition(is_present(text(field(staff_page, "total_records"))), "The collection wrapper needs total_records."); require_condition(either(equal(field(staff_page, "has_more"), true), equal(field(staff_page, "has_more"), false)), "Expected a Boolean has_more value."); for (const staff_record of items(staff_rows)) { let staff_record_id = positive_id(text(field(staff_record, "id"))); let staff_event_id = positive_id(text(field(staff_record, "event_id"))); if (is_present(selected_event_id)) { require_condition(equal(staff_event_id, selected_event_id), "A returned row belongs to a different Event."); } if (remember_id(staff_seen_ids, staff_record_id)) { print_value(concat(staff_record_id, concat("\t", staff_event_id))); } } if (equal(field(staff_page, "has_more"), false)) { break; } require_condition(not_value(is_empty(staff_rows)), "An empty page has has_more=true; stop and reconcile the query."); staff_offset = add_offset(staff_offset, count(staff_rows)); } let travel_query = {"$limit": selected_page_size}; if (is_present(selected_event_id)) { travel_query["filter_by_event_id"] = selected_event_id; } if (is_present(tagged_user_filter)) { travel_query["filter_by_tagged_user_ids"] = tagged_user_filter; travel_query["filter_by_tagged_user_ids_match_type"] = tag_match_type; } let travel_offset = "0"; let travel_seen_ids = new_id_set(); print_value("Travel record ID\tEvent ID"); while (true) { travel_query["$offset"] = travel_offset; let travel_response = await call("travel_pages", travel_query, null, null); let travel_page = travel_response.body; let travel_rows = items(field(travel_page, "list_data")); require_condition(equal(text(field(travel_page, "records_found")), text(count(travel_rows))), "records_found does not match this page's rows."); require_condition(is_present(text(field(travel_page, "total_records"))), "The collection wrapper needs total_records."); require_condition(either(equal(field(travel_page, "has_more"), true), equal(field(travel_page, "has_more"), false)), "Expected a Boolean has_more value."); for (const travel_record of items(travel_rows)) { let travel_record_id = positive_id(text(field(travel_record, "id"))); let travel_event_id = positive_id(text(field(travel_record, "event_id"))); if (is_present(selected_event_id)) { require_condition(equal(travel_event_id, selected_event_id), "A returned row belongs to a different Event."); } if (remember_id(travel_seen_ids, travel_record_id)) { print_value(concat(travel_record_id, concat("\t", travel_event_id))); } } if (equal(field(travel_page, "has_more"), false)) { break; } require_condition(not_value(is_empty(travel_rows)), "An empty page has has_more=true; stop and reconcile the query."); travel_offset = add_offset(travel_offset, count(travel_rows)); } } if (require.main === module) main().catch(error => { console.error(error.message); process.exitCode = 1; }); module.exports = { main }; ``` ```python # 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\":{\"staff_pages\":{\"method\":\"GET\",\"path\":\"/events/staff\"},\"travel_pages\":{\"method\":\"GET\",\"path\":\"/events/travel_reservations\"}}}") 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) 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, key=None): route = SPEC["requests"][name] headers = {"Authorization": "Bearer " + API_KEY, "Accept": "application/json"} if route["method"] == "POST": if not key: raise RuntimeError("Persist a logical create key before sending POST") headers["Idempotency-Key"] = key data = None if body is None else json.dumps(body).encode("utf-8") if data is not None: headers["Content-Type"] = "application/json" query = urllib.parse.urlencode(params or {}) url = BASE + route["path"] + ("?" + query if query else "") # Only GET has automatic retries in this workflow. A PATCH or DELETE that got no response or a # server error is never resent blindly: it may already have been applied, so the caller reads the record first. resend = route["method"] == "GET" for attempt in range(5): try: status, raw, response_headers = transport(route["method"], url, headers, data) except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException): if not resend: raise ApiError(0, None, uncertain=True) if attempt == 4: raise time.sleep(2 ** attempt) continue response_headers = {k.lower(): v for k, v in response_headers.items()} result = None if status != 304 and raw: try: result = decode_json(raw.decode("utf-8")) except (ValueError, UnicodeError): if status < 400: raise RuntimeError("Expected a JSON success response") if status >= 500 and not resend: raise ApiError(status, result, uncertain=True) retry = resend and (status == 429 or status >= 500) if retry: if attempt == 4: raise RuntimeError("Retry limit reached; check the request outcome before starting a new create") delay = response_headers.get("retry-after", str(2 ** attempt)) time.sleep(max(0, float(delay))) continue if status >= 400: raise ApiError(status, result) return {"status": status, "body": result, "headers": response_headers, "raw": raw} raise RuntimeError("Retry limit reached") def 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 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 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] def is_empty(value): return count(value) == 0 def is_present(value): return value is not None and value != "" def new_id_set(): return set() def not_value(value): if not isinstance(value, bool): raise RuntimeError("Expected a Boolean") return not value def optional(name, fallback): value = os.environ.get(name) return fallback if value is None or value == "" else value def page_size(value): if not re.fullmatch(r"[1-9][0-9]*", value) or int(value) > 2147483647: raise RuntimeError("Page size must be a positive int32") return 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 remember_id(seen, value): if value in seen: return False seen.add(value) return True def require_condition(value, message): if value is not True: raise RuntimeError(message) 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(): selected_page_size = page_size(optional("EXHIBITDAY_PAGE_SIZE", "100")) selected_event_id = optional("EXHIBITDAY_EVENT_ID", "") if is_present(selected_event_id): selected_event_id = positive_id(selected_event_id) tagged_user_filter = optional("EXHIBITDAY_TAGGED_USER_IDS_JSON", "") tag_match_type = optional("EXHIBITDAY_TAG_MATCH_TYPE", "any") require_condition(either(equal(tag_match_type, "any"), equal(tag_match_type, "all")), "Choose any or all for EXHIBITDAY_TAG_MATCH_TYPE.") staff_query = {"$limit": selected_page_size} if is_present(selected_event_id): staff_query["filter_by_event_id"] = selected_event_id staff_offset = "0" staff_seen_ids = new_id_set() print_value("Staff record ID\tEvent ID") while True: staff_query["$offset"] = staff_offset staff_response = call("staff_pages", staff_query, None, None) staff_page = staff_response["body"] staff_rows = items(field(staff_page, "list_data")) require_condition(equal(text(field(staff_page, "records_found")), text(count(staff_rows))), "records_found does not match this page's rows.") require_condition(is_present(text(field(staff_page, "total_records"))), "The collection wrapper needs total_records.") require_condition(either(equal(field(staff_page, "has_more"), True), equal(field(staff_page, "has_more"), False)), "Expected a Boolean has_more value.") for staff_record in items(staff_rows): staff_record_id = positive_id(text(field(staff_record, "id"))) staff_event_id = positive_id(text(field(staff_record, "event_id"))) if is_present(selected_event_id): require_condition(equal(staff_event_id, selected_event_id), "A returned row belongs to a different Event.") if remember_id(staff_seen_ids, staff_record_id): print_value(concat(staff_record_id, concat("\t", staff_event_id))) if equal(field(staff_page, "has_more"), False): break require_condition(not_value(is_empty(staff_rows)), "An empty page has has_more=true; stop and reconcile the query.") staff_offset = add_offset(staff_offset, count(staff_rows)) travel_query = {"$limit": selected_page_size} if is_present(selected_event_id): travel_query["filter_by_event_id"] = selected_event_id if is_present(tagged_user_filter): travel_query["filter_by_tagged_user_ids"] = tagged_user_filter travel_query["filter_by_tagged_user_ids_match_type"] = tag_match_type travel_offset = "0" travel_seen_ids = new_id_set() print_value("Travel record ID\tEvent ID") while True: travel_query["$offset"] = travel_offset travel_response = call("travel_pages", travel_query, None, None) travel_page = travel_response["body"] travel_rows = items(field(travel_page, "list_data")) require_condition(equal(text(field(travel_page, "records_found")), text(count(travel_rows))), "records_found does not match this page's rows.") require_condition(is_present(text(field(travel_page, "total_records"))), "The collection wrapper needs total_records.") require_condition(either(equal(field(travel_page, "has_more"), True), equal(field(travel_page, "has_more"), False)), "Expected a Boolean has_more value.") for travel_record in items(travel_rows): travel_record_id = positive_id(text(field(travel_record, "id"))) travel_event_id = positive_id(text(field(travel_record, "event_id"))) if is_present(selected_event_id): require_condition(equal(travel_event_id, selected_event_id), "A returned row belongs to a different Event.") if remember_id(travel_seen_ids, travel_record_id): print_value(concat(travel_record_id, concat("\t", travel_event_id))) if equal(field(travel_page, "has_more"), False): break require_condition(not_value(is_empty(travel_rows)), "An empty page has has_more=true; stop and reconcile the query.") travel_offset = add_offset(travel_offset, count(travel_rows)) if __name__ == "__main__": main() ``` ```csharp // .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\":true,\"requests\":{\"staff_pages\":{\"method\":\"GET\",\"path\":\"/events/staff\"},\"travel_pages\":{\"method\":\"GET\",\"path\":\"/events/travel_reservations\"}}}"); static readonly string ApiKey = HeaderKey(Required("EXHIBITDAY_API_KEY")); static string HeaderKey(string value) { if(value.Any(c=>c<32||c>126))throw new Exception("Use the API key as one ASCII header value without control characters");return value; } static readonly HttpClient Client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false }) { Timeout = TimeSpan.FromSeconds(30) }; internal static Func> Send = request => Client.SendAsync(request); sealed class Result { public int Status; public JsonNode Body; public Dictionary Headers; public string Raw; } // 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(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 Call(string name, JsonObject query = null, JsonNode body = null, string key = null) { var route = Spec["requests"][name]; var method = Text(route["method"]); var headers = new Dictionary(StringComparer.OrdinalIgnoreCase) { ["Authorization"] = "Bearer " + ApiKey, ["Accept"] = "application/json" }; if (method == "POST") { if (string.IsNullOrEmpty(key)) throw new Exception("Persist a logical create key before sending POST"); headers["Idempotency-Key"] = key; } 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); // 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. var resend = method == "GET"; 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 Send(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 = resend && (status == 429 || status >= 500); 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, Raw = raw }; } } throw new Exception("Retry limit reached"); } static string AddOffset(string offset,long received) { var result=checked(long.Parse(offset,CultureInfo.InvariantCulture)+received);if(received<=0||result>int.MaxValue)throw new Exception("Cannot advance this int32 offset; reconcile the query");return result.ToString(CultureInfo.InvariantCulture); } static string Concat(string left,string right) => left+right; static JsonArray Items(JsonNode value) => value as JsonArray ?? throw new Exception("Expected a JSON array"); static long Count(JsonNode value) => Items(value).Count; static bool Either(bool left,bool right) => left || right; static object Scalar(object value) { if(value is JsonValue json){if(json.TryGetValue(out var boolean))return boolean;if(json.TryGetValue(out var text))return text;return json.ToJsonString();}return value; } static bool Equal(object left,object right) => object.Equals(Scalar(left),Scalar(right)); static JsonNode Field(JsonNode value,string name) { if(value is not JsonObject obj || !obj.TryGetPropertyValue(name,out var item))throw new Exception("Missing response field: "+name);return item; } static bool IsEmpty(JsonNode value) => Count(value)==0; static bool IsPresent(string value) => value!=null && value!=""; static HashSet NewIdSet() => new HashSet(StringComparer.Ordinal); static bool NotValue(bool value) => !value; static string Optional(string name,string fallback) { var value=Environment.GetEnvironmentVariable(name);return value==null||value==""?fallback:value; } static string PageSize(string value) { if(string.IsNullOrEmpty(value)||value[0]=='0'||!value.All(c=>c>='0'&&c<='9')||!int.TryParse(value,NumberStyles.None,CultureInfo.InvariantCulture,out var limit)||limit<=0)throw new Exception("Page size must be a positive int32");return value; } static string PositiveId(string value) { if(string.IsNullOrEmpty(value)||value[0]=='0'||!value.All(c=>c>='0'&&c<='9')||!long.TryParse(value,NumberStyles.None,CultureInfo.InvariantCulture,out var id)||id<=0)throw new Exception("Use a positive record ID");return value; } static void PrintValue(object value) => Console.WriteLine(value is string text ? text : JsonSerializer.Serialize(value)); static bool RememberId(HashSet seen,string value) => seen.Add(value); static void RequireCondition(bool value,string message) { if(!value)throw new Exception(message); } static string Text(object value) => value==null?"":value is JsonNode node?Text(node):Convert.ToString(value,CultureInfo.InvariantCulture); internal static async Task Run() { var selected_page_size = PageSize(Optional("EXHIBITDAY_PAGE_SIZE", "100")); var selected_event_id = Optional("EXHIBITDAY_EVENT_ID", ""); if (IsPresent(selected_event_id)) { selected_event_id = PositiveId(selected_event_id); } var tagged_user_filter = Optional("EXHIBITDAY_TAGGED_USER_IDS_JSON", ""); var tag_match_type = Optional("EXHIBITDAY_TAG_MATCH_TYPE", "any"); RequireCondition(Either(Equal(tag_match_type, "any"), Equal(tag_match_type, "all")), "Choose any or all for EXHIBITDAY_TAG_MATCH_TYPE."); var staff_query = new JsonObject { ["$limit"] = selected_page_size }; if (IsPresent(selected_event_id)) { staff_query["filter_by_event_id"] = selected_event_id; } var staff_offset = "0"; var staff_seen_ids = NewIdSet(); PrintValue("Staff record ID\tEvent ID"); while (true) { staff_query["$offset"] = staff_offset; var staff_response = await Call("staff_pages", staff_query, null, null); var staff_page = staff_response.Body; var staff_rows = Items(Field(staff_page, "list_data")); RequireCondition(Equal(Text(Field(staff_page, "records_found")), Text(Count(staff_rows))), "records_found does not match this page's rows."); RequireCondition(IsPresent(Text(Field(staff_page, "total_records"))), "The collection wrapper needs total_records."); RequireCondition(Either(Equal(Field(staff_page, "has_more"), true), Equal(Field(staff_page, "has_more"), false)), "Expected a Boolean has_more value."); foreach (var staff_record in Items(staff_rows)) { var staff_record_id = PositiveId(Text(Field(staff_record, "id"))); var staff_event_id = PositiveId(Text(Field(staff_record, "event_id"))); if (IsPresent(selected_event_id)) { RequireCondition(Equal(staff_event_id, selected_event_id), "A returned row belongs to a different Event."); } if (RememberId(staff_seen_ids, staff_record_id)) { PrintValue(Concat(staff_record_id, Concat("\t", staff_event_id))); } } if (Equal(Field(staff_page, "has_more"), false)) { break; } RequireCondition(NotValue(IsEmpty(staff_rows)), "An empty page has has_more=true; stop and reconcile the query."); staff_offset = AddOffset(staff_offset, Count(staff_rows)); } var travel_query = new JsonObject { ["$limit"] = selected_page_size }; if (IsPresent(selected_event_id)) { travel_query["filter_by_event_id"] = selected_event_id; } if (IsPresent(tagged_user_filter)) { travel_query["filter_by_tagged_user_ids"] = tagged_user_filter; travel_query["filter_by_tagged_user_ids_match_type"] = tag_match_type; } var travel_offset = "0"; var travel_seen_ids = NewIdSet(); PrintValue("Travel record ID\tEvent ID"); while (true) { travel_query["$offset"] = travel_offset; var travel_response = await Call("travel_pages", travel_query, null, null); var travel_page = travel_response.Body; var travel_rows = Items(Field(travel_page, "list_data")); RequireCondition(Equal(Text(Field(travel_page, "records_found")), Text(Count(travel_rows))), "records_found does not match this page's rows."); RequireCondition(IsPresent(Text(Field(travel_page, "total_records"))), "The collection wrapper needs total_records."); RequireCondition(Either(Equal(Field(travel_page, "has_more"), true), Equal(Field(travel_page, "has_more"), false)), "Expected a Boolean has_more value."); foreach (var travel_record in Items(travel_rows)) { var travel_record_id = PositiveId(Text(Field(travel_record, "id"))); var travel_event_id = PositiveId(Text(Field(travel_record, "event_id"))); if (IsPresent(selected_event_id)) { RequireCondition(Equal(travel_event_id, selected_event_id), "A returned row belongs to a different Event."); } if (RememberId(travel_seen_ids, travel_record_id)) { PrintValue(Concat(travel_record_id, Concat("\t", travel_event_id))); } } if (Equal(Field(travel_page, "has_more"), false)) { break; } RequireCondition(NotValue(IsEmpty(travel_rows)), "An empty page has has_more=true; stop and reconcile the query."); travel_offset = AddOffset(travel_offset, Count(travel_rows)); } } static Task Main() => Run(); } ``` ```java // 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 SPEC = JSON.fromJson("{\"preserveNumbers\":true,\"requests\":{\"staff_pages\":{\"method\":\"GET\",\"path\":\"/events/staff\"},\"travel_pages\":{\"method\":\"GET\",\"path\":\"/events/travel_reservations\"}}}", Map.class); static final String API_KEY = headerKey(required("EXHIBITDAY_API_KEY")); static String headerKey(String value){if(value.chars().anyMatch(c->c<32||c>126))throw new IllegalArgumentException("Use the API key as one ASCII header value without control characters");return value;} static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).followRedirects(HttpClient.Redirect.NEVER).build(); interface RequestSender { HttpResponse send(HttpRequest request)throws IOException,InterruptedException; } static RequestSender SEND=request->CLIENT.send(request,HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); static class Result { int status; Object body; Map headers; String raw; Result(int s, Object b, Map h,String r) {status=s;body=b;headers=h;raw=r;} } // 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 obj(Object value) {return value==null?new LinkedHashMap<>(): (Map)value;} @SuppressWarnings("unchecked") static List list(Object value) {return value==null?Collections.emptyList():(List)value;} static Map map(Object... pairs) {Map result=new LinkedHashMap<>();for(int i=0;i query,Object body,String key) { Map route=obj(obj(SPEC.get("requests")).get(name));String method=text(route.get("method")); Map headers=map("Authorization","Bearer " + API_KEY,"Accept","application/json"); if(method.equals("POST")){if(key==null||key.isEmpty())throw new IllegalArgumentException("Persist a logical create key before sending POST");headers.put("Idempotency-Key",key);} 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); // 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. boolean resend=method.equals("GET"); 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 response; try {response=SEND.send(request.build());} 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();Object parsed=null; if(status!=304&&!response.body().isEmpty()) { try {parsed=JSON.fromJson(response.body(),Object.class);} catch(RuntimeException error){if(status<400)throw new IllegalStateException("Expected a JSON success response",error);} } Map 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=resend&&(status==429||status>=500); 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,response.body()); } throw new IllegalStateException("Retry limit reached"); } static String add_offset(String offset,long received){long result=Math.addExact(Long.parseLong(offset),received);if(received<=0||result>Integer.MAX_VALUE)throw new IllegalStateException("Cannot advance this int32 offset; reconcile the query");return Long.toString(result);} static String concat(String left,String right){return left+right;} static List items(Object value){if(!(value instanceof List))throw new IllegalStateException("Expected a JSON array");return list(value);} static long count(Object value){return items(value).size();} static boolean either(boolean left,boolean right){return left||right;} static boolean equal(Object left,Object right){return Objects.equals(left,right);} static Object field(Object value,String name){if(!(value instanceof Map)||!obj(value).containsKey(name))throw new IllegalStateException("Missing response field: "+name);return obj(value).get(name);} static boolean is_empty(Object value){return count(value)==0;} static boolean is_present(String value){return value!=null&&!value.isEmpty();} static Set new_id_set(){return new HashSet<>();} static boolean not_value(boolean value){return !value;} static String optional(String name,String fallback){String value=System.getenv(name);return value==null||value.isEmpty()?fallback:value;} static String page_size(String value){try{if(value==null||!value.matches("[1-9][0-9]*")||Integer.parseInt(value)<=0)throw new IllegalArgumentException();return value;}catch(RuntimeException error){throw new IllegalArgumentException("Page size must be a positive int32");}} static String positive_id(String value){try{if(value==null||!value.matches("[1-9][0-9]*")||Long.parseLong(value)<=0)throw new IllegalArgumentException();return value;}catch(RuntimeException error){throw new IllegalArgumentException("Use a positive record ID");}} static void print_value(Object value){try{String text=value instanceof String?(String)value:JSON.toJson(value);System.out.write((text+"\n").getBytes(StandardCharsets.UTF_8));}catch(IOException error){throw new UncheckedIOException(error);}} static boolean remember_id(Set seen,String value){return seen.add(value);} static void require_condition(boolean value,String message){if(!value)throw new IllegalStateException(message);} static void run()throws Exception { String selected_page_size = page_size(optional("EXHIBITDAY_PAGE_SIZE", "100")); String selected_event_id = optional("EXHIBITDAY_EVENT_ID", ""); if (is_present(selected_event_id)) { selected_event_id = positive_id(selected_event_id); } String tagged_user_filter = optional("EXHIBITDAY_TAGGED_USER_IDS_JSON", ""); String tag_match_type = optional("EXHIBITDAY_TAG_MATCH_TYPE", "any"); require_condition(either(equal(tag_match_type, "any"), equal(tag_match_type, "all")), "Choose any or all for EXHIBITDAY_TAG_MATCH_TYPE."); Map staff_query = map("$limit", selected_page_size); if (is_present(selected_event_id)) { staff_query.put("filter_by_event_id", selected_event_id); } String staff_offset = "0"; Set staff_seen_ids = new_id_set(); print_value("Staff record ID\tEvent ID"); while (true) { staff_query.put("$offset", staff_offset); Result staff_response = call("staff_pages", staff_query, null, null); Object staff_page = staff_response.body; List staff_rows = items(field(staff_page, "list_data")); require_condition(equal(text(field(staff_page, "records_found")), text(count(staff_rows))), "records_found does not match this page's rows."); require_condition(is_present(text(field(staff_page, "total_records"))), "The collection wrapper needs total_records."); require_condition(either(equal(field(staff_page, "has_more"), true), equal(field(staff_page, "has_more"), false)), "Expected a Boolean has_more value."); for (Object staff_record : items(staff_rows)) { String staff_record_id = positive_id(text(field(staff_record, "id"))); String staff_event_id = positive_id(text(field(staff_record, "event_id"))); if (is_present(selected_event_id)) { require_condition(equal(staff_event_id, selected_event_id), "A returned row belongs to a different Event."); } if (remember_id(staff_seen_ids, staff_record_id)) { print_value(concat(staff_record_id, concat("\t", staff_event_id))); } } if (equal(field(staff_page, "has_more"), false)) { break; } require_condition(not_value(is_empty(staff_rows)), "An empty page has has_more=true; stop and reconcile the query."); staff_offset = add_offset(staff_offset, count(staff_rows)); } Map travel_query = map("$limit", selected_page_size); if (is_present(selected_event_id)) { travel_query.put("filter_by_event_id", selected_event_id); } if (is_present(tagged_user_filter)) { travel_query.put("filter_by_tagged_user_ids", tagged_user_filter); travel_query.put("filter_by_tagged_user_ids_match_type", tag_match_type); } String travel_offset = "0"; Set travel_seen_ids = new_id_set(); print_value("Travel record ID\tEvent ID"); while (true) { travel_query.put("$offset", travel_offset); Result travel_response = call("travel_pages", travel_query, null, null); Object travel_page = travel_response.body; List travel_rows = items(field(travel_page, "list_data")); require_condition(equal(text(field(travel_page, "records_found")), text(count(travel_rows))), "records_found does not match this page's rows."); require_condition(is_present(text(field(travel_page, "total_records"))), "The collection wrapper needs total_records."); require_condition(either(equal(field(travel_page, "has_more"), true), equal(field(travel_page, "has_more"), false)), "Expected a Boolean has_more value."); for (Object travel_record : items(travel_rows)) { String travel_record_id = positive_id(text(field(travel_record, "id"))); String travel_event_id = positive_id(text(field(travel_record, "event_id"))); if (is_present(selected_event_id)) { require_condition(equal(travel_event_id, selected_event_id), "A returned row belongs to a different Event."); } if (remember_id(travel_seen_ids, travel_record_id)) { print_value(concat(travel_record_id, concat("\t", travel_event_id))); } } if (equal(field(travel_page, "has_more"), false)) { break; } require_condition(not_value(is_empty(travel_rows)), "An empty page has has_more=true; stop and reconcile the query."); travel_offset = add_offset(travel_offset, count(travel_rows)); } } public static void main(String[] args)throws Exception {run();} } ``` ```php $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, ?string $key = null): array { global $spec, $apiKey, $transport; $route = $spec['requests'][$name]; $headers = ['Authorization' => 'Bearer ' . $apiKey, 'Accept' => 'application/json']; if ($route['method'] === 'POST') { if ($key === null || $key === '') throw new RuntimeException('Persist a logical create key before sending POST'); $headers['Idempotency-Key'] = $key; // 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); // 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 = 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 = $resend && ($status === 429 || $status >= 500); 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, 'raw' => $raw]; } throw new RuntimeException('Retry limit reached'); } $transport = Closure::fromCallable('nativeTransport'); function add_offset(string $offset,int $received):string{$result=(int)$offset+$received;if($received<=0||$result>2147483647)throw new RuntimeException("Cannot advance this int32 offset; reconcile the query");return (string)$result;} function concat(string $left,string $right):string{return $left.$right;} function either(bool $left,bool $right):bool{return $left||$right;} function equal(mixed $left,mixed $right):bool{return $left===$right;} function field(mixed $value,string $name):mixed{if(!is_array($value)||!array_key_exists($name,$value))throw new RuntimeException("Missing response field: ".$name);return $value[$name];} function items(mixed $value):array{if(!is_array($value)||!array_is_list($value))throw new RuntimeException("Expected a JSON array");return $value;} function is_empty(mixed $value):bool{return count(items($value))===0;} function is_present(?string $value):bool{return $value!==null&&$value!=="";} function new_id_set():array{return [];} function not_value(bool $value):bool{return !$value;} function page_size(string $value):string{if(!preg_match("/^[1-9][0-9]*$/D",$value)||strlen($value)>10||(strlen($value)===10&&strcmp($value,"2147483647")>0))throw new RuntimeException("Page size must be a positive int32");return $value;} function positive_id(string $value):string{if(!preg_match("/^[1-9][0-9]*$/D",$value)||strlen($value)>19||(strlen($value)===19&&strcmp($value,"9223372036854775807")>0))throw new RuntimeException("Use a positive record ID");return $value;} function print_value(mixed $value):void{echo (is_string($value)?$value:json_encode($value,JSON_THROW_ON_ERROR))."\n";} function remember_id(array &$seen,string $value):bool{if(array_key_exists($value,$seen))return false;$seen[$value]=true;return true;} function require_condition(bool $value,string $message):void{if(!$value)throw new RuntimeException($message);} function text(mixed $value):string{if($value===null)return "";if(is_string($value))return $value;if(is_bool($value))return $value?"true":"false";if(is_int($value))return (string)$value;throw new RuntimeException("Expected a scalar response value");} function main():void { $selected_page_size = page_size(optional('EXHIBITDAY_PAGE_SIZE', '100')); $selected_event_id = optional('EXHIBITDAY_EVENT_ID', ''); if (is_present($selected_event_id)) { $selected_event_id = positive_id($selected_event_id); } $tagged_user_filter = optional('EXHIBITDAY_TAGGED_USER_IDS_JSON', ''); $tag_match_type = optional('EXHIBITDAY_TAG_MATCH_TYPE', 'any'); require_condition(either(equal($tag_match_type, 'any'), equal($tag_match_type, 'all')), 'Choose any or all for EXHIBITDAY_TAG_MATCH_TYPE.'); $staff_query = ['$limit' => $selected_page_size]; if (is_present($selected_event_id)) { $staff_query['filter_by_event_id'] = $selected_event_id; } $staff_offset = '0'; $staff_seen_ids = new_id_set(); print_value(json_decode('"Staff record ID\\tEvent ID"', false, 512, JSON_THROW_ON_ERROR)); while (true) { $staff_query['$offset'] = $staff_offset; $staff_response = call('staff_pages', $staff_query, null, null); $staff_page = $staff_response["body"]; $staff_rows = items(field($staff_page, 'list_data')); require_condition(equal(text(field($staff_page, 'records_found')), text(count($staff_rows))), 'records_found does not match this page\'s rows.'); require_condition(is_present(text(field($staff_page, 'total_records'))), 'The collection wrapper needs total_records.'); require_condition(either(equal(field($staff_page, 'has_more'), true), equal(field($staff_page, 'has_more'), false)), 'Expected a Boolean has_more value.'); foreach (items($staff_rows) as $staff_record) { $staff_record_id = positive_id(text(field($staff_record, 'id'))); $staff_event_id = positive_id(text(field($staff_record, 'event_id'))); if (is_present($selected_event_id)) { require_condition(equal($staff_event_id, $selected_event_id), 'A returned row belongs to a different Event.'); } if (remember_id($staff_seen_ids, $staff_record_id)) { print_value(concat($staff_record_id, concat(json_decode('"\\t"', false, 512, JSON_THROW_ON_ERROR), $staff_event_id))); } } if (equal(field($staff_page, 'has_more'), false)) { break; } require_condition(not_value(is_empty($staff_rows)), 'An empty page has has_more=true; stop and reconcile the query.'); $staff_offset = add_offset($staff_offset, count($staff_rows)); } $travel_query = ['$limit' => $selected_page_size]; if (is_present($selected_event_id)) { $travel_query['filter_by_event_id'] = $selected_event_id; } if (is_present($tagged_user_filter)) { $travel_query['filter_by_tagged_user_ids'] = $tagged_user_filter; $travel_query['filter_by_tagged_user_ids_match_type'] = $tag_match_type; } $travel_offset = '0'; $travel_seen_ids = new_id_set(); print_value(json_decode('"Travel record ID\\tEvent ID"', false, 512, JSON_THROW_ON_ERROR)); while (true) { $travel_query['$offset'] = $travel_offset; $travel_response = call('travel_pages', $travel_query, null, null); $travel_page = $travel_response["body"]; $travel_rows = items(field($travel_page, 'list_data')); require_condition(equal(text(field($travel_page, 'records_found')), text(count($travel_rows))), 'records_found does not match this page\'s rows.'); require_condition(is_present(text(field($travel_page, 'total_records'))), 'The collection wrapper needs total_records.'); require_condition(either(equal(field($travel_page, 'has_more'), true), equal(field($travel_page, 'has_more'), false)), 'Expected a Boolean has_more value.'); foreach (items($travel_rows) as $travel_record) { $travel_record_id = positive_id(text(field($travel_record, 'id'))); $travel_event_id = positive_id(text(field($travel_record, 'event_id'))); if (is_present($selected_event_id)) { require_condition(equal($travel_event_id, $selected_event_id), 'A returned row belongs to a different Event.'); } if (remember_id($travel_seen_ids, $travel_record_id)) { print_value(concat($travel_record_id, concat(json_decode('"\\t"', false, 512, JSON_THROW_ON_ERROR), $travel_event_id))); } } if (equal(field($travel_page, 'has_more'), false)) { break; } require_condition(not_value(is_empty($travel_rows)), 'An empty page has has_more=true; stop and reconcile the query.'); $travel_offset = add_offset($travel_offset, count($travel_rows)); } } if (realpath($_SERVER['SCRIPT_FILENAME'] ?? '') === __FILE__) main(); ``` ```ruby # 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":true,"requests":{"staff_pages":{"method":"GET","path":"/events/staff"},"travel_pages":{"method":"GET","path":"/events/travel_reservations"}}}') API_KEY = ENV.fetch('EXHIBITDAY_API_KEY') raise 'Use the API key as one ASCII header value without control characters' if API_KEY.each_codepoint.any?{|point|point<32||point>126} 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, 'DELETE' => Net::HTTP::Delete }.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, key = nil) route = SPEC.fetch('requests').fetch(name) headers = { 'Authorization' => 'Bearer ' + API_KEY, 'Accept' => 'application/json' } if route.fetch('method') == 'POST' headers['Idempotency-Key'] = key || raise('Persist a logical create key before sending POST') # 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) # 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.fetch('method') == 'GET' 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 = resend && (status == 429 || (500..599).cover?(status)) 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, raw: raw } end raise 'Retry limit reached' end def add_offset(offset,received) result=Integer(offset)+received raise "Cannot advance this int32 offset; reconcile the query" if received<=0 || result>2147483647 result.to_s end def concat(left,right) left+right end def items(value) raise "Expected a JSON array" unless value.is_a?(Array) value end def count(value) items(value).length end def either(left,right) raise "Expected Boolean criteria" unless [true,false].include?(left) && [true,false].include?(right) left || right end def equal(left,right) left.class==right.class && left==right end def field(value,name) raise "Missing response field: #{name}" unless value.is_a?(Hash) && value.key?(name) value.fetch(name) end def is_empty(value) count(value)==0 end def is_present(value) !value.nil? && value!="" end def new_id_set {} end def not_value(value) raise "Expected a Boolean" unless value==true || value==false !value end def optional(name,fallback) value=ENV[name] value.nil? || value.empty? ? fallback : value end def page_size(value) raise "Page size must be a positive int32" unless /\A[1-9][0-9]*\z/.match?(value) && Integer(value)<=2147483647 value end def positive_id(value) raise "Use a positive record ID" unless /\A[1-9][0-9]*\z/.match?(value) && Integer(value)<=9223372036854775807 value end def print_value(value) STDOUT.binmode.write((value.is_a?(String)?value:JSON.generate(value))+"\n") end def remember_id(seen,value) return false if seen.key?(value) seen[value]=true true end def require_condition(value,message) raise message unless value==true end def text(value) return "" if value.nil? return value.to_s if value.is_a?(String)||value.is_a?(Integer)||value==true||value==false raise "Expected a scalar response value" end def main selected_page_size = page_size(optional('EXHIBITDAY_PAGE_SIZE', '100')) selected_event_id = optional('EXHIBITDAY_EVENT_ID', '') if is_present(selected_event_id) selected_event_id = positive_id(selected_event_id) end tagged_user_filter = optional('EXHIBITDAY_TAGGED_USER_IDS_JSON', '') tag_match_type = optional('EXHIBITDAY_TAG_MATCH_TYPE', 'any') require_condition(either(equal(tag_match_type, 'any'), equal(tag_match_type, 'all')), 'Choose any or all for EXHIBITDAY_TAG_MATCH_TYPE.') staff_query = {'$limit' => selected_page_size} if is_present(selected_event_id) staff_query['filter_by_event_id'] = selected_event_id end staff_offset = '0' staff_seen_ids = new_id_set() print_value(JSON.parse('"Staff record ID\\tEvent ID"')) while true staff_query['$offset'] = staff_offset staff_response = call('staff_pages', staff_query, nil, nil) staff_page = staff_response.fetch(:body) staff_rows = items(field(staff_page, 'list_data')) require_condition(equal(text(field(staff_page, 'records_found')), text(count(staff_rows))), 'records_found does not match this page\'s rows.') require_condition(is_present(text(field(staff_page, 'total_records'))), 'The collection wrapper needs total_records.') require_condition(either(equal(field(staff_page, 'has_more'), true), equal(field(staff_page, 'has_more'), false)), 'Expected a Boolean has_more value.') items(staff_rows).each do |staff_record| staff_record_id = positive_id(text(field(staff_record, 'id'))) staff_event_id = positive_id(text(field(staff_record, 'event_id'))) if is_present(selected_event_id) require_condition(equal(staff_event_id, selected_event_id), 'A returned row belongs to a different Event.') end if remember_id(staff_seen_ids, staff_record_id) print_value(concat(staff_record_id, concat(JSON.parse('"\\t"'), staff_event_id))) end end if equal(field(staff_page, 'has_more'), false) break end require_condition(not_value(is_empty(staff_rows)), 'An empty page has has_more=true; stop and reconcile the query.') staff_offset = add_offset(staff_offset, count(staff_rows)) end travel_query = {'$limit' => selected_page_size} if is_present(selected_event_id) travel_query['filter_by_event_id'] = selected_event_id end if is_present(tagged_user_filter) travel_query['filter_by_tagged_user_ids'] = tagged_user_filter travel_query['filter_by_tagged_user_ids_match_type'] = tag_match_type end travel_offset = '0' travel_seen_ids = new_id_set() print_value(JSON.parse('"Travel record ID\\tEvent ID"')) while true travel_query['$offset'] = travel_offset travel_response = call('travel_pages', travel_query, nil, nil) travel_page = travel_response.fetch(:body) travel_rows = items(field(travel_page, 'list_data')) require_condition(equal(text(field(travel_page, 'records_found')), text(count(travel_rows))), 'records_found does not match this page\'s rows.') require_condition(is_present(text(field(travel_page, 'total_records'))), 'The collection wrapper needs total_records.') require_condition(either(equal(field(travel_page, 'has_more'), true), equal(field(travel_page, 'has_more'), false)), 'Expected a Boolean has_more value.') items(travel_rows).each do |travel_record| travel_record_id = positive_id(text(field(travel_record, 'id'))) travel_event_id = positive_id(text(field(travel_record, 'event_id'))) if is_present(selected_event_id) require_condition(equal(travel_event_id, selected_event_id), 'A returned row belongs to a different Event.') end if remember_id(travel_seen_ids, travel_record_id) print_value(concat(travel_record_id, concat(JSON.parse('"\\t"'), travel_event_id))) end end if equal(field(travel_page, 'has_more'), false) break end require_condition(not_value(is_empty(travel_rows)), 'An empty page has has_more=true; stop and reconcile the query.') travel_offset = add_offset(travel_offset, count(travel_rows)) end end main if $PROGRAM_NAME == __FILE__ ``` ```go // Go 1.18+; standard library only. Set EXHIBITDAY_API_KEY. package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "net/url" "os" "strconv" "strings" "time" ) const base = "https://api.exhibitday.com/v1" const specification = "{\"preserveNumbers\":true,\"requests\":{\"staff_pages\":{\"method\":\"GET\",\"path\":\"/events/staff\"},\"travel_pages\":{\"method\":\"GET\",\"path\":\"/events/travel_reservations\"}}}" 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 }} var send = client.Do type result struct { status int; body any; headers http.Header; raw []byte } // 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 call(name string, query map[string]string, body any, key string) result { route := object(object(spec["requests"])[name]); method := text(route["method"]) headers := map[string]string{"Authorization": "Bearer " + apiKey, "Accept": "application/json"} if method == "POST" { if key == "" { panic("Persist a logical create key before sending POST") }; 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() } // 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 := method == "GET" 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 := send(request) if err != nil { if !resend { panic(apiError{0, "", "No response", true}) }; if attempt == 4 { panic(err) }; time.Sleep(time.Second*time.Duration(1<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 := resend && (response.StatusCode == 429 || response.StatusCode >= 500) if retry { if attempt == 4 { panic("Retry limit reached; check the outcome before starting a new create") } seconds := float64(int64(1)<= 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, raw} } panic("Retry limit reached") } func add_offset(offset string,received int64)string{previous,err:=strconv.ParseInt(offset,10,32);if err!=nil||received<=0||received>2147483647-previous{panic("Cannot advance this int32 offset; reconcile the query")};return strconv.FormatInt(previous+received,10)} func concat(left,right string)string{return left+right} func items(value any)[]any{result,ok:=value.([]any);if !ok{panic("Expected a JSON array")};return result} func count(value any)int64{return int64(len(items(value)))} func either(left,right bool)bool{return left||right} func equal(left,right any)bool{switch a:=left.(type){case string:b,ok:=right.(string);return ok&&a==b;case bool:b,ok:=right.(bool);return ok&&a==b;case int64:b,ok:=right.(int64);return ok&&a==b};return left==nil&&right==nil} func field(value any,name string)any{obj,ok:=value.(map[string]any);if !ok{panic("Missing response object")};item,found:=obj[name];if !found{panic("Missing response field: "+name)};return item} func is_empty(value any)bool{return count(value)==0} func is_present(value string)bool{return value!=""} func new_id_set()map[string]bool{return map[string]bool{}} func not_value(value bool)bool{return !value} func optional(name,fallback string)string{value:=os.Getenv(name);if value==""{return fallback};return value} func page_size(value string)string{valid:=len(value)>0&&value[0]!='0';for _,ch:=range value{valid=valid&&ch>='0'&&ch<='9'};size,err:=strconv.ParseInt(value,10,32);if !valid||err!=nil||size<=0{panic("Page size must be a positive int32")};return value} func positive_id(value string)string{valid:=len(value)>0&&value[0]!='0';for _,ch:=range value{valid=valid&&ch>='0'&&ch<='9'};id,err:=strconv.ParseInt(value,10,64);if !valid||err!=nil||id<=0{panic("Use a positive record ID")};return value} func print_value(value any){if result,ok:=value.(string);ok{fmt.Println(result);return};raw,err:=json.Marshal(value);if err!=nil{panic(err)};fmt.Println(string(raw))} func remember_id(seen map[string]bool,value string)bool{if seen[value]{return false};seen[value]=true;return true} func require_condition(value bool,message string){if !value{panic(message)}} func workflow() { selected_page_size := page_size(optional("EXHIBITDAY_PAGE_SIZE", "100")) selected_event_id := optional("EXHIBITDAY_EVENT_ID", "") if is_present(selected_event_id) { selected_event_id = positive_id(selected_event_id) } tagged_user_filter := optional("EXHIBITDAY_TAGGED_USER_IDS_JSON", "") tag_match_type := optional("EXHIBITDAY_TAG_MATCH_TYPE", "any") require_condition(either(equal(tag_match_type, "any"), equal(tag_match_type, "all")), "Choose any or all for EXHIBITDAY_TAG_MATCH_TYPE.") staff_query := map[string]string{"$limit": selected_page_size} if is_present(selected_event_id) { staff_query["filter_by_event_id"] = selected_event_id } staff_offset := "0" staff_seen_ids := new_id_set() print_value("Staff record ID\tEvent ID") for true { staff_query["$offset"] = staff_offset staff_response := call("staff_pages", staff_query, nil, "") staff_page := staff_response.body staff_rows := items(field(staff_page, "list_data")) require_condition(equal(text(field(staff_page, "records_found")), text(count(staff_rows))), "records_found does not match this page's rows.") require_condition(is_present(text(field(staff_page, "total_records"))), "The collection wrapper needs total_records.") require_condition(either(equal(field(staff_page, "has_more"), true), equal(field(staff_page, "has_more"), false)), "Expected a Boolean has_more value.") for _, staff_record := range items(staff_rows) { staff_record_id := positive_id(text(field(staff_record, "id"))) staff_event_id := positive_id(text(field(staff_record, "event_id"))) if is_present(selected_event_id) { require_condition(equal(staff_event_id, selected_event_id), "A returned row belongs to a different Event.") } if remember_id(staff_seen_ids, staff_record_id) { print_value(concat(staff_record_id, concat("\t", staff_event_id))) } } if equal(field(staff_page, "has_more"), false) { break } require_condition(not_value(is_empty(staff_rows)), "An empty page has has_more=true; stop and reconcile the query.") staff_offset = add_offset(staff_offset, count(staff_rows)) } travel_query := map[string]string{"$limit": selected_page_size} if is_present(selected_event_id) { travel_query["filter_by_event_id"] = selected_event_id } if is_present(tagged_user_filter) { travel_query["filter_by_tagged_user_ids"] = tagged_user_filter travel_query["filter_by_tagged_user_ids_match_type"] = tag_match_type } travel_offset := "0" travel_seen_ids := new_id_set() print_value("Travel record ID\tEvent ID") for true { travel_query["$offset"] = travel_offset travel_response := call("travel_pages", travel_query, nil, "") travel_page := travel_response.body travel_rows := items(field(travel_page, "list_data")) require_condition(equal(text(field(travel_page, "records_found")), text(count(travel_rows))), "records_found does not match this page's rows.") require_condition(is_present(text(field(travel_page, "total_records"))), "The collection wrapper needs total_records.") require_condition(either(equal(field(travel_page, "has_more"), true), equal(field(travel_page, "has_more"), false)), "Expected a Boolean has_more value.") for _, travel_record := range items(travel_rows) { travel_record_id := positive_id(text(field(travel_record, "id"))) travel_event_id := positive_id(text(field(travel_record, "event_id"))) if is_present(selected_event_id) { require_condition(equal(travel_event_id, selected_event_id), "A returned row belongs to a different Event.") } if remember_id(travel_seen_ids, travel_record_id) { print_value(concat(travel_record_id, concat("\t", travel_event_id))) } } if equal(field(travel_page, "has_more"), false) { break } require_condition(not_value(is_empty(travel_rows)), "An empty page has has_more=true; stop and reconcile the query.") travel_offset = add_offset(travel_offset, count(travel_rows)) } } func header_key(value string)string{for _,ch:=range value{if ch<32||ch>126{panic("Use the API key as one ASCII header value without control characters")}};return value} func main(){apiKey=header_key(required("EXHIBITDAY_API_KEY"));if err:=json.Unmarshal([]byte(specification),&spec);err!=nil{panic(err)};workflow()} ``` #### Things to keep in mind - Lists leave out records on an Event tab that is hidden. If you filter a list to one Event whose tab is hidden, the response includes a warning that names the tab. Tasks are the exception: hiding an Event's Tasks tab does not hide its Tasks. - Staff uses `filter_by_attendee_user_ids` and matches any listed person. Travel, Playbook Activities and Event Misc. Expenses/Credits use `filter_by_tagged_user_ids` with `filter_by_tagged_user_ids_match_type`. Send an ID array as JSON text in the GET query string. - People filters match saved assignments or tags, including IDs of inactive or removed people that are still on the record. IDs with no saved match return nothing. The API returns only records your key can read. - Records can shift between pages when someone adds, removes or edits them. Keep each ID once and reconcile longer exports when needed. - If a page is empty and `has_more` is true, investigate the result before continuing. - Related data options vary by endpoint. Turn on only what your report uses. #### Example response Response 200 — OK 304 — Not Modified 400 — Bad Request 401 — Unauthorized 404 — Not Found 409 — Conflict 429 — Too Many Requests 500 — Internal Server Error Example Successful request ```json { "list_type": "travel_reservation", "list_data": [ { "id": 201, "event_id": 5001, "event_name": "Spring Expo 2030", "reservation_type_id": 6, "booking_status_id": 20, "book_by_date": null, "date_booked": null, "booking_url": null, "cancellation_instructions": "", "vehicle_drop_off_location": null, "reservation_number": null, "origin_vendor_name": "Spring Expo Conference Hotel", "origin_flight_number": null, "origin_reservation_item_info": null, "origin_checkin_location": null, "origin_checkin_date": "2030-01-14", "origin_checkin_time": null, "origin_reservation_details": null, "origin_destination_location": null, "origin_destination_date": null, "origin_destination_time": null, "origin_reservation_final_details": null, "return_vendor_name": null, "return_flight_number": null, "return_reservation_item_info": null, "return_checkin_location": null, "return_checkin_date": "2030-01-17", "return_checkin_time": null, "return_reservation_details": null, "return_destination_location": null, "return_destination_date": null, "return_destination_time": null, "return_reservation_final_details": null, "origin_vendor_address": null, "notes": "", "payment_status_id": 0, "payment_due_date": null, "next_payment_due_date": null, "payment_notes": null, "invoice_attachment": null, "reservation_type": "Hotel", "reservation_group": "Lodging", "booking_status": "Booked", "payment_status": { "id": 0, "name": "N/A" }, "cost": { "amount": 0.00, "cost_center_breakdown": [] }, "tagged_users": [ { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Alex", "last_name": "Morgan", "display_name": "Alex Morgan", "email": "alex@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, { "id": "66666666-7777-4888-8999-000000000000", "first_name": "Jordan", "last_name": "Lee", "display_name": "Jordan Lee", "email": "jordan@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true } ], "created_by": { "id": null, "first_name": "ExhibitDay", "last_name": "API", "display_name": "ExhibitDay API", "email": null, "type": null, "workspace_role": null, "is_active": true } }, { "id": 202, "event_id": 5002, "event_name": "Lakeshore Expo 2030", "reservation_type_id": 6, "booking_status_id": 20, "book_by_date": null, "date_booked": null, "booking_url": null, "cancellation_instructions": "", "vehicle_drop_off_location": null, "reservation_number": null, "origin_vendor_name": "Lakeshore Convention Hotel", "origin_flight_number": null, "origin_reservation_item_info": null, "origin_checkin_location": null, "origin_checkin_date": "2030-02-11", "origin_checkin_time": null, "origin_reservation_details": null, "origin_destination_location": null, "origin_destination_date": null, "origin_destination_time": null, "origin_reservation_final_details": null, "return_vendor_name": null, "return_flight_number": null, "return_reservation_item_info": null, "return_checkin_location": null, "return_checkin_date": "2030-02-14", "return_checkin_time": null, "return_reservation_details": null, "return_destination_location": null, "return_destination_date": null, "return_destination_time": null, "return_reservation_final_details": null, "origin_vendor_address": null, "notes": "", "payment_status_id": 0, "payment_due_date": null, "next_payment_due_date": null, "payment_notes": null, "invoice_attachment": null, "reservation_type": "Hotel", "reservation_group": "Lodging", "booking_status": "Booked", "payment_status": { "id": 0, "name": "N/A" }, "cost": { "amount": 0.00, "cost_center_breakdown": [] }, "tagged_users": [ { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Alex", "last_name": "Morgan", "display_name": "Alex Morgan", "email": "alex@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, { "id": "66666666-7777-4888-8999-000000000000", "first_name": "Jordan", "last_name": "Lee", "display_name": "Jordan Lee", "email": "jordan@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true } ], "created_by": { "id": null, "first_name": "ExhibitDay", "last_name": "API", "display_name": "ExhibitDay API", "email": null, "type": null, "workspace_role": null, "is_active": true } } ], "records_found": 2, "total_records": 3, "has_more": true } ``` Note: First Travel page. An illustrative workspace-wide page with two Hotel reservations. A third matching reservation remains for the next page. Note: There is no response body. Keep using your cached response. ```json { "status_code": 400, "status": "Bad Request", "message": "X-HTTP-Method-Override: hTTP method override is not supported.", "error_code": "invalid_request", "errors": [ "Send the documented HTTP method directly. X-HTTP-Method-Override cannot change a request's HTTP method." ], "error_params": [ "X-HTTP-Method-Override" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 400, "status": "Bad Request", "message": "filter_by_tagged_user_ids must be one user ID or an array of user IDs. Each ID is text of 1 to 128 characters; numbers, true/false, null, blank values and objects are not IDs. For example, send \"user-id\" or [\"user-id\",\"other-user-id\"].", "error_code": "invalid_request", "errors": [ "filter_by_tagged_user_ids must be one user ID or an array of user IDs. Each ID is text of 1 to 128 characters; numbers, true/false, null, blank values and objects are not IDs. For example, send \"user-id\" or [\"user-id\",\"other-user-id\"]." ], "error_params": [ "filter_by_tagged_user_ids" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "No API key was provided. Send your key in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "missing_api_key", "errors": [ "Copy the key from Workspace Settings > API & Integrations > API Access in ExhibitDay." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "The API key is not valid. Check that you copied the whole key from Workspace Settings > API & Integrations > API Access, then send it in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "invalid_api_key", "errors": [ "Check that you sent the whole key. If it was regenerated, use the current key from Workspace Settings > API & Integrations > API Access." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "Access to the ExhibitDay API is not enabled for your workspace. Please contact support@exhibitday.com to enable API Access. Once access is enabled, send your key in the Authorization header as 'Bearer YOUR_API_KEY'.", "error_code": "api_access_disabled", "errors": [ "Nothing was read or changed." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "The API key is not valid for this request. Send your current key in the Authorization header as 'Bearer YOUR_API_KEY'.", "error_code": "invalid_api_key", "errors": [ "The API key is not valid for this request. Send your current key in the Authorization header as 'Bearer YOUR_API_KEY'." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "Access to the ExhibitDay API is not enabled for your workspace. Please contact support@exhibitday.com to enable API Access. Once access is enabled, send your key in the Authorization header as 'Bearer YOUR_API_KEY'.", "error_code": "api_access_disabled", "errors": [ "Access to the ExhibitDay API is not enabled for your workspace. Please contact support@exhibitday.com to enable API Access. Once access is enabled, send your key in the Authorization header as 'Bearer YOUR_API_KEY'." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 404, "status": "Not Found", "message": "The invoice attachment is not available under this owning record.", "error_code": "not_found", "errors": [ "The invoice attachment is not available under this owning record." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "The invoice attachment or its owning record changed or has conflicting saved information. Retrieve the current record before retrying.", "error_code": "record_changed", "errors": [ "The invoice attachment or its owning record changed or has conflicting saved information. Retrieve the current record before retrying." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "The Travel entries changed while they were being read. Send the GET request again.", "error_code": "record_changed", "errors": [ "The Travel entries changed while they were being read. Send the GET request again." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 429, "status": "Too Many Requests", "message": "Error 429 - Too Many Requests", "error_code": "rate_limited", "errors": [ "Error 429 - Too Many Requests" ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "An unexpected error occurred. Please try again later." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "An unexpected error occurred. Please try again later." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` Note: Use the request_id from your own response when contacting support. ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "Check whether your change was saved before trying again." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` #### Related guides - [Keep Another System Updated with Event and Task Changes](https://api.exhibitday.com/Help/V1?guide=sync-changes) - [Export Event Costs to Excel or a Reporting Tool](https://api.exhibitday.com/Help/V1?guide=export-event-costs) - [Search Activity Audit Logs to See Who Changed What, and When](https://api.exhibitday.com/Help/V1?guide=workspace-activity) ### Avoid Overwriting Someone Else's Changes Guide page: https://api.exhibitday.com/Help/V1?guide=update-records-safely Update a record only if nobody else changed it since you read it. Example use case A supplier confirms the final artwork and you need to rename an existing Task while teammates are editing it. What you'll end up with A Task name update that checks the revision you read, followed by a readback of the current name and revision. Before you start Have a workspace API key and the ID of an existing Task that the key can read and edit. Good to know Keep the revision exactly as the API returns it. The PATCH leaves omitted fields as they are. #### At a glance Time to try About 10 minutes Effect on your data Updates records Endpoints 3 The example updates the Task name and writes a private local journal. - [`GET /v1/references/workspace_info`](https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-workspace_info) - [`GET /v1/tasks/info`](https://api.exhibitday.com/Help/V1?epf=2#get-v1-tasks-info) - [`PATCH /v1/tasks`](https://api.exhibitday.com/Help/V1?epf=2#patch-v1-tasks) #### How it works 1. The program reads the Task and saves its current revision. 2. It sends only the new name with that revision. A conflict stops the run. 3. It reads the Task again to confirm the saved name. #### Update the Task name The examples below read, update and verify one Task. #### Step 1: Confirm the workspace Check where the key will make changes so you can confirm the workspace. ```bash curl -X GET "https://api.exhibitday.com/v1/references/workspace_info" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "id": 98765 } ``` **Check:** Confirm id is the workspace you intended to use. #### Step 2: Read the current Task and its revision Request the current name and revision so the update can detect changes made since your read. ```bash curl -X GET "https://api.exhibitday.com/v1/tasks/info?id=12345&%24include_record_revision=true" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "id": 12345, "name": "Review booth artwork", "record_revision": "COPY_TASK_REVISION_FROM_YOUR_READ" } ``` **Check:** Confirm the Task ID and keep record_revision exactly as returned. The example below uses a placeholder. #### Step 3: Save only the Task name Send the new name with expected_revision from your read so the API can check for a conflict. ```bash curl -X PATCH "https://api.exhibitday.com/v1/tasks" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" --data-binary "{\"id\":12345,\"name\":\"Confirm booth artwork with the supplier\",\"expected_revision\":\"COPY_TASK_REVISION_FROM_YOUR_READ\"}" ``` Example response (shortened) ```json { "record_revision": "NEW_TASK_REVISION" } ``` **Check:** A successful response includes record_revision. If you get record_changed (HTTP 409), read the Task again and decide whether your change is still needed before sending another update. #### Step 4: Confirm the saved name Read the Task again to confirm its current name and revision. ```bash curl -X GET "https://api.exhibitday.com/v1/tasks/info?id=12345&%24include_record_revision=true" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "id": 12345, "name": "Confirm booth artwork with the supplier", "record_revision": "CURRENT_TASK_REVISION_FROM_READBACK" } ``` **Check:** Confirm the ID and name match your intended change. The revision is the current value from this read. **Careful.** Use the revision from your own read. After a conflict, review the latest Task before trying again. #### Try it #### Before running the example | Variable | What to put in it | Required? | | --- | --- | --- | | `EXHIBITDAY_API_KEY` | Your workspace API key. | Yes | | `EXHIBITDAY_TASK_ID` | The ID of an existing Task you can edit. | Yes | | `EXHIBITDAY_TASK_NAME` | The new Task name in plain text. | Yes | | `EXHIBITDAY_JOB_ID` | A stable ID for this logical change. | Yes | | `EXHIBITDAY_JOURNAL` | A private local path for this job's journal. | Yes | | `EXHIBITDAY_JOB_MODE` | Use new for a genuinely new job or resume with the existing journal. The default is resume. | No | **Careful.** This example updates an existing Task. Use a test Task. #### Bash ``` export EXHIBITDAY_API_KEY='YOUR_API_KEY' export EXHIBITDAY_TASK_ID='12345' export EXHIBITDAY_TASK_NAME='Confirm booth artwork with the supplier' ``` #### PowerShell ``` $env:EXHIBITDAY_API_KEY = 'YOUR_API_KEY' $env:EXHIBITDAY_TASK_ID = '12345' $env:EXHIBITDAY_TASK_NAME = 'Confirm booth artwork with the supplier' ``` Use your own Task ID and name. Set a private journal path and job ID. Set `EXHIBITDAY_JOB_MODE=new` for a new job, then run the complete example in your language. #### Complete example program Code Samples ```bash #!/usr/bin/env bash # Requires Bash, curl and Python3. No API key is written into the program. python3 - <<'EXHIBITDAY_PY' # Python 3; standard library only. Set EXHIBITDAY_API_KEY before running. import http.client import json import os import re import time import urllib.error import urllib.parse import urllib.request BASE = "https://api.exhibitday.com/v1" SPEC = json.loads("{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"read\":{\"method\":\"GET\",\"path\":\"/tasks/info\"},\"save\":{\"method\":\"PATCH\",\"path\":\"/tasks\"},\"readback\":{\"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("Persist a logical create key before sending POST") headers["Idempotency-Key"] = key data = None if body is None else json.dumps(body).encode("utf-8") if data is not None: headers["Content-Type"] = "application/json" query = urllib.parse.urlencode(params or {}) url = BASE + route["path"] + ("?" + query if query else "") # Only GET has automatic retries in this workflow. A PATCH or DELETE that got no response or a # server error is never resent blindly: it may already have been applied, so the caller reads the record first. resend = route["method"] == "GET" for attempt in range(5): try: status, raw, response_headers = transport(route["method"], url, headers, data) except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException): if not resend: raise ApiError(0, None, uncertain=True) if attempt == 4: raise time.sleep(2 ** attempt) continue response_headers = {k.lower(): v for k, v in response_headers.items()} result = None if status != 304 and raw: try: result = decode_json(raw.decode("utf-8")) except (ValueError, UnicodeError): if status < 400: raise RuntimeError("Expected a JSON success response") if status >= 500 and not resend: raise ApiError(status, result, uncertain=True) retry = resend and (status == 429 or status >= 500) if retry: if attempt == 4: raise RuntimeError("Retry limit reached; check the request outcome before starting a new create") delay = response_headers.get("retry-after", str(2 ** attempt)) time.sleep(max(0, float(delay))) continue if status >= 400: raise ApiError(status, result) return {"status": status, "body": result, "headers": response_headers, "raw": raw} raise RuntimeError("Retry limit reached") def both(left,right): return left and right def equal(left, right): return type(left) is type(right) and left == right def field(value, name): if not isinstance(value, dict) or name not in value: raise RuntimeError("Missing response field: " + name) return value[name] def is_present(value): return value is not None and value != "" """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 offsetlen(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)-offset:raise JournalRefusal('Incomplete journal frame; reconcile before retry') payload=raw[offset:offset+size];offset+=size if raw[offset:offset+1]!=b'\n' or digest(payload).encode('ascii')!=match[2]:raise JournalRefusal('Journal integrity check failed; reconcile before retry') records.append(read_strings(payload));offset+=1 return records class Journal: def __init__(self,path,base,workspace,slug,job,input_fingerprint,writes,mode="resume"): self.path=Path(path);self.lock=Path(str(self.path)+'.lock');self.fd=None;self.owned=False;self.identity=None;self.tainted=False;self.intents={};self.saved_values={} address=urlsplit(base) if address.scheme not in ('https','http')or not address.netloc or address.username is not None or address.query or address.fragment or not re.fullmatch('[a-z][a-z0-9-]*',slug):raise JournalRefusal('Use the actual API base and closed guide slug') if not job.strip() or not re.fullmatch('[1-9][0-9]*',workspace) or not re.fullmatch('[0-9A-F]{64}',input_fingerprint):raise JournalRefusal('Use an actual workspace, explicit stable job ID and exact input fingerprint') if mode not in ("new","resume"):raise JournalRefusal("Choose new or resume for this local job") self.allowed={};manifest=[] for step,method,route in writes: if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.allowed or method not in ('POST','PATCH','DELETE')or not re.fullmatch('/v1/[A-Za-z0-9_/-]+',route)or'//'in route:raise JournalRefusal('Use a closed unique write manifest') self.allowed[step]=(method,route);manifest.extend((step,method,route)) if not self.allowed:raise JournalRefusal('Only write workflows need a restart journal') self.header=['H','1',base,workspace,slug,job,input_fingerprint,digest(strings(manifest))] strings(self.header) try: self.fd=os.open(self.lock,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600);self.owned=True except FileExistsError:raise JournalRefusal('This journal is locked; do not run overlapping jobs or steal a stale lock') try: self.owner=secrets.token_hex(16);self.identity=os.fstat(self.fd) if os.write(self.fd,self.owner.encode('ascii'))!=len(self.owner):raise OSError('Incomplete lock identity write') os.fsync(self.fd) if self.path.is_symlink():raise JournalRefusal('Choose a private regular journal file') if mode=="resume" and not self.path.exists():raise JournalRefusal("Journal missing: stop and reconcile lost state before starting a new logical job") if mode=="new" and self.path.exists():raise JournalRefusal("A journal already exists; use resume for the same logical job") if mode=="new": with open(self.path,'xb',buffering=0)as target: target.write(PREAMBLE+frame(self.header));os.fsync(target.fileno()) records=decode(self.path.read_bytes()) if not records or records[0]!=self.header:raise JournalRefusal('Journal workspace/base/guide/job/input binding differs') for record in records[1:]:self.apply(record) if any(step not in self.saved_values for step in self.intents):raise JournalRefusal('A saved before-send intent lacks an ACK; stop and reconcile its outcome before retry') except BaseException: self.close();raise def apply(self,record): if not record:raise JournalRefusal('Empty journal record') if record[0]=='I': if len(record)!=6:raise JournalRefusal('Invalid intent shape') _,step,method,path,request_fingerprint,key=record if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.intents or self.allowed.get(step)!=(method,path)or not re.fullmatch('[0-9A-F]{64}',request_fingerprint)or any(name not in self.saved_values for name in self.intents):raise JournalRefusal('Invalid, future or repeated journal intent') if method=='POST'and not re.fullmatch('[0-9a-f]{32}',key)or method!='POST'and key!='':raise JournalRefusal('Invalid persisted action key') self.intents[step]={'method':method,'path':path,'request_fingerprint':request_fingerprint,'idempotency_key':key} elif record[0]=='A': if len(record)<3:raise JournalRefusal('Invalid ACK shape') _,step,count,*pairs=record if not re.fullmatch('0|[1-9][0-9]*',count)or len(pairs)!=2*int(count)or step not in self.intents or step in self.saved_values:raise JournalRefusal('ACK without exactly one prior intent') names=pairs[::2] if names!=sorted(set(names))or any(not re.fullmatch('[a-z][a-z0-9_]*',name)or name in ('api_key','exhibitday_api_key')for name in names):raise JournalRefusal('ACK saved fields must be unique sorted secret-free identifiers') self.saved_values[step]=dict(zip(names,pairs[1::2])) else:raise JournalRefusal('Unknown journal transition') def append(self,record): # The reader commits state only after complete length/digest recognition. # A torn append is retained and refused, never silently truncated. self.require_active();raw=frame(record) try: with open(self.path,'ab',buffering=0)as target: view=memoryview(raw) while view: written=target.write(view) if not written:raise OSError('Journal write did not advance') view=view[written:] os.fsync(target.fileno()) except BaseException: self.tainted=True;raise def require_active(self): if not self.owned or self.fd is None or self.identity is None or self.tainted:raise JournalRefusal('The journal scope is closed or its IO outcome needs reconciliation') current=self.lock.stat(follow_symlinks=False) if current.st_dev!=self.identity.st_dev or current.st_ino!=self.identity.st_ino or self.lock.read_text(encoding='ascii')!=self.owner:raise JournalRefusal('The journal lock was replaced; stop without deleting it') def acknowledged(self,step): self.require_active();return step in self.saved_values def saved(self,step): self.require_active() if step not in self.saved_values:raise JournalRefusal('No acknowledged state exists for this step') return dict(self.saved_values[step]) def begin(self,step,method,path,request_fingerprint): self.require_active() if step in self.intents:raise JournalRefusal('Never blindly repeat an existing action intent') key=secrets.token_hex(16)if method=='POST'else'' record=['I',step,method,path,request_fingerprint,key] # Validate on an isolated state before touching the file. old=dict(self.intents) try:self.apply(record) finally:self.intents=old self.append(record);self.apply(record) return dict(self.intents[step]) def acknowledge(self,step,saved): self.require_active() record=['A',step,str(len(saved))] for name,value in sorted(saved.items()):record.extend((name,value)) old={name:dict(value)for name,value in self.saved_values.items()} try:self.apply(record);strings(record) finally:self.saved_values=old self.append(record);self.apply(record) def close(self): if self.owned: if self.tainted: os.close(self.fd);self.fd=None;self.owned=False return # Retain this lock after failed journal IO; manual reconciliation is required. try:self.require_active() except BaseException: os.close(self.fd);self.fd=None;self.owned=False;raise os.close(self.fd);self.fd=None;self.owned=False self.lock.unlink() def __enter__(self):return self def __exit__(self,*args):self.close() def journal_values(value): if not isinstance(value, dict) or any(not isinstance(k, str) or not isinstance(v, str) for k,v in value.items()): raise JournalRefusal('Saved/fingerprint values must be exact string fields') return dict(value) def journal_acknowledge(job, step, saved): job.acknowledge(step,journal_values(saved)) def journal_acknowledged(job, step): return job.acknowledged(step) def journal_begin(job, step, method, path, request_fingerprint): return job.begin(step,method,path,request_fingerprint) def journal_fingerprint(value): return fingerprint(journal_values(value)) def journal_saved(job, step): return job.saved(step) def 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 positive_id(value): if not re.fullmatch(r"[1-9][0-9]*", value) or int(value) > 9223372036854775807: raise RuntimeError("Use a positive record ID") return value def print_value(value): print(value if isinstance(value, str) else json.dumps(value, ensure_ascii=False)) def require_condition(value, message): if value is not True: raise RuntimeError(message) def required(name): value = os.environ.get(name) if value is None or not value.strip(): raise RuntimeError("Set " + name) return value def response_status(value): return str(value["status"]) def task_name(value): utf8(value) if '<' in value or '>' in value: raise JournalRefusal('For this example, enter plain task text without angle brackets') value=value.replace('\r\n',' ').replace('\n','').replace('\r','').strip('\u0009\u000A\u000B\u000C\u000D\u0020\u0085\u00A0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u2028\u2029\u202F\u205F\u3000') if not value or len(value.encode('utf-16-le'))//2>400: raise JournalRefusal('Choose a nonblank task name of at most400 UTF16 code units') return value def text(value): if value is None: return "" if isinstance(value, str): return value if isinstance(value, bool): return "true" if value else "false" if isinstance(value, int): return str(value) raise RuntimeError("Expected a scalar response value") def main(): selected_task_id = positive_id(required("EXHIBITDAY_TASK_ID")) desired_task_name = task_name(required("EXHIBITDAY_TASK_NAME")) journal_path = required("EXHIBITDAY_JOURNAL") stable_job_id = required("EXHIBITDAY_JOB_ID") job_mode = optional("EXHIBITDAY_JOB_MODE", "resume") workspace_binding_response = call("workspace_binding", {}, None, None) require_condition(equal(response_status(workspace_binding_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement.") workspace_binding = workspace_binding_response["body"] owned_workspace_id = positive_id(text(field(workspace_binding, "id"))) current_task_response = call("read", {"id": selected_task_id, "$include_record_revision": "true"}, None, None) require_condition(equal(response_status(current_task_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement.") current_task = current_task_response["body"] require_condition(equal(text(field(current_task, "id")), selected_task_id), "The current Task ID differs from the requested Task.") current_task_revision = text(field(current_task, "record_revision")) require_condition(is_present(current_task_revision), "Read the actual Task with $include_record_revision=true; an opaque revision is required.") input_fingerprint = journal_fingerprint({"workflow_contract_sha256": "33C19FE95C143455286D674AAD34FFDCA4D1CAF0132A232A37F8D2BF39BB9DE4", "task_id": selected_task_id, "desired_name": desired_task_name}) update_job = open_journal(journal_path, "https://api.exhibitday.com/v1", owned_workspace_id, "update-records-safely", stable_job_id, input_fingerprint, [["save", "PATCH", "/v1/tasks"]], job_mode) try: if journal_acknowledged(update_job, "save"): saved_task = journal_saved(update_job, "save") require_condition(both(equal(text(field(saved_task, "id")), selected_task_id), equal(text(field(saved_task, "name")), desired_task_name)), "Acknowledged state does not match this Task/name; stop and reconcile.") else: task_patch = {"id": selected_task_id, "name": desired_task_name, "expected_revision": current_task_revision} write_fingerprint = journal_fingerprint({"id": selected_task_id, "name": desired_task_name, "expected_revision": current_task_revision}) journal_begin(update_job, "save", "PATCH", "/v1/tasks", write_fingerprint) saved_task_response = call("save", {}, task_patch, None) require_condition(equal(response_status(saved_task_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement.") saved_task_receipt = saved_task_response["body"] saved_task_revision = text(field(saved_task_receipt, "record_revision")) require_condition(is_present(saved_task_revision), "A valid save acknowledgement must include its new record_revision.") journal_acknowledge(update_job, "save", {"id": selected_task_id, "name": desired_task_name, "record_revision": saved_task_revision}) task_readback_response = call("readback", {"id": selected_task_id, "$include_record_revision": "true"}, None, None) require_condition(equal(response_status(task_readback_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement.") task_readback = task_readback_response["body"] require_condition(both(equal(text(field(task_readback, "id")), selected_task_id), equal(text(field(task_readback, "name")), desired_task_name)), "The current Task no longer matches the acknowledged change; review it instead of automatically restoring the name.") require_condition(is_present(text(field(task_readback, "record_revision"))), "The readback needs the actual current record_revision.") print_value({"task_id": text(field(task_readback, "id")), "name": text(field(task_readback, "name")), "record_revision": text(field(task_readback, "record_revision"))}) finally: update_job.close() if __name__ == "__main__": main() EXHIBITDAY_PY ``` ```javascript // Server-side Node.js with fetch; built-in modules only. Set EXHIBITDAY_API_KEY. const BASE = "https://api.exhibitday.com/v1"; const SPEC = JSON.parse("{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"read\":{\"method\":\"GET\",\"path\":\"/tasks/info\"},\"save\":{\"method\":\"PATCH\",\"path\":\"/tasks\"},\"readback\":{\"method\":\"GET\",\"path\":\"/tasks/info\"}}}"); const API_KEY = process.env.EXHIBITDAY_API_KEY; if (!API_KEY || !API_KEY.trim()) throw new Error("Set EXHIBITDAY_API_KEY"); if (/[^\x20-\x7e]/.test(API_KEY)) throw new Error("Use the API key as one ASCII header value without control characters"); 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, errors: result.errors, error_params: result.error_params, 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, key = null) { const route = SPEC.requests[name]; const headers = { Authorization: "Bearer " + API_KEY, Accept: "application/json" }; if (route.method === "POST") { if (!key) throw new Error("Persist a logical create key before sending POST"); headers["Idempotency-Key"] = key; } 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 : ""); // 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. const resend = route.method === "GET"; 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 = resend && (response.status === 429 || response.status >= 500); 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, raw }; } throw new Error("Retry limit reached"); } function both(left,right) { return left && right; } function equal(left, right) { return typeof left === typeof right && left === right; } function field(value, name) { if (!value || Array.isArray(value) || typeof value !== "object" || !Object.hasOwn(value, name)) throw new Error("Missing response field: " + name); return value[name]; } function is_present(value) { return value !== null && value !== undefined && value !== ""; } 'use strict'; // Private client restart state. No HTTP or application dependency. const fs = require('node:fs'); const crypto = require('node:crypto'); const PREAMBLE = Buffer.from('EXHIBITDAY-GUIDE-JOURNAL 1\n', 'ascii'); class JournalRefusal extends Error {} function ascii(raw) { if (raw.some(value => value > 127)) throw new JournalRefusal('Journal framing must be canonical ASCII'); return raw.toString('ascii'); } function utf8(value) { if (typeof value !== 'string') throw new JournalRefusal('Journal fields are exact strings'); for (const unit of value) if (unit.length === 1 && unit.charCodeAt(0) >= 0xd800 && unit.charCodeAt(0) <= 0xdfff) throw new JournalRefusal('Invalid Unicode journal field'); return Buffer.from(value, 'utf8'); } function strings(values) { const parts = []; for (const value of values) { const raw = utf8(value); parts.push(Buffer.from(String(raw.length) + ':', 'ascii'), raw); } return Buffer.concat(parts); } function readStrings(raw) { const values = []; let offset = 0; while (offset < raw.length) { const end = raw.indexOf(58, offset); if (end < 0) throw new JournalRefusal('Incomplete journal string length'); const length = ascii(raw.subarray(offset, end)); if (!/^(0|[1-9][0-9]*)$/.test(length)) throw new JournalRefusal('Noncanonical journal string length'); const size = BigInt(length); offset = end + 1; if (size > BigInt(raw.length - offset)) throw new JournalRefusal('Incomplete journal string'); const count = Number(size); values.push(new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(raw.subarray(offset, offset + count))); offset += count; } return values; } function digest(raw) { return crypto.createHash('sha256').update(raw).digest('hex').toUpperCase(); } function fingerprint(pairs) { const values = []; for (const name of Object.keys(pairs).sort()) { if (!/^[A-Za-z0-9_.-]+$/.test(name) || ['api_key', 'exhibitday_api_key'].includes(name.toLowerCase())) throw new JournalRefusal('Use explicit secret-free fingerprint field names'); values.push(name, pairs[name]); } return digest(strings(values)); } function frame(values) { const raw = strings(values); return Buffer.concat([Buffer.from(String(raw.length) + ' ' + digest(raw) + '\n', 'ascii'), raw, Buffer.from('\n')]); } function decode(raw) { if (!raw.subarray(0, PREAMBLE.length).equals(PREAMBLE)) throw new JournalRefusal('Unknown or incomplete journal version'); let offset = PREAMBLE.length; const records = []; while (offset < raw.length) { const end = raw.indexOf(10, offset); if (end < 0) throw new JournalRefusal('Incomplete journal frame header; reconcile before retry'); const match = /^(0|[1-9][0-9]*) ([0-9A-F]{64})$/.exec(ascii(raw.subarray(offset, end))); if (!match) throw new JournalRefusal('Invalid journal frame header'); const size = BigInt(match[1]); offset = end + 1; if (size >= BigInt(raw.length - offset)) throw new JournalRefusal('Incomplete journal frame; reconcile before retry'); const count = Number(size), payload = raw.subarray(offset, offset + count); offset += count; if (raw[offset] !== 10 || digest(payload) !== match[2]) throw new JournalRefusal('Journal integrity check failed; reconcile before retry'); records.push(readStrings(payload)); offset++; } return records; } function writeAll(fd, raw) { let offset = 0; while (offset < raw.length) { const count = fs.writeSync(fd, raw, offset, raw.length - offset); if (!count) throw new Error('Journal write did not advance'); offset += count; } } function same(left, right) { return left.length === right.length && left.every((value, index) => value === right[index]); } class Journal { constructor(path, base, workspace, slug, job, inputFingerprint, writes, mode = 'resume') { this.path = path; this.lock = path + '.lock'; this.fd = null; this.owned = false; this.identity = null; this.tainted = false; this.intents = new Map(); this.savedValues = new Map(); this.allowed = new Map(); if (!['new', 'resume'].includes(mode)) throw new JournalRefusal('Choose new or resume for this local job'); const address = new URL(base); if (!['https:', 'http:'].includes(address.protocol) || !address.hostname || address.username || address.password || address.search || address.hash || !/^[a-z][a-z0-9-]*$/.test(slug)) throw new JournalRefusal('Use the actual API base and closed guide slug'); if (!job.trim() || !/^[1-9][0-9]*$/.test(workspace) || !/^[0-9A-F]{64}$/.test(inputFingerprint)) throw new JournalRefusal('Use an actual workspace, stable explicit job ID and exact input fingerprint'); const manifest = []; for (const [step, method, route] of writes) { if (!/^[a-z][a-z0-9_-]*$/.test(step) || this.allowed.has(step) || !['POST', 'PATCH', 'DELETE'].includes(method) || !/^\/v1\/[A-Za-z0-9_/-]+$/.test(route) || route.includes('//')) throw new JournalRefusal('Use a closed unique write manifest'); this.allowed.set(step, [method, route]); manifest.push(step, method, route); } if (!this.allowed.size) throw new JournalRefusal('Only write workflows need a restart journal'); this.header = ['H', '1', base, workspace, slug, job, inputFingerprint, digest(strings(manifest))]; strings(this.header); try { this.fd = fs.openSync(this.lock, 'wx', 0o600); this.owned = true; } catch (error) { if (error.code === 'EEXIST') throw new JournalRefusal('This journal is locked; do not overlap jobs or steal a stale lock'); throw error; } try { this.owner = crypto.randomBytes(16).toString('hex'); this.identity = fs.fstatSync(this.fd, { bigint: true }); writeAll(this.fd, Buffer.from(this.owner, 'ascii')); fs.fsyncSync(this.fd); let exists = true; try { if (fs.lstatSync(path).isSymbolicLink()) throw new JournalRefusal('Choose a private regular journal file'); } catch (error) { if (error.code === 'ENOENT') exists = false; else throw error; } if (mode === 'resume' && !exists) throw new JournalRefusal('Journal missing: stop and reconcile lost state before starting a new logical job'); if (mode === 'new' && exists) throw new JournalRefusal('Journal already exists; use resume for the same logical job'); if (mode === 'new') { const target = fs.openSync(path, 'wx', 0o600); try { writeAll(target, Buffer.concat([PREAMBLE, frame(this.header)])); fs.fsyncSync(target); } finally { fs.closeSync(target); } } const records = decode(fs.readFileSync(path)); if (!records.length || !same(records[0], this.header)) throw new JournalRefusal('Journal workspace/base/guide/job/input binding differs'); for (const record of records.slice(1)) this.apply(record); if ([...this.intents.keys()].some(step => !this.savedValues.has(step))) throw new JournalRefusal('Saved before-send intent lacks ACK; stop and reconcile before retry'); } catch (error) { this.close(); throw error; } } apply(record) { if (record[0] === 'I') { if (record.length !== 6) throw new JournalRefusal('Invalid intent shape'); const [, step, method, path, requestFingerprint, key] = record; if (!/^[a-z][a-z0-9_-]*$/.test(step) || this.intents.has(step) || !this.allowed.has(step) || !same(this.allowed.get(step), [method, path]) || !/^[0-9A-F]{64}$/.test(requestFingerprint) || [...this.intents.keys()].some(name => !this.savedValues.has(name))) throw new JournalRefusal('Invalid, future or repeated intent'); if ((method === 'POST' && !/^[0-9a-f]{32}$/.test(key)) || (method !== 'POST' && key !== '')) throw new JournalRefusal('Invalid persisted action key'); this.intents.set(step, { method, path, request_fingerprint: requestFingerprint, idempotency_key: key }); } else if (record[0] === 'A') { const [, step, count, ...pairs] = record; if (record.length < 3 || !/^(0|[1-9][0-9]*)$/.test(count) || BigInt(pairs.length) !== 2n * BigInt(count) || !this.intents.has(step) || this.savedValues.has(step)) throw new JournalRefusal('ACK without exactly one prior intent'); const names = pairs.filter((_, index) => index % 2 === 0); if (!same(names, [...new Set(names)].sort()) || names.some(name => !/^[a-z][a-z0-9_]*$/.test(name) || ['api_key', 'exhibitday_api_key'].includes(name))) throw new JournalRefusal('ACK fields must be unique sorted secret-free identifiers'); this.savedValues.set(step, Object.fromEntries(names.map((name, index) => [name, pairs[index * 2 + 1]]))); } else throw new JournalRefusal('Unknown journal transition'); } requireActive() { if (!this.owned || this.fd === null || this.identity === null || this.tainted) throw new JournalRefusal('Journal is closed or its IO outcome needs reconciliation'); const current = fs.lstatSync(this.lock, { bigint: true }); if (current.dev !== this.identity.dev || current.ino !== this.identity.ino || ascii(fs.readFileSync(this.lock)) !== this.owner) throw new JournalRefusal('Journal lock was replaced; stop without deleting it'); } append(record) { this.requireActive(); const raw = frame(record); let target; try { target = fs.openSync(this.path, 'a'); writeAll(target, raw); fs.fsyncSync(target); } catch (error) { this.tainted = true; throw error; } finally { if (target !== undefined) fs.closeSync(target); } } acknowledged(step) { this.requireActive(); return this.savedValues.has(step); } saved(step) { this.requireActive(); if (!this.savedValues.has(step)) throw new JournalRefusal('No acknowledged state exists'); return { ...this.savedValues.get(step) }; } begin(step, method, path, requestFingerprint) { this.requireActive(); if (this.intents.has(step)) throw new JournalRefusal('Never blindly repeat an existing action'); const key = method === 'POST' ? crypto.randomBytes(16).toString('hex') : '', record = ['I', step, method, path, requestFingerprint, key]; const old = new Map(this.intents); try { this.apply(record); } finally { this.intents = old; } this.append(record); this.apply(record); return { ...this.intents.get(step) }; } acknowledge(step, saved) { this.requireActive(); const names = Object.keys(saved).sort(), record = ['A', step, String(names.length)]; for (const name of names) record.push(name, saved[name]); const old = new Map(this.savedValues); try { this.apply(record); strings(record); } finally { this.savedValues = old; } this.append(record); this.apply(record); } close() { if (!this.owned) return; if (this.tainted) { fs.closeSync(this.fd); this.fd = null; this.owned = false; return; } try { this.requireActive(); } catch (error) { fs.closeSync(this.fd); this.fd = null; this.owned = false; throw error; } fs.closeSync(this.fd); this.fd = null; this.owned = false; fs.unlinkSync(this.lock); } } function journal_values(value) { if (!value || typeof value !== 'object' || Array.isArray(value) || Object.values(value).some(item=>typeof item!=='string')) throw new JournalRefusal('Saved/fingerprint values must be exact strings'); return {...value}; } function journal_acknowledge(job,step,saved) { job.acknowledge(step,journal_values(saved)); } function journal_acknowledged(job,step) { return job.acknowledged(step); } function journal_begin(job,step,method,path,requestFingerprint) { return job.begin(step,method,path,requestFingerprint); } function journal_fingerprint(value) { return fingerprint(journal_values(value)); } function journal_saved(job,step) { return job.saved(step); } function open_journal(path,base,workspace,slug,job,inputFingerprint,writes,mode) { return new Journal(path,base,workspace,slug,job,inputFingerprint,writes,mode); } function optional(name, fallback) { const value = process.env[name]; return value === undefined || value === "" ? fallback : value; } function positive_id(value) { if (!/^[1-9][0-9]*$/.test(value) || BigInt(value) > 9223372036854775807n) throw new Error("Use a positive record ID"); return value; } function print_value(value) { console.log(typeof value === "string" ? value : JSON.stringify(value)); } function require_condition(value, message) { if (value !== true) throw new Error(message); } function required(name) { const value = process.env[name]; if (value === undefined || !value.trim()) throw new Error("Set " + name); return value; } function response_status(value) { return String(value.status); } function task_name(value) { utf8(value); if(value.includes('<')||value.includes('>'))throw new JournalRefusal('For this example, enter plain task text without angle brackets'); value=value.replaceAll('\r\n',' ').replaceAll('\n','').replaceAll('\r','').replace(/^[\u0009-\u000D\u0020\u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]+|[\u0009-\u000D\u0020\u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]+$/g,''); if(!value||value.length>400)throw new JournalRefusal('Choose a nonblank task name of at most400 UTF16 code units');return value; } function text(value) { if (value === null || value === undefined) return ""; if (["string", "boolean", "bigint"].includes(typeof value)) return String(value); throw new Error("Expected a scalar response value"); } async function main() { let selected_task_id = positive_id(required("EXHIBITDAY_TASK_ID")); let desired_task_name = task_name(required("EXHIBITDAY_TASK_NAME")); let journal_path = required("EXHIBITDAY_JOURNAL"); let stable_job_id = required("EXHIBITDAY_JOB_ID"); let job_mode = optional("EXHIBITDAY_JOB_MODE", "resume"); let workspace_binding_response = await call("workspace_binding", {}, null, null); require_condition(equal(response_status(workspace_binding_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement."); let workspace_binding = workspace_binding_response.body; let owned_workspace_id = positive_id(text(field(workspace_binding, "id"))); let current_task_response = await call("read", {"id": selected_task_id, "$include_record_revision": "true"}, null, null); require_condition(equal(response_status(current_task_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement."); let current_task = current_task_response.body; require_condition(equal(text(field(current_task, "id")), selected_task_id), "The current Task ID differs from the requested Task."); let current_task_revision = text(field(current_task, "record_revision")); require_condition(is_present(current_task_revision), "Read the actual Task with $include_record_revision=true; an opaque revision is required."); let input_fingerprint = journal_fingerprint({"workflow_contract_sha256": "33C19FE95C143455286D674AAD34FFDCA4D1CAF0132A232A37F8D2BF39BB9DE4", "task_id": selected_task_id, "desired_name": desired_task_name}); let update_job = open_journal(journal_path, "https://api.exhibitday.com/v1", owned_workspace_id, "update-records-safely", stable_job_id, input_fingerprint, [["save", "PATCH", "/v1/tasks"]], job_mode); try { if (journal_acknowledged(update_job, "save")) { let saved_task = journal_saved(update_job, "save"); require_condition(both(equal(text(field(saved_task, "id")), selected_task_id), equal(text(field(saved_task, "name")), desired_task_name)), "Acknowledged state does not match this Task/name; stop and reconcile."); } else { let task_patch = {"id": selected_task_id, "name": desired_task_name, "expected_revision": current_task_revision}; let write_fingerprint = journal_fingerprint({"id": selected_task_id, "name": desired_task_name, "expected_revision": current_task_revision}); journal_begin(update_job, "save", "PATCH", "/v1/tasks", write_fingerprint); let saved_task_response = await call("save", {}, task_patch, null); require_condition(equal(response_status(saved_task_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement."); let saved_task_receipt = saved_task_response.body; let saved_task_revision = text(field(saved_task_receipt, "record_revision")); require_condition(is_present(saved_task_revision), "A valid save acknowledgement must include its new record_revision."); journal_acknowledge(update_job, "save", {"id": selected_task_id, "name": desired_task_name, "record_revision": saved_task_revision}); } let task_readback_response = await call("readback", {"id": selected_task_id, "$include_record_revision": "true"}, null, null); require_condition(equal(response_status(task_readback_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement."); let task_readback = task_readback_response.body; require_condition(both(equal(text(field(task_readback, "id")), selected_task_id), equal(text(field(task_readback, "name")), desired_task_name)), "The current Task no longer matches the acknowledged change; review it instead of automatically restoring the name."); require_condition(is_present(text(field(task_readback, "record_revision"))), "The readback needs the actual current record_revision."); print_value({"task_id": text(field(task_readback, "id")), "name": text(field(task_readback, "name")), "record_revision": text(field(task_readback, "record_revision"))}); } finally { update_job.close(); } } if (require.main === module) main().catch(error => { console.error(error.message); process.exitCode = 1; }); module.exports = { main }; ``` ```python # Python 3; standard library only. Set EXHIBITDAY_API_KEY before running. import http.client import json import os import re import time import urllib.error import urllib.parse import urllib.request BASE = "https://api.exhibitday.com/v1" SPEC = json.loads("{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"read\":{\"method\":\"GET\",\"path\":\"/tasks/info\"},\"save\":{\"method\":\"PATCH\",\"path\":\"/tasks\"},\"readback\":{\"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) 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, key=None): route = SPEC["requests"][name] headers = {"Authorization": "Bearer " + API_KEY, "Accept": "application/json"} if route["method"] == "POST": if not key: raise RuntimeError("Persist a logical create key before sending POST") headers["Idempotency-Key"] = key data = None if body is None else json.dumps(body).encode("utf-8") if data is not None: headers["Content-Type"] = "application/json" query = urllib.parse.urlencode(params or {}) url = BASE + route["path"] + ("?" + query if query else "") # Only GET has automatic retries in this workflow. A PATCH or DELETE that got no response or a # server error is never resent blindly: it may already have been applied, so the caller reads the record first. resend = route["method"] == "GET" for attempt in range(5): try: status, raw, response_headers = transport(route["method"], url, headers, data) except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException): if not resend: raise ApiError(0, None, uncertain=True) if attempt == 4: raise time.sleep(2 ** attempt) continue response_headers = {k.lower(): v for k, v in response_headers.items()} result = None if status != 304 and raw: try: result = decode_json(raw.decode("utf-8")) except (ValueError, UnicodeError): if status < 400: raise RuntimeError("Expected a JSON success response") if status >= 500 and not resend: raise ApiError(status, result, uncertain=True) retry = resend and (status == 429 or status >= 500) if retry: if attempt == 4: raise RuntimeError("Retry limit reached; check the request outcome before starting a new create") delay = response_headers.get("retry-after", str(2 ** attempt)) time.sleep(max(0, float(delay))) continue if status >= 400: raise ApiError(status, result) return {"status": status, "body": result, "headers": response_headers, "raw": raw} raise RuntimeError("Retry limit reached") def both(left,right): return left and right def equal(left, right): return type(left) is type(right) and left == right def field(value, name): if not isinstance(value, dict) or name not in value: raise RuntimeError("Missing response field: " + name) return value[name] def is_present(value): return value is not None and value != "" """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 offsetlen(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)-offset:raise JournalRefusal('Incomplete journal frame; reconcile before retry') payload=raw[offset:offset+size];offset+=size if raw[offset:offset+1]!=b'\n' or digest(payload).encode('ascii')!=match[2]:raise JournalRefusal('Journal integrity check failed; reconcile before retry') records.append(read_strings(payload));offset+=1 return records class Journal: def __init__(self,path,base,workspace,slug,job,input_fingerprint,writes,mode="resume"): self.path=Path(path);self.lock=Path(str(self.path)+'.lock');self.fd=None;self.owned=False;self.identity=None;self.tainted=False;self.intents={};self.saved_values={} address=urlsplit(base) if address.scheme not in ('https','http')or not address.netloc or address.username is not None or address.query or address.fragment or not re.fullmatch('[a-z][a-z0-9-]*',slug):raise JournalRefusal('Use the actual API base and closed guide slug') if not job.strip() or not re.fullmatch('[1-9][0-9]*',workspace) or not re.fullmatch('[0-9A-F]{64}',input_fingerprint):raise JournalRefusal('Use an actual workspace, explicit stable job ID and exact input fingerprint') if mode not in ("new","resume"):raise JournalRefusal("Choose new or resume for this local job") self.allowed={};manifest=[] for step,method,route in writes: if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.allowed or method not in ('POST','PATCH','DELETE')or not re.fullmatch('/v1/[A-Za-z0-9_/-]+',route)or'//'in route:raise JournalRefusal('Use a closed unique write manifest') self.allowed[step]=(method,route);manifest.extend((step,method,route)) if not self.allowed:raise JournalRefusal('Only write workflows need a restart journal') self.header=['H','1',base,workspace,slug,job,input_fingerprint,digest(strings(manifest))] strings(self.header) try: self.fd=os.open(self.lock,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600);self.owned=True except FileExistsError:raise JournalRefusal('This journal is locked; do not run overlapping jobs or steal a stale lock') try: self.owner=secrets.token_hex(16);self.identity=os.fstat(self.fd) if os.write(self.fd,self.owner.encode('ascii'))!=len(self.owner):raise OSError('Incomplete lock identity write') os.fsync(self.fd) if self.path.is_symlink():raise JournalRefusal('Choose a private regular journal file') if mode=="resume" and not self.path.exists():raise JournalRefusal("Journal missing: stop and reconcile lost state before starting a new logical job") if mode=="new" and self.path.exists():raise JournalRefusal("A journal already exists; use resume for the same logical job") if mode=="new": with open(self.path,'xb',buffering=0)as target: target.write(PREAMBLE+frame(self.header));os.fsync(target.fileno()) records=decode(self.path.read_bytes()) if not records or records[0]!=self.header:raise JournalRefusal('Journal workspace/base/guide/job/input binding differs') for record in records[1:]:self.apply(record) if any(step not in self.saved_values for step in self.intents):raise JournalRefusal('A saved before-send intent lacks an ACK; stop and reconcile its outcome before retry') except BaseException: self.close();raise def apply(self,record): if not record:raise JournalRefusal('Empty journal record') if record[0]=='I': if len(record)!=6:raise JournalRefusal('Invalid intent shape') _,step,method,path,request_fingerprint,key=record if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.intents or self.allowed.get(step)!=(method,path)or not re.fullmatch('[0-9A-F]{64}',request_fingerprint)or any(name not in self.saved_values for name in self.intents):raise JournalRefusal('Invalid, future or repeated journal intent') if method=='POST'and not re.fullmatch('[0-9a-f]{32}',key)or method!='POST'and key!='':raise JournalRefusal('Invalid persisted action key') self.intents[step]={'method':method,'path':path,'request_fingerprint':request_fingerprint,'idempotency_key':key} elif record[0]=='A': if len(record)<3:raise JournalRefusal('Invalid ACK shape') _,step,count,*pairs=record if not re.fullmatch('0|[1-9][0-9]*',count)or len(pairs)!=2*int(count)or step not in self.intents or step in self.saved_values:raise JournalRefusal('ACK without exactly one prior intent') names=pairs[::2] if names!=sorted(set(names))or any(not re.fullmatch('[a-z][a-z0-9_]*',name)or name in ('api_key','exhibitday_api_key')for name in names):raise JournalRefusal('ACK saved fields must be unique sorted secret-free identifiers') self.saved_values[step]=dict(zip(names,pairs[1::2])) else:raise JournalRefusal('Unknown journal transition') def append(self,record): # The reader commits state only after complete length/digest recognition. # A torn append is retained and refused, never silently truncated. self.require_active();raw=frame(record) try: with open(self.path,'ab',buffering=0)as target: view=memoryview(raw) while view: written=target.write(view) if not written:raise OSError('Journal write did not advance') view=view[written:] os.fsync(target.fileno()) except BaseException: self.tainted=True;raise def require_active(self): if not self.owned or self.fd is None or self.identity is None or self.tainted:raise JournalRefusal('The journal scope is closed or its IO outcome needs reconciliation') current=self.lock.stat(follow_symlinks=False) if current.st_dev!=self.identity.st_dev or current.st_ino!=self.identity.st_ino or self.lock.read_text(encoding='ascii')!=self.owner:raise JournalRefusal('The journal lock was replaced; stop without deleting it') def acknowledged(self,step): self.require_active();return step in self.saved_values def saved(self,step): self.require_active() if step not in self.saved_values:raise JournalRefusal('No acknowledged state exists for this step') return dict(self.saved_values[step]) def begin(self,step,method,path,request_fingerprint): self.require_active() if step in self.intents:raise JournalRefusal('Never blindly repeat an existing action intent') key=secrets.token_hex(16)if method=='POST'else'' record=['I',step,method,path,request_fingerprint,key] # Validate on an isolated state before touching the file. old=dict(self.intents) try:self.apply(record) finally:self.intents=old self.append(record);self.apply(record) return dict(self.intents[step]) def acknowledge(self,step,saved): self.require_active() record=['A',step,str(len(saved))] for name,value in sorted(saved.items()):record.extend((name,value)) old={name:dict(value)for name,value in self.saved_values.items()} try:self.apply(record);strings(record) finally:self.saved_values=old self.append(record);self.apply(record) def close(self): if self.owned: if self.tainted: os.close(self.fd);self.fd=None;self.owned=False return # Retain this lock after failed journal IO; manual reconciliation is required. try:self.require_active() except BaseException: os.close(self.fd);self.fd=None;self.owned=False;raise os.close(self.fd);self.fd=None;self.owned=False self.lock.unlink() def __enter__(self):return self def __exit__(self,*args):self.close() def journal_values(value): if not isinstance(value, dict) or any(not isinstance(k, str) or not isinstance(v, str) for k,v in value.items()): raise JournalRefusal('Saved/fingerprint values must be exact string fields') return dict(value) def journal_acknowledge(job, step, saved): job.acknowledge(step,journal_values(saved)) def journal_acknowledged(job, step): return job.acknowledged(step) def journal_begin(job, step, method, path, request_fingerprint): return job.begin(step,method,path,request_fingerprint) def journal_fingerprint(value): return fingerprint(journal_values(value)) def journal_saved(job, step): return job.saved(step) def 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 positive_id(value): if not re.fullmatch(r"[1-9][0-9]*", value) or int(value) > 9223372036854775807: raise RuntimeError("Use a positive record ID") return value def print_value(value): print(value if isinstance(value, str) else json.dumps(value, ensure_ascii=False)) def require_condition(value, message): if value is not True: raise RuntimeError(message) def required(name): value = os.environ.get(name) if value is None or not value.strip(): raise RuntimeError("Set " + name) return value def response_status(value): return str(value["status"]) def task_name(value): utf8(value) if '<' in value or '>' in value: raise JournalRefusal('For this example, enter plain task text without angle brackets') value=value.replace('\r\n',' ').replace('\n','').replace('\r','').strip('\u0009\u000A\u000B\u000C\u000D\u0020\u0085\u00A0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u2028\u2029\u202F\u205F\u3000') if not value or len(value.encode('utf-16-le'))//2>400: raise JournalRefusal('Choose a nonblank task name of at most400 UTF16 code units') return value def text(value): if value is None: return "" if isinstance(value, str): return value if isinstance(value, bool): return "true" if value else "false" if isinstance(value, int): return str(value) raise RuntimeError("Expected a scalar response value") def main(): selected_task_id = positive_id(required("EXHIBITDAY_TASK_ID")) desired_task_name = task_name(required("EXHIBITDAY_TASK_NAME")) journal_path = required("EXHIBITDAY_JOURNAL") stable_job_id = required("EXHIBITDAY_JOB_ID") job_mode = optional("EXHIBITDAY_JOB_MODE", "resume") workspace_binding_response = call("workspace_binding", {}, None, None) require_condition(equal(response_status(workspace_binding_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement.") workspace_binding = workspace_binding_response["body"] owned_workspace_id = positive_id(text(field(workspace_binding, "id"))) current_task_response = call("read", {"id": selected_task_id, "$include_record_revision": "true"}, None, None) require_condition(equal(response_status(current_task_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement.") current_task = current_task_response["body"] require_condition(equal(text(field(current_task, "id")), selected_task_id), "The current Task ID differs from the requested Task.") current_task_revision = text(field(current_task, "record_revision")) require_condition(is_present(current_task_revision), "Read the actual Task with $include_record_revision=true; an opaque revision is required.") input_fingerprint = journal_fingerprint({"workflow_contract_sha256": "33C19FE95C143455286D674AAD34FFDCA4D1CAF0132A232A37F8D2BF39BB9DE4", "task_id": selected_task_id, "desired_name": desired_task_name}) update_job = open_journal(journal_path, "https://api.exhibitday.com/v1", owned_workspace_id, "update-records-safely", stable_job_id, input_fingerprint, [["save", "PATCH", "/v1/tasks"]], job_mode) try: if journal_acknowledged(update_job, "save"): saved_task = journal_saved(update_job, "save") require_condition(both(equal(text(field(saved_task, "id")), selected_task_id), equal(text(field(saved_task, "name")), desired_task_name)), "Acknowledged state does not match this Task/name; stop and reconcile.") else: task_patch = {"id": selected_task_id, "name": desired_task_name, "expected_revision": current_task_revision} write_fingerprint = journal_fingerprint({"id": selected_task_id, "name": desired_task_name, "expected_revision": current_task_revision}) journal_begin(update_job, "save", "PATCH", "/v1/tasks", write_fingerprint) saved_task_response = call("save", {}, task_patch, None) require_condition(equal(response_status(saved_task_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement.") saved_task_receipt = saved_task_response["body"] saved_task_revision = text(field(saved_task_receipt, "record_revision")) require_condition(is_present(saved_task_revision), "A valid save acknowledgement must include its new record_revision.") journal_acknowledge(update_job, "save", {"id": selected_task_id, "name": desired_task_name, "record_revision": saved_task_revision}) task_readback_response = call("readback", {"id": selected_task_id, "$include_record_revision": "true"}, None, None) require_condition(equal(response_status(task_readback_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement.") task_readback = task_readback_response["body"] require_condition(both(equal(text(field(task_readback, "id")), selected_task_id), equal(text(field(task_readback, "name")), desired_task_name)), "The current Task no longer matches the acknowledged change; review it instead of automatically restoring the name.") require_condition(is_present(text(field(task_readback, "record_revision"))), "The readback needs the actual current record_revision.") print_value({"task_id": text(field(task_readback, "id")), "name": text(field(task_readback, "name")), "record_revision": text(field(task_readback, "record_revision"))}) finally: update_job.close() if __name__ == "__main__": main() ``` ```csharp // .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\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"read\":{\"method\":\"GET\",\"path\":\"/tasks/info\"},\"save\":{\"method\":\"PATCH\",\"path\":\"/tasks\"},\"readback\":{\"method\":\"GET\",\"path\":\"/tasks/info\"}}}"); static readonly string ApiKey = HeaderKey(Required("EXHIBITDAY_API_KEY")); static string HeaderKey(string value) { if(value.Any(c=>c<32||c>126))throw new Exception("Use the API key as one ASCII header value without control characters");return value; } static readonly HttpClient Client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false }) { Timeout = TimeSpan.FromSeconds(30) }; internal static Func> Send = request => Client.SendAsync(request); sealed class Result { public int Status; public JsonNode Body; public Dictionary Headers; public string Raw; } // 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(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 Call(string name, JsonObject query = null, JsonNode body = null, string key = null) { var route = Spec["requests"][name]; var method = Text(route["method"]); var headers = new Dictionary(StringComparer.OrdinalIgnoreCase) { ["Authorization"] = "Bearer " + ApiKey, ["Accept"] = "application/json" }; if (method == "POST") { if (string.IsNullOrEmpty(key)) throw new Exception("Persist a logical create key before sending POST"); headers["Idempotency-Key"] = key; } 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); // 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. var resend = method == "GET"; 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 Send(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 = resend && (status == 429 || status >= 500); 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, Raw = raw }; } } throw new Exception("Retry limit reached"); } static bool Both(bool left,bool right)=>left&&right; static object Scalar(object value) { if(value is JsonValue json){if(json.TryGetValue(out var boolean))return boolean;if(json.TryGetValue(out var text))return text;return json.ToJsonString();}return value; } static bool Equal(object left,object right) => object.Equals(Scalar(left),Scalar(right)); static JsonNode Field(JsonNode value,string name) { if(value is not JsonObject obj || !obj.TryGetPropertyValue(name,out var item))throw new Exception("Missing response field: "+name);return item; } static bool IsPresent(string value) => value!=null && value!=""; public sealed class JournalRefusal : Exception { public JournalRefusal(string message) : base(message) {} } public static class JournalProtocol { public static readonly byte[] Preamble = Encoding.ASCII.GetBytes("EXHIBITDAY-GUIDE-JOURNAL 1\n"); static readonly UTF8Encoding Utf8 = new UTF8Encoding(false, true); static bool Match(string value,string pattern) => value != null && System.Text.RegularExpressions.Regex.IsMatch(value,"\\A(?:"+pattern+")\\z",System.Text.RegularExpressions.RegexOptions.CultureInvariant); public static bool Valid(string value,string pattern) => Match(value,pattern); static string Ascii(byte[] raw,int start,int count) { for(var i=start;i127)throw new JournalRefusal("Journal framing must be canonical ASCII");return Encoding.ASCII.GetString(raw,start,count); } public static byte[] Strings(IEnumerable values) { using var data=new MemoryStream(); foreach(var value in values){if(value==null)throw new JournalRefusal("Journal fields are exact strings");var item=Utf8.GetBytes(value);var prefix=Encoding.ASCII.GetBytes(item.Length.ToString(CultureInfo.InvariantCulture)+":");data.Write(prefix);data.Write(item);} return data.ToArray(); } public static List ReadStrings(byte[] raw) { var values=new List();var offset=0; while(offsetraw.Length-offset)throw new JournalRefusal("Incomplete journal string");values.Add(Utf8.GetString(raw,offset,(int)size));offset+=(int)size;} return values; } public static string Digest(byte[] raw)=>Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(raw)); public static string Fingerprint(IReadOnlyDictionary pairs) { var values=new List();foreach(var name in pairs.Keys.OrderBy(n=>n,StringComparer.Ordinal)){ if(!Match(name,"[A-Za-z0-9_.-]+")||new[]{"api_key","exhibitday_api_key"}.Contains(name.ToLowerInvariant()))throw new JournalRefusal("Use explicit secret-free fingerprint names");values.Add(name);values.Add(pairs[name]);} return Digest(Strings(values)); } public static byte[] Frame(IEnumerable values) { var payload=Strings(values);var header=Encoding.ASCII.GetBytes(payload.Length.ToString(CultureInfo.InvariantCulture)+" "+Digest(payload)+"\n"); using var data=new MemoryStream();data.Write(header);data.Write(payload);data.WriteByte(10);return data.ToArray(); } public static List> Decode(byte[] raw) { if(raw.Length>(); while(offset=raw.Length-offset)throw new JournalRefusal("Incomplete frame; reconcile before retry");var payload=raw.AsSpan(offset,(int)size).ToArray();offset+=(int)size; if(raw[offset]!=10||Digest(payload)!=split[1])throw new JournalRefusal("Journal integrity failed; reconcile before retry");records.Add(ReadStrings(payload));offset++;} return records; } } public sealed class Journal : IDisposable { readonly string path,lockPath,owner;readonly List header; readonly Dictionary allowed=new Dictionary(StringComparer.Ordinal); Dictionary> intents=new Dictionary>(StringComparer.Ordinal),savedValues=new Dictionary>(StringComparer.Ordinal); FileStream lockStream;bool owned,tainted;DateTime creation; static FileStream CreatePrivate(string target,FileAccess access,FileShare share) { var options=new FileStreamOptions{Mode=FileMode.CreateNew,Access=access,Share=share}; if(!OperatingSystem.IsWindows())options.UnixCreateMode=UnixFileMode.UserRead|UnixFileMode.UserWrite; return new FileStream(target,options); } public Journal(string path,string apiBase,string workspace,string slug,string job,string inputFingerprint,IEnumerable<(string Step,string Method,string Path)> writes,string mode="resume") { this.path=path;lockPath=path+".lock";owner=Convert.ToHexString(System.Security.Cryptography.RandomNumberGenerator.GetBytes(16)).ToLowerInvariant(); if(!Uri.TryCreate(apiBase,UriKind.Absolute,out var address)||address.Scheme!="https"&&address.Scheme!="http"||address.UserInfo.Length!=0||address.Query.Length!=0||address.Fragment.Length!=0||!JournalProtocol.Valid(slug,"[a-z][a-z0-9-]*"))throw new JournalRefusal("Use the actual API base and closed guide slug"); if(string.IsNullOrWhiteSpace(job)||!JournalProtocol.Valid(workspace,"[1-9][0-9]*")||!JournalProtocol.Valid(inputFingerprint,"[0-9A-F]{64}"))throw new JournalRefusal("Use actual workspace, stable explicit job ID and exact fingerprint"); if(mode!="new"&&mode!="resume")throw new JournalRefusal("Choose new or resume for this local job"); var manifest=new List();foreach(var write in writes){ if(!JournalProtocol.Valid(write.Step,"[a-z][a-z0-9_-]*")||allowed.ContainsKey(write.Step)||!new[]{"POST","PATCH","DELETE"}.Contains(write.Method)||!JournalProtocol.Valid(write.Path,"/v1/[A-Za-z0-9_/-]+")||write.Path.Contains("//"))throw new JournalRefusal("Use a closed unique write manifest"); allowed.Add(write.Step,(write.Method,write.Path));manifest.AddRange(new[]{write.Step,write.Method,write.Path});} if(allowed.Count==0)throw new JournalRefusal("Only write workflows need a restart journal"); header=new List{"H","1",apiBase,workspace,slug,job,inputFingerprint,JournalProtocol.Digest(JournalProtocol.Strings(manifest))};JournalProtocol.Strings(header); try{lockStream=CreatePrivate(lockPath,FileAccess.ReadWrite,FileShare.Read);owned=true;} catch(IOException)when(File.Exists(lockPath)){throw new JournalRefusal("This journal is locked; do not overlap jobs or steal a stale lock");} try{ var token=Encoding.ASCII.GetBytes(owner);lockStream.Write(token);lockStream.Flush(true);creation=File.GetCreationTimeUtc(lockPath); if(File.Exists(path)&&(File.GetAttributes(path)&FileAttributes.ReparsePoint)!=0)throw new JournalRefusal("Choose a private regular journal file"); if(mode=="resume"&&!File.Exists(path))throw new JournalRefusal("Journal missing: stop and reconcile lost state before starting a new logical job"); if(mode=="new"&&File.Exists(path))throw new JournalRefusal("Journal exists; use resume for the same logical job"); if(mode=="new"){using var output=CreatePrivate(path,FileAccess.Write,FileShare.None);output.Write(JournalProtocol.Preamble);output.Write(JournalProtocol.Frame(header));output.Flush(true);} var records=JournalProtocol.Decode(File.ReadAllBytes(path));if(records.Count==0||!records[0].SequenceEqual(header))throw new JournalRefusal("Journal workspace/base/guide/job/input binding differs"); foreach(var record in records.Skip(1))Apply(record);if(intents.Keys.Any(step=>!savedValues.ContainsKey(step)))throw new JournalRefusal("Saved intent lacks ACK; stop and reconcile before retry"); }catch{Dispose();throw;} } void Apply(IReadOnlyList record) { if(record.Count==0)throw new JournalRefusal("Empty journal record"); if(record[0]=="I"){ if(record.Count!=6)throw new JournalRefusal("Invalid intent shape");var step=record[1];var method=record[2];var route=record[3];var fingerprint=record[4];var key=record[5]; if(!JournalProtocol.Valid(step,"[a-z][a-z0-9_-]*")||intents.ContainsKey(step)||!allowed.TryGetValue(step,out var expected)||expected!=(method,route)||!JournalProtocol.Valid(fingerprint,"[0-9A-F]{64}")||intents.Keys.Any(name=>!savedValues.ContainsKey(name)))throw new JournalRefusal("Invalid, future or repeated intent"); if(method=="POST"&&!JournalProtocol.Valid(key,"[0-9a-f]{32}")||method!="POST"&&key!="")throw new JournalRefusal("Invalid persisted action key"); intents.Add(step,new Dictionary{{"method",method},{"path",route},{"request_fingerprint",fingerprint},{"idempotency_key",key}}); }else if(record[0]=="A"){ if(record.Count<3||!JournalProtocol.Valid(record[2],"0|[1-9][0-9]*")||!long.TryParse(record[2],NumberStyles.None,CultureInfo.InvariantCulture,out var count)||count!=(record.Count-3L)/2||record.Count%2!=1||!intents.ContainsKey(record[1])||savedValues.ContainsKey(record[1]))throw new JournalRefusal("ACK without exactly one prior intent"); var names=record.Skip(3).Where((_,index)=>index%2==0).ToArray(); if(!names.SequenceEqual(names.Distinct(StringComparer.Ordinal).OrderBy(name=>name,StringComparer.Ordinal))||names.Any(name=>!JournalProtocol.Valid(name,"[a-z][a-z0-9_]*")||name=="api_key"||name=="exhibitday_api_key"))throw new JournalRefusal("ACK fields must be unique sorted secret-free identifiers"); var saved=new Dictionary(StringComparer.Ordinal);for(var i=0;i record) { RequireActive();var raw=JournalProtocol.Frame(record); try{using var output=new FileStream(path,FileMode.Append,FileAccess.Write,FileShare.None);output.Write(raw);output.Flush(true);} catch{tainted=true;throw;} } public bool Acknowledged(string step){RequireActive();return savedValues.ContainsKey(step);} public Dictionary Saved(string step){RequireActive();if(!savedValues.ContainsKey(step))throw new JournalRefusal("No acknowledged state exists");return new Dictionary(savedValues[step],StringComparer.Ordinal);} public Dictionary Begin(string step,string method,string route,string requestFingerprint) { RequireActive();if(intents.ContainsKey(step))throw new JournalRefusal("Never blindly repeat an existing action"); var key=method=="POST"?Convert.ToHexString(System.Security.Cryptography.RandomNumberGenerator.GetBytes(16)).ToLowerInvariant():""; var record=new[]{"I",step,method,route,requestFingerprint,key};var previous=new Dictionary>(intents,StringComparer.Ordinal);try{Apply(record);}finally{intents=previous;} Append(record);Apply(record);return new Dictionary(intents[step],StringComparer.Ordinal); } public void Acknowledge(string step,IReadOnlyDictionary saved) { RequireActive();var record=new List{"A",step,saved.Count.ToString(CultureInfo.InvariantCulture)};foreach(var name in saved.Keys.OrderBy(name=>name,StringComparer.Ordinal))record.AddRange(new[]{name,saved[name]}); var previous=new Dictionary>(savedValues,StringComparer.Ordinal);try{Apply(record);JournalProtocol.Strings(record);}finally{savedValues=previous;} Append(record);Apply(record); } public void Dispose() { if(!owned)return;if(tainted){lockStream.Dispose();lockStream=null;owned=false;return;} try{RequireActive();}catch{lockStream.Dispose();lockStream=null;owned=false;throw;} lockStream.Dispose();lockStream=null;owned=false;File.Delete(lockPath); } } static Dictionary JournalValues(JsonNode value) { if(value is not JsonObject fields)throw new JournalRefusal("Saved/fingerprint values need an explicit object"); var result=new Dictionary(StringComparer.Ordinal); foreach(var field in fields){if(field.Value is not JsonValue item || !item.TryGetValue(out var text) || text==null)throw new JournalRefusal("Saved/fingerprint values must be exact strings");result.Add(field.Key,text);}return result; } static JsonObject JournalObject(IReadOnlyDictionary fields){var result=new JsonObject();foreach(var field in fields)result.Add(field.Key,JsonValue.Create(field.Value));return result;} static void JournalAcknowledge(Journal job,string step,JsonNode saved)=>job.Acknowledge(step,JournalValues(saved)); static bool JournalAcknowledged(Journal job,string step)=>job.Acknowledged(step); static JsonNode JournalBegin(Journal job,string step,string method,string path,string requestFingerprint)=>JournalObject(job.Begin(step,method,path,requestFingerprint)); static string JournalFingerprint(JsonNode value)=>JournalProtocol.Fingerprint(JournalValues(value)); static JsonNode JournalSaved(Journal job,string step)=>JournalObject(job.Saved(step)); static Journal OpenJournal(string path,string apiBase,string workspace,string slug,string job,string inputFingerprint,JsonNode manifest,string mode) { if(manifest is not JsonArray rows)throw new JournalRefusal("A closed write manifest is required");var writes=new List<(string,string,string)>(); foreach(var row in rows){if(row is not JsonArray fields || fields.Count!=3)throw new JournalRefusal("Each write must bind its step/method/path");var values=fields.Select(value=>value is JsonValue item&&item.TryGetValue(out var text)&&text!=null?text:throw new JournalRefusal("Manifest values are exact strings")).ToArray();writes.Add((values[0],values[1],values[2]));} return new Journal(path,apiBase,workspace,slug,job,inputFingerprint,writes,mode); } static string Optional(string name,string fallback) { var value=Environment.GetEnvironmentVariable(name);return value==null||value==""?fallback:value; } static string PositiveId(string value) { if(string.IsNullOrEmpty(value)||value[0]=='0'||!value.All(c=>c>='0'&&c<='9')||!long.TryParse(value,NumberStyles.None,CultureInfo.InvariantCulture,out var id)||id<=0)throw new Exception("Use a positive record ID");return value; } static void PrintValue(object value) => Console.WriteLine(value is string text ? text : JsonSerializer.Serialize(value)); static void RequireCondition(bool value,string message) { if(!value)throw new Exception(message); } static string ResponseStatus(Result value)=>value.Status.ToString(CultureInfo.InvariantCulture); static bool TaskSpace(char c)=>c>=9&&c<=13||c==32||c==0x85||c==0xA0||c==0x1680||c>=0x2000&&c<=0x200A||c==0x2028||c==0x2029||c==0x202F||c==0x205F||c==0x3000; static string TaskName(string value){JournalProtocol.Strings(new[]{value});if(value.Contains('<')||value.Contains('>'))throw new JournalRefusal("For this example, enter plain task text without angle brackets");value=value.Replace("\r\n"," ").Replace("\n","").Replace("\r","");int start=0,end=value.Length;while(startstart&&TaskSpace(value[end-1]))end--;value=value.Substring(start,end-start);if(value.Length==0||value.Length>400)throw new JournalRefusal("Choose a nonblank task name of at most400 UTF16 code units");return value;} static string Text(object value) => value==null?"":value is JsonNode node?Text(node):Convert.ToString(value,CultureInfo.InvariantCulture); internal static async Task Run() { var selected_task_id = PositiveId(Required("EXHIBITDAY_TASK_ID")); var desired_task_name = TaskName(Required("EXHIBITDAY_TASK_NAME")); var journal_path = Required("EXHIBITDAY_JOURNAL"); var stable_job_id = Required("EXHIBITDAY_JOB_ID"); var job_mode = Optional("EXHIBITDAY_JOB_MODE", "resume"); var workspace_binding_response = await Call("workspace_binding", new JsonObject { }, null, null); RequireCondition(Equal(ResponseStatus(workspace_binding_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement."); var workspace_binding = workspace_binding_response.Body; var owned_workspace_id = PositiveId(Text(Field(workspace_binding, "id"))); var current_task_response = await Call("read", new JsonObject { ["id"] = selected_task_id, ["$include_record_revision"] = "true" }, null, null); RequireCondition(Equal(ResponseStatus(current_task_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement."); var current_task = current_task_response.Body; RequireCondition(Equal(Text(Field(current_task, "id")), selected_task_id), "The current Task ID differs from the requested Task."); var current_task_revision = Text(Field(current_task, "record_revision")); RequireCondition(IsPresent(current_task_revision), "Read the actual Task with $include_record_revision=true; an opaque revision is required."); var input_fingerprint = JournalFingerprint(new JsonObject { ["workflow_contract_sha256"] = "33C19FE95C143455286D674AAD34FFDCA4D1CAF0132A232A37F8D2BF39BB9DE4", ["task_id"] = selected_task_id, ["desired_name"] = desired_task_name }); using (var update_job = OpenJournal(journal_path, "https://api.exhibitday.com/v1", owned_workspace_id, "update-records-safely", stable_job_id, input_fingerprint, new JsonArray(new JsonArray("save", "PATCH", "/v1/tasks")), job_mode)) { if (JournalAcknowledged(update_job, "save")) { var saved_task = JournalSaved(update_job, "save"); RequireCondition(Both(Equal(Text(Field(saved_task, "id")), selected_task_id), Equal(Text(Field(saved_task, "name")), desired_task_name)), "Acknowledged state does not match this Task/name; stop and reconcile."); } else { var task_patch = new JsonObject { ["id"] = selected_task_id, ["name"] = desired_task_name, ["expected_revision"] = current_task_revision }; var write_fingerprint = JournalFingerprint(new JsonObject { ["id"] = selected_task_id, ["name"] = desired_task_name, ["expected_revision"] = current_task_revision }); JournalBegin(update_job, "save", "PATCH", "/v1/tasks", write_fingerprint); var saved_task_response = await Call("save", new JsonObject { }, task_patch, null); RequireCondition(Equal(ResponseStatus(saved_task_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement."); var saved_task_receipt = saved_task_response.Body; var saved_task_revision = Text(Field(saved_task_receipt, "record_revision")); RequireCondition(IsPresent(saved_task_revision), "A valid save acknowledgement must include its new record_revision."); JournalAcknowledge(update_job, "save", new JsonObject { ["id"] = selected_task_id, ["name"] = desired_task_name, ["record_revision"] = saved_task_revision }); } var task_readback_response = await Call("readback", new JsonObject { ["id"] = selected_task_id, ["$include_record_revision"] = "true" }, null, null); RequireCondition(Equal(ResponseStatus(task_readback_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement."); var task_readback = task_readback_response.Body; RequireCondition(Both(Equal(Text(Field(task_readback, "id")), selected_task_id), Equal(Text(Field(task_readback, "name")), desired_task_name)), "The current Task no longer matches the acknowledged change; review it instead of automatically restoring the name."); RequireCondition(IsPresent(Text(Field(task_readback, "record_revision"))), "The readback needs the actual current record_revision."); PrintValue(new JsonObject { ["task_id"] = Text(Field(task_readback, "id")), ["name"] = Text(Field(task_readback, "name")), ["record_revision"] = Text(Field(task_readback, "record_revision")) }); } } static Task Main() => Run(); } ``` ```java // 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 SPEC = JSON.fromJson("{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"read\":{\"method\":\"GET\",\"path\":\"/tasks/info\"},\"save\":{\"method\":\"PATCH\",\"path\":\"/tasks\"},\"readback\":{\"method\":\"GET\",\"path\":\"/tasks/info\"}}}", Map.class); static final String API_KEY = headerKey(required("EXHIBITDAY_API_KEY")); static String headerKey(String value){if(value.chars().anyMatch(c->c<32||c>126))throw new IllegalArgumentException("Use the API key as one ASCII header value without control characters");return value;} static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).followRedirects(HttpClient.Redirect.NEVER).build(); interface RequestSender { HttpResponse send(HttpRequest request)throws IOException,InterruptedException; } static RequestSender SEND=request->CLIENT.send(request,HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); static class Result { int status; Object body; Map headers; String raw; Result(int s, Object b, Map h,String r) {status=s;body=b;headers=h;raw=r;} } // 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 obj(Object value) {return value==null?new LinkedHashMap<>(): (Map)value;} @SuppressWarnings("unchecked") static List list(Object value) {return value==null?Collections.emptyList():(List)value;} static Map map(Object... pairs) {Map result=new LinkedHashMap<>();for(int i=0;i query,Object body,String key) { Map route=obj(obj(SPEC.get("requests")).get(name));String method=text(route.get("method")); Map headers=map("Authorization","Bearer " + API_KEY,"Accept","application/json"); if(method.equals("POST")){if(key==null||key.isEmpty())throw new IllegalArgumentException("Persist a logical create key before sending POST");headers.put("Idempotency-Key",key);} 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); // 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. boolean resend=method.equals("GET"); 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 response; try {response=SEND.send(request.build());} 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();Object parsed=null; if(status!=304&&!response.body().isEmpty()) { try {parsed=JSON.fromJson(response.body(),Object.class);} catch(RuntimeException error){if(status<400)throw new IllegalStateException("Expected a JSON success response",error);} } Map 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=resend&&(status==429||status>=500); 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,response.body()); } throw new IllegalStateException("Retry limit reached"); } static boolean both(boolean left,boolean right){return left&&right;} static boolean equal(Object left,Object right){return Objects.equals(left,right);} static Object field(Object value,String name){if(!(value instanceof Map)||!obj(value).containsKey(name))throw new IllegalStateException("Missing response field: "+name);return obj(value).get(name);} static boolean is_present(String value){return value!=null&&!value.isEmpty();} // Private client restart state only. No transport, application or JSON interpreter. static final class Journal implements AutoCloseable { public static final class Refusal extends IllegalStateException { Refusal(String message){super(message);} } public static final byte[] PREAMBLE="EXHIBITDAY-GUIDE-JOURNAL 1\n".getBytes(StandardCharsets.US_ASCII); static boolean valid(String value,String pattern){return value!=null&&value.matches(pattern);} static byte[] utf8(String value)throws java.nio.charset.CharacterCodingException { if(value==null)throw new Refusal("Journal fields are exact strings"); java.nio.ByteBuffer encoded=StandardCharsets.UTF_8.newEncoder().onMalformedInput(java.nio.charset.CodingErrorAction.REPORT).onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT).encode(java.nio.CharBuffer.wrap(value));byte[] raw=new byte[encoded.remaining()];encoded.get(raw);return raw; } static String ascii(byte[] raw,int start,int count){for(int i=start;i127)throw new Refusal("Journal framing must be canonical ASCII");return new String(raw,start,count,StandardCharsets.US_ASCII);} public static byte[] strings(Collection values)throws IOException { ByteArrayOutputStream output=new ByteArrayOutputStream();for(String value:values){byte[] raw=utf8(value);output.write((raw.length+":").getBytes(StandardCharsets.US_ASCII));output.write(raw);}return output.toByteArray(); } static int find(byte[] raw,int offset,int value){for(int i=offset;i readStrings(byte[] raw)throws IOException { List values=new ArrayList<>();int offset=0; while(offset0)throw new Refusal("Incomplete journal string");int count=size.intValueExact(); values.add(StandardCharsets.UTF_8.newDecoder().onMalformedInput(java.nio.charset.CodingErrorAction.REPORT).onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT).decode(java.nio.ByteBuffer.wrap(raw,offset,count)).toString());offset+=count;} return values; } public static String digest(byte[] raw){try{byte[] hash=java.security.MessageDigest.getInstance("SHA-256").digest(raw);StringBuilder text=new StringBuilder();for(byte item:hash)text.append(String.format(Locale.ROOT,"%02X",item&255));return text.toString();}catch(java.security.NoSuchAlgorithmException error){throw new IllegalStateException(error);}} public static String fingerprint(Map pairs)throws IOException { List values=new ArrayList<>();for(String name:new TreeSet<>(pairs.keySet())){if(!valid(name,"[A-Za-z0-9_.-]+")||Arrays.asList("api_key","exhibitday_api_key").contains(name.toLowerCase(Locale.ROOT)))throw new Refusal("Use explicit secret-free fingerprint names");values.add(name);values.add(pairs.get(name));}return digest(strings(values)); } public static byte[] frame(Collection values)throws IOException {byte[] payload=strings(values);ByteArrayOutputStream output=new ByteArrayOutputStream();output.write((payload.length+" "+digest(payload)+"\n").getBytes(StandardCharsets.US_ASCII));output.write(payload);output.write(10);return output.toByteArray();} public static List> decode(byte[] raw)throws IOException { if(raw.length> records=new ArrayList<>(); while(offset=0)throw new Refusal("Incomplete frame; reconcile before retry");int count=size.intValueExact();byte[] payload=Arrays.copyOfRange(raw,offset,offset+count);offset+=count; if(raw[offset]!=10||!digest(payload).equals(fields[1]))throw new Refusal("Journal integrity failed; reconcile before retry");records.add(readStrings(payload));offset++;}return records; } static void writeAll(java.nio.channels.FileChannel target,byte[] raw)throws IOException {java.nio.ByteBuffer data=java.nio.ByteBuffer.wrap(raw);while(data.hasRemaining())if(target.write(data)<=0)throw new IOException("Journal write did not advance");} static java.nio.channels.FileChannel createPrivate(Path path,OpenOption... options)throws IOException { java.nio.file.attribute.FileAttribute[] attributes=FileSystems.getDefault().supportedFileAttributeViews().contains("posix")?new java.nio.file.attribute.FileAttribute[]{java.nio.file.attribute.PosixFilePermissions.asFileAttribute(java.nio.file.attribute.PosixFilePermissions.fromString("rw-------"))}:new java.nio.file.attribute.FileAttribute[0]; return java.nio.channels.FileChannel.open(path,new HashSet<>(Arrays.asList(options)),attributes); } final Path path,lockPath;final String owner;final List header; final Map> allowed=new LinkedHashMap<>();Map> intents=new LinkedHashMap<>(),savedValues=new LinkedHashMap<>(); java.nio.channels.FileChannel lock;boolean owned,tainted;Object fileKey;java.nio.file.attribute.FileTime creation; public Journal(Path path,String apiBase,String workspace,String slug,String job,String inputFingerprint,List> writes)throws IOException {this(path,apiBase,workspace,slug,job,inputFingerprint,writes,"resume");} public Journal(Path path,String apiBase,String workspace,String slug,String job,String inputFingerprint,List> writes,String mode)throws IOException { this.path=path;lockPath=Path.of(path.toString()+".lock");byte[] random=new byte[16];new java.security.SecureRandom().nextBytes(random);StringBuilder token=new StringBuilder();for(byte item:random)token.append(String.format(Locale.ROOT,"%02x",item&255));owner=token.toString(); URI address=URI.create(apiBase);if(!Arrays.asList("https","http").contains(address.getScheme())||address.getHost()==null||address.getUserInfo()!=null||address.getRawQuery()!=null||address.getRawFragment()!=null||!valid(slug,"[a-z][a-z0-9-]*"))throw new Refusal("Use actual API base and closed guide slug"); if(job==null||job.trim().isEmpty()||!valid(workspace,"[1-9][0-9]*")||!valid(inputFingerprint,"[0-9A-F]{64}"))throw new Refusal("Use actual workspace, stable explicit job ID and exact fingerprint"); if(!Arrays.asList("new","resume").contains(mode))throw new Refusal("Choose new or resume for this local job"); List manifest=new ArrayList<>();for(List item:writes){if(item.size()!=3)throw new Refusal("Invalid write manifest shape");String step=item.get(0),method=item.get(1),route=item.get(2); if(!valid(step,"[a-z][a-z0-9_-]*")||allowed.containsKey(step)||!Arrays.asList("POST","PATCH","DELETE").contains(method)||!valid(route,"/v1/[A-Za-z0-9_/-]+")||route.contains("//"))throw new Refusal("Use a closed unique write manifest");allowed.put(step,List.of(method,route));manifest.addAll(item);} if(allowed.isEmpty())throw new Refusal("Only write workflows need a restart journal");header=List.of("H","1",apiBase,workspace,slug,job,inputFingerprint,digest(strings(manifest)));strings(header); try{lock=createPrivate(lockPath,StandardOpenOption.CREATE_NEW,StandardOpenOption.READ,StandardOpenOption.WRITE);owned=true;}catch(FileAlreadyExistsException error){throw new Refusal("This journal is locked; do not overlap jobs or steal a stale lock");} try{writeAll(lock,owner.getBytes(StandardCharsets.US_ASCII));lock.force(true);java.nio.file.attribute.BasicFileAttributes identity=Files.readAttributes(lockPath,java.nio.file.attribute.BasicFileAttributes.class,LinkOption.NOFOLLOW_LINKS);fileKey=identity.fileKey();creation=identity.creationTime(); if(Files.isSymbolicLink(path))throw new Refusal("Choose a private regular journal file"); if(mode.equals("resume")&&!Files.exists(path))throw new Refusal("Journal missing: stop and reconcile lost state before starting a new logical job"); if(mode.equals("new")&&Files.exists(path))throw new Refusal("Journal exists; use resume for the same logical job"); if(mode.equals("new")){try(java.nio.channels.FileChannel target=createPrivate(path,StandardOpenOption.CREATE_NEW,StandardOpenOption.WRITE)){writeAll(target,PREAMBLE);writeAll(target,frame(header));target.force(true);}} List> records=decode(Files.readAllBytes(path));if(records.isEmpty()||!records.get(0).equals(header))throw new Refusal("Journal workspace/base/guide/job/input binding differs");for(List record:records.subList(1,records.size()))apply(record); if(intents.keySet().stream().anyMatch(step->!savedValues.containsKey(step)))throw new Refusal("Saved intent lacks ACK; stop and reconcile before retry"); }catch(IOException|RuntimeException error){close();throw error;} } void apply(List record){ if(record.isEmpty())throw new Refusal("Empty journal record"); if(record.get(0).equals("I")){ if(record.size()!=6)throw new Refusal("Invalid intent shape");String step=record.get(1),method=record.get(2),route=record.get(3),fingerprint=record.get(4),key=record.get(5); if(!valid(step,"[a-z][a-z0-9_-]*")||intents.containsKey(step)||!List.of(method,route).equals(allowed.get(step))||!valid(fingerprint,"[0-9A-F]{64}")||intents.keySet().stream().anyMatch(name->!savedValues.containsKey(name)))throw new Refusal("Invalid, future or repeated intent"); if(method.equals("POST")&&!valid(key,"[0-9a-f]{32}")||!method.equals("POST")&&!key.isEmpty())throw new Refusal("Invalid persisted action key");intents.put(step,new LinkedHashMap<>(Map.of("method",method,"path",route,"request_fingerprint",fingerprint,"idempotency_key",key))); }else if(record.get(0).equals("A")){ if(record.size()<3||!valid(record.get(2),"0|[1-9][0-9]*")||!new java.math.BigInteger(record.get(2)).multiply(java.math.BigInteger.TWO).equals(java.math.BigInteger.valueOf(record.size()-3))||!intents.containsKey(record.get(1))||savedValues.containsKey(record.get(1)))throw new Refusal("ACK without exactly one prior intent"); List names=new ArrayList<>();for(int i=3;i(new TreeSet<>(names)))||names.stream().anyMatch(name->!valid(name,"[a-z][a-z0-9_]*")||name.equals("api_key")||name.equals("exhibitday_api_key")))throw new Refusal("ACK fields must be unique sorted secret-free identifiers"); Map saved=new LinkedHashMap<>();for(int i=0;i record)throws IOException {requireActive();byte[] raw=frame(record);try(java.nio.channels.FileChannel target=java.nio.channels.FileChannel.open(path,StandardOpenOption.WRITE,StandardOpenOption.APPEND)){writeAll(target,raw);target.force(true);}catch(IOException|RuntimeException error){tainted=true;throw error;}} public boolean acknowledged(String step)throws IOException{requireActive();return savedValues.containsKey(step);} public Map saved(String step)throws IOException{requireActive();if(!savedValues.containsKey(step))throw new Refusal("No acknowledged state exists");return new LinkedHashMap<>(savedValues.get(step));} public Map begin(String step,String method,String route,String requestFingerprint)throws IOException { requireActive();if(intents.containsKey(step))throw new Refusal("Never blindly repeat an existing action");String key="";if(method.equals("POST")){byte[] bytes=new byte[16];new java.security.SecureRandom().nextBytes(bytes);StringBuilder text=new StringBuilder();for(byte item:bytes)text.append(String.format(Locale.ROOT,"%02x",item&255));key=text.toString();} List record=List.of("I",step,method,route,requestFingerprint,key);Map> previous=new LinkedHashMap<>(intents);try{apply(record);}finally{intents=previous;}append(record);apply(record);return new LinkedHashMap<>(intents.get(step)); } public void acknowledge(String step,Map saved)throws IOException { requireActive();List record=new ArrayList<>(List.of("A",step,Integer.toString(saved.size())));for(String name:new TreeSet<>(saved.keySet())){record.add(name);record.add(saved.get(name));} Map> previous=new LinkedHashMap<>(savedValues);try{apply(record);strings(record);}finally{savedValues=previous;}append(record);apply(record); } public void close()throws IOException { if(!owned)return;if(tainted){lock.close();lock=null;owned=false;return;} try{requireActive();}catch(IOException|RuntimeException error){lock.close();lock=null;owned=false;throw error;}lock.close();lock=null;owned=false;Files.delete(lockPath); } } static Map journal_values(Object value){if(!(value instanceof Map))throw new Journal.Refusal("Saved/fingerprint values need an explicit object");Map result=new LinkedHashMap<>();for(Map.Entry field:((Map)value).entrySet()){if(!(field.getKey() instanceof String)||!(field.getValue() instanceof String))throw new Journal.Refusal("Saved/fingerprint values must be exact strings");result.put((String)field.getKey(),(String)field.getValue());}return result;} static void journal_acknowledge(Journal job,String step,Object saved)throws IOException{job.acknowledge(step,journal_values(saved));} static boolean journal_acknowledged(Journal job,String step)throws IOException{return job.acknowledged(step);} static Object journal_begin(Journal job,String step,String method,String path,String requestFingerprint)throws IOException{return new LinkedHashMap(job.begin(step,method,path,requestFingerprint));} static String journal_fingerprint(Object value)throws IOException{return Journal.fingerprint(journal_values(value));} static Object journal_saved(Journal job,String step)throws IOException{return new LinkedHashMap(job.saved(step));} static Journal open_journal(String path,String base,String workspace,String slug,String job,String inputFingerprint,Object manifest,String mode)throws IOException { if(!(manifest instanceof List))throw new Journal.Refusal("A closed write manifest is required");List> writes=new ArrayList<>();for(Object row:(List)manifest){if(!(row instanceof List)||((List)row).size()!=3)throw new Journal.Refusal("Each write must bind step/method/path");List fields=new ArrayList<>();for(Object value:(List)row){if(!(value instanceof String))throw new Journal.Refusal("Manifest values are exact strings");fields.add((String)value);}writes.add(fields);}return new Journal(Path.of(path),base,workspace,slug,job,inputFingerprint,writes,mode); } static String optional(String name,String fallback){String value=System.getenv(name);return value==null||value.isEmpty()?fallback:value;} static String positive_id(String value){try{if(value==null||!value.matches("[1-9][0-9]*")||Long.parseLong(value)<=0)throw new IllegalArgumentException();return value;}catch(RuntimeException error){throw new IllegalArgumentException("Use a positive record ID");}} static void print_value(Object value){try{String text=value instanceof String?(String)value:JSON.toJson(value);System.out.write((text+"\n").getBytes(StandardCharsets.UTF_8));}catch(IOException error){throw new UncheckedIOException(error);}} static void require_condition(boolean value,String message){if(!value)throw new IllegalStateException(message);} static String response_status(Result value){return Integer.toString(value.status);} static boolean task_space(char c){return c>=9&&c<=13||c==32||c==0x85||c==0xA0||c==0x1680||c>=0x2000&&c<=0x200A||c==0x2028||c==0x2029||c==0x202F||c==0x205F||c==0x3000;} static String task_name(String value)throws IOException{Journal.strings(List.of(value));if(value.indexOf('<')>=0||value.indexOf('>')>=0)throw new Journal.Refusal("For this example, enter plain task text without angle brackets");value=value.replace("\r\n"," ").replace("\n","").replace("\r","");int start=0,end=value.length();while(startstart&&task_space(value.charAt(end-1)))end--;value=value.substring(start,end);if(value.isEmpty()||value.length()>400)throw new Journal.Refusal("Choose a nonblank task name of at most400 UTF16 code units");return value;} static void run()throws Exception { String selected_task_id = positive_id(required("EXHIBITDAY_TASK_ID")); String desired_task_name = task_name(required("EXHIBITDAY_TASK_NAME")); String journal_path = required("EXHIBITDAY_JOURNAL"); String stable_job_id = required("EXHIBITDAY_JOB_ID"); String job_mode = optional("EXHIBITDAY_JOB_MODE", "resume"); Result workspace_binding_response = call("workspace_binding", map(), null, null); require_condition(equal(response_status(workspace_binding_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement."); Object workspace_binding = workspace_binding_response.body; String owned_workspace_id = positive_id(text(field(workspace_binding, "id"))); Result current_task_response = call("read", map("id", selected_task_id, "$include_record_revision", "true"), null, null); require_condition(equal(response_status(current_task_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement."); Object current_task = current_task_response.body; require_condition(equal(text(field(current_task, "id")), selected_task_id), "The current Task ID differs from the requested Task."); String current_task_revision = text(field(current_task, "record_revision")); require_condition(is_present(current_task_revision), "Read the actual Task with $include_record_revision=true; an opaque revision is required."); String input_fingerprint = journal_fingerprint(map("workflow_contract_sha256", "33C19FE95C143455286D674AAD34FFDCA4D1CAF0132A232A37F8D2BF39BB9DE4", "task_id", selected_task_id, "desired_name", desired_task_name)); try (Journal update_job = open_journal(journal_path, "https://api.exhibitday.com/v1", owned_workspace_id, "update-records-safely", stable_job_id, input_fingerprint, Arrays.asList(Arrays.asList("save", "PATCH", "/v1/tasks")), job_mode)) { if (journal_acknowledged(update_job, "save")) { Object saved_task = journal_saved(update_job, "save"); require_condition(both(equal(text(field(saved_task, "id")), selected_task_id), equal(text(field(saved_task, "name")), desired_task_name)), "Acknowledged state does not match this Task/name; stop and reconcile."); } else { Object task_patch = map("id", selected_task_id, "name", desired_task_name, "expected_revision", current_task_revision); String write_fingerprint = journal_fingerprint(map("id", selected_task_id, "name", desired_task_name, "expected_revision", current_task_revision)); journal_begin(update_job, "save", "PATCH", "/v1/tasks", write_fingerprint); Result saved_task_response = call("save", map(), task_patch, null); require_condition(equal(response_status(saved_task_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement."); Object saved_task_receipt = saved_task_response.body; String saved_task_revision = text(field(saved_task_receipt, "record_revision")); require_condition(is_present(saved_task_revision), "A valid save acknowledgement must include its new record_revision."); journal_acknowledge(update_job, "save", map("id", selected_task_id, "name", desired_task_name, "record_revision", saved_task_revision)); } Result task_readback_response = call("readback", map("id", selected_task_id, "$include_record_revision", "true"), null, null); require_condition(equal(response_status(task_readback_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement."); Object task_readback = task_readback_response.body; require_condition(both(equal(text(field(task_readback, "id")), selected_task_id), equal(text(field(task_readback, "name")), desired_task_name)), "The current Task no longer matches the acknowledged change; review it instead of automatically restoring the name."); require_condition(is_present(text(field(task_readback, "record_revision"))), "The readback needs the actual current record_revision."); print_value(map("task_id", text(field(task_readback, "id")), "name", text(field(task_readback, "name")), "record_revision", text(field(task_readback, "record_revision")))); } } public static void main(String[] args)throws Exception {run();} } ``` ```php $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, ?string $key = null): array { global $spec, $apiKey, $transport; $route = $spec['requests'][$name]; $headers = ['Authorization' => 'Bearer ' . $apiKey, 'Accept' => 'application/json']; if ($route['method'] === 'POST') { if ($key === null || $key === '') throw new RuntimeException('Persist a logical create key before sending POST'); $headers['Idempotency-Key'] = $key; // 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); // 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 = 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 = $resend && ($status === 429 || $status >= 500); 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, 'raw' => $raw]; } throw new RuntimeException('Retry limit reached'); } $transport = Closure::fromCallable('nativeTransport'); function both(bool $left,bool $right):bool{return $left&&$right;} function equal(mixed $left,mixed $right):bool{return $left===$right;} function field(mixed $value,string $name):mixed{if(!is_array($value)||!array_key_exists($name,$value))throw new RuntimeException("Missing response field: ".$name);return $value[$name];} function is_present(?string $value):bool{return $value!==null&&$value!=="";} final class JournalRefusal extends RuntimeException {} final class JournalProtocol { public const PREAMBLE="EXHIBITDAY-GUIDE-JOURNAL 1\n"; public static function utf8(mixed $value):string {if(!is_string($value)||preg_match('//u',$value)!==1)throw new JournalRefusal('Journal fields must be exact valid UTF8 strings');return$value;} public static function strings(array $values):string {$raw='';foreach($values as$value){$item=self::utf8($value);$raw.=strlen($item).':'.$item;}return$raw;} private static function length(string $text,int $remaining):int {if(!preg_match('/\A(?:0|[1-9][0-9]*)\z/',$text))throw new JournalRefusal('Noncanonical string length');$maximum=(string)$remaining;if(strlen($text)>strlen($maximum)||(strlen($text)===strlen($maximum)&&strcmp($text,$maximum)>0))throw new JournalRefusal('Incomplete journal string/frame');return(int)$text;} public static function readStrings(string $raw):array {$values=[];$offset=0;while($offset=strlen($raw)-$offset)throw new JournalRefusal('Incomplete frame; reconcile before retry');$payload=substr($raw,$offset,$size);$offset+=$size;if($raw[$offset]!=="\n"||self::digest($payload)!==$match[2])throw new JournalRefusal('Journal integrity failed; reconcile before retry');$records[]=self::readStrings($payload);$offset++;}return$records;} public static function writeAll($file,string $raw):void {$offset=0;while($offsetpath=$path;$this->lockPath=$path.'.lock';$this->owner=bin2hex(random_bytes(16));$address=parse_url($base); if($address===false||!in_array($address['scheme']??null,['https','http'],true)||!isset($address['host'])||isset($address['user'])||isset($address['pass'])||isset($address['query'])||isset($address['fragment'])||!preg_match('/\A[a-z][a-z0-9-]*\z/',$slug))throw new JournalRefusal('Use actual API base and closed guide slug'); if(trim($job)===''||!preg_match('/\A[1-9][0-9]*\z/',$workspace)||!preg_match('/\A[0-9A-F]{64}\z/',$inputFingerprint))throw new JournalRefusal('Use actual workspace, stable explicit job ID and exact fingerprint'); if(!in_array($mode,['new','resume'],true))throw new JournalRefusal('Choose new or resume for this local job'); $manifest=[];foreach($writes as$write){if(!is_array($write)||!array_is_list($write)||count($write)!==3)throw new JournalRefusal('Invalid write manifest');[$step,$method,$route]=$write; if(!is_string($step)||!preg_match('/\A[a-z][a-z0-9_-]*\z/',$step)||isset($this->allowed[$step])||!in_array($method,['POST','PATCH','DELETE'],true)||!is_string($route)||!preg_match('~\A/v1/[A-Za-z0-9_/-]+\z~',$route)||str_contains($route,'//'))throw new JournalRefusal('Use a closed unique write manifest');$this->allowed[$step]=[$method,$route];array_push($manifest,$step,$method,$route);} if($this->allowed===[])throw new JournalRefusal('Only write workflows need restart journal');$this->header=['H','1',$base,$workspace,$slug,$job,$inputFingerprint,JournalProtocol::digest(JournalProtocol::strings($manifest))];JournalProtocol::strings($this->header); $this->file=JournalProtocol::createPrivate($this->lockPath);$this->owned=true; try{ JournalProtocol::writeAll($this->file,$this->owner);$identity=fstat($this->file);if($identity===false)throw new JournalRefusal('Cannot bind acquired lock identity');$this->identity=$identity; clearstatcache(true,$path);if(is_link($path))throw new JournalRefusal('Choose private regular journal file'); $exists=file_exists($path);if($mode==='resume'&&!$exists)throw new JournalRefusal('Journal missing: stop and reconcile lost state before starting a new logical job');if($mode==='new'&&$exists)throw new JournalRefusal('Journal exists; use resume for the same logical job'); if($mode==='new'){$target=JournalProtocol::createPrivate($path);try{JournalProtocol::writeAll($target,JournalProtocol::PREAMBLE.JournalProtocol::frame($this->header));}finally{fclose($target);}} $raw=file_get_contents($path);if($raw===false)throw new JournalRefusal('Cannot read journal');$records=JournalProtocol::decode($raw);if($records===[]||$records[0]!==$this->header)throw new JournalRefusal('Journal workspace/base/guide/job/input binding differs');foreach(array_slice($records,1)as$record)$this->apply($record); if(array_diff(array_keys($this->intents),array_keys($this->savedValues))!==[])throw new JournalRefusal('Saved intent lacks ACK; stop and reconcile before retry'); }catch(Throwable $error){$this->close();throw$error;} } private function apply(array $record):void { if(($record[0]??null)==='I'){ if(count($record)!==6)throw new JournalRefusal('Invalid intent shape');[,$step,$method,$route,$fingerprint,$key]=$record; if(!preg_match('/\A[a-z][a-z0-9_-]*\z/',$step)||isset($this->intents[$step])||($this->allowed[$step]??null)!==[$method,$route]||!preg_match('/\A[0-9A-F]{64}\z/',$fingerprint)||array_diff(array_keys($this->intents),array_keys($this->savedValues))!==[])throw new JournalRefusal('Invalid, future or repeated intent'); if(($method==='POST'&&!preg_match('/\A[0-9a-f]{32}\z/',$key))||($method!=='POST'&&$key!==''))throw new JournalRefusal('Invalid persisted action key');$this->intents[$step]=['method'=>$method,'path'=>$route,'request_fingerprint'=>$fingerprint,'idempotency_key'=>$key]; }elseif(($record[0]??null)==='A'){ if(count($record)<3)throw new JournalRefusal('Invalid ACK shape');[,$step,$count]=$record;$pairs=array_slice($record,3); if(!preg_match('/\A(?:0|[1-9][0-9]*)\z/',$count)||(string)intdiv(count($pairs),2)!==$count||count($pairs)%2!==0||!isset($this->intents[$step])||isset($this->savedValues[$step]))throw new JournalRefusal('ACK without exactly one prior intent'); $names=[];for($i=0;$i$name){if(!preg_match('/\A[a-z][a-z0-9_]*\z/',$name)||in_array($name,['api_key','exhibitday_api_key'],true))throw new JournalRefusal('Use secret-free ACK field names');$saved[$name]=$pairs[$i*2+1];}$this->savedValues[$step]=$saved; }else throw new JournalRefusal('Unknown journal transition'); } private function requireActive():void { if(!$this->owned||$this->file===null||$this->tainted)throw new JournalRefusal('Journal closed or IO outcome needs reconciliation');clearstatcache(true,$this->lockPath);$current=@lstat($this->lockPath);$token=@file_get_contents($this->lockPath); if($current===false||($current['dev']??null)!==($this->identity['dev']??null)||($current['ino']??null)!==($this->identity['ino']??null)||$token!==$this->owner)throw new JournalRefusal('Journal lock replaced; stop without deleting it'); } private function append(array $record):void { $this->requireActive();$raw=JournalProtocol::frame($record);$target=null; try{$target=@fopen($this->path,'ab');if($target===false)throw new JournalRefusal('Cannot append journal; stop and reconcile');JournalProtocol::writeAll($target,$raw);}catch(Throwable $error){$this->tainted=true;throw$error;}finally{if(is_resource($target))fclose($target);} } public function acknowledged(string $step):bool{$this->requireActive();return isset($this->savedValues[$step]);} public function saved(string $step):array{$this->requireActive();if(!isset($this->savedValues[$step]))throw new JournalRefusal('No acknowledged state exists');return$this->savedValues[$step];} public function beginAction(string $step,string $method,string $route,string $requestFingerprint):array { $this->requireActive();if(isset($this->intents[$step]))throw new JournalRefusal('Never blindly repeat an existing action');$key=$method==='POST'?bin2hex(random_bytes(16)):'';$record=['I',$step,$method,$route,$requestFingerprint,$key];$previous=$this->intents;try{$this->apply($record);}finally{$this->intents=$previous;}$this->append($record);$this->apply($record);return$this->intents[$step]; } public function acknowledge(string $step,array $saved):void { $this->requireActive();$record=['A',$step,(string)count($saved)];$names=array_keys($saved);sort($names,SORT_STRING);foreach($names as$name){$record[]=$name;$record[]=$saved[$name];}$previous=$this->savedValues;try{$this->apply($record);JournalProtocol::strings($record);}finally{$this->savedValues=$previous;}$this->append($record);$this->apply($record); } public function close():void { if(!$this->owned)return;if($this->tainted){fclose($this->file);$this->file=null;$this->owned=false;return;} try{$this->requireActive();}catch(Throwable $error){fclose($this->file);$this->file=null;$this->owned=false;throw$error;}fclose($this->file);$this->file=null;$this->owned=false;if(!unlink($this->lockPath))throw new JournalRefusal('Could not release owned journal lock'); } } function journal_values(mixed $value):array{if(!is_object($value))throw new JournalRefusal('Saved/fingerprint values need an explicit object');$result=get_object_vars($value);foreach($result as$name=>$item)if(!is_string($name)||!is_string($item))throw new JournalRefusal('Saved/fingerprint values must be exact strings');return$result;} function journal_acknowledge(GuideJournal $job,string $step,mixed $saved):void{$job->acknowledge($step,journal_values($saved));} function journal_acknowledged(GuideJournal $job,string $step):bool{return $job->acknowledged($step);} function journal_begin(GuideJournal $job,string $step,string $method,string $path,string $requestFingerprint):array{return $job->beginAction($step,$method,$path,$requestFingerprint);} function journal_fingerprint(mixed $value):string{return JournalProtocol::fingerprint(journal_values($value));} function journal_saved(GuideJournal $job,string $step):array{return $job->saved($step);} function open_journal(string $path,string $base,string $workspace,string $slug,string $job,string $inputFingerprint,array $writes,string $mode):GuideJournal{return new GuideJournal($path,$base,$workspace,$slug,$job,$inputFingerprint,$writes,$mode);} function positive_id(string $value):string{if(!preg_match("/^[1-9][0-9]*$/D",$value)||strlen($value)>19||(strlen($value)===19&&strcmp($value,"9223372036854775807")>0))throw new RuntimeException("Use a positive record ID");return $value;} function print_value(mixed $value):void{echo (is_string($value)?$value:json_encode($value,JSON_THROW_ON_ERROR))."\n";} function require_condition(bool $value,string $message):void{if(!$value)throw new RuntimeException($message);} function response_status(array $value):string{return(string)$value["status"];} function task_name(string $value):string{JournalProtocol::utf8($value);if(str_contains($value,'<')||str_contains($value,'>'))throw new JournalRefusal('For this example, enter plain task text without angle brackets');$value=str_replace(["\r\n","\n","\r"],[' ','',''],$value);$value=preg_replace('~\A[\x{0009}-\x{000D}\x{0020}\x{0085}\x{00A0}\x{1680}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+|[\x{0009}-\x{000D}\x{0020}\x{0085}\x{00A0}\x{1680}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+\z~u','',$value);if($value===null||$value===''||preg_match_all('/./us',$value)+preg_match_all('/[\x{10000}-\x{10FFFF}]/u',$value)>400)throw new JournalRefusal('Choose a nonblank task name of at most400 UTF16 code units');return$value;} function text(mixed $value):string{if($value===null)return "";if(is_string($value))return $value;if(is_bool($value))return $value?"true":"false";if(is_int($value))return (string)$value;throw new RuntimeException("Expected a scalar response value");} function main():void { $selected_task_id = positive_id(required('EXHIBITDAY_TASK_ID')); $desired_task_name = task_name(required('EXHIBITDAY_TASK_NAME')); $journal_path = required('EXHIBITDAY_JOURNAL'); $stable_job_id = required('EXHIBITDAY_JOB_ID'); $job_mode = optional('EXHIBITDAY_JOB_MODE', 'resume'); $workspace_binding_response = call('workspace_binding', [], null, null); require_condition(equal(response_status($workspace_binding_response), '200'), 'Expected the endpoint\'s documented HTTP200 acknowledgement.'); $workspace_binding = $workspace_binding_response["body"]; $owned_workspace_id = positive_id(text(field($workspace_binding, 'id'))); $current_task_response = call('read', ['id' => $selected_task_id, '$include_record_revision' => 'true'], null, null); require_condition(equal(response_status($current_task_response), '200'), 'Expected the endpoint\'s documented HTTP200 acknowledgement.'); $current_task = $current_task_response["body"]; require_condition(equal(text(field($current_task, 'id')), $selected_task_id), 'The current Task ID differs from the requested Task.'); $current_task_revision = text(field($current_task, 'record_revision')); require_condition(is_present($current_task_revision), 'Read the actual Task with $include_record_revision=true; an opaque revision is required.'); $input_fingerprint = journal_fingerprint((object)['workflow_contract_sha256' => '33C19FE95C143455286D674AAD34FFDCA4D1CAF0132A232A37F8D2BF39BB9DE4', 'task_id' => $selected_task_id, 'desired_name' => $desired_task_name]); $update_job = open_journal($journal_path, 'https://api.exhibitday.com/v1', $owned_workspace_id, 'update-records-safely', $stable_job_id, $input_fingerprint, [['save', 'PATCH', '/v1/tasks']], $job_mode); try { if (journal_acknowledged($update_job, 'save')) { $saved_task = journal_saved($update_job, 'save'); require_condition(both(equal(text(field($saved_task, 'id')), $selected_task_id), equal(text(field($saved_task, 'name')), $desired_task_name)), 'Acknowledged state does not match this Task/name; stop and reconcile.'); } else { $task_patch = (object)['id' => $selected_task_id, 'name' => $desired_task_name, 'expected_revision' => $current_task_revision]; $write_fingerprint = journal_fingerprint((object)['id' => $selected_task_id, 'name' => $desired_task_name, 'expected_revision' => $current_task_revision]); journal_begin($update_job, 'save', 'PATCH', '/v1/tasks', $write_fingerprint); $saved_task_response = call('save', [], $task_patch, null); require_condition(equal(response_status($saved_task_response), '200'), 'Expected the endpoint\'s documented HTTP200 acknowledgement.'); $saved_task_receipt = $saved_task_response["body"]; $saved_task_revision = text(field($saved_task_receipt, 'record_revision')); require_condition(is_present($saved_task_revision), 'A valid save acknowledgement must include its new record_revision.'); journal_acknowledge($update_job, 'save', (object)['id' => $selected_task_id, 'name' => $desired_task_name, 'record_revision' => $saved_task_revision]); } $task_readback_response = call('readback', ['id' => $selected_task_id, '$include_record_revision' => 'true'], null, null); require_condition(equal(response_status($task_readback_response), '200'), 'Expected the endpoint\'s documented HTTP200 acknowledgement.'); $task_readback = $task_readback_response["body"]; require_condition(both(equal(text(field($task_readback, 'id')), $selected_task_id), equal(text(field($task_readback, 'name')), $desired_task_name)), 'The current Task no longer matches the acknowledged change; review it instead of automatically restoring the name.'); require_condition(is_present(text(field($task_readback, 'record_revision'))), 'The readback needs the actual current record_revision.'); print_value((object)['task_id' => text(field($task_readback, 'id')), 'name' => text(field($task_readback, 'name')), 'record_revision' => text(field($task_readback, 'record_revision'))]); } finally { $update_job->close(); } } if (realpath($_SERVER['SCRIPT_FILENAME'] ?? '') === __FILE__) main(); ``` ```ruby # 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":true,"requests":{"workspace_binding":{"method":"GET","path":"/references/workspace_info"},"read":{"method":"GET","path":"/tasks/info"},"save":{"method":"PATCH","path":"/tasks"},"readback":{"method":"GET","path":"/tasks/info"}}}') API_KEY = ENV.fetch('EXHIBITDAY_API_KEY') raise 'Use the API key as one ASCII header value without control characters' if API_KEY.each_codepoint.any?{|point|point<32||point>126} 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, 'DELETE' => Net::HTTP::Delete }.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, key = nil) route = SPEC.fetch('requests').fetch(name) headers = { 'Authorization' => 'Bearer ' + API_KEY, 'Accept' => 'application/json' } if route.fetch('method') == 'POST' headers['Idempotency-Key'] = key || raise('Persist a logical create key before sending POST') # 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) # 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.fetch('method') == 'GET' 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 = resend && (status == 429 || (500..599).cover?(status)) 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, raw: raw } end raise 'Retry limit reached' end def both(left,right);left&&right;end def equal(left,right) left.class==right.class && left==right end def field(value,name) raise "Missing response field: #{name}" unless value.is_a?(Hash) && value.key?(name) value.fetch(name) end def is_present(value) !value.nil? && value!="" end require 'digest' require 'securerandom' require 'uri' # Private client restart state, with no transport or application dependency. module GuideJournalProtocol PREAMBLE="EXHIBITDAY-GUIDE-JOURNAL 1\n".b.freeze class Refusal < StandardError; end def self.utf8(value) raise Refusal,'Journal fields are exact strings' unless value.is_a?(String)&&value.valid_encoding? raw=value.encode(Encoding::UTF_8) raise Refusal,'Invalid UTF8 journal field' unless raw.valid_encoding? raw.b end def self.strings(values) values.map{|value|raw=utf8(value);raw.bytesize.to_s.b+':'.b+raw}.join.b end def self.read_strings(raw) values=[];offset=0 while offsetraw.bytesize-offset value=raw.byteslice(offset,size).dup.force_encoding(Encoding::UTF_8);raise Refusal,'Invalid UTF8 string' unless value.valid_encoding? values<=raw.bytesize-offset payload=raw.byteslice(offset,size);offset+=size raise Refusal,'Journal integrity failed; reconcile before retry' unless raw.getbyte(offset)==10&&digest(payload)==match[2] records<0 offset+=written end file.flush;file.fsync end end class GuideJournal P=GuideJournalProtocol def initialize(path,base,workspace,slug,job,input_fingerprint,writes,mode='resume') @path=path.dup;@lock_path=path+'.lock';@file=nil;@owned=false;@tainted=false;@intents={};@saved={};@allowed={} address=URI(base) raise P::Refusal,'Use actual API base and closed guide slug' unless ['https','http'].include?(address.scheme)&&address.host&&address.userinfo.nil?&&address.query.nil?&&address.fragment.nil?&&slug.match?(/\A[a-z][a-z0-9-]*\z/) raise P::Refusal,'Use actual workspace, stable explicit job ID and exact fingerprint' unless !job.strip.empty?&&workspace.match?(/\A[1-9][0-9]*\z/)&&input_fingerprint.match?(/\A[0-9A-F]{64}\z/) raise P::Refusal,'Choose new or resume for this local job' unless ['new','resume'].include?(mode) manifest=[] writes.each do|step,method,route| raise P::Refusal,'Use closed unique write manifest' unless step.match?(/\A[a-z][a-z0-9_-]*\z/)&&!@allowed.key?(step)&&['POST','PATCH','DELETE'].include?(method)&&route.match?(/\A\/v1\/[A-Za-z0-9_\/-]+\z/)&&!route.include?('//') @allowed[step.dup.freeze]=[method.dup.freeze,route.dup.freeze].freeze;manifest.concat([step,method,route]) end raise P::Refusal,'Only write workflows need a restart journal' if @allowed.empty? @header=['H','1',base,workspace,slug,job,input_fingerprint,P.digest(P.strings(manifest))].map{|value|value.dup.freeze}.freeze;P.strings(@header) begin @file=File.open(@lock_path,File::RDWR|File::CREAT|File::EXCL,0o600);@file.binmode;@owned=true rescue Errno::EEXIST raise P::Refusal,'This journal is locked; do not overlap jobs or steal a stale lock' end begin @owner=SecureRandom.hex(16).freeze;P.write_all(@file,@owner.b);@identity=@file.stat # Ruby's Windows fstat reports dev=0 while lstat reports the drive number. # Both expose the same exact inode. Retain it plus the initial path device; # compare like-for-like instead of treating the differing dev APIs as equal. named_identity=File.lstat(@lock_path);raise P::Refusal,'Lock identity did not bind' unless named_identity.ino==@identity.ino @path_device=named_identity.dev raise P::Refusal,'Choose a private regular journal file' if File.symlink?(@path) raise P::Refusal,'Journal missing: stop and reconcile lost state before starting a new logical job' if mode=='resume'&&!File.exist?(@path) raise P::Refusal,'Journal exists; use resume for the same logical job' if mode=='new'&&File.exist?(@path) if mode=='new' File.open(@path,File::WRONLY|File::CREAT|File::EXCL,0o600){|target|target.binmode;P.write_all(target,P::PREAMBLE+P.frame(@header))} end records=P.decode(File.binread(@path));raise P::Refusal,'Journal workspace/base/guide/job/input binding differs' if records.empty?||records[0]!=@header records.drop(1).each{|record|apply(record)} raise P::Refusal,'Saved intent lacks ACK; stop and reconcile before retry' if @intents.keys.any?{|step|!@saved.key?(step)} rescue Exception close;raise end end def apply(record) case record[0] when 'I' raise P::Refusal,'Invalid intent shape' unless record.length==6 _,step,method,route,fingerprint,key=record raise P::Refusal,'Invalid, future or repeated intent' unless step.match?(/\A[a-z][a-z0-9_-]*\z/)&&!@intents.key?(step)&&@allowed[step]==[method,route]&&fingerprint.match?(/\A[0-9A-F]{64}\z/)&&!@intents.keys.any?{|name|!@saved.key?(name)} raise P::Refusal,'Invalid persisted action key' unless (method=='POST'&&key.match?(/\A[0-9a-f]{32}\z/))||(method!='POST'&&key=='') @intents[step.dup.freeze]={'method'=>method.dup.freeze,'path'=>route.dup.freeze,'request_fingerprint'=>fingerprint.dup.freeze,'idempotency_key'=>key.dup.freeze}.freeze when 'A' raise P::Refusal,'Invalid ACK shape' unless record.length>=3 _,step,count,*pairs=record raise P::Refusal,'ACK without exactly one prior intent' unless count.match?(/\A(?:0|[1-9][0-9]*)\z/)&&pairs.length==2*count.to_i&&@intents.key?(step)&&!@saved.key?(step) names=pairs.each_slice(2).map(&:first) raise P::Refusal,'ACK fields must be unique sorted secret-free identifiers' unless names==names.uniq.sort&&names.all?{|name|name.match?(/\A[a-z][a-z0-9_]*\z/)&&!['api_key','exhibitday_api_key'].include?(name)} @saved[step.dup.freeze]=pairs.each_slice(2).to_h.transform_values{|value|value.dup.freeze}.freeze else raise P::Refusal,'Unknown journal transition' end end def require_active raise P::Refusal,'Journal is closed or IO outcome needs reconciliation' unless @owned&&@file&&!@tainted current=File.lstat(@lock_path) raise P::Refusal,'Journal lock replaced; stop without deleting it' unless current.dev==@path_device&¤t.ino==@identity.ino&&File.binread(@lock_path)==@owner.b end def append(record) require_active;raw=P.frame(record) begin File.open(@path,'ab'){|target|P.write_all(target,raw)} rescue Exception @tainted=true;raise end end def acknowledged(step);require_active;@saved.key?(step);end def saved(step) require_active;raise P::Refusal,'No acknowledged state exists' unless @saved.key?(step) @saved.fetch(step).transform_values(&:dup) end def begin_action(step,method,route,request_fingerprint) require_active;raise P::Refusal,'Never blindly repeat an action' if @intents.key?(step) record=['I',step,method,route,request_fingerprint,method=='POST'?SecureRandom.hex(16):''] previous=@intents.dup;begin;apply(record);ensure;@intents=previous;end append(record);apply(record);@intents.fetch(step).transform_values(&:dup) end def acknowledge(step,saved) require_active;record=['A',step,saved.length.to_s];saved.keys.sort.each{|name|record.concat([name,saved.fetch(name)])} previous=@saved.dup;begin;apply(record);P.strings(record);ensure;@saved=previous;end append(record);apply(record) end def close return unless @owned if @tainted;@file.close;@file=nil;@owned=false;return;end begin;require_active;rescue Exception;@file.close;@file=nil;@owned=false;raise;end @file.close;@file=nil;@owned=false;File.unlink(@lock_path) end end def journal_values(value) raise GuideJournalProtocol::Refusal,'Saved/fingerprint values must be exact strings' unless value.is_a?(Hash)&&value.all?{|name,item|name.is_a?(String)&&item.is_a?(String)} value.transform_values(&:dup) end def journal_acknowledge(job,step,saved);job.acknowledge(step,journal_values(saved));end def journal_acknowledged(job,step);job.acknowledged(step);end def journal_begin(job,step,method,path,request_fingerprint);job.begin_action(step,method,path,request_fingerprint);end def journal_fingerprint(value);GuideJournalProtocol.fingerprint(journal_values(value));end def journal_saved(job,step);job.saved(step);end def open_journal(path,base,workspace,slug,job,input_fingerprint,writes,mode);GuideJournal.new(path,base,workspace,slug,job,input_fingerprint,writes,mode);end def optional(name,fallback) value=ENV[name] value.nil? || value.empty? ? fallback : value end def positive_id(value) raise "Use a positive record ID" unless /\A[1-9][0-9]*\z/.match?(value) && Integer(value)<=9223372036854775807 value end def print_value(value) STDOUT.binmode.write((value.is_a?(String)?value:JSON.generate(value))+"\n") end def require_condition(value,message) raise message unless value==true end def required(name) value=ENV[name] raise "Set #{name}" if value.nil? || value.strip.empty? value end def response_status(value);value.fetch(:status).to_s;end def task_name(value) GuideJournalProtocol.utf8(value) raise GuideJournalProtocol::Refusal,'For this example, enter plain task text without angle brackets' if value.include?('<')||value.include?('>') value=value.gsub("\r\n",' ').delete("\r\n").gsub(/\A[\u0009-\u000D\u0020\u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]+|[\u0009-\u000D\u0020\u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]+\z/,'') raise GuideJournalProtocol::Refusal,'Choose a nonblank task name of at most400 UTF16 code units' if value.empty?||value.encode('UTF-16LE').bytesize/2>400 value end def text(value) return "" if value.nil? return value.to_s if value.is_a?(String)||value.is_a?(Integer)||value==true||value==false raise "Expected a scalar response value" end def main selected_task_id = positive_id(required('EXHIBITDAY_TASK_ID')) desired_task_name = task_name(required('EXHIBITDAY_TASK_NAME')) journal_path = required('EXHIBITDAY_JOURNAL') stable_job_id = required('EXHIBITDAY_JOB_ID') job_mode = optional('EXHIBITDAY_JOB_MODE', 'resume') workspace_binding_response = call('workspace_binding', {}, nil, nil) require_condition(equal(response_status(workspace_binding_response), '200'), 'Expected the endpoint\'s documented HTTP200 acknowledgement.') workspace_binding = workspace_binding_response.fetch(:body) owned_workspace_id = positive_id(text(field(workspace_binding, 'id'))) current_task_response = call('read', {'id' => selected_task_id, '$include_record_revision' => 'true'}, nil, nil) require_condition(equal(response_status(current_task_response), '200'), 'Expected the endpoint\'s documented HTTP200 acknowledgement.') current_task = current_task_response.fetch(:body) require_condition(equal(text(field(current_task, 'id')), selected_task_id), 'The current Task ID differs from the requested Task.') current_task_revision = text(field(current_task, 'record_revision')) require_condition(is_present(current_task_revision), 'Read the actual Task with $include_record_revision=true; an opaque revision is required.') input_fingerprint = journal_fingerprint({'workflow_contract_sha256' => '33C19FE95C143455286D674AAD34FFDCA4D1CAF0132A232A37F8D2BF39BB9DE4', 'task_id' => selected_task_id, 'desired_name' => desired_task_name}) update_job = open_journal(journal_path, 'https://api.exhibitday.com/v1', owned_workspace_id, 'update-records-safely', stable_job_id, input_fingerprint, [['save', 'PATCH', '/v1/tasks']], job_mode) begin if journal_acknowledged(update_job, 'save') saved_task = journal_saved(update_job, 'save') require_condition(both(equal(text(field(saved_task, 'id')), selected_task_id), equal(text(field(saved_task, 'name')), desired_task_name)), 'Acknowledged state does not match this Task/name; stop and reconcile.') else task_patch = {'id' => selected_task_id, 'name' => desired_task_name, 'expected_revision' => current_task_revision} write_fingerprint = journal_fingerprint({'id' => selected_task_id, 'name' => desired_task_name, 'expected_revision' => current_task_revision}) journal_begin(update_job, 'save', 'PATCH', '/v1/tasks', write_fingerprint) saved_task_response = call('save', {}, task_patch, nil) require_condition(equal(response_status(saved_task_response), '200'), 'Expected the endpoint\'s documented HTTP200 acknowledgement.') saved_task_receipt = saved_task_response.fetch(:body) saved_task_revision = text(field(saved_task_receipt, 'record_revision')) require_condition(is_present(saved_task_revision), 'A valid save acknowledgement must include its new record_revision.') journal_acknowledge(update_job, 'save', {'id' => selected_task_id, 'name' => desired_task_name, 'record_revision' => saved_task_revision}) end task_readback_response = call('readback', {'id' => selected_task_id, '$include_record_revision' => 'true'}, nil, nil) require_condition(equal(response_status(task_readback_response), '200'), 'Expected the endpoint\'s documented HTTP200 acknowledgement.') task_readback = task_readback_response.fetch(:body) require_condition(both(equal(text(field(task_readback, 'id')), selected_task_id), equal(text(field(task_readback, 'name')), desired_task_name)), 'The current Task no longer matches the acknowledged change; review it instead of automatically restoring the name.') require_condition(is_present(text(field(task_readback, 'record_revision'))), 'The readback needs the actual current record_revision.') print_value({'task_id' => text(field(task_readback, 'id')), 'name' => text(field(task_readback, 'name')), 'record_revision' => text(field(task_readback, 'record_revision'))}) ensure update_job.close() end end main if $PROGRAM_NAME == __FILE__ ``` ```go // Go 1.18+; standard library only. Set EXHIBITDAY_API_KEY. package main import ( "bytes" "crypto/rand" "crypto/sha256" "encoding/hex" "regexp" "sort" "unicode/utf8" "encoding/json" "fmt" "io" "net/http" "net/url" "os" "strconv" "strings" "time" ) const base = "https://api.exhibitday.com/v1" const specification = "{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"read\":{\"method\":\"GET\",\"path\":\"/tasks/info\"},\"save\":{\"method\":\"PATCH\",\"path\":\"/tasks\"},\"readback\":{\"method\":\"GET\",\"path\":\"/tasks/info\"}}}" 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 }} var send = client.Do type result struct { status int; body any; headers http.Header; raw []byte } // 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 call(name string, query map[string]string, body any, key string) result { route := object(object(spec["requests"])[name]); method := text(route["method"]) headers := map[string]string{"Authorization": "Bearer " + apiKey, "Accept": "application/json"} if method == "POST" { if key == "" { panic("Persist a logical create key before sending POST") }; 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() } // 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 := method == "GET" 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 := send(request) if err != nil { if !resend { panic(apiError{0, "", "No response", true}) }; if attempt == 4 { panic(err) }; time.Sleep(time.Second*time.Duration(1<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 := resend && (response.StatusCode == 429 || response.StatusCode >= 500) if retry { if attempt == 4 { panic("Retry limit reached; check the outcome before starting a new create") } seconds := float64(int64(1)<= 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, raw} } panic("Retry limit reached") } func both(left,right bool)bool{return left&&right} func equal(left,right any)bool{switch a:=left.(type){case string:b,ok:=right.(string);return ok&&a==b;case bool:b,ok:=right.(bool);return ok&&a==b;case int64:b,ok:=right.(int64);return ok&&a==b};return left==nil&&right==nil} func field(value any,name string)any{obj,ok:=value.(map[string]any);if !ok{panic("Missing response object")};item,found:=obj[name];if !found{panic("Missing response field: "+name)};return item} func is_present(value string)bool{return value!=""} // Private client restart state only; no API transport or workflow interpreter. const journalPreamble = "EXHIBITDAY-GUIDE-JOURNAL 1\n" type journalRefusal struct{ message string } func (e journalRefusal) Error() string { return e.message } func journalNeed(ok bool, message string) { if !ok { panic(journalRefusal{message}) } } func journalMatch(value, pattern string) bool { return regexp.MustCompile("\\A(?:"+pattern+")\\z").MatchString(value) } func journalStrings(values []string) []byte { var output bytes.Buffer for _,value:=range values { journalNeed(utf8.ValidString(value),"Journal fields must be valid UTF8 strings"); output.WriteString(strconv.Itoa(len(value))+":");output.WriteString(value) } return output.Bytes() } func journalReadStrings(raw []byte) []string { values:=[]string{};offset:=0 for offset=0,"Incomplete journal string length");end:=offset+relative;text:=string(raw[offset:end]);journalNeed(journalMatch(text,"0|[1-9][0-9]*"),"Noncanonical journal string length");size,err:=strconv.ParseUint(text,10,64);offset=end+1;journalNeed(err==nil&&size<=uint64(len(raw)-offset),"Incomplete journal string");count:=int(size);value:=string(raw[offset:offset+count]);journalNeed(utf8.ValidString(value),"Invalid UTF8 journal field");values=append(values,value);offset+=count } return values } func journalDigest(raw []byte) string { hash:=sha256.Sum256(raw);return strings.ToUpper(hex.EncodeToString(hash[:])) } func journalFingerprint(pairs map[string]string) string { names:=make([]string,0,len(pairs));for name:=range pairs { names=append(names,name) };sort.Strings(names);values:=[]string{} for _,name:=range names { lower:=strings.ToLower(name);journalNeed(journalMatch(name,"[A-Za-z0-9_.-]+")&&lower!="api_key"&&lower!="exhibitday_api_key","Use explicit secret-free fingerprint names");values=append(values,name,pairs[name]) } return journalDigest(journalStrings(values)) } func journalFrame(values []string) []byte { raw:=journalStrings(values);header:=[]byte(strconv.Itoa(len(raw))+" "+journalDigest(raw)+"\n");result:=append(header,raw...);return append(result,'\n') } func journalDecode(raw []byte) [][]string { journalNeed(bytes.HasPrefix(raw,[]byte(journalPreamble)),"Unknown or incomplete journal version");offset:=len(journalPreamble);records:=[][]string{} for offset=0,"Incomplete frame header; reconcile before retry");end:=offset+relative;header:=string(raw[offset:end]);journalNeed(journalMatch(header,"(0|[1-9][0-9]*) [0-9A-F]{64}"),"Invalid frame header");fields:=strings.Split(header," ");size,err:=strconv.ParseUint(fields[0],10,64);offset=end+1;journalNeed(err==nil&&size0 { count,err:=file.Write(raw);if err!=nil{return err};if count<=0{return io.ErrShortWrite};raw=raw[count:] } return file.Sync() } func journalWriteFile(path string,flags int,raw []byte) (err error) { file,err:=os.OpenFile(path,flags,0600);if err!=nil{return err};defer func(){closed:=file.Close();if err==nil{err=closed}}();return journalWriteAll(file,raw) } func journalCopy(source map[string]string) map[string]string { copy:=map[string]string{};for name,value:=range source{copy[name]=value};return copy } func journalCopyStates(source map[string]map[string]string) map[string]map[string]string { copy:=map[string]map[string]string{};for name,value:=range source{copy[name]=journalCopy(value)};return copy } type guideJournal struct { path,lockPath,owner string header []string allowed map[string][2]string intents,savedValues map[string]map[string]string file *os.File identity os.FileInfo owned,tainted bool } func openGuideJournal(path,base,workspace,slug,job,inputFingerprint string,writes [][3]string,modes ...string) (result *guideJournal) { mode:="resume";journalNeed(len(modes)<=1,"Choose one local job mode");if len(modes)==1{mode=modes[0]};journalNeed(mode=="new"||mode=="resume","Choose new or resume for this local job") address,err:=url.Parse(base);journalNeed(err==nil&&address.Hostname()!=""&&(address.Scheme=="https"||address.Scheme=="http")&&address.User==nil&&address.RawQuery==""&&address.Fragment==""&&journalMatch(slug,"[a-z][a-z0-9-]*"),"Use actual API base and closed guide slug") journalNeed(strings.TrimSpace(job)!=""&&journalMatch(workspace,"[1-9][0-9]*")&&journalMatch(inputFingerprint,"[0-9A-F]{64}"),"Use actual workspace, stable explicit job ID and exact fingerprint") j:=&guideJournal{path:path,lockPath:path+".lock",allowed:map[string][2]string{},intents:map[string]map[string]string{},savedValues:map[string]map[string]string{}} manifest:=[]string{};for _,write:=range writes { step,method,route:=write[0],write[1],write[2];_,exists:=j.allowed[step];journalNeed(journalMatch(step,"[a-z][a-z0-9_-]*")&&!exists&&(method=="POST"||method=="PATCH"||method=="DELETE")&&journalMatch(route,"/v1/[A-Za-z0-9_/-]+")&&!strings.Contains(route,"//"),"Use a closed unique write manifest");j.allowed[step]=[2]string{method,route};manifest=append(manifest,step,method,route) } journalNeed(len(j.allowed)>0,"Only write workflows need a restart journal");j.header=[]string{"H","1",base,workspace,slug,job,inputFingerprint,journalDigest(journalStrings(manifest))};journalStrings(j.header) j.file,err=os.OpenFile(j.lockPath,os.O_RDWR|os.O_CREATE|os.O_EXCL,0600);if err!=nil { if os.IsExist(err){panic(journalRefusal{"This journal is locked; do not overlap jobs or steal a stale lock"})};panic(err) };j.owned=true defer func(){ if observed:=recover();observed!=nil { j.Close();panic(observed) } }() random:=make([]byte,16);if _,err=io.ReadFull(rand.Reader,random);err!=nil{panic(err)};j.owner=hex.EncodeToString(random);if err=journalWriteAll(j.file,[]byte(j.owner));err!=nil{panic(err)};j.identity,err=j.file.Stat();if err!=nil{panic(err)} info,err:=os.Lstat(path);if err!=nil&&!os.IsNotExist(err){panic(err)};exists:=err==nil;if exists{journalNeed(info.Mode()&os.ModeSymlink==0,"Choose a private regular journal file")};journalNeed(mode!="resume"||exists,"Journal missing: stop and reconcile lost state before starting a new logical job");journalNeed(mode!="new"||!exists,"Journal exists; use resume for the same logical job");if mode=="new"{raw:=append([]byte(journalPreamble),journalFrame(j.header)...);if err=journalWriteFile(path,os.O_WRONLY|os.O_CREATE|os.O_EXCL,raw);err!=nil{panic(err)}} raw,err:=os.ReadFile(path);if err!=nil{panic(err)};records:=journalDecode(raw);journalNeed(len(records)>0&&stringsEqual(records[0],j.header),"Journal workspace/base/guide/job/input binding differs");for _,record:=range records[1:]{j.apply(record)};for step:=range j.intents{_,ok:=j.savedValues[step];journalNeed(ok,"Saved intent lacks ACK; stop and reconcile before retry")};return j } func stringsEqual(left,right []string) bool { if len(left)!=len(right){return false};for i,value:=range left{if value!=right[i]{return false}};return true } func (j *guideJournal) apply(record []string) { journalNeed(len(record)>0,"Empty journal record") if record[0]=="I" { journalNeed(len(record)==6,"Invalid intent shape");step,method,route,fingerprint,key:=record[1],record[2],record[3],record[4],record[5];_,exists:=j.intents[step];expected,allowed:=j.allowed[step];pending:=false;for name:=range j.intents{if _,ok:=j.savedValues[name];!ok{pending=true}} journalNeed(journalMatch(step,"[a-z][a-z0-9_-]*")&&!exists&&allowed&&expected==[2]string{method,route}&&journalMatch(fingerprint,"[0-9A-F]{64}")&&!pending,"Invalid, future or repeated intent");journalNeed(method=="POST"&&journalMatch(key,"[0-9a-f]{32}")||method!="POST"&&key=="","Invalid persisted action key");j.intents[step]=map[string]string{"method":method,"path":route,"request_fingerprint":fingerprint,"idempotency_key":key} }else if record[0]=="A" { journalNeed(len(record)>=3,"Invalid ACK shape");step,text:=record[1],record[2];count,err:=strconv.ParseUint(text,10,64);_,prior:=j.intents[step];_,done:=j.savedValues[step];journalNeed(journalMatch(text,"0|[1-9][0-9]*")&&err==nil&&len(record)%2==1&&count==uint64((len(record)-3)/2)&&prior&&!done,"ACK without exactly one prior intent");names:=[]string{};for i:=3;i0&&value[0]!='0';for _,ch:=range value{valid=valid&&ch>='0'&&ch<='9'};id,err:=strconv.ParseInt(value,10,64);if !valid||err!=nil||id<=0{panic("Use a positive record ID")};return value} func print_value(value any){if result,ok:=value.(string);ok{fmt.Println(result);return};raw,err:=json.Marshal(value);if err!=nil{panic(err)};fmt.Println(string(raw))} func require_condition(value bool,message string){if !value{panic(message)}} func response_status(value result)string{return strconv.Itoa(value.status)} func task_space(c rune)bool{return c>=9&&c<=13||c==32||c==0x85||c==0xA0||c==0x1680||c>=0x2000&&c<=0x200A||c==0x2028||c==0x2029||c==0x202F||c==0x205F||c==0x3000} func task_name(value string)string{journalNeed(utf8.ValidString(value),"Use valid UTF8 task text");journalNeed(!strings.ContainsAny(value,"<>"),"For this example, enter plain task text without angle brackets");value=strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(value,"\r\n"," "),"\n",""),"\r","");value=strings.TrimFunc(value,task_space);units:=0;for _,character:=range value{units++;if character>0xFFFF{units++}};journalNeed(value!=""&&units<=400,"Choose a nonblank task name of at most400 UTF16 code units");return value} func workflow() { selected_task_id := positive_id(required("EXHIBITDAY_TASK_ID")) desired_task_name := task_name(required("EXHIBITDAY_TASK_NAME")) journal_path := required("EXHIBITDAY_JOURNAL") stable_job_id := required("EXHIBITDAY_JOB_ID") job_mode := optional("EXHIBITDAY_JOB_MODE", "resume") workspace_binding_response := call("workspace_binding", map[string]string{}, nil, "") require_condition(equal(response_status(workspace_binding_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement.") workspace_binding := workspace_binding_response.body owned_workspace_id := positive_id(text(field(workspace_binding, "id"))) current_task_response := call("read", map[string]string{"id": selected_task_id, "$include_record_revision": "true"}, nil, "") require_condition(equal(response_status(current_task_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement.") current_task := current_task_response.body require_condition(equal(text(field(current_task, "id")), selected_task_id), "The current Task ID differs from the requested Task.") current_task_revision := text(field(current_task, "record_revision")) require_condition(is_present(current_task_revision), "Read the actual Task with $include_record_revision=true; an opaque revision is required.") input_fingerprint := journal_fingerprint(map[string]any{"workflow_contract_sha256": "33C19FE95C143455286D674AAD34FFDCA4D1CAF0132A232A37F8D2BF39BB9DE4", "task_id": selected_task_id, "desired_name": desired_task_name}) func() { update_job := open_journal(journal_path, "https://api.exhibitday.com/v1", owned_workspace_id, "update-records-safely", stable_job_id, input_fingerprint, []any{[]any{"save", "PATCH", "/v1/tasks"}}, job_mode) defer update_job.Close() if journal_acknowledged(update_job, "save") { saved_task := journal_saved(update_job, "save") require_condition(both(equal(text(field(saved_task, "id")), selected_task_id), equal(text(field(saved_task, "name")), desired_task_name)), "Acknowledged state does not match this Task/name; stop and reconcile.") } else { task_patch := map[string]any{"id": selected_task_id, "name": desired_task_name, "expected_revision": current_task_revision} write_fingerprint := journal_fingerprint(map[string]any{"id": selected_task_id, "name": desired_task_name, "expected_revision": current_task_revision}) journal_begin(update_job, "save", "PATCH", "/v1/tasks", write_fingerprint) saved_task_response := call("save", map[string]string{}, task_patch, "") require_condition(equal(response_status(saved_task_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement.") saved_task_receipt := saved_task_response.body saved_task_revision := text(field(saved_task_receipt, "record_revision")) require_condition(is_present(saved_task_revision), "A valid save acknowledgement must include its new record_revision.") journal_acknowledge(update_job, "save", map[string]any{"id": selected_task_id, "name": desired_task_name, "record_revision": saved_task_revision}) } task_readback_response := call("readback", map[string]string{"id": selected_task_id, "$include_record_revision": "true"}, nil, "") require_condition(equal(response_status(task_readback_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement.") task_readback := task_readback_response.body require_condition(both(equal(text(field(task_readback, "id")), selected_task_id), equal(text(field(task_readback, "name")), desired_task_name)), "The current Task no longer matches the acknowledged change; review it instead of automatically restoring the name.") require_condition(is_present(text(field(task_readback, "record_revision"))), "The readback needs the actual current record_revision.") print_value(map[string]any{"task_id": text(field(task_readback, "id")), "name": text(field(task_readback, "name")), "record_revision": text(field(task_readback, "record_revision"))}) }() } func header_key(value string)string{for _,ch:=range value{if ch<32||ch>126{panic("Use the API key as one ASCII header value without control characters")}};return value} func main(){apiKey=header_key(required("EXHIBITDAY_API_KEY"));if err:=json.Unmarshal([]byte(specification),&spec);err!=nil{panic(err)};workflow()} ``` #### Example response Response 200 — OK 304 — Not Modified 400 — Bad Request 401 — Unauthorized 404 — Not Found 409 — Conflict 429 — Too Many Requests 500 — Internal Server Error Example Successful request ```json { "id": 12345, "exhibitday_url": "https://www.exhibitday.com/Workspace/TaskView/98765?tid=12345", "event_task_section_id": null, "event_task_section": "Uncategorized", "display_rank": 0, "name": "Confirm booth artwork with the supplier", "due_date": "2030-01-10", "assignee": null, "is_completed": false, "task_completed_timestamp": null, "task_completed_by": null, "details": "Confirm the final artwork with the display supplier.", "comments": [ { "id": 16346, "comment": "I will confirm the remaining details.", "comment_created_timestamp": "2030-01-02T17:01:00Z", "comment_last_update_timestamp": "2030-01-02T17:01:00Z", "commenter": { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true } }, { "id": 16347, "comment": "The setup checklist is ready.", "comment_created_timestamp": "2030-01-02T17:02:00Z", "comment_last_update_timestamp": "2030-01-02T17:02:00Z", "commenter": { "id": "66666666-7777-4888-8999-aaaaaaaaaaaa", "first_name": "Alex", "last_name": "Jordan", "display_name": "Alex Jordan", "email": "alex@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true } } ], "event": { "id": 5001, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=5001", "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": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": null, "email": "jane@example.invalid", "type": null, "workspace_role": null, "is_active": null }, "task_created_timestamp": "2030-01-02T17:00:00Z", "task_last_update_timestamp": "2030-01-02T17:02:00Z", "integration_metadata_field_1": null, "integration_metadata_field_2": null, "integration_metadata_field_3": null, "integration_metadata_field_4": null, "integration_metadata_field_5": null, "record_revision": "r1:RzQikEQb0JBtVlK-B6zztQ2jKFgyUwn8eN1X1EUbRQQ" } ``` Note: The Task as read after the update. It includes the record revision you requested and, by default, the Task's comments. Note: There is no response body. Keep using your cached response. ```json { "status_code": 400, "status": "Bad Request", "message": "HTTP method override is not supported.", "error_code": "invalid_request", "errors": [ "Send the documented HTTP method directly. X-HTTP-Method-Override cannot change a request's HTTP method." ], "error_params": [ "X-HTTP-Method-Override" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "No API key was provided. Send your key in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "missing_api_key", "errors": [ "Copy the key from Workspace Settings > API & Integrations > API Access in ExhibitDay." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "The API key is not valid. Check that you copied the whole key from Workspace Settings > API & Integrations > API Access, then send it in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "invalid_api_key", "errors": [ "Check that you sent the whole key. If it was regenerated, use the current key from Workspace Settings > API & Integrations > API Access." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "Access to the ExhibitDay API is not enabled for your workspace. Please contact support@exhibitday.com to enable API Access. Once access is enabled, send your key in the Authorization header as 'Bearer YOUR_API_KEY'.", "error_code": "api_access_disabled", "errors": [ "Nothing was read or changed." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 404, "status": "Not Found", "message": "Task not found. Invalid Task ID: 12345.", "error_code": "not_found", "errors": [ "Task not found. Invalid Task ID: 12345." ], "error_params": [ "id" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "The record was being changed while it was read, so no record_revision could be issued. Read it again.", "error_code": "record_changed", "errors": [ "The record was being changed while it was read, so no record_revision could be issued. Read it again." ], "error_params": [ "$include_record_revision" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 429, "status": "Too Many Requests", "message": "Error 429 - Too Many Requests", "error_code": "rate_limited", "errors": [ "Error 429 - Too Many Requests" ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "An unexpected error occurred. Please try again later." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` Note: Use the request_id from your own response when contacting support. ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "Check whether your change was saved before trying again." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` #### Things to keep in mind - Enter a plain Task name without angle brackets. - The program normalizes line breaks and trims surrounding whitespace. - The name must be nonblank and at most 400 UTF-16 code units. Some characters count as two. #### If a run stops - Keep the journal private. It records what the program tried to save and which save it confirmed. - To continue a run with no unresolved save, use `EXHIBITDAY_JOB_MODE=resume` with the same job ID, journal path and inputs. - A resumed run skips an acknowledged update. It stops if the current name differs from the name it saved. - If a save stops with a conflict, a lost response or a missing revision, check the Task in ExhibitDay before running the program again. - If you still need a change after checking the old run, use `EXHIBITDAY_JOB_MODE=new` with a new job ID and journal path. - Run only one copy per journal. - If a crash leaves a `.lock` file, make sure no copy using that journal is running or can start. Then remove the lock file and keep the journal. #### Related guides - [Create Tasks from Forms, Tickets or Other Apps](https://api.exhibitday.com/Help/V1?guide=create-tasks) - [Handle Errors and Retry Failed Requests](https://api.exhibitday.com/Help/V1?guide=errors-and-retries) ### Link ExhibitDay Events to Your CRM or ERP Records Guide page: https://api.exhibitday.com/Help/V1?guide=match-records Link each record in your CRM or ERP (for example Salesforce, HubSpot or NetSuite) to the matching ExhibitDay Event, even after names change. Example use case You connect ExhibitDay to a CRM or ERP and want the same records to stay linked even after their names change. What you'll end up with A confirmed pair of IDs to save in your integration and a safe way to find an existing match. Before you start Have your workspace API key, your system's Event ID and a place to store the pair. This guide assumes your system's ID for each Event is already stored in integration_metadata_field_1, one of five API-only text fields on each Event. If another integration already uses field 1, choose a free field (1 to 5) and use it consistently. Good to know Match on IDs. Two Events can have the same name, and names can change. #### At a glance Time to try About 5 minutes Effect on your data Read-only Endpoints 2 The example reads Events and prints the confirmed pair. - [`GET /v1/events`](https://api.exhibitday.com/Help/V1?epf=1#get-v1-events) - [`GET /v1/events/info`](https://api.exhibitday.com/Help/V1?epf=1#get-v1-events-info) #### How it works 1. Your system keeps its own ID for each show. The example assumes that ID is already stored in the Event's integration_metadata_field_1. 2. If you already saved the ExhibitDay Event ID, the program checks it directly. Otherwise, it searches by your system's ID and requires exactly one match. 3. After it confirms both IDs, save the pair in your system. Use the ExhibitDay Event ID for later requests. The examples show how to find and confirm a match. If you already saved the ExhibitDay Event ID, skip Step 1 and confirm it in Step 2. #### Step 1: Search by your system's ID If you do not have a saved Event ID, search Events by integration_metadata_field_1, the field where your system's ID is stored, and read every page. ```bash curl -X GET "https://api.exhibitday.com/v1/events?filter_by_integration_metadata_field_1=crm%3Aevent%3Aspring-expo-2030&%24limit=100&%24offset=0" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "has_more": false, "list_data": [ { "id": 12345, "integration_metadata_field_1": "crm:event:spring-expo-2030" } ] } ``` Use list_data[].id to identify a candidate. When has_more is true, continue to the next page. **Check:** Look for one distinct Event with the full external ID. If none match, create the Event or link an existing one with [Create or Update Events from Your CRM](https://api.exhibitday.com/Help/V1?guide=event-setup-crm). If several match, stop and review. #### Step 2: Confirm the match and save the pair Read the chosen Event by ID to confirm the link before saving it. ```bash curl -X GET "https://api.exhibitday.com/v1/events/info?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "id": 12345, "integration_metadata_field_1": "crm:event:spring-expo-2030" } ``` Save this id in your integration after checking the stored key. **Check:** Confirm that integration_metadata_field_1 equals your external ID. Save the Event id with your external ID. **Careful.** If a saved ID no longer matches, the example stops. Review the saved link before trying a different ID. #### Try it #### Before running the example | Variable | What to put in it | Required? | | --- | --- | --- | | `EXHIBITDAY_API_KEY` | Your workspace API key. | Yes | | `EXHIBITDAY_EXTERNAL_EVENT_KEY` | Your system's Event ID, exactly as stored in ExhibitDay, up to 3,000 characters. | Yes | | `EXHIBITDAY_PAGE_SIZE` | A positive number of Events per page. Defaults to 100. | No | | `EXHIBITDAY_EVENT_ID` | A previously saved ExhibitDay Event ID. When set, the example goes straight to confirmation. | No | **Note.** This example only reads data. It prints the confirmed pair so you can save it. #### Bash ``` export EXHIBITDAY_API_KEY='YOUR_API_KEY' export EXHIBITDAY_EXTERNAL_EVENT_KEY='crm:event:spring-expo-2030' ``` #### PowerShell ``` $env:EXHIBITDAY_API_KEY = 'YOUR_API_KEY' $env:EXHIBITDAY_EXTERNAL_EVENT_KEY = 'crm:event:spring-expo-2030' ``` Then copy the complete example program below in your language and run it. #### Complete example program Code Samples ```bash #!/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\":{\"find_match\":{\"method\":\"GET\",\"path\":\"/events\"},\"confirm_match\":{\"method\":\"GET\",\"path\":\"/events/info\"}}}") API_KEY = os.environ["EXHIBITDAY_API_KEY"] if any(ord(char) < 32 or ord(char) > 126 for char in API_KEY): raise RuntimeError("Use the API key as one ASCII header value without control characters") if not API_KEY.strip(): raise RuntimeError("Set EXHIBITDAY_API_KEY") def decode_json(text): if SPEC["preserveNumbers"]: # Quote JSON NUMBER tokens, never text inside a JSON string, to keep CSV decimals exact. text = re.sub(r'"(?:\\.|[^"\\])*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?', lambda m: m[0] if m[0].startswith('"') else json.dumps(m[0]), text) return json.loads(text) from pathlib import Path # This terminal version uses curl for HTTP and Python's standard library for JSON/CSV. import subprocess import tempfile def transport(method, url, headers, data): with tempfile.TemporaryDirectory(prefix="exhibitday-guide-") as directory: folder = Path(directory) # curl may leave no output file for a valid bodyless304 response. (folder / "body").write_bytes(b"") command = ["curl", "--disable", "--silent", "--show-error", "--request", method, "--url", url, "--max-time", "30", "--dump-header", str(folder / "headers"), "--output", str(folder / "body"), "--write-out", "%{http_code}"] for name, value in headers.items(): command += ["--header", name + ": " + value] if data is not None: (folder / "request").write_bytes(data) command += ["--data-binary", "@" + str(folder / "request")] result = subprocess.run(command, capture_output=True, text=True) if result.returncode: raise urllib.error.URLError(result.stderr.strip()) response_headers = {} blocks = (folder / "headers").read_text(encoding="iso-8859-1").replace("\r\n", "\n").strip().split("\n\n") for line in blocks[-1].splitlines()[1:]: name, separator, value = line.partition(":") if separator: response_headers[name] = value.strip() return int(result.stdout), (folder / "body").read_bytes(), response_headers class ApiError(RuntimeError): """An API error response. Branch on error_code (and status), never on the message text. uncertain is True when a PATCH or DELETE got no response or a server error: it may or may not have been applied.""" def __init__(self, status, body, uncertain=False): self.status = status self.uncertain = uncertain self.error_code = body.get("error_code") if isinstance(body, dict) else None super().__init__(f"{body.get('error_code')} {body.get('error_params')}: {body.get('errors')} (request {body.get('request_id')})" if isinstance(body, dict) else "HTTP " + str(status) if status else "No response") def call(name, params=None, body=None, key=None): route = SPEC["requests"][name] headers = {"Authorization": "Bearer " + API_KEY, "Accept": "application/json"} if route["method"] == "POST": if not key: raise RuntimeError("Persist a logical create key before sending POST") headers["Idempotency-Key"] = key data = None if body is None else json.dumps(body).encode("utf-8") if data is not None: headers["Content-Type"] = "application/json" query = urllib.parse.urlencode(params or {}) url = BASE + route["path"] + ("?" + query if query else "") # Only GET has automatic retries in this workflow. A PATCH or DELETE that got no response or a # server error is never resent blindly: it may already have been applied, so the caller reads the record first. resend = route["method"] == "GET" for attempt in range(5): try: status, raw, response_headers = transport(route["method"], url, headers, data) except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException): if not resend: raise ApiError(0, None, uncertain=True) if attempt == 4: raise time.sleep(2 ** attempt) continue response_headers = {k.lower(): v for k, v in response_headers.items()} result = None if status != 304 and raw: try: result = decode_json(raw.decode("utf-8")) except (ValueError, UnicodeError): if status < 400: raise RuntimeError("Expected a JSON success response") if status >= 500 and not resend: raise ApiError(status, result, uncertain=True) retry = resend and (status == 429 or status >= 500) if retry: if attempt == 4: raise RuntimeError("Retry limit reached; check the request outcome before starting a new create") delay = response_headers.get("retry-after", str(2 ** attempt)) time.sleep(max(0, float(delay))) continue if status >= 400: raise ApiError(status, result) return {"status": status, "body": result, "headers": response_headers, "raw": raw} raise RuntimeError("Retry limit reached") def 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 items(value): if not isinstance(value, list): raise RuntimeError("Expected a JSON array") return value def count(value): return len(items(value)) 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] def is_empty(value): return count(value) == 0 def is_present(value): return value is not None and value != "" def not_value(value): if not isinstance(value, bool): raise RuntimeError("Expected a Boolean") return not value def optional(name, fallback): value = os.environ.get(name) return fallback if value is None or value == "" else value def page_size(value): if not re.fullmatch(r"[1-9][0-9]*", value) or int(value) > 2147483647: raise RuntimeError("Page size must be a positive int32") return value def positive_id(value): if not re.fullmatch(r"[1-9][0-9]*", value) or int(value) > 9223372036854775807: raise RuntimeError("Use a positive record ID") return value def print_value(value): print(value if isinstance(value, str) else json.dumps(value, ensure_ascii=False)) def require_condition(value, message): if value is not True: raise RuntimeError(message) def required(name): value = os.environ.get(name) if value is None or not value.strip(): raise RuntimeError("Set " + name) return value def 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(): external_event_key = required("EXHIBITDAY_EXTERNAL_EVENT_KEY") matched_event_id = optional("EXHIBITDAY_EVENT_ID", "") if is_present(matched_event_id): matched_event_id = positive_id(matched_event_id) else: matching_page_size = page_size(optional("EXHIBITDAY_PAGE_SIZE", "100")) matching_offset = "0" matching_query = {"filter_by_integration_metadata_field_1": external_event_key, "$limit": matching_page_size} while True: matching_query["$offset"] = matching_offset matching_response = call("find_match", matching_query, None, None) matching_page = matching_response["body"] matching_rows = items(field(matching_page, "list_data")) require_condition(equal(text(field(matching_page, "records_found")), text(count(matching_rows))), "records_found does not match this page's rows.") require_condition(is_present(text(field(matching_page, "total_records"))), "The collection wrapper needs total_records.") require_condition(either(equal(field(matching_page, "has_more"), True), equal(field(matching_page, "has_more"), False)), "Expected a Boolean has_more value.") for matching_event in items(matching_rows): if equal(text(field(matching_event, "integration_metadata_field_1")), external_event_key): candidate_event_id = positive_id(text(field(matching_event, "id"))) if is_present(matched_event_id): require_condition(equal(matched_event_id, candidate_event_id), "Multiple Events have this exact external key; resolve the ambiguity before linking.") matched_event_id = candidate_event_id if equal(field(matching_page, "has_more"), False): break require_condition(not_value(is_empty(matching_rows)), "An empty page has has_more=true; stop and reconcile the search.") matching_offset = add_offset(matching_offset, count(matching_rows)) require_condition(is_present(matched_event_id), "No exact match was found. Decide explicitly whether to create or link a record.") confirmation_query = {"id": matched_event_id} confirmed_response = call("confirm_match", confirmation_query, None, None) confirmed_event = confirmed_response["body"] require_condition(equal(text(field(confirmed_event, "id")), matched_event_id), "The confirmed Event ID differs from the selected Event.") require_condition(equal(text(field(confirmed_event, "integration_metadata_field_1")), external_event_key), "The Event's current metadata differs from the intended external key. Stop for review.") print_value({"external_event_key": external_event_key, "event_id": matched_event_id}) if __name__ == "__main__": main() EXHIBITDAY_PY ``` ```javascript // Server-side Node.js with fetch; built-in modules only. Set EXHIBITDAY_API_KEY. const BASE = "https://api.exhibitday.com/v1"; const SPEC = JSON.parse("{\"preserveNumbers\":true,\"requests\":{\"find_match\":{\"method\":\"GET\",\"path\":\"/events\"},\"confirm_match\":{\"method\":\"GET\",\"path\":\"/events/info\"}}}"); const API_KEY = process.env.EXHIBITDAY_API_KEY; if (!API_KEY || !API_KEY.trim()) throw new Error("Set EXHIBITDAY_API_KEY"); if (/[^\x20-\x7e]/.test(API_KEY)) throw new Error("Use the API key as one ASCII header value without control characters"); 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, errors: result.errors, error_params: result.error_params, 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, key = null) { const route = SPEC.requests[name]; const headers = { Authorization: "Bearer " + API_KEY, Accept: "application/json" }; if (route.method === "POST") { if (!key) throw new Error("Persist a logical create key before sending POST"); headers["Idempotency-Key"] = key; } 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 : ""); // 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. const resend = route.method === "GET"; 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 = resend && (response.status === 429 || response.status >= 500); 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, raw }; } throw new Error("Retry limit reached"); } function add_offset(offset, received) { const result = BigInt(offset) + received; if (received <= 0n || result > 2147483647n) throw new Error("Cannot advance this int32 offset; reconcile the query"); return result.toString(); } function items(value) { if (!Array.isArray(value)) throw new Error("Expected a JSON array"); return value; } function count(value) { return BigInt(items(value).length); } function either(left, right) { if (typeof left !== "boolean" || typeof right !== "boolean") throw new Error("Expected Boolean criteria"); return left || right; } function equal(left, right) { return typeof left === typeof right && left === right; } function field(value, name) { if (!value || Array.isArray(value) || typeof value !== "object" || !Object.hasOwn(value, name)) throw new Error("Missing response field: " + name); return value[name]; } function is_empty(value) { return count(value) === 0n; } function is_present(value) { return value !== null && value !== undefined && value !== ""; } function not_value(value) { if (typeof value !== "boolean") throw new Error("Expected a Boolean"); return !value; } function optional(name, fallback) { const value = process.env[name]; return value === undefined || value === "" ? fallback : value; } function page_size(value) { if (!/^[1-9][0-9]*$/.test(value) || BigInt(value) > 2147483647n) throw new Error("Page size must be a positive int32"); return value; } function positive_id(value) { if (!/^[1-9][0-9]*$/.test(value) || BigInt(value) > 9223372036854775807n) throw new Error("Use a positive record ID"); return value; } function print_value(value) { console.log(typeof value === "string" ? value : JSON.stringify(value)); } function require_condition(value, message) { if (value !== true) throw new Error(message); } function required(name) { const value = process.env[name]; if (value === undefined || !value.trim()) throw new Error("Set " + name); return value; } function text(value) { if (value === null || value === undefined) return ""; if (["string", "boolean", "bigint"].includes(typeof value)) return String(value); throw new Error("Expected a scalar response value"); } async function main() { let external_event_key = required("EXHIBITDAY_EXTERNAL_EVENT_KEY"); let matched_event_id = optional("EXHIBITDAY_EVENT_ID", ""); if (is_present(matched_event_id)) { matched_event_id = positive_id(matched_event_id); } else { let matching_page_size = page_size(optional("EXHIBITDAY_PAGE_SIZE", "100")); let matching_offset = "0"; let matching_query = {"filter_by_integration_metadata_field_1": external_event_key, "$limit": matching_page_size}; while (true) { matching_query["$offset"] = matching_offset; let matching_response = await call("find_match", matching_query, null, null); let matching_page = matching_response.body; let matching_rows = items(field(matching_page, "list_data")); require_condition(equal(text(field(matching_page, "records_found")), text(count(matching_rows))), "records_found does not match this page's rows."); require_condition(is_present(text(field(matching_page, "total_records"))), "The collection wrapper needs total_records."); require_condition(either(equal(field(matching_page, "has_more"), true), equal(field(matching_page, "has_more"), false)), "Expected a Boolean has_more value."); for (const matching_event of items(matching_rows)) { if (equal(text(field(matching_event, "integration_metadata_field_1")), external_event_key)) { let candidate_event_id = positive_id(text(field(matching_event, "id"))); if (is_present(matched_event_id)) { require_condition(equal(matched_event_id, candidate_event_id), "Multiple Events have this exact external key; resolve the ambiguity before linking."); } matched_event_id = candidate_event_id; } } if (equal(field(matching_page, "has_more"), false)) { break; } require_condition(not_value(is_empty(matching_rows)), "An empty page has has_more=true; stop and reconcile the search."); matching_offset = add_offset(matching_offset, count(matching_rows)); } require_condition(is_present(matched_event_id), "No exact match was found. Decide explicitly whether to create or link a record."); } let confirmation_query = {"id": matched_event_id}; let confirmed_response = await call("confirm_match", confirmation_query, null, null); let confirmed_event = confirmed_response.body; require_condition(equal(text(field(confirmed_event, "id")), matched_event_id), "The confirmed Event ID differs from the selected Event."); require_condition(equal(text(field(confirmed_event, "integration_metadata_field_1")), external_event_key), "The Event's current metadata differs from the intended external key. Stop for review."); print_value({"external_event_key": external_event_key, "event_id": matched_event_id}); } if (require.main === module) main().catch(error => { console.error(error.message); process.exitCode = 1; }); module.exports = { main }; ``` ```python # 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\":{\"find_match\":{\"method\":\"GET\",\"path\":\"/events\"},\"confirm_match\":{\"method\":\"GET\",\"path\":\"/events/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) 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, key=None): route = SPEC["requests"][name] headers = {"Authorization": "Bearer " + API_KEY, "Accept": "application/json"} if route["method"] == "POST": if not key: raise RuntimeError("Persist a logical create key before sending POST") headers["Idempotency-Key"] = key data = None if body is None else json.dumps(body).encode("utf-8") if data is not None: headers["Content-Type"] = "application/json" query = urllib.parse.urlencode(params or {}) url = BASE + route["path"] + ("?" + query if query else "") # Only GET has automatic retries in this workflow. A PATCH or DELETE that got no response or a # server error is never resent blindly: it may already have been applied, so the caller reads the record first. resend = route["method"] == "GET" for attempt in range(5): try: status, raw, response_headers = transport(route["method"], url, headers, data) except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException): if not resend: raise ApiError(0, None, uncertain=True) if attempt == 4: raise time.sleep(2 ** attempt) continue response_headers = {k.lower(): v for k, v in response_headers.items()} result = None if status != 304 and raw: try: result = decode_json(raw.decode("utf-8")) except (ValueError, UnicodeError): if status < 400: raise RuntimeError("Expected a JSON success response") if status >= 500 and not resend: raise ApiError(status, result, uncertain=True) retry = resend and (status == 429 or status >= 500) if retry: if attempt == 4: raise RuntimeError("Retry limit reached; check the request outcome before starting a new create") delay = response_headers.get("retry-after", str(2 ** attempt)) time.sleep(max(0, float(delay))) continue if status >= 400: raise ApiError(status, result) return {"status": status, "body": result, "headers": response_headers, "raw": raw} raise RuntimeError("Retry limit reached") def 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 items(value): if not isinstance(value, list): raise RuntimeError("Expected a JSON array") return value def count(value): return len(items(value)) 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] def is_empty(value): return count(value) == 0 def is_present(value): return value is not None and value != "" def not_value(value): if not isinstance(value, bool): raise RuntimeError("Expected a Boolean") return not value def optional(name, fallback): value = os.environ.get(name) return fallback if value is None or value == "" else value def page_size(value): if not re.fullmatch(r"[1-9][0-9]*", value) or int(value) > 2147483647: raise RuntimeError("Page size must be a positive int32") return value def positive_id(value): if not re.fullmatch(r"[1-9][0-9]*", value) or int(value) > 9223372036854775807: raise RuntimeError("Use a positive record ID") return value def print_value(value): print(value if isinstance(value, str) else json.dumps(value, ensure_ascii=False)) def require_condition(value, message): if value is not True: raise RuntimeError(message) def required(name): value = os.environ.get(name) if value is None or not value.strip(): raise RuntimeError("Set " + name) return value def 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(): external_event_key = required("EXHIBITDAY_EXTERNAL_EVENT_KEY") matched_event_id = optional("EXHIBITDAY_EVENT_ID", "") if is_present(matched_event_id): matched_event_id = positive_id(matched_event_id) else: matching_page_size = page_size(optional("EXHIBITDAY_PAGE_SIZE", "100")) matching_offset = "0" matching_query = {"filter_by_integration_metadata_field_1": external_event_key, "$limit": matching_page_size} while True: matching_query["$offset"] = matching_offset matching_response = call("find_match", matching_query, None, None) matching_page = matching_response["body"] matching_rows = items(field(matching_page, "list_data")) require_condition(equal(text(field(matching_page, "records_found")), text(count(matching_rows))), "records_found does not match this page's rows.") require_condition(is_present(text(field(matching_page, "total_records"))), "The collection wrapper needs total_records.") require_condition(either(equal(field(matching_page, "has_more"), True), equal(field(matching_page, "has_more"), False)), "Expected a Boolean has_more value.") for matching_event in items(matching_rows): if equal(text(field(matching_event, "integration_metadata_field_1")), external_event_key): candidate_event_id = positive_id(text(field(matching_event, "id"))) if is_present(matched_event_id): require_condition(equal(matched_event_id, candidate_event_id), "Multiple Events have this exact external key; resolve the ambiguity before linking.") matched_event_id = candidate_event_id if equal(field(matching_page, "has_more"), False): break require_condition(not_value(is_empty(matching_rows)), "An empty page has has_more=true; stop and reconcile the search.") matching_offset = add_offset(matching_offset, count(matching_rows)) require_condition(is_present(matched_event_id), "No exact match was found. Decide explicitly whether to create or link a record.") confirmation_query = {"id": matched_event_id} confirmed_response = call("confirm_match", confirmation_query, None, None) confirmed_event = confirmed_response["body"] require_condition(equal(text(field(confirmed_event, "id")), matched_event_id), "The confirmed Event ID differs from the selected Event.") require_condition(equal(text(field(confirmed_event, "integration_metadata_field_1")), external_event_key), "The Event's current metadata differs from the intended external key. Stop for review.") print_value({"external_event_key": external_event_key, "event_id": matched_event_id}) if __name__ == "__main__": main() ``` ```csharp // .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\":true,\"requests\":{\"find_match\":{\"method\":\"GET\",\"path\":\"/events\"},\"confirm_match\":{\"method\":\"GET\",\"path\":\"/events/info\"}}}"); static readonly string ApiKey = HeaderKey(Required("EXHIBITDAY_API_KEY")); static string HeaderKey(string value) { if(value.Any(c=>c<32||c>126))throw new Exception("Use the API key as one ASCII header value without control characters");return value; } static readonly HttpClient Client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false }) { Timeout = TimeSpan.FromSeconds(30) }; internal static Func> Send = request => Client.SendAsync(request); sealed class Result { public int Status; public JsonNode Body; public Dictionary Headers; public string Raw; } // 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(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 Call(string name, JsonObject query = null, JsonNode body = null, string key = null) { var route = Spec["requests"][name]; var method = Text(route["method"]); var headers = new Dictionary(StringComparer.OrdinalIgnoreCase) { ["Authorization"] = "Bearer " + ApiKey, ["Accept"] = "application/json" }; if (method == "POST") { if (string.IsNullOrEmpty(key)) throw new Exception("Persist a logical create key before sending POST"); headers["Idempotency-Key"] = key; } 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); // 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. var resend = method == "GET"; 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 Send(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 = resend && (status == 429 || status >= 500); 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, Raw = raw }; } } throw new Exception("Retry limit reached"); } static string AddOffset(string offset,long received) { var result=checked(long.Parse(offset,CultureInfo.InvariantCulture)+received);if(received<=0||result>int.MaxValue)throw new Exception("Cannot advance this int32 offset; reconcile the query");return result.ToString(CultureInfo.InvariantCulture); } static JsonArray Items(JsonNode value) => value as JsonArray ?? throw new Exception("Expected a JSON array"); static long Count(JsonNode value) => Items(value).Count; static bool Either(bool left,bool right) => left || right; static object Scalar(object value) { if(value is JsonValue json){if(json.TryGetValue(out var boolean))return boolean;if(json.TryGetValue(out var text))return text;return json.ToJsonString();}return value; } static bool Equal(object left,object right) => object.Equals(Scalar(left),Scalar(right)); static JsonNode Field(JsonNode value,string name) { if(value is not JsonObject obj || !obj.TryGetPropertyValue(name,out var item))throw new Exception("Missing response field: "+name);return item; } static bool IsEmpty(JsonNode value) => Count(value)==0; static bool IsPresent(string value) => value!=null && value!=""; static bool NotValue(bool value) => !value; static string Optional(string name,string fallback) { var value=Environment.GetEnvironmentVariable(name);return value==null||value==""?fallback:value; } static string PageSize(string value) { if(string.IsNullOrEmpty(value)||value[0]=='0'||!value.All(c=>c>='0'&&c<='9')||!int.TryParse(value,NumberStyles.None,CultureInfo.InvariantCulture,out var limit)||limit<=0)throw new Exception("Page size must be a positive int32");return value; } static string PositiveId(string value) { if(string.IsNullOrEmpty(value)||value[0]=='0'||!value.All(c=>c>='0'&&c<='9')||!long.TryParse(value,NumberStyles.None,CultureInfo.InvariantCulture,out var id)||id<=0)throw new Exception("Use a positive record ID");return value; } static void PrintValue(object value) => Console.WriteLine(value is string text ? text : JsonSerializer.Serialize(value)); static void RequireCondition(bool value,string message) { if(!value)throw new Exception(message); } static string Text(object value) => value==null?"":value is JsonNode node?Text(node):Convert.ToString(value,CultureInfo.InvariantCulture); internal static async Task Run() { var external_event_key = Required("EXHIBITDAY_EXTERNAL_EVENT_KEY"); var matched_event_id = Optional("EXHIBITDAY_EVENT_ID", ""); if (IsPresent(matched_event_id)) { matched_event_id = PositiveId(matched_event_id); } else { var matching_page_size = PageSize(Optional("EXHIBITDAY_PAGE_SIZE", "100")); var matching_offset = "0"; var matching_query = new JsonObject { ["filter_by_integration_metadata_field_1"] = external_event_key, ["$limit"] = matching_page_size }; while (true) { matching_query["$offset"] = matching_offset; var matching_response = await Call("find_match", matching_query, null, null); var matching_page = matching_response.Body; var matching_rows = Items(Field(matching_page, "list_data")); RequireCondition(Equal(Text(Field(matching_page, "records_found")), Text(Count(matching_rows))), "records_found does not match this page's rows."); RequireCondition(IsPresent(Text(Field(matching_page, "total_records"))), "The collection wrapper needs total_records."); RequireCondition(Either(Equal(Field(matching_page, "has_more"), true), Equal(Field(matching_page, "has_more"), false)), "Expected a Boolean has_more value."); foreach (var matching_event in Items(matching_rows)) { if (Equal(Text(Field(matching_event, "integration_metadata_field_1")), external_event_key)) { var candidate_event_id = PositiveId(Text(Field(matching_event, "id"))); if (IsPresent(matched_event_id)) { RequireCondition(Equal(matched_event_id, candidate_event_id), "Multiple Events have this exact external key; resolve the ambiguity before linking."); } matched_event_id = candidate_event_id; } } if (Equal(Field(matching_page, "has_more"), false)) { break; } RequireCondition(NotValue(IsEmpty(matching_rows)), "An empty page has has_more=true; stop and reconcile the search."); matching_offset = AddOffset(matching_offset, Count(matching_rows)); } RequireCondition(IsPresent(matched_event_id), "No exact match was found. Decide explicitly whether to create or link a record."); } var confirmation_query = new JsonObject { ["id"] = matched_event_id }; var confirmed_response = await Call("confirm_match", confirmation_query, null, null); var confirmed_event = confirmed_response.Body; RequireCondition(Equal(Text(Field(confirmed_event, "id")), matched_event_id), "The confirmed Event ID differs from the selected Event."); RequireCondition(Equal(Text(Field(confirmed_event, "integration_metadata_field_1")), external_event_key), "The Event's current metadata differs from the intended external key. Stop for review."); PrintValue(new JsonObject { ["external_event_key"] = external_event_key, ["event_id"] = matched_event_id }); } static Task Main() => Run(); } ``` ```java // 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 SPEC = JSON.fromJson("{\"preserveNumbers\":true,\"requests\":{\"find_match\":{\"method\":\"GET\",\"path\":\"/events\"},\"confirm_match\":{\"method\":\"GET\",\"path\":\"/events/info\"}}}", Map.class); static final String API_KEY = headerKey(required("EXHIBITDAY_API_KEY")); static String headerKey(String value){if(value.chars().anyMatch(c->c<32||c>126))throw new IllegalArgumentException("Use the API key as one ASCII header value without control characters");return value;} static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).followRedirects(HttpClient.Redirect.NEVER).build(); interface RequestSender { HttpResponse send(HttpRequest request)throws IOException,InterruptedException; } static RequestSender SEND=request->CLIENT.send(request,HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); static class Result { int status; Object body; Map headers; String raw; Result(int s, Object b, Map h,String r) {status=s;body=b;headers=h;raw=r;} } // 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 obj(Object value) {return value==null?new LinkedHashMap<>(): (Map)value;} @SuppressWarnings("unchecked") static List list(Object value) {return value==null?Collections.emptyList():(List)value;} static Map map(Object... pairs) {Map result=new LinkedHashMap<>();for(int i=0;i query,Object body,String key) { Map route=obj(obj(SPEC.get("requests")).get(name));String method=text(route.get("method")); Map headers=map("Authorization","Bearer " + API_KEY,"Accept","application/json"); if(method.equals("POST")){if(key==null||key.isEmpty())throw new IllegalArgumentException("Persist a logical create key before sending POST");headers.put("Idempotency-Key",key);} 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); // 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. boolean resend=method.equals("GET"); 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 response; try {response=SEND.send(request.build());} 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();Object parsed=null; if(status!=304&&!response.body().isEmpty()) { try {parsed=JSON.fromJson(response.body(),Object.class);} catch(RuntimeException error){if(status<400)throw new IllegalStateException("Expected a JSON success response",error);} } Map 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=resend&&(status==429||status>=500); 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,response.body()); } throw new IllegalStateException("Retry limit reached"); } static String add_offset(String offset,long received){long result=Math.addExact(Long.parseLong(offset),received);if(received<=0||result>Integer.MAX_VALUE)throw new IllegalStateException("Cannot advance this int32 offset; reconcile the query");return Long.toString(result);} static List items(Object value){if(!(value instanceof List))throw new IllegalStateException("Expected a JSON array");return list(value);} static long count(Object value){return items(value).size();} static boolean either(boolean left,boolean right){return left||right;} static boolean equal(Object left,Object right){return Objects.equals(left,right);} static Object field(Object value,String name){if(!(value instanceof Map)||!obj(value).containsKey(name))throw new IllegalStateException("Missing response field: "+name);return obj(value).get(name);} static boolean is_empty(Object value){return count(value)==0;} static boolean is_present(String value){return value!=null&&!value.isEmpty();} static boolean not_value(boolean value){return !value;} static String optional(String name,String fallback){String value=System.getenv(name);return value==null||value.isEmpty()?fallback:value;} static String page_size(String value){try{if(value==null||!value.matches("[1-9][0-9]*")||Integer.parseInt(value)<=0)throw new IllegalArgumentException();return value;}catch(RuntimeException error){throw new IllegalArgumentException("Page size must be a positive int32");}} static String positive_id(String value){try{if(value==null||!value.matches("[1-9][0-9]*")||Long.parseLong(value)<=0)throw new IllegalArgumentException();return value;}catch(RuntimeException error){throw new IllegalArgumentException("Use a positive record ID");}} static void print_value(Object value){try{String text=value instanceof String?(String)value:JSON.toJson(value);System.out.write((text+"\n").getBytes(StandardCharsets.UTF_8));}catch(IOException error){throw new UncheckedIOException(error);}} static void require_condition(boolean value,String message){if(!value)throw new IllegalStateException(message);} static void run()throws Exception { String external_event_key = required("EXHIBITDAY_EXTERNAL_EVENT_KEY"); String matched_event_id = optional("EXHIBITDAY_EVENT_ID", ""); if (is_present(matched_event_id)) { matched_event_id = positive_id(matched_event_id); } else { String matching_page_size = page_size(optional("EXHIBITDAY_PAGE_SIZE", "100")); String matching_offset = "0"; Map matching_query = map("filter_by_integration_metadata_field_1", external_event_key, "$limit", matching_page_size); while (true) { matching_query.put("$offset", matching_offset); Result matching_response = call("find_match", matching_query, null, null); Object matching_page = matching_response.body; List matching_rows = items(field(matching_page, "list_data")); require_condition(equal(text(field(matching_page, "records_found")), text(count(matching_rows))), "records_found does not match this page's rows."); require_condition(is_present(text(field(matching_page, "total_records"))), "The collection wrapper needs total_records."); require_condition(either(equal(field(matching_page, "has_more"), true), equal(field(matching_page, "has_more"), false)), "Expected a Boolean has_more value."); for (Object matching_event : items(matching_rows)) { if (equal(text(field(matching_event, "integration_metadata_field_1")), external_event_key)) { String candidate_event_id = positive_id(text(field(matching_event, "id"))); if (is_present(matched_event_id)) { require_condition(equal(matched_event_id, candidate_event_id), "Multiple Events have this exact external key; resolve the ambiguity before linking."); } matched_event_id = candidate_event_id; } } if (equal(field(matching_page, "has_more"), false)) { break; } require_condition(not_value(is_empty(matching_rows)), "An empty page has has_more=true; stop and reconcile the search."); matching_offset = add_offset(matching_offset, count(matching_rows)); } require_condition(is_present(matched_event_id), "No exact match was found. Decide explicitly whether to create or link a record."); } Map confirmation_query = map("id", matched_event_id); Result confirmed_response = call("confirm_match", confirmation_query, null, null); Object confirmed_event = confirmed_response.body; require_condition(equal(text(field(confirmed_event, "id")), matched_event_id), "The confirmed Event ID differs from the selected Event."); require_condition(equal(text(field(confirmed_event, "integration_metadata_field_1")), external_event_key), "The Event's current metadata differs from the intended external key. Stop for review."); print_value(map("external_event_key", external_event_key, "event_id", matched_event_id)); } public static void main(String[] args)throws Exception {run();} } ``` ```php $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, ?string $key = null): array { global $spec, $apiKey, $transport; $route = $spec['requests'][$name]; $headers = ['Authorization' => 'Bearer ' . $apiKey, 'Accept' => 'application/json']; if ($route['method'] === 'POST') { if ($key === null || $key === '') throw new RuntimeException('Persist a logical create key before sending POST'); $headers['Idempotency-Key'] = $key; // 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); // 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 = 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 = $resend && ($status === 429 || $status >= 500); 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, 'raw' => $raw]; } throw new RuntimeException('Retry limit reached'); } $transport = Closure::fromCallable('nativeTransport'); function add_offset(string $offset,int $received):string{$result=(int)$offset+$received;if($received<=0||$result>2147483647)throw new RuntimeException("Cannot advance this int32 offset; reconcile the query");return (string)$result;} function either(bool $left,bool $right):bool{return $left||$right;} function equal(mixed $left,mixed $right):bool{return $left===$right;} function field(mixed $value,string $name):mixed{if(!is_array($value)||!array_key_exists($name,$value))throw new RuntimeException("Missing response field: ".$name);return $value[$name];} function items(mixed $value):array{if(!is_array($value)||!array_is_list($value))throw new RuntimeException("Expected a JSON array");return $value;} function is_empty(mixed $value):bool{return count(items($value))===0;} function is_present(?string $value):bool{return $value!==null&&$value!=="";} function not_value(bool $value):bool{return !$value;} function page_size(string $value):string{if(!preg_match("/^[1-9][0-9]*$/D",$value)||strlen($value)>10||(strlen($value)===10&&strcmp($value,"2147483647")>0))throw new RuntimeException("Page size must be a positive int32");return $value;} function positive_id(string $value):string{if(!preg_match("/^[1-9][0-9]*$/D",$value)||strlen($value)>19||(strlen($value)===19&&strcmp($value,"9223372036854775807")>0))throw new RuntimeException("Use a positive record ID");return $value;} function print_value(mixed $value):void{echo (is_string($value)?$value:json_encode($value,JSON_THROW_ON_ERROR))."\n";} function require_condition(bool $value,string $message):void{if(!$value)throw new RuntimeException($message);} function text(mixed $value):string{if($value===null)return "";if(is_string($value))return $value;if(is_bool($value))return $value?"true":"false";if(is_int($value))return (string)$value;throw new RuntimeException("Expected a scalar response value");} function main():void { $external_event_key = required('EXHIBITDAY_EXTERNAL_EVENT_KEY'); $matched_event_id = optional('EXHIBITDAY_EVENT_ID', ''); if (is_present($matched_event_id)) { $matched_event_id = positive_id($matched_event_id); } else { $matching_page_size = page_size(optional('EXHIBITDAY_PAGE_SIZE', '100')); $matching_offset = '0'; $matching_query = ['filter_by_integration_metadata_field_1' => $external_event_key, '$limit' => $matching_page_size]; while (true) { $matching_query['$offset'] = $matching_offset; $matching_response = call('find_match', $matching_query, null, null); $matching_page = $matching_response["body"]; $matching_rows = items(field($matching_page, 'list_data')); require_condition(equal(text(field($matching_page, 'records_found')), text(count($matching_rows))), 'records_found does not match this page\'s rows.'); require_condition(is_present(text(field($matching_page, 'total_records'))), 'The collection wrapper needs total_records.'); require_condition(either(equal(field($matching_page, 'has_more'), true), equal(field($matching_page, 'has_more'), false)), 'Expected a Boolean has_more value.'); foreach (items($matching_rows) as $matching_event) { if (equal(text(field($matching_event, 'integration_metadata_field_1')), $external_event_key)) { $candidate_event_id = positive_id(text(field($matching_event, 'id'))); if (is_present($matched_event_id)) { require_condition(equal($matched_event_id, $candidate_event_id), 'Multiple Events have this exact external key; resolve the ambiguity before linking.'); } $matched_event_id = $candidate_event_id; } } if (equal(field($matching_page, 'has_more'), false)) { break; } require_condition(not_value(is_empty($matching_rows)), 'An empty page has has_more=true; stop and reconcile the search.'); $matching_offset = add_offset($matching_offset, count($matching_rows)); } require_condition(is_present($matched_event_id), 'No exact match was found. Decide explicitly whether to create or link a record.'); } $confirmation_query = ['id' => $matched_event_id]; $confirmed_response = call('confirm_match', $confirmation_query, null, null); $confirmed_event = $confirmed_response["body"]; require_condition(equal(text(field($confirmed_event, 'id')), $matched_event_id), 'The confirmed Event ID differs from the selected Event.'); require_condition(equal(text(field($confirmed_event, 'integration_metadata_field_1')), $external_event_key), 'The Event\'s current metadata differs from the intended external key. Stop for review.'); print_value((object)['external_event_key' => $external_event_key, 'event_id' => $matched_event_id]); } if (realpath($_SERVER['SCRIPT_FILENAME'] ?? '') === __FILE__) main(); ``` ```ruby # 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":true,"requests":{"find_match":{"method":"GET","path":"/events"},"confirm_match":{"method":"GET","path":"/events/info"}}}') API_KEY = ENV.fetch('EXHIBITDAY_API_KEY') raise 'Use the API key as one ASCII header value without control characters' if API_KEY.each_codepoint.any?{|point|point<32||point>126} 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, 'DELETE' => Net::HTTP::Delete }.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, key = nil) route = SPEC.fetch('requests').fetch(name) headers = { 'Authorization' => 'Bearer ' + API_KEY, 'Accept' => 'application/json' } if route.fetch('method') == 'POST' headers['Idempotency-Key'] = key || raise('Persist a logical create key before sending POST') # 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) # 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.fetch('method') == 'GET' 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 = resend && (status == 429 || (500..599).cover?(status)) 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, raw: raw } end raise 'Retry limit reached' end def add_offset(offset,received) result=Integer(offset)+received raise "Cannot advance this int32 offset; reconcile the query" if received<=0 || result>2147483647 result.to_s end def items(value) raise "Expected a JSON array" unless value.is_a?(Array) value end def count(value) items(value).length end def either(left,right) raise "Expected Boolean criteria" unless [true,false].include?(left) && [true,false].include?(right) left || right end def equal(left,right) left.class==right.class && left==right end def field(value,name) raise "Missing response field: #{name}" unless value.is_a?(Hash) && value.key?(name) value.fetch(name) end def is_empty(value) count(value)==0 end def is_present(value) !value.nil? && value!="" end def not_value(value) raise "Expected a Boolean" unless value==true || value==false !value end def optional(name,fallback) value=ENV[name] value.nil? || value.empty? ? fallback : value end def page_size(value) raise "Page size must be a positive int32" unless /\A[1-9][0-9]*\z/.match?(value) && Integer(value)<=2147483647 value end def positive_id(value) raise "Use a positive record ID" unless /\A[1-9][0-9]*\z/.match?(value) && Integer(value)<=9223372036854775807 value end def print_value(value) STDOUT.binmode.write((value.is_a?(String)?value:JSON.generate(value))+"\n") end def require_condition(value,message) raise message unless value==true end def required(name) value=ENV[name] raise "Set #{name}" if value.nil? || value.strip.empty? value end def text(value) return "" if value.nil? return value.to_s if value.is_a?(String)||value.is_a?(Integer)||value==true||value==false raise "Expected a scalar response value" end def main external_event_key = required('EXHIBITDAY_EXTERNAL_EVENT_KEY') matched_event_id = optional('EXHIBITDAY_EVENT_ID', '') if is_present(matched_event_id) matched_event_id = positive_id(matched_event_id) else matching_page_size = page_size(optional('EXHIBITDAY_PAGE_SIZE', '100')) matching_offset = '0' matching_query = {'filter_by_integration_metadata_field_1' => external_event_key, '$limit' => matching_page_size} while true matching_query['$offset'] = matching_offset matching_response = call('find_match', matching_query, nil, nil) matching_page = matching_response.fetch(:body) matching_rows = items(field(matching_page, 'list_data')) require_condition(equal(text(field(matching_page, 'records_found')), text(count(matching_rows))), 'records_found does not match this page\'s rows.') require_condition(is_present(text(field(matching_page, 'total_records'))), 'The collection wrapper needs total_records.') require_condition(either(equal(field(matching_page, 'has_more'), true), equal(field(matching_page, 'has_more'), false)), 'Expected a Boolean has_more value.') items(matching_rows).each do |matching_event| if equal(text(field(matching_event, 'integration_metadata_field_1')), external_event_key) candidate_event_id = positive_id(text(field(matching_event, 'id'))) if is_present(matched_event_id) require_condition(equal(matched_event_id, candidate_event_id), 'Multiple Events have this exact external key; resolve the ambiguity before linking.') end matched_event_id = candidate_event_id end end if equal(field(matching_page, 'has_more'), false) break end require_condition(not_value(is_empty(matching_rows)), 'An empty page has has_more=true; stop and reconcile the search.') matching_offset = add_offset(matching_offset, count(matching_rows)) end require_condition(is_present(matched_event_id), 'No exact match was found. Decide explicitly whether to create or link a record.') end confirmation_query = {'id' => matched_event_id} confirmed_response = call('confirm_match', confirmation_query, nil, nil) confirmed_event = confirmed_response.fetch(:body) require_condition(equal(text(field(confirmed_event, 'id')), matched_event_id), 'The confirmed Event ID differs from the selected Event.') require_condition(equal(text(field(confirmed_event, 'integration_metadata_field_1')), external_event_key), 'The Event\'s current metadata differs from the intended external key. Stop for review.') print_value({'external_event_key' => external_event_key, 'event_id' => matched_event_id}) end main if $PROGRAM_NAME == __FILE__ ``` ```go // Go 1.18+; standard library only. Set EXHIBITDAY_API_KEY. package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "net/url" "os" "strconv" "strings" "time" ) const base = "https://api.exhibitday.com/v1" const specification = "{\"preserveNumbers\":true,\"requests\":{\"find_match\":{\"method\":\"GET\",\"path\":\"/events\"},\"confirm_match\":{\"method\":\"GET\",\"path\":\"/events/info\"}}}" 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 }} var send = client.Do type result struct { status int; body any; headers http.Header; raw []byte } // 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 call(name string, query map[string]string, body any, key string) result { route := object(object(spec["requests"])[name]); method := text(route["method"]) headers := map[string]string{"Authorization": "Bearer " + apiKey, "Accept": "application/json"} if method == "POST" { if key == "" { panic("Persist a logical create key before sending POST") }; 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() } // 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 := method == "GET" 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 := send(request) if err != nil { if !resend { panic(apiError{0, "", "No response", true}) }; if attempt == 4 { panic(err) }; time.Sleep(time.Second*time.Duration(1<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 := resend && (response.StatusCode == 429 || response.StatusCode >= 500) if retry { if attempt == 4 { panic("Retry limit reached; check the outcome before starting a new create") } seconds := float64(int64(1)<= 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, raw} } panic("Retry limit reached") } func add_offset(offset string,received int64)string{previous,err:=strconv.ParseInt(offset,10,32);if err!=nil||received<=0||received>2147483647-previous{panic("Cannot advance this int32 offset; reconcile the query")};return strconv.FormatInt(previous+received,10)} func items(value any)[]any{result,ok:=value.([]any);if !ok{panic("Expected a JSON array")};return result} func count(value any)int64{return int64(len(items(value)))} func either(left,right bool)bool{return left||right} func equal(left,right any)bool{switch a:=left.(type){case string:b,ok:=right.(string);return ok&&a==b;case bool:b,ok:=right.(bool);return ok&&a==b;case int64:b,ok:=right.(int64);return ok&&a==b};return left==nil&&right==nil} func field(value any,name string)any{obj,ok:=value.(map[string]any);if !ok{panic("Missing response object")};item,found:=obj[name];if !found{panic("Missing response field: "+name)};return item} func is_empty(value any)bool{return count(value)==0} func is_present(value string)bool{return value!=""} func not_value(value bool)bool{return !value} func optional(name,fallback string)string{value:=os.Getenv(name);if value==""{return fallback};return value} func page_size(value string)string{valid:=len(value)>0&&value[0]!='0';for _,ch:=range value{valid=valid&&ch>='0'&&ch<='9'};size,err:=strconv.ParseInt(value,10,32);if !valid||err!=nil||size<=0{panic("Page size must be a positive int32")};return value} func positive_id(value string)string{valid:=len(value)>0&&value[0]!='0';for _,ch:=range value{valid=valid&&ch>='0'&&ch<='9'};id,err:=strconv.ParseInt(value,10,64);if !valid||err!=nil||id<=0{panic("Use a positive record ID")};return value} func print_value(value any){if result,ok:=value.(string);ok{fmt.Println(result);return};raw,err:=json.Marshal(value);if err!=nil{panic(err)};fmt.Println(string(raw))} func require_condition(value bool,message string){if !value{panic(message)}} func workflow() { external_event_key := required("EXHIBITDAY_EXTERNAL_EVENT_KEY") matched_event_id := optional("EXHIBITDAY_EVENT_ID", "") if is_present(matched_event_id) { matched_event_id = positive_id(matched_event_id) } else { matching_page_size := page_size(optional("EXHIBITDAY_PAGE_SIZE", "100")) matching_offset := "0" matching_query := map[string]string{"filter_by_integration_metadata_field_1": external_event_key, "$limit": matching_page_size} for true { matching_query["$offset"] = matching_offset matching_response := call("find_match", matching_query, nil, "") matching_page := matching_response.body matching_rows := items(field(matching_page, "list_data")) require_condition(equal(text(field(matching_page, "records_found")), text(count(matching_rows))), "records_found does not match this page's rows.") require_condition(is_present(text(field(matching_page, "total_records"))), "The collection wrapper needs total_records.") require_condition(either(equal(field(matching_page, "has_more"), true), equal(field(matching_page, "has_more"), false)), "Expected a Boolean has_more value.") for _, matching_event := range items(matching_rows) { if equal(text(field(matching_event, "integration_metadata_field_1")), external_event_key) { candidate_event_id := positive_id(text(field(matching_event, "id"))) if is_present(matched_event_id) { require_condition(equal(matched_event_id, candidate_event_id), "Multiple Events have this exact external key; resolve the ambiguity before linking.") } matched_event_id = candidate_event_id } } if equal(field(matching_page, "has_more"), false) { break } require_condition(not_value(is_empty(matching_rows)), "An empty page has has_more=true; stop and reconcile the search.") matching_offset = add_offset(matching_offset, count(matching_rows)) } require_condition(is_present(matched_event_id), "No exact match was found. Decide explicitly whether to create or link a record.") } confirmation_query := map[string]string{"id": matched_event_id} confirmed_response := call("confirm_match", confirmation_query, nil, "") confirmed_event := confirmed_response.body require_condition(equal(text(field(confirmed_event, "id")), matched_event_id), "The confirmed Event ID differs from the selected Event.") require_condition(equal(text(field(confirmed_event, "integration_metadata_field_1")), external_event_key), "The Event's current metadata differs from the intended external key. Stop for review.") print_value(map[string]any{"external_event_key": external_event_key, "event_id": matched_event_id}) } func header_key(value string)string{for _,ch:=range value{if ch<32||ch>126{panic("Use the API key as one ASCII header value without control characters")}};return value} func main(){apiKey=header_key(required("EXHIBITDAY_API_KEY"));if err:=json.Unmarshal([]byte(specification),&spec);err!=nil{panic(err)};workflow()} ``` #### Example response Response 200 — OK 304 — Not Modified 400 — Bad Request 401 — Unauthorized 404 — Not Found 409 — Conflict 429 — Too Many Requests 500 — Internal Server Error Example Successful request ```json { "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", "star_rating": 0, "tags": [ "International", "Field Marketing" ], "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, "booth_reservation_cost": { "amount": 125.50, "cost_center_breakdown": [ { "cost_center_id": 34567, "cost_center": "Marketing", "charge": 75.50 }, { "cost_center_id": 34568, "cost_center": "Operations", "charge": 50.00 } ] }, "cost_booth_reservation": 125.50, "booth_reservation_payment_status_id": 0, "booth_reservation_payment_status": "", "booth_reservation_payment_due_date": null, "booth_reservation_next_payment_due_date": null, "booth_reservation_payment_notes": null, "booth_reservation_invoice_attachment": { "id": 182345, "filename": "booth-reservation-invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" }, "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": 100.50, "cost_sponsorships": 0.00, "total_sum_event_costs": 226.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, "roo_score": null, "event_created_timestamp": "2029-12-01T17:00:00Z", "event_last_update_timestamp": "2030-01-02T17:00:00Z", "event_created_by": null, "custom_fields": [ { "label": "Integration status", "value": "Ready", "notes": "", "field_name": "custom_67890", "field_type": "Text (Single-line)", "field_event_tab": "Info" }, { "label": "Setup instructions", "value": "Place the display beside the entrance.", "notes": "", "field_name": "custom_67891", "field_type": "Text (Single-line)", "field_event_tab": "Booth" } ], "task_sections": [ { "id": 13346, "name": "Planning", "display_rank": 1 }, { "id": 13347, "name": "At the Event", "display_rank": 2 } ], "tasks": [ { "id": 14346, "exhibitday_url": "https://www.exhibitday.com/Workspace/TaskView/98765?tid=14346", "event_task_section_id": 13346, "event_task_section": "Planning", "display_rank": 1, "name": "Confirm booth setup", "due_date": "2026-12-12", "assignee": { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, "is_completed": false, "task_completed_timestamp": null, "task_created_timestamp": "2029-12-01T17:01:00Z", "task_last_update_timestamp": "2029-12-01T17:01:00Z" }, { "id": 14347, "exhibitday_url": "https://www.exhibitday.com/Workspace/TaskView/98765?tid=14347", "event_task_section_id": 13347, "event_task_section": "At the Event", "display_rank": 2, "name": "Prepare the staff schedule", "due_date": "2026-12-13", "assignee": { "id": "66666666-7777-4888-8999-aaaaaaaaaaaa", "first_name": "Alex", "last_name": "Jordan", "display_name": "Alex Jordan", "email": "alex@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, "is_completed": false, "task_completed_timestamp": null, "task_created_timestamp": "2029-12-01T17:02:00Z", "task_last_update_timestamp": "2029-12-01T17:02:00Z" } ], "misc_expenses_credits": [ { "id": 15346, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=12345&riType=8&riSub=0&riId=15346", "description": "Conference meals", "is_credit": false, "cost": { "amount": 125.50, "cost_center_breakdown": [ { "cost_center_id": 34567, "cost_center": "Marketing", "charge": 75.50 }, { "cost_center_id": 34568, "cost_center": "Operations", "charge": 50.00 } ] }, "notes": "", "payment_due_date": null, "payment_status": { "id": 0, "name": "Not Specified" }, "next_payment_due_date": null, "next_partial_payment_due_date": null, "payment_notes": null, "invoice_attachment": { "id": 685346, "filename": "expense-invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" }, "event_misc_expense_credit_created_timestamp": "2029-12-01T17:00:00Z", "event_misc_expense_credit_last_update_timestamp": "2029-12-01T17:00:00Z" }, { "id": 15347, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=12345&riType=8&riSub=0&riId=15347", "description": "Supplier refund", "is_credit": true, "cost": { "amount": -25.00, "cost_center_breakdown": [ { "cost_center_id": 34567, "cost_center": "Marketing", "charge": -15.00 }, { "cost_center_id": 34568, "cost_center": "Operations", "charge": -10.00 } ] }, "notes": "", "payment_due_date": null, "payment_status": { "id": 0, "name": "Not Specified" }, "next_payment_due_date": null, "next_partial_payment_due_date": null, "payment_notes": null, "invoice_attachment": { "id": 685347, "filename": "expense-invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" }, "event_misc_expense_credit_created_timestamp": "2029-12-01T17:00:00Z", "event_misc_expense_credit_last_update_timestamp": "2029-12-01T17:00:00Z" } ], "integration_metadata_field_1": "crm:event:spring-expo-2030", "integration_metadata_field_2": null, "integration_metadata_field_3": null, "integration_metadata_field_4": null, "integration_metadata_field_5": null } ``` Note: Confirmed Event match. An illustrative Event whose stored integration key exactly matches the external key. The mapping is printed only after this confirmation. Note: There is no response body. Keep using your cached response. ```json { "status_code": 400, "status": "Bad Request", "message": "HTTP method override is not supported.", "error_code": "invalid_request", "errors": [ "Send the documented HTTP method directly. X-HTTP-Method-Override cannot change a request's HTTP method." ], "error_params": [ "X-HTTP-Method-Override" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "No API key was provided. Send your key in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "missing_api_key", "errors": [ "Copy the key from Workspace Settings > API & Integrations > API Access in ExhibitDay." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "The API key is not valid. Check that you copied the whole key from Workspace Settings > API & Integrations > API Access, then send it in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "invalid_api_key", "errors": [ "Check that you sent the whole key. If it was regenerated, use the current key from Workspace Settings > API & Integrations > API Access." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "Access to the ExhibitDay API is not enabled for your workspace. Please contact support@exhibitday.com to enable API Access. Once access is enabled, send your key in the Authorization header as 'Bearer YOUR_API_KEY'.", "error_code": "api_access_disabled", "errors": [ "Nothing was read or changed." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 404, "status": "Not Found", "message": "Event not found. Invalid Event ID: 12345.", "error_code": "not_found", "errors": [ "Event not found. Invalid Event ID: 12345." ], "error_params": [ "id" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "The invoice attachment or its owning record changed or has conflicting saved information. Retrieve the current record before retrying.", "error_code": "record_changed", "errors": [ "The invoice attachment or its owning record changed or has conflicting saved information. Retrieve the current record before retrying." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "The Booth Reservation payment information changed or has an unsupported saved status. Retrieve the current Event before retrying.", "error_code": "record_changed", "errors": [ "The Booth Reservation payment information changed or has an unsupported saved status. Retrieve the current Event before retrying." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "The Event objective score changed or could not be read consistently. Retrieve the Event before retrying.", "error_code": "record_changed", "errors": [ "The Event objective score changed or could not be read consistently. Retrieve the Event before retrying." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "The record was being changed while it was read, so no record_revision could be issued. Read it again.", "error_code": "record_changed", "errors": [ "The record was being changed while it was read, so no record_revision could be issued. Read it again." ], "error_params": [ "$include_record_revision" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 429, "status": "Too Many Requests", "message": "Error 429 - Too Many Requests", "error_code": "rate_limited", "errors": [ "Error 429 - Too Many Requests" ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "An unexpected error occurred. Please try again later." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` Note: Use the request_id from your own response when contacting support. ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "Check whether your change was saved before trying again." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` #### Things to keep in mind - A record missing from a list is not proof that it was deleted: lists leave out records on Event tabs that are hidden. Check the Event's tab settings before removing your copy. - Keep IDs as text or exact integers. The example prints `event_id` as text to preserve every digit. - Agree which integration uses each integration field before storing values there. - Check each match. More than one Event can have the same key. - The search trims surrounding spaces and may ignore letter case. The example compares the stored key exactly before printing a match. - If you use another example to create a record and lose the response, check whether the record exists before you try again. See [Handle Errors and Retry Failed Requests](https://api.exhibitday.com/Help/V1?guide=errors-and-retries). - Track deletions separately. A change-feed cursor does not list deleted records. #### Related guides - [Create or Update Events from Your CRM](https://api.exhibitday.com/Help/V1?guide=event-setup-crm) - [Keep Another System Updated with Event and Task Changes](https://api.exhibitday.com/Help/V1?guide=sync-changes) ### Set an Event's Exhibit Hall Dates and Hours Guide page: https://api.exhibitday.com/Help/V1?guide=dates-times-time-zones Set an Event's Exhibit Hall days, hours and time zone, then confirm them. Example use case The organizer confirms your Exhibit Hall hours and you want to replace the tentative schedule. What you'll end up with The complete saved Exhibit Hall group with each date, local time, time-zone label and description verified. Before you start Have a workspace API key and the ID of an existing Event whose Information tab you can edit. Good to know Booth Setup and Booth Dismantle have their own date groups. This example changes only the Exhibit Hall group. #### At a glance Time to try About 10 minutes Effect on your data Updates records Endpoints 3 The program replaces the Event's complete Exhibit Hall schedule with two example dates and writes a private local journal. - [`GET /v1/references/workspace_info`](https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-workspace_info) - [`GET /v1/events/dates`](https://api.exhibitday.com/Help/V1?epf=1#get-v1-events-dates) - [`PATCH /v1/events/dates`](https://api.exhibitday.com/Help/V1?epf=1#patch-v1-events-dates) #### How it works 1. The program reads the Exhibit Hall group and keeps its current revision. 2. It replaces that group with the two example dates and local times. A conflict stops the save. 3. It reads the same group again and checks the saved dates, times, time-zone labels and descriptions. #### Set the Exhibit Hall schedule The examples below replace and verify the complete Exhibit Hall group. #### Step 1: Confirm the workspace Check the workspace summary so you know where the key will make changes. ```bash curl -X GET "https://api.exhibitday.com/v1/references/workspace_info" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "id": 98765 } ``` **Check:** Confirm id belongs to the workspace you intended to use. #### Step 2: Read the Exhibit Hall Dates group Read date type 1 with its revision to identify the complete group you will replace. ```bash curl -X GET "https://api.exhibitday.com/v1/events/dates?event_id=5001&filter_by_date_type_id=1&%24include_record_revision=true" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_data": [ { "event_id": 5001, "date_type_id": 1, "date_type": "Exhibit Hall", "dates": [ { "date": "2030-01-15", "start_time": "09:00:00", "end_time": "15:00:00", "timezone": "America/New_York", "description": "Earlier exhibit schedule" } ], "record_revision": "COPY_DATES_REVISION_FROM_YOUR_READ" } ] } ``` **Check:** Confirm the Event ID, date type and single returned group. Keep that group's record_revision for the PATCH. #### Step 3: Replace the complete schedule Send every Exhibit Hall date and time you want to keep, with the revision from your read. ```bash curl -X PATCH "https://api.exhibitday.com/v1/events/dates" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" --data-binary "{\"event_id\":5001,\"date_type_id\":1,\"dates\":[{\"date\":\"2030-01-15\",\"start_time\":\"09:00\",\"end_time\":\"17:00\",\"timezone\":\"America/New_York\",\"description\":\"Exhibit hours\"},{\"date\":\"2030-01-16\",\"start_time\":\"09:00\",\"end_time\":\"16:00\",\"timezone\":\"America/New_York\",\"description\":\"Final exhibit day\"}],\"expected_revision\":\"COPY_DATES_REVISION_FROM_YOUR_READ\"}" ``` Example response ```json { "status_code": 200, "status": "OK", "message": "Event Dates updated.", "errors": [], "record_revision": "NEW_DATES_REVISION" } ``` **Check:** The response includes record_revision. Omitted rows are removed from this group. The other date groups are left as they are. #### Step 4: Verify the saved schedule Read the same date group again to confirm what was saved. ```bash curl -X GET "https://api.exhibitday.com/v1/events/dates?event_id=5001&filter_by_date_type_id=1" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_data": [ { "event_id": 5001, "date_type_id": 1, "date_type": "Exhibit Hall", "dates": [ { "date": "2030-01-15", "start_time": "09:00:00", "end_time": "17:00:00", "timezone": "America/New_York", "description": "Exhibit hours" }, { "date": "2030-01-16", "start_time": "09:00:00", "end_time": "16:00:00", "timezone": "America/New_York", "description": "Final exhibit day" } ] } ] } ``` **Check:** Compare all five fields for every row in the returned order. For example, a submitted time of 09:00 is returned as 09:00:00. **Careful.** Review the complete replacement before sending it. Use the revision from your own read. #### Try it #### Before running the example | Variable | What to put in it | Required? | | --- | --- | --- | | `EXHIBITDAY_API_KEY` | Your workspace API key. | Yes | | `EXHIBITDAY_EVENT_ID` | The ID of an existing Event you can edit. | Yes | | `EXHIBITDAY_JOB_ID` | A stable ID for this logical change. | Yes | | `EXHIBITDAY_JOURNAL` | A private local path for this job's journal. | Yes | | `EXHIBITDAY_JOB_MODE` | Use new for a new job or resume with its existing journal. The default is resume. | No | **Careful.** This example changes data in your workspace. Use a test Event. #### Bash ``` export EXHIBITDAY_API_KEY='YOUR_API_KEY' export EXHIBITDAY_EVENT_ID='5001' ``` #### PowerShell ``` $env:EXHIBITDAY_API_KEY = 'YOUR_API_KEY' $env:EXHIBITDAY_EVENT_ID = '5001' ``` Use your own test Event ID. Set a private journal path and job ID. Set `EXHIBITDAY_JOB_MODE=new` for a new job, then run the complete example in your language. #### Complete example program Code Samples ```bash #!/usr/bin/env bash # Requires Bash, curl and Python3. No API key is written into the program. python3 - <<'EXHIBITDAY_PY' # Python 3; standard library only. Set EXHIBITDAY_API_KEY before running. import http.client import json import os import re import time import urllib.error import urllib.parse import urllib.request BASE = "https://api.exhibitday.com/v1" SPEC = json.loads("{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"read_group\":{\"method\":\"GET\",\"path\":\"/events/dates\"},\"replace_group\":{\"method\":\"PATCH\",\"path\":\"/events/dates\"},\"verify_group\":{\"method\":\"GET\",\"path\":\"/events/dates\"}}}") API_KEY = os.environ["EXHIBITDAY_API_KEY"] if any(ord(char) < 32 or ord(char) > 126 for char in API_KEY): raise RuntimeError("Use the API key as one ASCII header value without control characters") if not API_KEY.strip(): raise RuntimeError("Set EXHIBITDAY_API_KEY") def decode_json(text): if SPEC["preserveNumbers"]: # Quote JSON NUMBER tokens, never text inside a JSON string, to keep CSV decimals exact. text = re.sub(r'"(?:\\.|[^"\\])*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?', lambda m: m[0] if m[0].startswith('"') else json.dumps(m[0]), text) return json.loads(text) from pathlib import Path # This terminal version uses curl for HTTP and Python's standard library for JSON/CSV. import subprocess import tempfile def transport(method, url, headers, data): with tempfile.TemporaryDirectory(prefix="exhibitday-guide-") as directory: folder = Path(directory) # curl may leave no output file for a valid bodyless304 response. (folder / "body").write_bytes(b"") command = ["curl", "--disable", "--silent", "--show-error", "--request", method, "--url", url, "--max-time", "30", "--dump-header", str(folder / "headers"), "--output", str(folder / "body"), "--write-out", "%{http_code}"] for name, value in headers.items(): command += ["--header", name + ": " + value] if data is not None: (folder / "request").write_bytes(data) command += ["--data-binary", "@" + str(folder / "request")] result = subprocess.run(command, capture_output=True, text=True) if result.returncode: raise urllib.error.URLError(result.stderr.strip()) response_headers = {} blocks = (folder / "headers").read_text(encoding="iso-8859-1").replace("\r\n", "\n").strip().split("\n\n") for line in blocks[-1].splitlines()[1:]: name, separator, value = line.partition(":") if separator: response_headers[name] = value.strip() return int(result.stdout), (folder / "body").read_bytes(), response_headers class ApiError(RuntimeError): """An API error response. Branch on error_code (and status), never on the message text. uncertain is True when a PATCH or DELETE got no response or a server error: it may or may not have been applied.""" def __init__(self, status, body, uncertain=False): self.status = status self.uncertain = uncertain self.error_code = body.get("error_code") if isinstance(body, dict) else None super().__init__(f"{body.get('error_code')} {body.get('error_params')}: {body.get('errors')} (request {body.get('request_id')})" if isinstance(body, dict) else "HTTP " + str(status) if status else "No response") def call(name, params=None, body=None, key=None): route = SPEC["requests"][name] headers = {"Authorization": "Bearer " + API_KEY, "Accept": "application/json"} if route["method"] == "POST": if not key: raise RuntimeError("Persist a logical create key before sending POST") headers["Idempotency-Key"] = key data = None if body is None else json.dumps(body).encode("utf-8") if data is not None: headers["Content-Type"] = "application/json" query = urllib.parse.urlencode(params or {}) url = BASE + route["path"] + ("?" + query if query else "") # Only GET has automatic retries in this workflow. A PATCH or DELETE that got no response or a # server error is never resent blindly: it may already have been applied, so the caller reads the record first. resend = route["method"] == "GET" for attempt in range(5): try: status, raw, response_headers = transport(route["method"], url, headers, data) except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException): if not resend: raise ApiError(0, None, uncertain=True) if attempt == 4: raise time.sleep(2 ** attempt) continue response_headers = {k.lower(): v for k, v in response_headers.items()} result = None if status != 304 and raw: try: result = decode_json(raw.decode("utf-8")) except (ValueError, UnicodeError): if status < 400: raise RuntimeError("Expected a JSON success response") if status >= 500 and not resend: raise ApiError(status, result, uncertain=True) retry = resend and (status == 429 or status >= 500) if retry: if attempt == 4: raise RuntimeError("Retry limit reached; check the request outcome before starting a new create") delay = response_headers.get("retry-after", str(2 ** attempt)) time.sleep(max(0, float(delay))) continue if status >= 400: raise ApiError(status, result) return {"status": status, "body": result, "headers": response_headers, "raw": raw} raise RuntimeError("Retry limit reached") def both(left,right): return left and right def deep_equal(left,right): if type(left) is not type(right): return False if isinstance(left,dict): return left.keys()==right.keys() and all(deep_equal(left[k],right[k]) for k in left) if isinstance(left,list): return len(left)==len(right) and all(deep_equal(a,b) for a,b in zip(left,right)) return left==right def equal(left, right): return type(left) is type(right) and left == right def field(value, name): if not isinstance(value, dict) or name not in value: raise RuntimeError("Missing response field: " + name) return value[name] def is_present(value): return value is not None and value != "" """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 offsetlen(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)-offset:raise JournalRefusal('Incomplete journal frame; reconcile before retry') payload=raw[offset:offset+size];offset+=size if raw[offset:offset+1]!=b'\n' or digest(payload).encode('ascii')!=match[2]:raise JournalRefusal('Journal integrity check failed; reconcile before retry') records.append(read_strings(payload));offset+=1 return records class Journal: def __init__(self,path,base,workspace,slug,job,input_fingerprint,writes,mode="resume"): self.path=Path(path);self.lock=Path(str(self.path)+'.lock');self.fd=None;self.owned=False;self.identity=None;self.tainted=False;self.intents={};self.saved_values={} address=urlsplit(base) if address.scheme not in ('https','http')or not address.netloc or address.username is not None or address.query or address.fragment or not re.fullmatch('[a-z][a-z0-9-]*',slug):raise JournalRefusal('Use the actual API base and closed guide slug') if not job.strip() or not re.fullmatch('[1-9][0-9]*',workspace) or not re.fullmatch('[0-9A-F]{64}',input_fingerprint):raise JournalRefusal('Use an actual workspace, explicit stable job ID and exact input fingerprint') if mode not in ("new","resume"):raise JournalRefusal("Choose new or resume for this local job") self.allowed={};manifest=[] for step,method,route in writes: if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.allowed or method not in ('POST','PATCH','DELETE')or not re.fullmatch('/v1/[A-Za-z0-9_/-]+',route)or'//'in route:raise JournalRefusal('Use a closed unique write manifest') self.allowed[step]=(method,route);manifest.extend((step,method,route)) if not self.allowed:raise JournalRefusal('Only write workflows need a restart journal') self.header=['H','1',base,workspace,slug,job,input_fingerprint,digest(strings(manifest))] strings(self.header) try: self.fd=os.open(self.lock,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600);self.owned=True except FileExistsError:raise JournalRefusal('This journal is locked; do not run overlapping jobs or steal a stale lock') try: self.owner=secrets.token_hex(16);self.identity=os.fstat(self.fd) if os.write(self.fd,self.owner.encode('ascii'))!=len(self.owner):raise OSError('Incomplete lock identity write') os.fsync(self.fd) if self.path.is_symlink():raise JournalRefusal('Choose a private regular journal file') if mode=="resume" and not self.path.exists():raise JournalRefusal("Journal missing: stop and reconcile lost state before starting a new logical job") if mode=="new" and self.path.exists():raise JournalRefusal("A journal already exists; use resume for the same logical job") if mode=="new": with open(self.path,'xb',buffering=0)as target: target.write(PREAMBLE+frame(self.header));os.fsync(target.fileno()) records=decode(self.path.read_bytes()) if not records or records[0]!=self.header:raise JournalRefusal('Journal workspace/base/guide/job/input binding differs') for record in records[1:]:self.apply(record) if any(step not in self.saved_values for step in self.intents):raise JournalRefusal('A saved before-send intent lacks an ACK; stop and reconcile its outcome before retry') except BaseException: self.close();raise def apply(self,record): if not record:raise JournalRefusal('Empty journal record') if record[0]=='I': if len(record)!=6:raise JournalRefusal('Invalid intent shape') _,step,method,path,request_fingerprint,key=record if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.intents or self.allowed.get(step)!=(method,path)or not re.fullmatch('[0-9A-F]{64}',request_fingerprint)or any(name not in self.saved_values for name in self.intents):raise JournalRefusal('Invalid, future or repeated journal intent') if method=='POST'and not re.fullmatch('[0-9a-f]{32}',key)or method!='POST'and key!='':raise JournalRefusal('Invalid persisted action key') self.intents[step]={'method':method,'path':path,'request_fingerprint':request_fingerprint,'idempotency_key':key} elif record[0]=='A': if len(record)<3:raise JournalRefusal('Invalid ACK shape') _,step,count,*pairs=record if not re.fullmatch('0|[1-9][0-9]*',count)or len(pairs)!=2*int(count)or step not in self.intents or step in self.saved_values:raise JournalRefusal('ACK without exactly one prior intent') names=pairs[::2] if names!=sorted(set(names))or any(not re.fullmatch('[a-z][a-z0-9_]*',name)or name in ('api_key','exhibitday_api_key')for name in names):raise JournalRefusal('ACK saved fields must be unique sorted secret-free identifiers') self.saved_values[step]=dict(zip(names,pairs[1::2])) else:raise JournalRefusal('Unknown journal transition') def append(self,record): # The reader commits state only after complete length/digest recognition. # A torn append is retained and refused, never silently truncated. self.require_active();raw=frame(record) try: with open(self.path,'ab',buffering=0)as target: view=memoryview(raw) while view: written=target.write(view) if not written:raise OSError('Journal write did not advance') view=view[written:] os.fsync(target.fileno()) except BaseException: self.tainted=True;raise def require_active(self): if not self.owned or self.fd is None or self.identity is None or self.tainted:raise JournalRefusal('The journal scope is closed or its IO outcome needs reconciliation') current=self.lock.stat(follow_symlinks=False) if current.st_dev!=self.identity.st_dev or current.st_ino!=self.identity.st_ino or self.lock.read_text(encoding='ascii')!=self.owner:raise JournalRefusal('The journal lock was replaced; stop without deleting it') def acknowledged(self,step): self.require_active();return step in self.saved_values def saved(self,step): self.require_active() if step not in self.saved_values:raise JournalRefusal('No acknowledged state exists for this step') return dict(self.saved_values[step]) def begin(self,step,method,path,request_fingerprint): self.require_active() if step in self.intents:raise JournalRefusal('Never blindly repeat an existing action intent') key=secrets.token_hex(16)if method=='POST'else'' record=['I',step,method,path,request_fingerprint,key] # Validate on an isolated state before touching the file. old=dict(self.intents) try:self.apply(record) finally:self.intents=old self.append(record);self.apply(record) return dict(self.intents[step]) def acknowledge(self,step,saved): self.require_active() record=['A',step,str(len(saved))] for name,value in sorted(saved.items()):record.extend((name,value)) old={name:dict(value)for name,value in self.saved_values.items()} try:self.apply(record);strings(record) finally:self.saved_values=old self.append(record);self.apply(record) def close(self): if self.owned: if self.tainted: os.close(self.fd);self.fd=None;self.owned=False return # Retain this lock after failed journal IO; manual reconciliation is required. try:self.require_active() except BaseException: os.close(self.fd);self.fd=None;self.owned=False;raise os.close(self.fd);self.fd=None;self.owned=False self.lock.unlink() def __enter__(self):return self def __exit__(self,*args):self.close() def journal_values(value): if not isinstance(value, dict) or any(not isinstance(k, str) or not isinstance(v, str) for k,v in value.items()): raise JournalRefusal('Saved/fingerprint values must be exact string fields') return dict(value) def journal_acknowledge(job, step, saved): job.acknowledge(step,journal_values(saved)) def journal_acknowledged(job, step): return job.acknowledged(step) def journal_begin(job, step, method, path, request_fingerprint): return job.begin(step,method,path,request_fingerprint) def journal_fingerprint(value): return fingerprint(journal_values(value)) def journal_saved(job, step): return job.saved(step) def 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 positive_id(value): if not re.fullmatch(r"[1-9][0-9]*", value) or int(value) > 9223372036854775807: raise RuntimeError("Use a positive record ID") return value def print_value(value): print(value if isinstance(value, str) else json.dumps(value, ensure_ascii=False)) def require_condition(value, message): if value is not True: raise RuntimeError(message) def required(name): value = os.environ.get(name) if value is None or not value.strip(): raise RuntimeError("Set " + name) return value def response_status(value): return str(value["status"]) def items(value): if not isinstance(value, list): raise RuntimeError("Expected a JSON array") return value 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(): selected_event_id = positive_id(required("EXHIBITDAY_EVENT_ID")) desired_dates = [{"date": "2030-01-15", "start_time": "09:00", "end_time": "17:00", "timezone": "America/New_York", "description": "Exhibit hours"}, {"date": "2030-01-16", "start_time": "09:00", "end_time": "16:00", "timezone": "America/New_York", "description": "Final exhibit day"}] expected_dates = [{"date": "2030-01-15", "start_time": "09:00:00", "end_time": "17:00:00", "timezone": "America/New_York", "description": "Exhibit hours"}, {"date": "2030-01-16", "start_time": "09:00:00", "end_time": "16:00:00", "timezone": "America/New_York", "description": "Final exhibit day"}] journal_path = required("EXHIBITDAY_JOURNAL") stable_job_id = required("EXHIBITDAY_JOB_ID") job_mode = optional("EXHIBITDAY_JOB_MODE", "resume") workspace_response = call("workspace_binding", {}, None, None) require_condition(equal(response_status(workspace_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement.") owned_workspace = workspace_response["body"] owned_workspace_id = positive_id(text(field(owned_workspace, "id"))) current_dates_response = call("read_group", {"event_id": selected_event_id, "filter_by_date_type_id": "1", "$include_record_revision": "true"}, None, None) require_condition(equal(response_status(current_dates_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement.") current_dates_page = current_dates_response["body"] require_condition(both(equal(text(field(current_dates_page, "records_found")), "1"), both(equal(text(field(current_dates_page, "total_records")), "1"), equal(field(current_dates_page, "has_more"), False))), "Expected one complete selected Dates group.") current_dates_group = single(field(current_dates_page, "list_data")) require_condition(both(equal(text(field(current_dates_group, "event_id")), selected_event_id), equal(text(field(current_dates_group, "date_type_id")), "1")), "The Dates group does not match this Event and Exhibit Hall type.") current_dates_revision = text(field(current_dates_group, "record_revision")) require_condition(is_present(current_dates_revision), "Read the actual selected group with its record_revision before replacing it.") input_fingerprint = journal_fingerprint({"workflow_contract_sha256": "3422CE4F7C1283E1F77ACB98BE12123B5E2D0F078EB80BE01232C22F2941E85D", "event_id": selected_event_id, "date_type_id": "1", "dates": "[{\"date\":\"2030-01-15\",\"start_time\":\"09:00:00\",\"end_time\":\"17:00:00\",\"timezone\":\"America/New_York\",\"description\":\"Exhibit hours\"},{\"date\":\"2030-01-16\",\"start_time\":\"09:00:00\",\"end_time\":\"16:00:00\",\"timezone\":\"America/New_York\",\"description\":\"Final exhibit day\"}]"}) dates_job = open_journal(journal_path, "https://api.exhibitday.com/v1", owned_workspace_id, "dates-times-time-zones", stable_job_id, input_fingerprint, [["replace_group", "PATCH", "/v1/events/dates"]], job_mode) try: if journal_acknowledged(dates_job, "replace_group"): saved_dates = journal_saved(dates_job, "replace_group") require_condition(both(equal(text(field(saved_dates, "event_id")), selected_event_id), equal(text(field(saved_dates, "date_type_id")), "1")), "The saved ACK belongs to a different Event/group; stop and reconcile.") else: dates_patch = {"event_id": selected_event_id, "date_type_id": "1", "dates": desired_dates, "expected_revision": current_dates_revision} write_fingerprint = journal_fingerprint({"event_id": selected_event_id, "date_type_id": "1", "dates": "[{\"date\":\"2030-01-15\",\"start_time\":\"09:00:00\",\"end_time\":\"17:00:00\",\"timezone\":\"America/New_York\",\"description\":\"Exhibit hours\"},{\"date\":\"2030-01-16\",\"start_time\":\"09:00:00\",\"end_time\":\"16:00:00\",\"timezone\":\"America/New_York\",\"description\":\"Final exhibit day\"}]", "expected_revision": current_dates_revision}) journal_begin(dates_job, "replace_group", "PATCH", "/v1/events/dates", write_fingerprint) saved_dates_response = call("replace_group", {}, dates_patch, None) require_condition(equal(response_status(saved_dates_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement.") dates_receipt = saved_dates_response["body"] saved_dates_revision = text(field(dates_receipt, "record_revision")) require_condition(is_present(saved_dates_revision), "A checked Dates save ACK requires its actual returned revision.") journal_acknowledge(dates_job, "replace_group", {"event_id": selected_event_id, "date_type_id": "1", "record_revision": saved_dates_revision}) dates_readback_response = call("verify_group", {"event_id": selected_event_id, "filter_by_date_type_id": "1"}, None, None) require_condition(equal(response_status(dates_readback_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement.") dates_readback_page = dates_readback_response["body"] require_condition(both(equal(text(field(dates_readback_page, "records_found")), "1"), both(equal(text(field(dates_readback_page, "total_records")), "1"), equal(field(dates_readback_page, "has_more"), False))), "Readback must contain one complete selected group, without another page.") dates_readback_group = single(field(dates_readback_page, "list_data")) require_condition(both(equal(text(field(dates_readback_group, "event_id")), selected_event_id), equal(text(field(dates_readback_group, "date_type_id")), "1")), "Readback belongs to another Event or Dates group.") require_condition(deep_equal(field(dates_readback_group, "dates"), expected_dates), "The complete saved Dates list differs; review it instead of automatically restoring the example's dates.") print_value({"event_id": selected_event_id, "date_type_id": "1", "dates_verified": "true"}) finally: dates_job.close() if __name__ == "__main__": main() EXHIBITDAY_PY ``` ```javascript // Server-side Node.js with fetch; built-in modules only. Set EXHIBITDAY_API_KEY. const BASE = "https://api.exhibitday.com/v1"; const SPEC = JSON.parse("{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"read_group\":{\"method\":\"GET\",\"path\":\"/events/dates\"},\"replace_group\":{\"method\":\"PATCH\",\"path\":\"/events/dates\"},\"verify_group\":{\"method\":\"GET\",\"path\":\"/events/dates\"}}}"); const API_KEY = process.env.EXHIBITDAY_API_KEY; if (!API_KEY || !API_KEY.trim()) throw new Error("Set EXHIBITDAY_API_KEY"); if (/[^\x20-\x7e]/.test(API_KEY)) throw new Error("Use the API key as one ASCII header value without control characters"); 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, errors: result.errors, error_params: result.error_params, 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, key = null) { const route = SPEC.requests[name]; const headers = { Authorization: "Bearer " + API_KEY, Accept: "application/json" }; if (route.method === "POST") { if (!key) throw new Error("Persist a logical create key before sending POST"); headers["Idempotency-Key"] = key; } 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 : ""); // 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. const resend = route.method === "GET"; 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 = resend && (response.status === 429 || response.status >= 500); 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, raw }; } throw new Error("Retry limit reached"); } function both(left,right) { return left && right; } function deep_equal(left,right) { if(left===null||right===null)return left===right; if(typeof left!==typeof right||Array.isArray(left)!==Array.isArray(right))return false; if(typeof left!=='object')return left===right; const a=Object.keys(left).sort(),b=Object.keys(right).sort();return a.length===b.length&&a.every((k,i)=>k===b[i]&&deep_equal(left[k],right[k])); } function equal(left, right) { return typeof left === typeof right && left === right; } function field(value, name) { if (!value || Array.isArray(value) || typeof value !== "object" || !Object.hasOwn(value, name)) throw new Error("Missing response field: " + name); return value[name]; } function is_present(value) { return value !== null && value !== undefined && value !== ""; } 'use strict'; // Private client restart state. No HTTP or application dependency. const fs = require('node:fs'); const crypto = require('node:crypto'); const PREAMBLE = Buffer.from('EXHIBITDAY-GUIDE-JOURNAL 1\n', 'ascii'); class JournalRefusal extends Error {} function ascii(raw) { if (raw.some(value => value > 127)) throw new JournalRefusal('Journal framing must be canonical ASCII'); return raw.toString('ascii'); } function utf8(value) { if (typeof value !== 'string') throw new JournalRefusal('Journal fields are exact strings'); for (const unit of value) if (unit.length === 1 && unit.charCodeAt(0) >= 0xd800 && unit.charCodeAt(0) <= 0xdfff) throw new JournalRefusal('Invalid Unicode journal field'); return Buffer.from(value, 'utf8'); } function strings(values) { const parts = []; for (const value of values) { const raw = utf8(value); parts.push(Buffer.from(String(raw.length) + ':', 'ascii'), raw); } return Buffer.concat(parts); } function readStrings(raw) { const values = []; let offset = 0; while (offset < raw.length) { const end = raw.indexOf(58, offset); if (end < 0) throw new JournalRefusal('Incomplete journal string length'); const length = ascii(raw.subarray(offset, end)); if (!/^(0|[1-9][0-9]*)$/.test(length)) throw new JournalRefusal('Noncanonical journal string length'); const size = BigInt(length); offset = end + 1; if (size > BigInt(raw.length - offset)) throw new JournalRefusal('Incomplete journal string'); const count = Number(size); values.push(new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(raw.subarray(offset, offset + count))); offset += count; } return values; } function digest(raw) { return crypto.createHash('sha256').update(raw).digest('hex').toUpperCase(); } function fingerprint(pairs) { const values = []; for (const name of Object.keys(pairs).sort()) { if (!/^[A-Za-z0-9_.-]+$/.test(name) || ['api_key', 'exhibitday_api_key'].includes(name.toLowerCase())) throw new JournalRefusal('Use explicit secret-free fingerprint field names'); values.push(name, pairs[name]); } return digest(strings(values)); } function frame(values) { const raw = strings(values); return Buffer.concat([Buffer.from(String(raw.length) + ' ' + digest(raw) + '\n', 'ascii'), raw, Buffer.from('\n')]); } function decode(raw) { if (!raw.subarray(0, PREAMBLE.length).equals(PREAMBLE)) throw new JournalRefusal('Unknown or incomplete journal version'); let offset = PREAMBLE.length; const records = []; while (offset < raw.length) { const end = raw.indexOf(10, offset); if (end < 0) throw new JournalRefusal('Incomplete journal frame header; reconcile before retry'); const match = /^(0|[1-9][0-9]*) ([0-9A-F]{64})$/.exec(ascii(raw.subarray(offset, end))); if (!match) throw new JournalRefusal('Invalid journal frame header'); const size = BigInt(match[1]); offset = end + 1; if (size >= BigInt(raw.length - offset)) throw new JournalRefusal('Incomplete journal frame; reconcile before retry'); const count = Number(size), payload = raw.subarray(offset, offset + count); offset += count; if (raw[offset] !== 10 || digest(payload) !== match[2]) throw new JournalRefusal('Journal integrity check failed; reconcile before retry'); records.push(readStrings(payload)); offset++; } return records; } function writeAll(fd, raw) { let offset = 0; while (offset < raw.length) { const count = fs.writeSync(fd, raw, offset, raw.length - offset); if (!count) throw new Error('Journal write did not advance'); offset += count; } } function same(left, right) { return left.length === right.length && left.every((value, index) => value === right[index]); } class Journal { constructor(path, base, workspace, slug, job, inputFingerprint, writes, mode = 'resume') { this.path = path; this.lock = path + '.lock'; this.fd = null; this.owned = false; this.identity = null; this.tainted = false; this.intents = new Map(); this.savedValues = new Map(); this.allowed = new Map(); if (!['new', 'resume'].includes(mode)) throw new JournalRefusal('Choose new or resume for this local job'); const address = new URL(base); if (!['https:', 'http:'].includes(address.protocol) || !address.hostname || address.username || address.password || address.search || address.hash || !/^[a-z][a-z0-9-]*$/.test(slug)) throw new JournalRefusal('Use the actual API base and closed guide slug'); if (!job.trim() || !/^[1-9][0-9]*$/.test(workspace) || !/^[0-9A-F]{64}$/.test(inputFingerprint)) throw new JournalRefusal('Use an actual workspace, stable explicit job ID and exact input fingerprint'); const manifest = []; for (const [step, method, route] of writes) { if (!/^[a-z][a-z0-9_-]*$/.test(step) || this.allowed.has(step) || !['POST', 'PATCH', 'DELETE'].includes(method) || !/^\/v1\/[A-Za-z0-9_/-]+$/.test(route) || route.includes('//')) throw new JournalRefusal('Use a closed unique write manifest'); this.allowed.set(step, [method, route]); manifest.push(step, method, route); } if (!this.allowed.size) throw new JournalRefusal('Only write workflows need a restart journal'); this.header = ['H', '1', base, workspace, slug, job, inputFingerprint, digest(strings(manifest))]; strings(this.header); try { this.fd = fs.openSync(this.lock, 'wx', 0o600); this.owned = true; } catch (error) { if (error.code === 'EEXIST') throw new JournalRefusal('This journal is locked; do not overlap jobs or steal a stale lock'); throw error; } try { this.owner = crypto.randomBytes(16).toString('hex'); this.identity = fs.fstatSync(this.fd, { bigint: true }); writeAll(this.fd, Buffer.from(this.owner, 'ascii')); fs.fsyncSync(this.fd); let exists = true; try { if (fs.lstatSync(path).isSymbolicLink()) throw new JournalRefusal('Choose a private regular journal file'); } catch (error) { if (error.code === 'ENOENT') exists = false; else throw error; } if (mode === 'resume' && !exists) throw new JournalRefusal('Journal missing: stop and reconcile lost state before starting a new logical job'); if (mode === 'new' && exists) throw new JournalRefusal('Journal already exists; use resume for the same logical job'); if (mode === 'new') { const target = fs.openSync(path, 'wx', 0o600); try { writeAll(target, Buffer.concat([PREAMBLE, frame(this.header)])); fs.fsyncSync(target); } finally { fs.closeSync(target); } } const records = decode(fs.readFileSync(path)); if (!records.length || !same(records[0], this.header)) throw new JournalRefusal('Journal workspace/base/guide/job/input binding differs'); for (const record of records.slice(1)) this.apply(record); if ([...this.intents.keys()].some(step => !this.savedValues.has(step))) throw new JournalRefusal('Saved before-send intent lacks ACK; stop and reconcile before retry'); } catch (error) { this.close(); throw error; } } apply(record) { if (record[0] === 'I') { if (record.length !== 6) throw new JournalRefusal('Invalid intent shape'); const [, step, method, path, requestFingerprint, key] = record; if (!/^[a-z][a-z0-9_-]*$/.test(step) || this.intents.has(step) || !this.allowed.has(step) || !same(this.allowed.get(step), [method, path]) || !/^[0-9A-F]{64}$/.test(requestFingerprint) || [...this.intents.keys()].some(name => !this.savedValues.has(name))) throw new JournalRefusal('Invalid, future or repeated intent'); if ((method === 'POST' && !/^[0-9a-f]{32}$/.test(key)) || (method !== 'POST' && key !== '')) throw new JournalRefusal('Invalid persisted action key'); this.intents.set(step, { method, path, request_fingerprint: requestFingerprint, idempotency_key: key }); } else if (record[0] === 'A') { const [, step, count, ...pairs] = record; if (record.length < 3 || !/^(0|[1-9][0-9]*)$/.test(count) || BigInt(pairs.length) !== 2n * BigInt(count) || !this.intents.has(step) || this.savedValues.has(step)) throw new JournalRefusal('ACK without exactly one prior intent'); const names = pairs.filter((_, index) => index % 2 === 0); if (!same(names, [...new Set(names)].sort()) || names.some(name => !/^[a-z][a-z0-9_]*$/.test(name) || ['api_key', 'exhibitday_api_key'].includes(name))) throw new JournalRefusal('ACK fields must be unique sorted secret-free identifiers'); this.savedValues.set(step, Object.fromEntries(names.map((name, index) => [name, pairs[index * 2 + 1]]))); } else throw new JournalRefusal('Unknown journal transition'); } requireActive() { if (!this.owned || this.fd === null || this.identity === null || this.tainted) throw new JournalRefusal('Journal is closed or its IO outcome needs reconciliation'); const current = fs.lstatSync(this.lock, { bigint: true }); if (current.dev !== this.identity.dev || current.ino !== this.identity.ino || ascii(fs.readFileSync(this.lock)) !== this.owner) throw new JournalRefusal('Journal lock was replaced; stop without deleting it'); } append(record) { this.requireActive(); const raw = frame(record); let target; try { target = fs.openSync(this.path, 'a'); writeAll(target, raw); fs.fsyncSync(target); } catch (error) { this.tainted = true; throw error; } finally { if (target !== undefined) fs.closeSync(target); } } acknowledged(step) { this.requireActive(); return this.savedValues.has(step); } saved(step) { this.requireActive(); if (!this.savedValues.has(step)) throw new JournalRefusal('No acknowledged state exists'); return { ...this.savedValues.get(step) }; } begin(step, method, path, requestFingerprint) { this.requireActive(); if (this.intents.has(step)) throw new JournalRefusal('Never blindly repeat an existing action'); const key = method === 'POST' ? crypto.randomBytes(16).toString('hex') : '', record = ['I', step, method, path, requestFingerprint, key]; const old = new Map(this.intents); try { this.apply(record); } finally { this.intents = old; } this.append(record); this.apply(record); return { ...this.intents.get(step) }; } acknowledge(step, saved) { this.requireActive(); const names = Object.keys(saved).sort(), record = ['A', step, String(names.length)]; for (const name of names) record.push(name, saved[name]); const old = new Map(this.savedValues); try { this.apply(record); strings(record); } finally { this.savedValues = old; } this.append(record); this.apply(record); } close() { if (!this.owned) return; if (this.tainted) { fs.closeSync(this.fd); this.fd = null; this.owned = false; return; } try { this.requireActive(); } catch (error) { fs.closeSync(this.fd); this.fd = null; this.owned = false; throw error; } fs.closeSync(this.fd); this.fd = null; this.owned = false; fs.unlinkSync(this.lock); } } function journal_values(value) { if (!value || typeof value !== 'object' || Array.isArray(value) || Object.values(value).some(item=>typeof item!=='string')) throw new JournalRefusal('Saved/fingerprint values must be exact strings'); return {...value}; } function journal_acknowledge(job,step,saved) { job.acknowledge(step,journal_values(saved)); } function journal_acknowledged(job,step) { return job.acknowledged(step); } function journal_begin(job,step,method,path,requestFingerprint) { return job.begin(step,method,path,requestFingerprint); } function journal_fingerprint(value) { return fingerprint(journal_values(value)); } function journal_saved(job,step) { return job.saved(step); } function open_journal(path,base,workspace,slug,job,inputFingerprint,writes,mode) { return new Journal(path,base,workspace,slug,job,inputFingerprint,writes,mode); } function optional(name, fallback) { const value = process.env[name]; return value === undefined || value === "" ? fallback : value; } function positive_id(value) { if (!/^[1-9][0-9]*$/.test(value) || BigInt(value) > 9223372036854775807n) throw new Error("Use a positive record ID"); return value; } function print_value(value) { console.log(typeof value === "string" ? value : JSON.stringify(value)); } function require_condition(value, message) { if (value !== true) throw new Error(message); } function required(name) { const value = process.env[name]; if (value === undefined || !value.trim()) throw new Error("Set " + name); return value; } function response_status(value) { return String(value.status); } function items(value) { if (!Array.isArray(value)) throw new Error("Expected a JSON array"); return value; } function single(value){const rows=items(value);if(rows.length!==1)throw new Error('Expected exactly one selected record');return rows[0];} function text(value) { if (value === null || value === undefined) return ""; if (["string", "boolean", "bigint"].includes(typeof value)) return String(value); throw new Error("Expected a scalar response value"); } async function main() { let selected_event_id = positive_id(required("EXHIBITDAY_EVENT_ID")); let desired_dates = [{"date": "2030-01-15", "start_time": "09:00", "end_time": "17:00", "timezone": "America/New_York", "description": "Exhibit hours"}, {"date": "2030-01-16", "start_time": "09:00", "end_time": "16:00", "timezone": "America/New_York", "description": "Final exhibit day"}]; let expected_dates = [{"date": "2030-01-15", "start_time": "09:00:00", "end_time": "17:00:00", "timezone": "America/New_York", "description": "Exhibit hours"}, {"date": "2030-01-16", "start_time": "09:00:00", "end_time": "16:00:00", "timezone": "America/New_York", "description": "Final exhibit day"}]; let journal_path = required("EXHIBITDAY_JOURNAL"); let stable_job_id = required("EXHIBITDAY_JOB_ID"); let job_mode = optional("EXHIBITDAY_JOB_MODE", "resume"); let workspace_response = await call("workspace_binding", {}, null, null); require_condition(equal(response_status(workspace_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement."); let owned_workspace = workspace_response.body; let owned_workspace_id = positive_id(text(field(owned_workspace, "id"))); let current_dates_response = await call("read_group", {"event_id": selected_event_id, "filter_by_date_type_id": "1", "$include_record_revision": "true"}, null, null); require_condition(equal(response_status(current_dates_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement."); let current_dates_page = current_dates_response.body; require_condition(both(equal(text(field(current_dates_page, "records_found")), "1"), both(equal(text(field(current_dates_page, "total_records")), "1"), equal(field(current_dates_page, "has_more"), false))), "Expected one complete selected Dates group."); let current_dates_group = single(field(current_dates_page, "list_data")); require_condition(both(equal(text(field(current_dates_group, "event_id")), selected_event_id), equal(text(field(current_dates_group, "date_type_id")), "1")), "The Dates group does not match this Event and Exhibit Hall type."); let current_dates_revision = text(field(current_dates_group, "record_revision")); require_condition(is_present(current_dates_revision), "Read the actual selected group with its record_revision before replacing it."); let input_fingerprint = journal_fingerprint({"workflow_contract_sha256": "3422CE4F7C1283E1F77ACB98BE12123B5E2D0F078EB80BE01232C22F2941E85D", "event_id": selected_event_id, "date_type_id": "1", "dates": "[{\"date\":\"2030-01-15\",\"start_time\":\"09:00:00\",\"end_time\":\"17:00:00\",\"timezone\":\"America/New_York\",\"description\":\"Exhibit hours\"},{\"date\":\"2030-01-16\",\"start_time\":\"09:00:00\",\"end_time\":\"16:00:00\",\"timezone\":\"America/New_York\",\"description\":\"Final exhibit day\"}]"}); let dates_job = open_journal(journal_path, "https://api.exhibitday.com/v1", owned_workspace_id, "dates-times-time-zones", stable_job_id, input_fingerprint, [["replace_group", "PATCH", "/v1/events/dates"]], job_mode); try { if (journal_acknowledged(dates_job, "replace_group")) { let saved_dates = journal_saved(dates_job, "replace_group"); require_condition(both(equal(text(field(saved_dates, "event_id")), selected_event_id), equal(text(field(saved_dates, "date_type_id")), "1")), "The saved ACK belongs to a different Event/group; stop and reconcile."); } else { let dates_patch = {"event_id": selected_event_id, "date_type_id": "1", "dates": desired_dates, "expected_revision": current_dates_revision}; let write_fingerprint = journal_fingerprint({"event_id": selected_event_id, "date_type_id": "1", "dates": "[{\"date\":\"2030-01-15\",\"start_time\":\"09:00:00\",\"end_time\":\"17:00:00\",\"timezone\":\"America/New_York\",\"description\":\"Exhibit hours\"},{\"date\":\"2030-01-16\",\"start_time\":\"09:00:00\",\"end_time\":\"16:00:00\",\"timezone\":\"America/New_York\",\"description\":\"Final exhibit day\"}]", "expected_revision": current_dates_revision}); journal_begin(dates_job, "replace_group", "PATCH", "/v1/events/dates", write_fingerprint); let saved_dates_response = await call("replace_group", {}, dates_patch, null); require_condition(equal(response_status(saved_dates_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement."); let dates_receipt = saved_dates_response.body; let saved_dates_revision = text(field(dates_receipt, "record_revision")); require_condition(is_present(saved_dates_revision), "A checked Dates save ACK requires its actual returned revision."); journal_acknowledge(dates_job, "replace_group", {"event_id": selected_event_id, "date_type_id": "1", "record_revision": saved_dates_revision}); } let dates_readback_response = await call("verify_group", {"event_id": selected_event_id, "filter_by_date_type_id": "1"}, null, null); require_condition(equal(response_status(dates_readback_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement."); let dates_readback_page = dates_readback_response.body; require_condition(both(equal(text(field(dates_readback_page, "records_found")), "1"), both(equal(text(field(dates_readback_page, "total_records")), "1"), equal(field(dates_readback_page, "has_more"), false))), "Readback must contain one complete selected group, without another page."); let dates_readback_group = single(field(dates_readback_page, "list_data")); require_condition(both(equal(text(field(dates_readback_group, "event_id")), selected_event_id), equal(text(field(dates_readback_group, "date_type_id")), "1")), "Readback belongs to another Event or Dates group."); require_condition(deep_equal(field(dates_readback_group, "dates"), expected_dates), "The complete saved Dates list differs; review it instead of automatically restoring the example's dates."); print_value({"event_id": selected_event_id, "date_type_id": "1", "dates_verified": "true"}); } finally { dates_job.close(); } } if (require.main === module) main().catch(error => { console.error(error.message); process.exitCode = 1; }); module.exports = { main }; ``` ```python # Python 3; standard library only. Set EXHIBITDAY_API_KEY before running. import http.client import json import os import re import time import urllib.error import urllib.parse import urllib.request BASE = "https://api.exhibitday.com/v1" SPEC = json.loads("{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"read_group\":{\"method\":\"GET\",\"path\":\"/events/dates\"},\"replace_group\":{\"method\":\"PATCH\",\"path\":\"/events/dates\"},\"verify_group\":{\"method\":\"GET\",\"path\":\"/events/dates\"}}}") 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) 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, key=None): route = SPEC["requests"][name] headers = {"Authorization": "Bearer " + API_KEY, "Accept": "application/json"} if route["method"] == "POST": if not key: raise RuntimeError("Persist a logical create key before sending POST") headers["Idempotency-Key"] = key data = None if body is None else json.dumps(body).encode("utf-8") if data is not None: headers["Content-Type"] = "application/json" query = urllib.parse.urlencode(params or {}) url = BASE + route["path"] + ("?" + query if query else "") # Only GET has automatic retries in this workflow. A PATCH or DELETE that got no response or a # server error is never resent blindly: it may already have been applied, so the caller reads the record first. resend = route["method"] == "GET" for attempt in range(5): try: status, raw, response_headers = transport(route["method"], url, headers, data) except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException): if not resend: raise ApiError(0, None, uncertain=True) if attempt == 4: raise time.sleep(2 ** attempt) continue response_headers = {k.lower(): v for k, v in response_headers.items()} result = None if status != 304 and raw: try: result = decode_json(raw.decode("utf-8")) except (ValueError, UnicodeError): if status < 400: raise RuntimeError("Expected a JSON success response") if status >= 500 and not resend: raise ApiError(status, result, uncertain=True) retry = resend and (status == 429 or status >= 500) if retry: if attempt == 4: raise RuntimeError("Retry limit reached; check the request outcome before starting a new create") delay = response_headers.get("retry-after", str(2 ** attempt)) time.sleep(max(0, float(delay))) continue if status >= 400: raise ApiError(status, result) return {"status": status, "body": result, "headers": response_headers, "raw": raw} raise RuntimeError("Retry limit reached") def both(left,right): return left and right def deep_equal(left,right): if type(left) is not type(right): return False if isinstance(left,dict): return left.keys()==right.keys() and all(deep_equal(left[k],right[k]) for k in left) if isinstance(left,list): return len(left)==len(right) and all(deep_equal(a,b) for a,b in zip(left,right)) return left==right def equal(left, right): return type(left) is type(right) and left == right def field(value, name): if not isinstance(value, dict) or name not in value: raise RuntimeError("Missing response field: " + name) return value[name] def is_present(value): return value is not None and value != "" """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 offsetlen(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)-offset:raise JournalRefusal('Incomplete journal frame; reconcile before retry') payload=raw[offset:offset+size];offset+=size if raw[offset:offset+1]!=b'\n' or digest(payload).encode('ascii')!=match[2]:raise JournalRefusal('Journal integrity check failed; reconcile before retry') records.append(read_strings(payload));offset+=1 return records class Journal: def __init__(self,path,base,workspace,slug,job,input_fingerprint,writes,mode="resume"): self.path=Path(path);self.lock=Path(str(self.path)+'.lock');self.fd=None;self.owned=False;self.identity=None;self.tainted=False;self.intents={};self.saved_values={} address=urlsplit(base) if address.scheme not in ('https','http')or not address.netloc or address.username is not None or address.query or address.fragment or not re.fullmatch('[a-z][a-z0-9-]*',slug):raise JournalRefusal('Use the actual API base and closed guide slug') if not job.strip() or not re.fullmatch('[1-9][0-9]*',workspace) or not re.fullmatch('[0-9A-F]{64}',input_fingerprint):raise JournalRefusal('Use an actual workspace, explicit stable job ID and exact input fingerprint') if mode not in ("new","resume"):raise JournalRefusal("Choose new or resume for this local job") self.allowed={};manifest=[] for step,method,route in writes: if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.allowed or method not in ('POST','PATCH','DELETE')or not re.fullmatch('/v1/[A-Za-z0-9_/-]+',route)or'//'in route:raise JournalRefusal('Use a closed unique write manifest') self.allowed[step]=(method,route);manifest.extend((step,method,route)) if not self.allowed:raise JournalRefusal('Only write workflows need a restart journal') self.header=['H','1',base,workspace,slug,job,input_fingerprint,digest(strings(manifest))] strings(self.header) try: self.fd=os.open(self.lock,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600);self.owned=True except FileExistsError:raise JournalRefusal('This journal is locked; do not run overlapping jobs or steal a stale lock') try: self.owner=secrets.token_hex(16);self.identity=os.fstat(self.fd) if os.write(self.fd,self.owner.encode('ascii'))!=len(self.owner):raise OSError('Incomplete lock identity write') os.fsync(self.fd) if self.path.is_symlink():raise JournalRefusal('Choose a private regular journal file') if mode=="resume" and not self.path.exists():raise JournalRefusal("Journal missing: stop and reconcile lost state before starting a new logical job") if mode=="new" and self.path.exists():raise JournalRefusal("A journal already exists; use resume for the same logical job") if mode=="new": with open(self.path,'xb',buffering=0)as target: target.write(PREAMBLE+frame(self.header));os.fsync(target.fileno()) records=decode(self.path.read_bytes()) if not records or records[0]!=self.header:raise JournalRefusal('Journal workspace/base/guide/job/input binding differs') for record in records[1:]:self.apply(record) if any(step not in self.saved_values for step in self.intents):raise JournalRefusal('A saved before-send intent lacks an ACK; stop and reconcile its outcome before retry') except BaseException: self.close();raise def apply(self,record): if not record:raise JournalRefusal('Empty journal record') if record[0]=='I': if len(record)!=6:raise JournalRefusal('Invalid intent shape') _,step,method,path,request_fingerprint,key=record if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.intents or self.allowed.get(step)!=(method,path)or not re.fullmatch('[0-9A-F]{64}',request_fingerprint)or any(name not in self.saved_values for name in self.intents):raise JournalRefusal('Invalid, future or repeated journal intent') if method=='POST'and not re.fullmatch('[0-9a-f]{32}',key)or method!='POST'and key!='':raise JournalRefusal('Invalid persisted action key') self.intents[step]={'method':method,'path':path,'request_fingerprint':request_fingerprint,'idempotency_key':key} elif record[0]=='A': if len(record)<3:raise JournalRefusal('Invalid ACK shape') _,step,count,*pairs=record if not re.fullmatch('0|[1-9][0-9]*',count)or len(pairs)!=2*int(count)or step not in self.intents or step in self.saved_values:raise JournalRefusal('ACK without exactly one prior intent') names=pairs[::2] if names!=sorted(set(names))or any(not re.fullmatch('[a-z][a-z0-9_]*',name)or name in ('api_key','exhibitday_api_key')for name in names):raise JournalRefusal('ACK saved fields must be unique sorted secret-free identifiers') self.saved_values[step]=dict(zip(names,pairs[1::2])) else:raise JournalRefusal('Unknown journal transition') def append(self,record): # The reader commits state only after complete length/digest recognition. # A torn append is retained and refused, never silently truncated. self.require_active();raw=frame(record) try: with open(self.path,'ab',buffering=0)as target: view=memoryview(raw) while view: written=target.write(view) if not written:raise OSError('Journal write did not advance') view=view[written:] os.fsync(target.fileno()) except BaseException: self.tainted=True;raise def require_active(self): if not self.owned or self.fd is None or self.identity is None or self.tainted:raise JournalRefusal('The journal scope is closed or its IO outcome needs reconciliation') current=self.lock.stat(follow_symlinks=False) if current.st_dev!=self.identity.st_dev or current.st_ino!=self.identity.st_ino or self.lock.read_text(encoding='ascii')!=self.owner:raise JournalRefusal('The journal lock was replaced; stop without deleting it') def acknowledged(self,step): self.require_active();return step in self.saved_values def saved(self,step): self.require_active() if step not in self.saved_values:raise JournalRefusal('No acknowledged state exists for this step') return dict(self.saved_values[step]) def begin(self,step,method,path,request_fingerprint): self.require_active() if step in self.intents:raise JournalRefusal('Never blindly repeat an existing action intent') key=secrets.token_hex(16)if method=='POST'else'' record=['I',step,method,path,request_fingerprint,key] # Validate on an isolated state before touching the file. old=dict(self.intents) try:self.apply(record) finally:self.intents=old self.append(record);self.apply(record) return dict(self.intents[step]) def acknowledge(self,step,saved): self.require_active() record=['A',step,str(len(saved))] for name,value in sorted(saved.items()):record.extend((name,value)) old={name:dict(value)for name,value in self.saved_values.items()} try:self.apply(record);strings(record) finally:self.saved_values=old self.append(record);self.apply(record) def close(self): if self.owned: if self.tainted: os.close(self.fd);self.fd=None;self.owned=False return # Retain this lock after failed journal IO; manual reconciliation is required. try:self.require_active() except BaseException: os.close(self.fd);self.fd=None;self.owned=False;raise os.close(self.fd);self.fd=None;self.owned=False self.lock.unlink() def __enter__(self):return self def __exit__(self,*args):self.close() def journal_values(value): if not isinstance(value, dict) or any(not isinstance(k, str) or not isinstance(v, str) for k,v in value.items()): raise JournalRefusal('Saved/fingerprint values must be exact string fields') return dict(value) def journal_acknowledge(job, step, saved): job.acknowledge(step,journal_values(saved)) def journal_acknowledged(job, step): return job.acknowledged(step) def journal_begin(job, step, method, path, request_fingerprint): return job.begin(step,method,path,request_fingerprint) def journal_fingerprint(value): return fingerprint(journal_values(value)) def journal_saved(job, step): return job.saved(step) def 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 positive_id(value): if not re.fullmatch(r"[1-9][0-9]*", value) or int(value) > 9223372036854775807: raise RuntimeError("Use a positive record ID") return value def print_value(value): print(value if isinstance(value, str) else json.dumps(value, ensure_ascii=False)) def require_condition(value, message): if value is not True: raise RuntimeError(message) def required(name): value = os.environ.get(name) if value is None or not value.strip(): raise RuntimeError("Set " + name) return value def response_status(value): return str(value["status"]) def items(value): if not isinstance(value, list): raise RuntimeError("Expected a JSON array") return value 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(): selected_event_id = positive_id(required("EXHIBITDAY_EVENT_ID")) desired_dates = [{"date": "2030-01-15", "start_time": "09:00", "end_time": "17:00", "timezone": "America/New_York", "description": "Exhibit hours"}, {"date": "2030-01-16", "start_time": "09:00", "end_time": "16:00", "timezone": "America/New_York", "description": "Final exhibit day"}] expected_dates = [{"date": "2030-01-15", "start_time": "09:00:00", "end_time": "17:00:00", "timezone": "America/New_York", "description": "Exhibit hours"}, {"date": "2030-01-16", "start_time": "09:00:00", "end_time": "16:00:00", "timezone": "America/New_York", "description": "Final exhibit day"}] journal_path = required("EXHIBITDAY_JOURNAL") stable_job_id = required("EXHIBITDAY_JOB_ID") job_mode = optional("EXHIBITDAY_JOB_MODE", "resume") workspace_response = call("workspace_binding", {}, None, None) require_condition(equal(response_status(workspace_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement.") owned_workspace = workspace_response["body"] owned_workspace_id = positive_id(text(field(owned_workspace, "id"))) current_dates_response = call("read_group", {"event_id": selected_event_id, "filter_by_date_type_id": "1", "$include_record_revision": "true"}, None, None) require_condition(equal(response_status(current_dates_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement.") current_dates_page = current_dates_response["body"] require_condition(both(equal(text(field(current_dates_page, "records_found")), "1"), both(equal(text(field(current_dates_page, "total_records")), "1"), equal(field(current_dates_page, "has_more"), False))), "Expected one complete selected Dates group.") current_dates_group = single(field(current_dates_page, "list_data")) require_condition(both(equal(text(field(current_dates_group, "event_id")), selected_event_id), equal(text(field(current_dates_group, "date_type_id")), "1")), "The Dates group does not match this Event and Exhibit Hall type.") current_dates_revision = text(field(current_dates_group, "record_revision")) require_condition(is_present(current_dates_revision), "Read the actual selected group with its record_revision before replacing it.") input_fingerprint = journal_fingerprint({"workflow_contract_sha256": "3422CE4F7C1283E1F77ACB98BE12123B5E2D0F078EB80BE01232C22F2941E85D", "event_id": selected_event_id, "date_type_id": "1", "dates": "[{\"date\":\"2030-01-15\",\"start_time\":\"09:00:00\",\"end_time\":\"17:00:00\",\"timezone\":\"America/New_York\",\"description\":\"Exhibit hours\"},{\"date\":\"2030-01-16\",\"start_time\":\"09:00:00\",\"end_time\":\"16:00:00\",\"timezone\":\"America/New_York\",\"description\":\"Final exhibit day\"}]"}) dates_job = open_journal(journal_path, "https://api.exhibitday.com/v1", owned_workspace_id, "dates-times-time-zones", stable_job_id, input_fingerprint, [["replace_group", "PATCH", "/v1/events/dates"]], job_mode) try: if journal_acknowledged(dates_job, "replace_group"): saved_dates = journal_saved(dates_job, "replace_group") require_condition(both(equal(text(field(saved_dates, "event_id")), selected_event_id), equal(text(field(saved_dates, "date_type_id")), "1")), "The saved ACK belongs to a different Event/group; stop and reconcile.") else: dates_patch = {"event_id": selected_event_id, "date_type_id": "1", "dates": desired_dates, "expected_revision": current_dates_revision} write_fingerprint = journal_fingerprint({"event_id": selected_event_id, "date_type_id": "1", "dates": "[{\"date\":\"2030-01-15\",\"start_time\":\"09:00:00\",\"end_time\":\"17:00:00\",\"timezone\":\"America/New_York\",\"description\":\"Exhibit hours\"},{\"date\":\"2030-01-16\",\"start_time\":\"09:00:00\",\"end_time\":\"16:00:00\",\"timezone\":\"America/New_York\",\"description\":\"Final exhibit day\"}]", "expected_revision": current_dates_revision}) journal_begin(dates_job, "replace_group", "PATCH", "/v1/events/dates", write_fingerprint) saved_dates_response = call("replace_group", {}, dates_patch, None) require_condition(equal(response_status(saved_dates_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement.") dates_receipt = saved_dates_response["body"] saved_dates_revision = text(field(dates_receipt, "record_revision")) require_condition(is_present(saved_dates_revision), "A checked Dates save ACK requires its actual returned revision.") journal_acknowledge(dates_job, "replace_group", {"event_id": selected_event_id, "date_type_id": "1", "record_revision": saved_dates_revision}) dates_readback_response = call("verify_group", {"event_id": selected_event_id, "filter_by_date_type_id": "1"}, None, None) require_condition(equal(response_status(dates_readback_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement.") dates_readback_page = dates_readback_response["body"] require_condition(both(equal(text(field(dates_readback_page, "records_found")), "1"), both(equal(text(field(dates_readback_page, "total_records")), "1"), equal(field(dates_readback_page, "has_more"), False))), "Readback must contain one complete selected group, without another page.") dates_readback_group = single(field(dates_readback_page, "list_data")) require_condition(both(equal(text(field(dates_readback_group, "event_id")), selected_event_id), equal(text(field(dates_readback_group, "date_type_id")), "1")), "Readback belongs to another Event or Dates group.") require_condition(deep_equal(field(dates_readback_group, "dates"), expected_dates), "The complete saved Dates list differs; review it instead of automatically restoring the example's dates.") print_value({"event_id": selected_event_id, "date_type_id": "1", "dates_verified": "true"}) finally: dates_job.close() if __name__ == "__main__": main() ``` ```csharp // .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\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"read_group\":{\"method\":\"GET\",\"path\":\"/events/dates\"},\"replace_group\":{\"method\":\"PATCH\",\"path\":\"/events/dates\"},\"verify_group\":{\"method\":\"GET\",\"path\":\"/events/dates\"}}}"); static readonly string ApiKey = HeaderKey(Required("EXHIBITDAY_API_KEY")); static string HeaderKey(string value) { if(value.Any(c=>c<32||c>126))throw new Exception("Use the API key as one ASCII header value without control characters");return value; } static readonly HttpClient Client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false }) { Timeout = TimeSpan.FromSeconds(30) }; internal static Func> Send = request => Client.SendAsync(request); sealed class Result { public int Status; public JsonNode Body; public Dictionary Headers; public string Raw; } // 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(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 Call(string name, JsonObject query = null, JsonNode body = null, string key = null) { var route = Spec["requests"][name]; var method = Text(route["method"]); var headers = new Dictionary(StringComparer.OrdinalIgnoreCase) { ["Authorization"] = "Bearer " + ApiKey, ["Accept"] = "application/json" }; if (method == "POST") { if (string.IsNullOrEmpty(key)) throw new Exception("Persist a logical create key before sending POST"); headers["Idempotency-Key"] = key; } 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); // 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. var resend = method == "GET"; 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 Send(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 = resend && (status == 429 || status >= 500); 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, Raw = raw }; } } throw new Exception("Retry limit reached"); } static bool Both(bool left,bool right)=>left&&right; static JsonNode CopyNode(JsonNode value) => value?.DeepClone(); static bool DeepEqual(JsonNode left,JsonNode right)=>JsonNode.DeepEquals(left,right); static object Scalar(object value) { if(value is JsonValue json){if(json.TryGetValue(out var boolean))return boolean;if(json.TryGetValue(out var text))return text;return json.ToJsonString();}return value; } static bool Equal(object left,object right) => object.Equals(Scalar(left),Scalar(right)); static JsonNode Field(JsonNode value,string name) { if(value is not JsonObject obj || !obj.TryGetPropertyValue(name,out var item))throw new Exception("Missing response field: "+name);return item; } static bool IsPresent(string value) => value!=null && value!=""; public sealed class JournalRefusal : Exception { public JournalRefusal(string message) : base(message) {} } public static class JournalProtocol { public static readonly byte[] Preamble = Encoding.ASCII.GetBytes("EXHIBITDAY-GUIDE-JOURNAL 1\n"); static readonly UTF8Encoding Utf8 = new UTF8Encoding(false, true); static bool Match(string value,string pattern) => value != null && System.Text.RegularExpressions.Regex.IsMatch(value,"\\A(?:"+pattern+")\\z",System.Text.RegularExpressions.RegexOptions.CultureInvariant); public static bool Valid(string value,string pattern) => Match(value,pattern); static string Ascii(byte[] raw,int start,int count) { for(var i=start;i127)throw new JournalRefusal("Journal framing must be canonical ASCII");return Encoding.ASCII.GetString(raw,start,count); } public static byte[] Strings(IEnumerable values) { using var data=new MemoryStream(); foreach(var value in values){if(value==null)throw new JournalRefusal("Journal fields are exact strings");var item=Utf8.GetBytes(value);var prefix=Encoding.ASCII.GetBytes(item.Length.ToString(CultureInfo.InvariantCulture)+":");data.Write(prefix);data.Write(item);} return data.ToArray(); } public static List ReadStrings(byte[] raw) { var values=new List();var offset=0; while(offsetraw.Length-offset)throw new JournalRefusal("Incomplete journal string");values.Add(Utf8.GetString(raw,offset,(int)size));offset+=(int)size;} return values; } public static string Digest(byte[] raw)=>Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(raw)); public static string Fingerprint(IReadOnlyDictionary pairs) { var values=new List();foreach(var name in pairs.Keys.OrderBy(n=>n,StringComparer.Ordinal)){ if(!Match(name,"[A-Za-z0-9_.-]+")||new[]{"api_key","exhibitday_api_key"}.Contains(name.ToLowerInvariant()))throw new JournalRefusal("Use explicit secret-free fingerprint names");values.Add(name);values.Add(pairs[name]);} return Digest(Strings(values)); } public static byte[] Frame(IEnumerable values) { var payload=Strings(values);var header=Encoding.ASCII.GetBytes(payload.Length.ToString(CultureInfo.InvariantCulture)+" "+Digest(payload)+"\n"); using var data=new MemoryStream();data.Write(header);data.Write(payload);data.WriteByte(10);return data.ToArray(); } public static List> Decode(byte[] raw) { if(raw.Length>(); while(offset=raw.Length-offset)throw new JournalRefusal("Incomplete frame; reconcile before retry");var payload=raw.AsSpan(offset,(int)size).ToArray();offset+=(int)size; if(raw[offset]!=10||Digest(payload)!=split[1])throw new JournalRefusal("Journal integrity failed; reconcile before retry");records.Add(ReadStrings(payload));offset++;} return records; } } public sealed class Journal : IDisposable { readonly string path,lockPath,owner;readonly List header; readonly Dictionary allowed=new Dictionary(StringComparer.Ordinal); Dictionary> intents=new Dictionary>(StringComparer.Ordinal),savedValues=new Dictionary>(StringComparer.Ordinal); FileStream lockStream;bool owned,tainted;DateTime creation; static FileStream CreatePrivate(string target,FileAccess access,FileShare share) { var options=new FileStreamOptions{Mode=FileMode.CreateNew,Access=access,Share=share}; if(!OperatingSystem.IsWindows())options.UnixCreateMode=UnixFileMode.UserRead|UnixFileMode.UserWrite; return new FileStream(target,options); } public Journal(string path,string apiBase,string workspace,string slug,string job,string inputFingerprint,IEnumerable<(string Step,string Method,string Path)> writes,string mode="resume") { this.path=path;lockPath=path+".lock";owner=Convert.ToHexString(System.Security.Cryptography.RandomNumberGenerator.GetBytes(16)).ToLowerInvariant(); if(!Uri.TryCreate(apiBase,UriKind.Absolute,out var address)||address.Scheme!="https"&&address.Scheme!="http"||address.UserInfo.Length!=0||address.Query.Length!=0||address.Fragment.Length!=0||!JournalProtocol.Valid(slug,"[a-z][a-z0-9-]*"))throw new JournalRefusal("Use the actual API base and closed guide slug"); if(string.IsNullOrWhiteSpace(job)||!JournalProtocol.Valid(workspace,"[1-9][0-9]*")||!JournalProtocol.Valid(inputFingerprint,"[0-9A-F]{64}"))throw new JournalRefusal("Use actual workspace, stable explicit job ID and exact fingerprint"); if(mode!="new"&&mode!="resume")throw new JournalRefusal("Choose new or resume for this local job"); var manifest=new List();foreach(var write in writes){ if(!JournalProtocol.Valid(write.Step,"[a-z][a-z0-9_-]*")||allowed.ContainsKey(write.Step)||!new[]{"POST","PATCH","DELETE"}.Contains(write.Method)||!JournalProtocol.Valid(write.Path,"/v1/[A-Za-z0-9_/-]+")||write.Path.Contains("//"))throw new JournalRefusal("Use a closed unique write manifest"); allowed.Add(write.Step,(write.Method,write.Path));manifest.AddRange(new[]{write.Step,write.Method,write.Path});} if(allowed.Count==0)throw new JournalRefusal("Only write workflows need a restart journal"); header=new List{"H","1",apiBase,workspace,slug,job,inputFingerprint,JournalProtocol.Digest(JournalProtocol.Strings(manifest))};JournalProtocol.Strings(header); try{lockStream=CreatePrivate(lockPath,FileAccess.ReadWrite,FileShare.Read);owned=true;} catch(IOException)when(File.Exists(lockPath)){throw new JournalRefusal("This journal is locked; do not overlap jobs or steal a stale lock");} try{ var token=Encoding.ASCII.GetBytes(owner);lockStream.Write(token);lockStream.Flush(true);creation=File.GetCreationTimeUtc(lockPath); if(File.Exists(path)&&(File.GetAttributes(path)&FileAttributes.ReparsePoint)!=0)throw new JournalRefusal("Choose a private regular journal file"); if(mode=="resume"&&!File.Exists(path))throw new JournalRefusal("Journal missing: stop and reconcile lost state before starting a new logical job"); if(mode=="new"&&File.Exists(path))throw new JournalRefusal("Journal exists; use resume for the same logical job"); if(mode=="new"){using var output=CreatePrivate(path,FileAccess.Write,FileShare.None);output.Write(JournalProtocol.Preamble);output.Write(JournalProtocol.Frame(header));output.Flush(true);} var records=JournalProtocol.Decode(File.ReadAllBytes(path));if(records.Count==0||!records[0].SequenceEqual(header))throw new JournalRefusal("Journal workspace/base/guide/job/input binding differs"); foreach(var record in records.Skip(1))Apply(record);if(intents.Keys.Any(step=>!savedValues.ContainsKey(step)))throw new JournalRefusal("Saved intent lacks ACK; stop and reconcile before retry"); }catch{Dispose();throw;} } void Apply(IReadOnlyList record) { if(record.Count==0)throw new JournalRefusal("Empty journal record"); if(record[0]=="I"){ if(record.Count!=6)throw new JournalRefusal("Invalid intent shape");var step=record[1];var method=record[2];var route=record[3];var fingerprint=record[4];var key=record[5]; if(!JournalProtocol.Valid(step,"[a-z][a-z0-9_-]*")||intents.ContainsKey(step)||!allowed.TryGetValue(step,out var expected)||expected!=(method,route)||!JournalProtocol.Valid(fingerprint,"[0-9A-F]{64}")||intents.Keys.Any(name=>!savedValues.ContainsKey(name)))throw new JournalRefusal("Invalid, future or repeated intent"); if(method=="POST"&&!JournalProtocol.Valid(key,"[0-9a-f]{32}")||method!="POST"&&key!="")throw new JournalRefusal("Invalid persisted action key"); intents.Add(step,new Dictionary{{"method",method},{"path",route},{"request_fingerprint",fingerprint},{"idempotency_key",key}}); }else if(record[0]=="A"){ if(record.Count<3||!JournalProtocol.Valid(record[2],"0|[1-9][0-9]*")||!long.TryParse(record[2],NumberStyles.None,CultureInfo.InvariantCulture,out var count)||count!=(record.Count-3L)/2||record.Count%2!=1||!intents.ContainsKey(record[1])||savedValues.ContainsKey(record[1]))throw new JournalRefusal("ACK without exactly one prior intent"); var names=record.Skip(3).Where((_,index)=>index%2==0).ToArray(); if(!names.SequenceEqual(names.Distinct(StringComparer.Ordinal).OrderBy(name=>name,StringComparer.Ordinal))||names.Any(name=>!JournalProtocol.Valid(name,"[a-z][a-z0-9_]*")||name=="api_key"||name=="exhibitday_api_key"))throw new JournalRefusal("ACK fields must be unique sorted secret-free identifiers"); var saved=new Dictionary(StringComparer.Ordinal);for(var i=0;i record) { RequireActive();var raw=JournalProtocol.Frame(record); try{using var output=new FileStream(path,FileMode.Append,FileAccess.Write,FileShare.None);output.Write(raw);output.Flush(true);} catch{tainted=true;throw;} } public bool Acknowledged(string step){RequireActive();return savedValues.ContainsKey(step);} public Dictionary Saved(string step){RequireActive();if(!savedValues.ContainsKey(step))throw new JournalRefusal("No acknowledged state exists");return new Dictionary(savedValues[step],StringComparer.Ordinal);} public Dictionary Begin(string step,string method,string route,string requestFingerprint) { RequireActive();if(intents.ContainsKey(step))throw new JournalRefusal("Never blindly repeat an existing action"); var key=method=="POST"?Convert.ToHexString(System.Security.Cryptography.RandomNumberGenerator.GetBytes(16)).ToLowerInvariant():""; var record=new[]{"I",step,method,route,requestFingerprint,key};var previous=new Dictionary>(intents,StringComparer.Ordinal);try{Apply(record);}finally{intents=previous;} Append(record);Apply(record);return new Dictionary(intents[step],StringComparer.Ordinal); } public void Acknowledge(string step,IReadOnlyDictionary saved) { RequireActive();var record=new List{"A",step,saved.Count.ToString(CultureInfo.InvariantCulture)};foreach(var name in saved.Keys.OrderBy(name=>name,StringComparer.Ordinal))record.AddRange(new[]{name,saved[name]}); var previous=new Dictionary>(savedValues,StringComparer.Ordinal);try{Apply(record);JournalProtocol.Strings(record);}finally{savedValues=previous;} Append(record);Apply(record); } public void Dispose() { if(!owned)return;if(tainted){lockStream.Dispose();lockStream=null;owned=false;return;} try{RequireActive();}catch{lockStream.Dispose();lockStream=null;owned=false;throw;} lockStream.Dispose();lockStream=null;owned=false;File.Delete(lockPath); } } static Dictionary JournalValues(JsonNode value) { if(value is not JsonObject fields)throw new JournalRefusal("Saved/fingerprint values need an explicit object"); var result=new Dictionary(StringComparer.Ordinal); foreach(var field in fields){if(field.Value is not JsonValue item || !item.TryGetValue(out var text) || text==null)throw new JournalRefusal("Saved/fingerprint values must be exact strings");result.Add(field.Key,text);}return result; } static JsonObject JournalObject(IReadOnlyDictionary fields){var result=new JsonObject();foreach(var field in fields)result.Add(field.Key,JsonValue.Create(field.Value));return result;} static void JournalAcknowledge(Journal job,string step,JsonNode saved)=>job.Acknowledge(step,JournalValues(saved)); static bool JournalAcknowledged(Journal job,string step)=>job.Acknowledged(step); static JsonNode JournalBegin(Journal job,string step,string method,string path,string requestFingerprint)=>JournalObject(job.Begin(step,method,path,requestFingerprint)); static string JournalFingerprint(JsonNode value)=>JournalProtocol.Fingerprint(JournalValues(value)); static JsonNode JournalSaved(Journal job,string step)=>JournalObject(job.Saved(step)); static Journal OpenJournal(string path,string apiBase,string workspace,string slug,string job,string inputFingerprint,JsonNode manifest,string mode) { if(manifest is not JsonArray rows)throw new JournalRefusal("A closed write manifest is required");var writes=new List<(string,string,string)>(); foreach(var row in rows){if(row is not JsonArray fields || fields.Count!=3)throw new JournalRefusal("Each write must bind its step/method/path");var values=fields.Select(value=>value is JsonValue item&&item.TryGetValue(out var text)&&text!=null?text:throw new JournalRefusal("Manifest values are exact strings")).ToArray();writes.Add((values[0],values[1],values[2]));} return new Journal(path,apiBase,workspace,slug,job,inputFingerprint,writes,mode); } static string Optional(string name,string fallback) { var value=Environment.GetEnvironmentVariable(name);return value==null||value==""?fallback:value; } static string PositiveId(string value) { if(string.IsNullOrEmpty(value)||value[0]=='0'||!value.All(c=>c>='0'&&c<='9')||!long.TryParse(value,NumberStyles.None,CultureInfo.InvariantCulture,out var id)||id<=0)throw new Exception("Use a positive record ID");return value; } static void PrintValue(object value) => Console.WriteLine(value is string text ? text : JsonSerializer.Serialize(value)); static void RequireCondition(bool value,string message) { if(!value)throw new Exception(message); } static string ResponseStatus(Result value)=>value.Status.ToString(CultureInfo.InvariantCulture); static JsonArray Items(JsonNode value) => value as JsonArray ?? throw new Exception("Expected a JSON array"); static JsonNode Single(JsonNode value){var rows=Items(value);if(rows.Count!=1)throw new Exception("Expected exactly one selected record");return rows[0];} static string Text(object value) => value==null?"":value is JsonNode node?Text(node):Convert.ToString(value,CultureInfo.InvariantCulture); internal static async Task Run() { var selected_event_id = PositiveId(Required("EXHIBITDAY_EVENT_ID")); var desired_dates = new JsonArray(new JsonObject { ["date"] = "2030-01-15", ["start_time"] = "09:00", ["end_time"] = "17:00", ["timezone"] = "America/New_York", ["description"] = "Exhibit hours" }, new JsonObject { ["date"] = "2030-01-16", ["start_time"] = "09:00", ["end_time"] = "16:00", ["timezone"] = "America/New_York", ["description"] = "Final exhibit day" }); var expected_dates = new JsonArray(new JsonObject { ["date"] = "2030-01-15", ["start_time"] = "09:00:00", ["end_time"] = "17:00:00", ["timezone"] = "America/New_York", ["description"] = "Exhibit hours" }, new JsonObject { ["date"] = "2030-01-16", ["start_time"] = "09:00:00", ["end_time"] = "16:00:00", ["timezone"] = "America/New_York", ["description"] = "Final exhibit day" }); var journal_path = Required("EXHIBITDAY_JOURNAL"); var stable_job_id = Required("EXHIBITDAY_JOB_ID"); var job_mode = Optional("EXHIBITDAY_JOB_MODE", "resume"); var workspace_response = await Call("workspace_binding", new JsonObject { }, null, null); RequireCondition(Equal(ResponseStatus(workspace_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement."); var owned_workspace = workspace_response.Body; var owned_workspace_id = PositiveId(Text(Field(owned_workspace, "id"))); var current_dates_response = await Call("read_group", new JsonObject { ["event_id"] = selected_event_id, ["filter_by_date_type_id"] = "1", ["$include_record_revision"] = "true" }, null, null); RequireCondition(Equal(ResponseStatus(current_dates_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement."); var current_dates_page = current_dates_response.Body; RequireCondition(Both(Equal(Text(Field(current_dates_page, "records_found")), "1"), Both(Equal(Text(Field(current_dates_page, "total_records")), "1"), Equal(Field(current_dates_page, "has_more"), false))), "Expected one complete selected Dates group."); var current_dates_group = Single(Field(current_dates_page, "list_data")); RequireCondition(Both(Equal(Text(Field(current_dates_group, "event_id")), selected_event_id), Equal(Text(Field(current_dates_group, "date_type_id")), "1")), "The Dates group does not match this Event and Exhibit Hall type."); var current_dates_revision = Text(Field(current_dates_group, "record_revision")); RequireCondition(IsPresent(current_dates_revision), "Read the actual selected group with its record_revision before replacing it."); var input_fingerprint = JournalFingerprint(new JsonObject { ["workflow_contract_sha256"] = "3422CE4F7C1283E1F77ACB98BE12123B5E2D0F078EB80BE01232C22F2941E85D", ["event_id"] = selected_event_id, ["date_type_id"] = "1", ["dates"] = "[{\"date\":\"2030-01-15\",\"start_time\":\"09:00:00\",\"end_time\":\"17:00:00\",\"timezone\":\"America/New_York\",\"description\":\"Exhibit hours\"},{\"date\":\"2030-01-16\",\"start_time\":\"09:00:00\",\"end_time\":\"16:00:00\",\"timezone\":\"America/New_York\",\"description\":\"Final exhibit day\"}]" }); using (var dates_job = OpenJournal(journal_path, "https://api.exhibitday.com/v1", owned_workspace_id, "dates-times-time-zones", stable_job_id, input_fingerprint, new JsonArray(new JsonArray("replace_group", "PATCH", "/v1/events/dates")), job_mode)) { if (JournalAcknowledged(dates_job, "replace_group")) { var saved_dates = JournalSaved(dates_job, "replace_group"); RequireCondition(Both(Equal(Text(Field(saved_dates, "event_id")), selected_event_id), Equal(Text(Field(saved_dates, "date_type_id")), "1")), "The saved ACK belongs to a different Event/group; stop and reconcile."); } else { var dates_patch = new JsonObject { ["event_id"] = selected_event_id, ["date_type_id"] = "1", ["dates"] = CopyNode(desired_dates), ["expected_revision"] = current_dates_revision }; var write_fingerprint = JournalFingerprint(new JsonObject { ["event_id"] = selected_event_id, ["date_type_id"] = "1", ["dates"] = "[{\"date\":\"2030-01-15\",\"start_time\":\"09:00:00\",\"end_time\":\"17:00:00\",\"timezone\":\"America/New_York\",\"description\":\"Exhibit hours\"},{\"date\":\"2030-01-16\",\"start_time\":\"09:00:00\",\"end_time\":\"16:00:00\",\"timezone\":\"America/New_York\",\"description\":\"Final exhibit day\"}]", ["expected_revision"] = current_dates_revision }); JournalBegin(dates_job, "replace_group", "PATCH", "/v1/events/dates", write_fingerprint); var saved_dates_response = await Call("replace_group", new JsonObject { }, dates_patch, null); RequireCondition(Equal(ResponseStatus(saved_dates_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement."); var dates_receipt = saved_dates_response.Body; var saved_dates_revision = Text(Field(dates_receipt, "record_revision")); RequireCondition(IsPresent(saved_dates_revision), "A checked Dates save ACK requires its actual returned revision."); JournalAcknowledge(dates_job, "replace_group", new JsonObject { ["event_id"] = selected_event_id, ["date_type_id"] = "1", ["record_revision"] = saved_dates_revision }); } var dates_readback_response = await Call("verify_group", new JsonObject { ["event_id"] = selected_event_id, ["filter_by_date_type_id"] = "1" }, null, null); RequireCondition(Equal(ResponseStatus(dates_readback_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement."); var dates_readback_page = dates_readback_response.Body; RequireCondition(Both(Equal(Text(Field(dates_readback_page, "records_found")), "1"), Both(Equal(Text(Field(dates_readback_page, "total_records")), "1"), Equal(Field(dates_readback_page, "has_more"), false))), "Readback must contain one complete selected group, without another page."); var dates_readback_group = Single(Field(dates_readback_page, "list_data")); RequireCondition(Both(Equal(Text(Field(dates_readback_group, "event_id")), selected_event_id), Equal(Text(Field(dates_readback_group, "date_type_id")), "1")), "Readback belongs to another Event or Dates group."); RequireCondition(DeepEqual(Field(dates_readback_group, "dates"), expected_dates), "The complete saved Dates list differs; review it instead of automatically restoring the example's dates."); PrintValue(new JsonObject { ["event_id"] = selected_event_id, ["date_type_id"] = "1", ["dates_verified"] = "true" }); } } static Task Main() => Run(); } ``` ```java // 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 SPEC = JSON.fromJson("{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"read_group\":{\"method\":\"GET\",\"path\":\"/events/dates\"},\"replace_group\":{\"method\":\"PATCH\",\"path\":\"/events/dates\"},\"verify_group\":{\"method\":\"GET\",\"path\":\"/events/dates\"}}}", Map.class); static final String API_KEY = headerKey(required("EXHIBITDAY_API_KEY")); static String headerKey(String value){if(value.chars().anyMatch(c->c<32||c>126))throw new IllegalArgumentException("Use the API key as one ASCII header value without control characters");return value;} static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).followRedirects(HttpClient.Redirect.NEVER).build(); interface RequestSender { HttpResponse send(HttpRequest request)throws IOException,InterruptedException; } static RequestSender SEND=request->CLIENT.send(request,HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); static class Result { int status; Object body; Map headers; String raw; Result(int s, Object b, Map h,String r) {status=s;body=b;headers=h;raw=r;} } // 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 obj(Object value) {return value==null?new LinkedHashMap<>(): (Map)value;} @SuppressWarnings("unchecked") static List list(Object value) {return value==null?Collections.emptyList():(List)value;} static Map map(Object... pairs) {Map result=new LinkedHashMap<>();for(int i=0;i query,Object body,String key) { Map route=obj(obj(SPEC.get("requests")).get(name));String method=text(route.get("method")); Map headers=map("Authorization","Bearer " + API_KEY,"Accept","application/json"); if(method.equals("POST")){if(key==null||key.isEmpty())throw new IllegalArgumentException("Persist a logical create key before sending POST");headers.put("Idempotency-Key",key);} 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); // 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. boolean resend=method.equals("GET"); 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 response; try {response=SEND.send(request.build());} 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();Object parsed=null; if(status!=304&&!response.body().isEmpty()) { try {parsed=JSON.fromJson(response.body(),Object.class);} catch(RuntimeException error){if(status<400)throw new IllegalStateException("Expected a JSON success response",error);} } Map 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=resend&&(status==429||status>=500); 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,response.body()); } throw new IllegalStateException("Retry limit reached"); } static boolean both(boolean left,boolean right){return left&&right;} static boolean deep_equal(Object left,Object right){return Objects.equals(left,right);} static boolean equal(Object left,Object right){return Objects.equals(left,right);} static Object field(Object value,String name){if(!(value instanceof Map)||!obj(value).containsKey(name))throw new IllegalStateException("Missing response field: "+name);return obj(value).get(name);} static boolean is_present(String value){return value!=null&&!value.isEmpty();} // Private client restart state only. No transport, application or JSON interpreter. static final class Journal implements AutoCloseable { public static final class Refusal extends IllegalStateException { Refusal(String message){super(message);} } public static final byte[] PREAMBLE="EXHIBITDAY-GUIDE-JOURNAL 1\n".getBytes(StandardCharsets.US_ASCII); static boolean valid(String value,String pattern){return value!=null&&value.matches(pattern);} static byte[] utf8(String value)throws java.nio.charset.CharacterCodingException { if(value==null)throw new Refusal("Journal fields are exact strings"); java.nio.ByteBuffer encoded=StandardCharsets.UTF_8.newEncoder().onMalformedInput(java.nio.charset.CodingErrorAction.REPORT).onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT).encode(java.nio.CharBuffer.wrap(value));byte[] raw=new byte[encoded.remaining()];encoded.get(raw);return raw; } static String ascii(byte[] raw,int start,int count){for(int i=start;i127)throw new Refusal("Journal framing must be canonical ASCII");return new String(raw,start,count,StandardCharsets.US_ASCII);} public static byte[] strings(Collection values)throws IOException { ByteArrayOutputStream output=new ByteArrayOutputStream();for(String value:values){byte[] raw=utf8(value);output.write((raw.length+":").getBytes(StandardCharsets.US_ASCII));output.write(raw);}return output.toByteArray(); } static int find(byte[] raw,int offset,int value){for(int i=offset;i readStrings(byte[] raw)throws IOException { List values=new ArrayList<>();int offset=0; while(offset0)throw new Refusal("Incomplete journal string");int count=size.intValueExact(); values.add(StandardCharsets.UTF_8.newDecoder().onMalformedInput(java.nio.charset.CodingErrorAction.REPORT).onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT).decode(java.nio.ByteBuffer.wrap(raw,offset,count)).toString());offset+=count;} return values; } public static String digest(byte[] raw){try{byte[] hash=java.security.MessageDigest.getInstance("SHA-256").digest(raw);StringBuilder text=new StringBuilder();for(byte item:hash)text.append(String.format(Locale.ROOT,"%02X",item&255));return text.toString();}catch(java.security.NoSuchAlgorithmException error){throw new IllegalStateException(error);}} public static String fingerprint(Map pairs)throws IOException { List values=new ArrayList<>();for(String name:new TreeSet<>(pairs.keySet())){if(!valid(name,"[A-Za-z0-9_.-]+")||Arrays.asList("api_key","exhibitday_api_key").contains(name.toLowerCase(Locale.ROOT)))throw new Refusal("Use explicit secret-free fingerprint names");values.add(name);values.add(pairs.get(name));}return digest(strings(values)); } public static byte[] frame(Collection values)throws IOException {byte[] payload=strings(values);ByteArrayOutputStream output=new ByteArrayOutputStream();output.write((payload.length+" "+digest(payload)+"\n").getBytes(StandardCharsets.US_ASCII));output.write(payload);output.write(10);return output.toByteArray();} public static List> decode(byte[] raw)throws IOException { if(raw.length> records=new ArrayList<>(); while(offset=0)throw new Refusal("Incomplete frame; reconcile before retry");int count=size.intValueExact();byte[] payload=Arrays.copyOfRange(raw,offset,offset+count);offset+=count; if(raw[offset]!=10||!digest(payload).equals(fields[1]))throw new Refusal("Journal integrity failed; reconcile before retry");records.add(readStrings(payload));offset++;}return records; } static void writeAll(java.nio.channels.FileChannel target,byte[] raw)throws IOException {java.nio.ByteBuffer data=java.nio.ByteBuffer.wrap(raw);while(data.hasRemaining())if(target.write(data)<=0)throw new IOException("Journal write did not advance");} static java.nio.channels.FileChannel createPrivate(Path path,OpenOption... options)throws IOException { java.nio.file.attribute.FileAttribute[] attributes=FileSystems.getDefault().supportedFileAttributeViews().contains("posix")?new java.nio.file.attribute.FileAttribute[]{java.nio.file.attribute.PosixFilePermissions.asFileAttribute(java.nio.file.attribute.PosixFilePermissions.fromString("rw-------"))}:new java.nio.file.attribute.FileAttribute[0]; return java.nio.channels.FileChannel.open(path,new HashSet<>(Arrays.asList(options)),attributes); } final Path path,lockPath;final String owner;final List header; final Map> allowed=new LinkedHashMap<>();Map> intents=new LinkedHashMap<>(),savedValues=new LinkedHashMap<>(); java.nio.channels.FileChannel lock;boolean owned,tainted;Object fileKey;java.nio.file.attribute.FileTime creation; public Journal(Path path,String apiBase,String workspace,String slug,String job,String inputFingerprint,List> writes)throws IOException {this(path,apiBase,workspace,slug,job,inputFingerprint,writes,"resume");} public Journal(Path path,String apiBase,String workspace,String slug,String job,String inputFingerprint,List> writes,String mode)throws IOException { this.path=path;lockPath=Path.of(path.toString()+".lock");byte[] random=new byte[16];new java.security.SecureRandom().nextBytes(random);StringBuilder token=new StringBuilder();for(byte item:random)token.append(String.format(Locale.ROOT,"%02x",item&255));owner=token.toString(); URI address=URI.create(apiBase);if(!Arrays.asList("https","http").contains(address.getScheme())||address.getHost()==null||address.getUserInfo()!=null||address.getRawQuery()!=null||address.getRawFragment()!=null||!valid(slug,"[a-z][a-z0-9-]*"))throw new Refusal("Use actual API base and closed guide slug"); if(job==null||job.trim().isEmpty()||!valid(workspace,"[1-9][0-9]*")||!valid(inputFingerprint,"[0-9A-F]{64}"))throw new Refusal("Use actual workspace, stable explicit job ID and exact fingerprint"); if(!Arrays.asList("new","resume").contains(mode))throw new Refusal("Choose new or resume for this local job"); List manifest=new ArrayList<>();for(List item:writes){if(item.size()!=3)throw new Refusal("Invalid write manifest shape");String step=item.get(0),method=item.get(1),route=item.get(2); if(!valid(step,"[a-z][a-z0-9_-]*")||allowed.containsKey(step)||!Arrays.asList("POST","PATCH","DELETE").contains(method)||!valid(route,"/v1/[A-Za-z0-9_/-]+")||route.contains("//"))throw new Refusal("Use a closed unique write manifest");allowed.put(step,List.of(method,route));manifest.addAll(item);} if(allowed.isEmpty())throw new Refusal("Only write workflows need a restart journal");header=List.of("H","1",apiBase,workspace,slug,job,inputFingerprint,digest(strings(manifest)));strings(header); try{lock=createPrivate(lockPath,StandardOpenOption.CREATE_NEW,StandardOpenOption.READ,StandardOpenOption.WRITE);owned=true;}catch(FileAlreadyExistsException error){throw new Refusal("This journal is locked; do not overlap jobs or steal a stale lock");} try{writeAll(lock,owner.getBytes(StandardCharsets.US_ASCII));lock.force(true);java.nio.file.attribute.BasicFileAttributes identity=Files.readAttributes(lockPath,java.nio.file.attribute.BasicFileAttributes.class,LinkOption.NOFOLLOW_LINKS);fileKey=identity.fileKey();creation=identity.creationTime(); if(Files.isSymbolicLink(path))throw new Refusal("Choose a private regular journal file"); if(mode.equals("resume")&&!Files.exists(path))throw new Refusal("Journal missing: stop and reconcile lost state before starting a new logical job"); if(mode.equals("new")&&Files.exists(path))throw new Refusal("Journal exists; use resume for the same logical job"); if(mode.equals("new")){try(java.nio.channels.FileChannel target=createPrivate(path,StandardOpenOption.CREATE_NEW,StandardOpenOption.WRITE)){writeAll(target,PREAMBLE);writeAll(target,frame(header));target.force(true);}} List> records=decode(Files.readAllBytes(path));if(records.isEmpty()||!records.get(0).equals(header))throw new Refusal("Journal workspace/base/guide/job/input binding differs");for(List record:records.subList(1,records.size()))apply(record); if(intents.keySet().stream().anyMatch(step->!savedValues.containsKey(step)))throw new Refusal("Saved intent lacks ACK; stop and reconcile before retry"); }catch(IOException|RuntimeException error){close();throw error;} } void apply(List record){ if(record.isEmpty())throw new Refusal("Empty journal record"); if(record.get(0).equals("I")){ if(record.size()!=6)throw new Refusal("Invalid intent shape");String step=record.get(1),method=record.get(2),route=record.get(3),fingerprint=record.get(4),key=record.get(5); if(!valid(step,"[a-z][a-z0-9_-]*")||intents.containsKey(step)||!List.of(method,route).equals(allowed.get(step))||!valid(fingerprint,"[0-9A-F]{64}")||intents.keySet().stream().anyMatch(name->!savedValues.containsKey(name)))throw new Refusal("Invalid, future or repeated intent"); if(method.equals("POST")&&!valid(key,"[0-9a-f]{32}")||!method.equals("POST")&&!key.isEmpty())throw new Refusal("Invalid persisted action key");intents.put(step,new LinkedHashMap<>(Map.of("method",method,"path",route,"request_fingerprint",fingerprint,"idempotency_key",key))); }else if(record.get(0).equals("A")){ if(record.size()<3||!valid(record.get(2),"0|[1-9][0-9]*")||!new java.math.BigInteger(record.get(2)).multiply(java.math.BigInteger.TWO).equals(java.math.BigInteger.valueOf(record.size()-3))||!intents.containsKey(record.get(1))||savedValues.containsKey(record.get(1)))throw new Refusal("ACK without exactly one prior intent"); List names=new ArrayList<>();for(int i=3;i(new TreeSet<>(names)))||names.stream().anyMatch(name->!valid(name,"[a-z][a-z0-9_]*")||name.equals("api_key")||name.equals("exhibitday_api_key")))throw new Refusal("ACK fields must be unique sorted secret-free identifiers"); Map saved=new LinkedHashMap<>();for(int i=0;i record)throws IOException {requireActive();byte[] raw=frame(record);try(java.nio.channels.FileChannel target=java.nio.channels.FileChannel.open(path,StandardOpenOption.WRITE,StandardOpenOption.APPEND)){writeAll(target,raw);target.force(true);}catch(IOException|RuntimeException error){tainted=true;throw error;}} public boolean acknowledged(String step)throws IOException{requireActive();return savedValues.containsKey(step);} public Map saved(String step)throws IOException{requireActive();if(!savedValues.containsKey(step))throw new Refusal("No acknowledged state exists");return new LinkedHashMap<>(savedValues.get(step));} public Map begin(String step,String method,String route,String requestFingerprint)throws IOException { requireActive();if(intents.containsKey(step))throw new Refusal("Never blindly repeat an existing action");String key="";if(method.equals("POST")){byte[] bytes=new byte[16];new java.security.SecureRandom().nextBytes(bytes);StringBuilder text=new StringBuilder();for(byte item:bytes)text.append(String.format(Locale.ROOT,"%02x",item&255));key=text.toString();} List record=List.of("I",step,method,route,requestFingerprint,key);Map> previous=new LinkedHashMap<>(intents);try{apply(record);}finally{intents=previous;}append(record);apply(record);return new LinkedHashMap<>(intents.get(step)); } public void acknowledge(String step,Map saved)throws IOException { requireActive();List record=new ArrayList<>(List.of("A",step,Integer.toString(saved.size())));for(String name:new TreeSet<>(saved.keySet())){record.add(name);record.add(saved.get(name));} Map> previous=new LinkedHashMap<>(savedValues);try{apply(record);strings(record);}finally{savedValues=previous;}append(record);apply(record); } public void close()throws IOException { if(!owned)return;if(tainted){lock.close();lock=null;owned=false;return;} try{requireActive();}catch(IOException|RuntimeException error){lock.close();lock=null;owned=false;throw error;}lock.close();lock=null;owned=false;Files.delete(lockPath); } } static Map journal_values(Object value){if(!(value instanceof Map))throw new Journal.Refusal("Saved/fingerprint values need an explicit object");Map result=new LinkedHashMap<>();for(Map.Entry field:((Map)value).entrySet()){if(!(field.getKey() instanceof String)||!(field.getValue() instanceof String))throw new Journal.Refusal("Saved/fingerprint values must be exact strings");result.put((String)field.getKey(),(String)field.getValue());}return result;} static void journal_acknowledge(Journal job,String step,Object saved)throws IOException{job.acknowledge(step,journal_values(saved));} static boolean journal_acknowledged(Journal job,String step)throws IOException{return job.acknowledged(step);} static Object journal_begin(Journal job,String step,String method,String path,String requestFingerprint)throws IOException{return new LinkedHashMap(job.begin(step,method,path,requestFingerprint));} static String journal_fingerprint(Object value)throws IOException{return Journal.fingerprint(journal_values(value));} static Object journal_saved(Journal job,String step)throws IOException{return new LinkedHashMap(job.saved(step));} static Journal open_journal(String path,String base,String workspace,String slug,String job,String inputFingerprint,Object manifest,String mode)throws IOException { if(!(manifest instanceof List))throw new Journal.Refusal("A closed write manifest is required");List> writes=new ArrayList<>();for(Object row:(List)manifest){if(!(row instanceof List)||((List)row).size()!=3)throw new Journal.Refusal("Each write must bind step/method/path");List fields=new ArrayList<>();for(Object value:(List)row){if(!(value instanceof String))throw new Journal.Refusal("Manifest values are exact strings");fields.add((String)value);}writes.add(fields);}return new Journal(Path.of(path),base,workspace,slug,job,inputFingerprint,writes,mode); } static String optional(String name,String fallback){String value=System.getenv(name);return value==null||value.isEmpty()?fallback:value;} static String positive_id(String value){try{if(value==null||!value.matches("[1-9][0-9]*")||Long.parseLong(value)<=0)throw new IllegalArgumentException();return value;}catch(RuntimeException error){throw new IllegalArgumentException("Use a positive record ID");}} static void print_value(Object value){try{String text=value instanceof String?(String)value:JSON.toJson(value);System.out.write((text+"\n").getBytes(StandardCharsets.UTF_8));}catch(IOException error){throw new UncheckedIOException(error);}} static void require_condition(boolean value,String message){if(!value)throw new IllegalStateException(message);} static String response_status(Result value){return Integer.toString(value.status);} static List items(Object value){if(!(value instanceof List))throw new IllegalStateException("Expected a JSON array");return list(value);} static Object single(Object value){List rows=items(value);if(rows.size()!=1)throw new IllegalStateException("Expected exactly one selected record");return rows.get(0);} static void run()throws Exception { String selected_event_id = positive_id(required("EXHIBITDAY_EVENT_ID")); List desired_dates = Arrays.asList(map("date", "2030-01-15", "start_time", "09:00", "end_time", "17:00", "timezone", "America/New_York", "description", "Exhibit hours"), map("date", "2030-01-16", "start_time", "09:00", "end_time", "16:00", "timezone", "America/New_York", "description", "Final exhibit day")); List expected_dates = Arrays.asList(map("date", "2030-01-15", "start_time", "09:00:00", "end_time", "17:00:00", "timezone", "America/New_York", "description", "Exhibit hours"), map("date", "2030-01-16", "start_time", "09:00:00", "end_time", "16:00:00", "timezone", "America/New_York", "description", "Final exhibit day")); String journal_path = required("EXHIBITDAY_JOURNAL"); String stable_job_id = required("EXHIBITDAY_JOB_ID"); String job_mode = optional("EXHIBITDAY_JOB_MODE", "resume"); Result workspace_response = call("workspace_binding", map(), null, null); require_condition(equal(response_status(workspace_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement."); Object owned_workspace = workspace_response.body; String owned_workspace_id = positive_id(text(field(owned_workspace, "id"))); Result current_dates_response = call("read_group", map("event_id", selected_event_id, "filter_by_date_type_id", "1", "$include_record_revision", "true"), null, null); require_condition(equal(response_status(current_dates_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement."); Object current_dates_page = current_dates_response.body; require_condition(both(equal(text(field(current_dates_page, "records_found")), "1"), both(equal(text(field(current_dates_page, "total_records")), "1"), equal(field(current_dates_page, "has_more"), false))), "Expected one complete selected Dates group."); Object current_dates_group = single(field(current_dates_page, "list_data")); require_condition(both(equal(text(field(current_dates_group, "event_id")), selected_event_id), equal(text(field(current_dates_group, "date_type_id")), "1")), "The Dates group does not match this Event and Exhibit Hall type."); String current_dates_revision = text(field(current_dates_group, "record_revision")); require_condition(is_present(current_dates_revision), "Read the actual selected group with its record_revision before replacing it."); String input_fingerprint = journal_fingerprint(map("workflow_contract_sha256", "3422CE4F7C1283E1F77ACB98BE12123B5E2D0F078EB80BE01232C22F2941E85D", "event_id", selected_event_id, "date_type_id", "1", "dates", "[{\"date\":\"2030-01-15\",\"start_time\":\"09:00:00\",\"end_time\":\"17:00:00\",\"timezone\":\"America/New_York\",\"description\":\"Exhibit hours\"},{\"date\":\"2030-01-16\",\"start_time\":\"09:00:00\",\"end_time\":\"16:00:00\",\"timezone\":\"America/New_York\",\"description\":\"Final exhibit day\"}]")); try (Journal dates_job = open_journal(journal_path, "https://api.exhibitday.com/v1", owned_workspace_id, "dates-times-time-zones", stable_job_id, input_fingerprint, Arrays.asList(Arrays.asList("replace_group", "PATCH", "/v1/events/dates")), job_mode)) { if (journal_acknowledged(dates_job, "replace_group")) { Object saved_dates = journal_saved(dates_job, "replace_group"); require_condition(both(equal(text(field(saved_dates, "event_id")), selected_event_id), equal(text(field(saved_dates, "date_type_id")), "1")), "The saved ACK belongs to a different Event/group; stop and reconcile."); } else { Object dates_patch = map("event_id", selected_event_id, "date_type_id", "1", "dates", desired_dates, "expected_revision", current_dates_revision); String write_fingerprint = journal_fingerprint(map("event_id", selected_event_id, "date_type_id", "1", "dates", "[{\"date\":\"2030-01-15\",\"start_time\":\"09:00:00\",\"end_time\":\"17:00:00\",\"timezone\":\"America/New_York\",\"description\":\"Exhibit hours\"},{\"date\":\"2030-01-16\",\"start_time\":\"09:00:00\",\"end_time\":\"16:00:00\",\"timezone\":\"America/New_York\",\"description\":\"Final exhibit day\"}]", "expected_revision", current_dates_revision)); journal_begin(dates_job, "replace_group", "PATCH", "/v1/events/dates", write_fingerprint); Result saved_dates_response = call("replace_group", map(), dates_patch, null); require_condition(equal(response_status(saved_dates_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement."); Object dates_receipt = saved_dates_response.body; String saved_dates_revision = text(field(dates_receipt, "record_revision")); require_condition(is_present(saved_dates_revision), "A checked Dates save ACK requires its actual returned revision."); journal_acknowledge(dates_job, "replace_group", map("event_id", selected_event_id, "date_type_id", "1", "record_revision", saved_dates_revision)); } Result dates_readback_response = call("verify_group", map("event_id", selected_event_id, "filter_by_date_type_id", "1"), null, null); require_condition(equal(response_status(dates_readback_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement."); Object dates_readback_page = dates_readback_response.body; require_condition(both(equal(text(field(dates_readback_page, "records_found")), "1"), both(equal(text(field(dates_readback_page, "total_records")), "1"), equal(field(dates_readback_page, "has_more"), false))), "Readback must contain one complete selected group, without another page."); Object dates_readback_group = single(field(dates_readback_page, "list_data")); require_condition(both(equal(text(field(dates_readback_group, "event_id")), selected_event_id), equal(text(field(dates_readback_group, "date_type_id")), "1")), "Readback belongs to another Event or Dates group."); require_condition(deep_equal(field(dates_readback_group, "dates"), expected_dates), "The complete saved Dates list differs; review it instead of automatically restoring the example's dates."); print_value(map("event_id", selected_event_id, "date_type_id", "1", "dates_verified", "true")); } } public static void main(String[] args)throws Exception {run();} } ``` ```php $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, ?string $key = null): array { global $spec, $apiKey, $transport; $route = $spec['requests'][$name]; $headers = ['Authorization' => 'Bearer ' . $apiKey, 'Accept' => 'application/json']; if ($route['method'] === 'POST') { if ($key === null || $key === '') throw new RuntimeException('Persist a logical create key before sending POST'); $headers['Idempotency-Key'] = $key; // 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); // 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 = 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 = $resend && ($status === 429 || $status >= 500); 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, 'raw' => $raw]; } throw new RuntimeException('Retry limit reached'); } $transport = Closure::fromCallable('nativeTransport'); function both(bool $left,bool $right):bool{return $left&&$right;} function deep_equal(mixed $left,mixed $right):bool { if(is_object($left))$left=get_object_vars($left);if(is_object($right))$right=get_object_vars($right); if(gettype($left)!==gettype($right))return false; if(!is_array($left))return$left===$right; if(array_is_list($left)!==array_is_list($right)||count($left)!==count($right))return false; foreach($left as$key=>$value)if(!array_key_exists($key,$right)||!deep_equal($value,$right[$key]))return false; return true; } function equal(mixed $left,mixed $right):bool{return $left===$right;} function field(mixed $value,string $name):mixed{if(!is_array($value)||!array_key_exists($name,$value))throw new RuntimeException("Missing response field: ".$name);return $value[$name];} function is_present(?string $value):bool{return $value!==null&&$value!=="";} final class JournalRefusal extends RuntimeException {} final class JournalProtocol { public const PREAMBLE="EXHIBITDAY-GUIDE-JOURNAL 1\n"; public static function utf8(mixed $value):string {if(!is_string($value)||preg_match('//u',$value)!==1)throw new JournalRefusal('Journal fields must be exact valid UTF8 strings');return$value;} public static function strings(array $values):string {$raw='';foreach($values as$value){$item=self::utf8($value);$raw.=strlen($item).':'.$item;}return$raw;} private static function length(string $text,int $remaining):int {if(!preg_match('/\A(?:0|[1-9][0-9]*)\z/',$text))throw new JournalRefusal('Noncanonical string length');$maximum=(string)$remaining;if(strlen($text)>strlen($maximum)||(strlen($text)===strlen($maximum)&&strcmp($text,$maximum)>0))throw new JournalRefusal('Incomplete journal string/frame');return(int)$text;} public static function readStrings(string $raw):array {$values=[];$offset=0;while($offset=strlen($raw)-$offset)throw new JournalRefusal('Incomplete frame; reconcile before retry');$payload=substr($raw,$offset,$size);$offset+=$size;if($raw[$offset]!=="\n"||self::digest($payload)!==$match[2])throw new JournalRefusal('Journal integrity failed; reconcile before retry');$records[]=self::readStrings($payload);$offset++;}return$records;} public static function writeAll($file,string $raw):void {$offset=0;while($offsetpath=$path;$this->lockPath=$path.'.lock';$this->owner=bin2hex(random_bytes(16));$address=parse_url($base); if($address===false||!in_array($address['scheme']??null,['https','http'],true)||!isset($address['host'])||isset($address['user'])||isset($address['pass'])||isset($address['query'])||isset($address['fragment'])||!preg_match('/\A[a-z][a-z0-9-]*\z/',$slug))throw new JournalRefusal('Use actual API base and closed guide slug'); if(trim($job)===''||!preg_match('/\A[1-9][0-9]*\z/',$workspace)||!preg_match('/\A[0-9A-F]{64}\z/',$inputFingerprint))throw new JournalRefusal('Use actual workspace, stable explicit job ID and exact fingerprint'); if(!in_array($mode,['new','resume'],true))throw new JournalRefusal('Choose new or resume for this local job'); $manifest=[];foreach($writes as$write){if(!is_array($write)||!array_is_list($write)||count($write)!==3)throw new JournalRefusal('Invalid write manifest');[$step,$method,$route]=$write; if(!is_string($step)||!preg_match('/\A[a-z][a-z0-9_-]*\z/',$step)||isset($this->allowed[$step])||!in_array($method,['POST','PATCH','DELETE'],true)||!is_string($route)||!preg_match('~\A/v1/[A-Za-z0-9_/-]+\z~',$route)||str_contains($route,'//'))throw new JournalRefusal('Use a closed unique write manifest');$this->allowed[$step]=[$method,$route];array_push($manifest,$step,$method,$route);} if($this->allowed===[])throw new JournalRefusal('Only write workflows need restart journal');$this->header=['H','1',$base,$workspace,$slug,$job,$inputFingerprint,JournalProtocol::digest(JournalProtocol::strings($manifest))];JournalProtocol::strings($this->header); $this->file=JournalProtocol::createPrivate($this->lockPath);$this->owned=true; try{ JournalProtocol::writeAll($this->file,$this->owner);$identity=fstat($this->file);if($identity===false)throw new JournalRefusal('Cannot bind acquired lock identity');$this->identity=$identity; clearstatcache(true,$path);if(is_link($path))throw new JournalRefusal('Choose private regular journal file'); $exists=file_exists($path);if($mode==='resume'&&!$exists)throw new JournalRefusal('Journal missing: stop and reconcile lost state before starting a new logical job');if($mode==='new'&&$exists)throw new JournalRefusal('Journal exists; use resume for the same logical job'); if($mode==='new'){$target=JournalProtocol::createPrivate($path);try{JournalProtocol::writeAll($target,JournalProtocol::PREAMBLE.JournalProtocol::frame($this->header));}finally{fclose($target);}} $raw=file_get_contents($path);if($raw===false)throw new JournalRefusal('Cannot read journal');$records=JournalProtocol::decode($raw);if($records===[]||$records[0]!==$this->header)throw new JournalRefusal('Journal workspace/base/guide/job/input binding differs');foreach(array_slice($records,1)as$record)$this->apply($record); if(array_diff(array_keys($this->intents),array_keys($this->savedValues))!==[])throw new JournalRefusal('Saved intent lacks ACK; stop and reconcile before retry'); }catch(Throwable $error){$this->close();throw$error;} } private function apply(array $record):void { if(($record[0]??null)==='I'){ if(count($record)!==6)throw new JournalRefusal('Invalid intent shape');[,$step,$method,$route,$fingerprint,$key]=$record; if(!preg_match('/\A[a-z][a-z0-9_-]*\z/',$step)||isset($this->intents[$step])||($this->allowed[$step]??null)!==[$method,$route]||!preg_match('/\A[0-9A-F]{64}\z/',$fingerprint)||array_diff(array_keys($this->intents),array_keys($this->savedValues))!==[])throw new JournalRefusal('Invalid, future or repeated intent'); if(($method==='POST'&&!preg_match('/\A[0-9a-f]{32}\z/',$key))||($method!=='POST'&&$key!==''))throw new JournalRefusal('Invalid persisted action key');$this->intents[$step]=['method'=>$method,'path'=>$route,'request_fingerprint'=>$fingerprint,'idempotency_key'=>$key]; }elseif(($record[0]??null)==='A'){ if(count($record)<3)throw new JournalRefusal('Invalid ACK shape');[,$step,$count]=$record;$pairs=array_slice($record,3); if(!preg_match('/\A(?:0|[1-9][0-9]*)\z/',$count)||(string)intdiv(count($pairs),2)!==$count||count($pairs)%2!==0||!isset($this->intents[$step])||isset($this->savedValues[$step]))throw new JournalRefusal('ACK without exactly one prior intent'); $names=[];for($i=0;$i$name){if(!preg_match('/\A[a-z][a-z0-9_]*\z/',$name)||in_array($name,['api_key','exhibitday_api_key'],true))throw new JournalRefusal('Use secret-free ACK field names');$saved[$name]=$pairs[$i*2+1];}$this->savedValues[$step]=$saved; }else throw new JournalRefusal('Unknown journal transition'); } private function requireActive():void { if(!$this->owned||$this->file===null||$this->tainted)throw new JournalRefusal('Journal closed or IO outcome needs reconciliation');clearstatcache(true,$this->lockPath);$current=@lstat($this->lockPath);$token=@file_get_contents($this->lockPath); if($current===false||($current['dev']??null)!==($this->identity['dev']??null)||($current['ino']??null)!==($this->identity['ino']??null)||$token!==$this->owner)throw new JournalRefusal('Journal lock replaced; stop without deleting it'); } private function append(array $record):void { $this->requireActive();$raw=JournalProtocol::frame($record);$target=null; try{$target=@fopen($this->path,'ab');if($target===false)throw new JournalRefusal('Cannot append journal; stop and reconcile');JournalProtocol::writeAll($target,$raw);}catch(Throwable $error){$this->tainted=true;throw$error;}finally{if(is_resource($target))fclose($target);} } public function acknowledged(string $step):bool{$this->requireActive();return isset($this->savedValues[$step]);} public function saved(string $step):array{$this->requireActive();if(!isset($this->savedValues[$step]))throw new JournalRefusal('No acknowledged state exists');return$this->savedValues[$step];} public function beginAction(string $step,string $method,string $route,string $requestFingerprint):array { $this->requireActive();if(isset($this->intents[$step]))throw new JournalRefusal('Never blindly repeat an existing action');$key=$method==='POST'?bin2hex(random_bytes(16)):'';$record=['I',$step,$method,$route,$requestFingerprint,$key];$previous=$this->intents;try{$this->apply($record);}finally{$this->intents=$previous;}$this->append($record);$this->apply($record);return$this->intents[$step]; } public function acknowledge(string $step,array $saved):void { $this->requireActive();$record=['A',$step,(string)count($saved)];$names=array_keys($saved);sort($names,SORT_STRING);foreach($names as$name){$record[]=$name;$record[]=$saved[$name];}$previous=$this->savedValues;try{$this->apply($record);JournalProtocol::strings($record);}finally{$this->savedValues=$previous;}$this->append($record);$this->apply($record); } public function close():void { if(!$this->owned)return;if($this->tainted){fclose($this->file);$this->file=null;$this->owned=false;return;} try{$this->requireActive();}catch(Throwable $error){fclose($this->file);$this->file=null;$this->owned=false;throw$error;}fclose($this->file);$this->file=null;$this->owned=false;if(!unlink($this->lockPath))throw new JournalRefusal('Could not release owned journal lock'); } } function journal_values(mixed $value):array{if(!is_object($value))throw new JournalRefusal('Saved/fingerprint values need an explicit object');$result=get_object_vars($value);foreach($result as$name=>$item)if(!is_string($name)||!is_string($item))throw new JournalRefusal('Saved/fingerprint values must be exact strings');return$result;} function journal_acknowledge(GuideJournal $job,string $step,mixed $saved):void{$job->acknowledge($step,journal_values($saved));} function journal_acknowledged(GuideJournal $job,string $step):bool{return $job->acknowledged($step);} function journal_begin(GuideJournal $job,string $step,string $method,string $path,string $requestFingerprint):array{return $job->beginAction($step,$method,$path,$requestFingerprint);} function journal_fingerprint(mixed $value):string{return JournalProtocol::fingerprint(journal_values($value));} function journal_saved(GuideJournal $job,string $step):array{return $job->saved($step);} function open_journal(string $path,string $base,string $workspace,string $slug,string $job,string $inputFingerprint,array $writes,string $mode):GuideJournal{return new GuideJournal($path,$base,$workspace,$slug,$job,$inputFingerprint,$writes,$mode);} function positive_id(string $value):string{if(!preg_match("/^[1-9][0-9]*$/D",$value)||strlen($value)>19||(strlen($value)===19&&strcmp($value,"9223372036854775807")>0))throw new RuntimeException("Use a positive record ID");return $value;} function print_value(mixed $value):void{echo (is_string($value)?$value:json_encode($value,JSON_THROW_ON_ERROR))."\n";} function require_condition(bool $value,string $message):void{if(!$value)throw new RuntimeException($message);} function response_status(array $value):string{return(string)$value["status"];} function items(mixed $value):array{if(!is_array($value)||!array_is_list($value))throw new RuntimeException("Expected a JSON array");return $value;} function single(mixed $value):mixed{$rows=items($value);if(count($rows)!==1)throw new RuntimeException('Expected exactly one selected record');return$rows[0];} function text(mixed $value):string{if($value===null)return "";if(is_string($value))return $value;if(is_bool($value))return $value?"true":"false";if(is_int($value))return (string)$value;throw new RuntimeException("Expected a scalar response value");} function main():void { $selected_event_id = positive_id(required('EXHIBITDAY_EVENT_ID')); $desired_dates = [(object)['date' => '2030-01-15', 'start_time' => '09:00', 'end_time' => '17:00', 'timezone' => 'America/New_York', 'description' => 'Exhibit hours'], (object)['date' => '2030-01-16', 'start_time' => '09:00', 'end_time' => '16:00', 'timezone' => 'America/New_York', 'description' => 'Final exhibit day']]; $expected_dates = [(object)['date' => '2030-01-15', 'start_time' => '09:00:00', 'end_time' => '17:00:00', 'timezone' => 'America/New_York', 'description' => 'Exhibit hours'], (object)['date' => '2030-01-16', 'start_time' => '09:00:00', 'end_time' => '16:00:00', 'timezone' => 'America/New_York', 'description' => 'Final exhibit day']]; $journal_path = required('EXHIBITDAY_JOURNAL'); $stable_job_id = required('EXHIBITDAY_JOB_ID'); $job_mode = optional('EXHIBITDAY_JOB_MODE', 'resume'); $workspace_response = call('workspace_binding', [], null, null); require_condition(equal(response_status($workspace_response), '200'), 'Expected the endpoint\'s documented HTTP200 acknowledgement.'); $owned_workspace = $workspace_response["body"]; $owned_workspace_id = positive_id(text(field($owned_workspace, 'id'))); $current_dates_response = call('read_group', ['event_id' => $selected_event_id, 'filter_by_date_type_id' => '1', '$include_record_revision' => 'true'], null, null); require_condition(equal(response_status($current_dates_response), '200'), 'Expected the endpoint\'s documented HTTP200 acknowledgement.'); $current_dates_page = $current_dates_response["body"]; require_condition(both(equal(text(field($current_dates_page, 'records_found')), '1'), both(equal(text(field($current_dates_page, 'total_records')), '1'), equal(field($current_dates_page, 'has_more'), false))), 'Expected one complete selected Dates group.'); $current_dates_group = single(field($current_dates_page, 'list_data')); require_condition(both(equal(text(field($current_dates_group, 'event_id')), $selected_event_id), equal(text(field($current_dates_group, 'date_type_id')), '1')), 'The Dates group does not match this Event and Exhibit Hall type.'); $current_dates_revision = text(field($current_dates_group, 'record_revision')); require_condition(is_present($current_dates_revision), 'Read the actual selected group with its record_revision before replacing it.'); $input_fingerprint = journal_fingerprint((object)['workflow_contract_sha256' => '3422CE4F7C1283E1F77ACB98BE12123B5E2D0F078EB80BE01232C22F2941E85D', 'event_id' => $selected_event_id, 'date_type_id' => '1', 'dates' => '[{"date":"2030-01-15","start_time":"09:00:00","end_time":"17:00:00","timezone":"America/New_York","description":"Exhibit hours"},{"date":"2030-01-16","start_time":"09:00:00","end_time":"16:00:00","timezone":"America/New_York","description":"Final exhibit day"}]']); $dates_job = open_journal($journal_path, 'https://api.exhibitday.com/v1', $owned_workspace_id, 'dates-times-time-zones', $stable_job_id, $input_fingerprint, [['replace_group', 'PATCH', '/v1/events/dates']], $job_mode); try { if (journal_acknowledged($dates_job, 'replace_group')) { $saved_dates = journal_saved($dates_job, 'replace_group'); require_condition(both(equal(text(field($saved_dates, 'event_id')), $selected_event_id), equal(text(field($saved_dates, 'date_type_id')), '1')), 'The saved ACK belongs to a different Event/group; stop and reconcile.'); } else { $dates_patch = (object)['event_id' => $selected_event_id, 'date_type_id' => '1', 'dates' => $desired_dates, 'expected_revision' => $current_dates_revision]; $write_fingerprint = journal_fingerprint((object)['event_id' => $selected_event_id, 'date_type_id' => '1', 'dates' => '[{"date":"2030-01-15","start_time":"09:00:00","end_time":"17:00:00","timezone":"America/New_York","description":"Exhibit hours"},{"date":"2030-01-16","start_time":"09:00:00","end_time":"16:00:00","timezone":"America/New_York","description":"Final exhibit day"}]', 'expected_revision' => $current_dates_revision]); journal_begin($dates_job, 'replace_group', 'PATCH', '/v1/events/dates', $write_fingerprint); $saved_dates_response = call('replace_group', [], $dates_patch, null); require_condition(equal(response_status($saved_dates_response), '200'), 'Expected the endpoint\'s documented HTTP200 acknowledgement.'); $dates_receipt = $saved_dates_response["body"]; $saved_dates_revision = text(field($dates_receipt, 'record_revision')); require_condition(is_present($saved_dates_revision), 'A checked Dates save ACK requires its actual returned revision.'); journal_acknowledge($dates_job, 'replace_group', (object)['event_id' => $selected_event_id, 'date_type_id' => '1', 'record_revision' => $saved_dates_revision]); } $dates_readback_response = call('verify_group', ['event_id' => $selected_event_id, 'filter_by_date_type_id' => '1'], null, null); require_condition(equal(response_status($dates_readback_response), '200'), 'Expected the endpoint\'s documented HTTP200 acknowledgement.'); $dates_readback_page = $dates_readback_response["body"]; require_condition(both(equal(text(field($dates_readback_page, 'records_found')), '1'), both(equal(text(field($dates_readback_page, 'total_records')), '1'), equal(field($dates_readback_page, 'has_more'), false))), 'Readback must contain one complete selected group, without another page.'); $dates_readback_group = single(field($dates_readback_page, 'list_data')); require_condition(both(equal(text(field($dates_readback_group, 'event_id')), $selected_event_id), equal(text(field($dates_readback_group, 'date_type_id')), '1')), 'Readback belongs to another Event or Dates group.'); require_condition(deep_equal(field($dates_readback_group, 'dates'), $expected_dates), 'The complete saved Dates list differs; review it instead of automatically restoring the example\'s dates.'); print_value((object)['event_id' => $selected_event_id, 'date_type_id' => '1', 'dates_verified' => 'true']); } finally { $dates_job->close(); } } if (realpath($_SERVER['SCRIPT_FILENAME'] ?? '') === __FILE__) main(); ``` ```ruby # 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":true,"requests":{"workspace_binding":{"method":"GET","path":"/references/workspace_info"},"read_group":{"method":"GET","path":"/events/dates"},"replace_group":{"method":"PATCH","path":"/events/dates"},"verify_group":{"method":"GET","path":"/events/dates"}}}') API_KEY = ENV.fetch('EXHIBITDAY_API_KEY') raise 'Use the API key as one ASCII header value without control characters' if API_KEY.each_codepoint.any?{|point|point<32||point>126} 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, 'DELETE' => Net::HTTP::Delete }.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, key = nil) route = SPEC.fetch('requests').fetch(name) headers = { 'Authorization' => 'Bearer ' + API_KEY, 'Accept' => 'application/json' } if route.fetch('method') == 'POST' headers['Idempotency-Key'] = key || raise('Persist a logical create key before sending POST') # 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) # 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.fetch('method') == 'GET' 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 = resend && (status == 429 || (500..599).cover?(status)) 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, raw: raw } end raise 'Retry limit reached' end def both(left,right);left&&right;end def deep_equal(left,right) return false unless left.class==right.class if left.is_a?(Hash) return left.keys.sort==right.keys.sort&&left.all?{|key,value|deep_equal(value,right[key])} end return left.length==right.length&&left.zip(right).all?{|a,b|deep_equal(a,b)} if left.is_a?(Array) left==right end def equal(left,right) left.class==right.class && left==right end def field(value,name) raise "Missing response field: #{name}" unless value.is_a?(Hash) && value.key?(name) value.fetch(name) end def is_present(value) !value.nil? && value!="" end require 'digest' require 'securerandom' require 'uri' # Private client restart state, with no transport or application dependency. module GuideJournalProtocol PREAMBLE="EXHIBITDAY-GUIDE-JOURNAL 1\n".b.freeze class Refusal < StandardError; end def self.utf8(value) raise Refusal,'Journal fields are exact strings' unless value.is_a?(String)&&value.valid_encoding? raw=value.encode(Encoding::UTF_8) raise Refusal,'Invalid UTF8 journal field' unless raw.valid_encoding? raw.b end def self.strings(values) values.map{|value|raw=utf8(value);raw.bytesize.to_s.b+':'.b+raw}.join.b end def self.read_strings(raw) values=[];offset=0 while offsetraw.bytesize-offset value=raw.byteslice(offset,size).dup.force_encoding(Encoding::UTF_8);raise Refusal,'Invalid UTF8 string' unless value.valid_encoding? values<=raw.bytesize-offset payload=raw.byteslice(offset,size);offset+=size raise Refusal,'Journal integrity failed; reconcile before retry' unless raw.getbyte(offset)==10&&digest(payload)==match[2] records<0 offset+=written end file.flush;file.fsync end end class GuideJournal P=GuideJournalProtocol def initialize(path,base,workspace,slug,job,input_fingerprint,writes,mode='resume') @path=path.dup;@lock_path=path+'.lock';@file=nil;@owned=false;@tainted=false;@intents={};@saved={};@allowed={} address=URI(base) raise P::Refusal,'Use actual API base and closed guide slug' unless ['https','http'].include?(address.scheme)&&address.host&&address.userinfo.nil?&&address.query.nil?&&address.fragment.nil?&&slug.match?(/\A[a-z][a-z0-9-]*\z/) raise P::Refusal,'Use actual workspace, stable explicit job ID and exact fingerprint' unless !job.strip.empty?&&workspace.match?(/\A[1-9][0-9]*\z/)&&input_fingerprint.match?(/\A[0-9A-F]{64}\z/) raise P::Refusal,'Choose new or resume for this local job' unless ['new','resume'].include?(mode) manifest=[] writes.each do|step,method,route| raise P::Refusal,'Use closed unique write manifest' unless step.match?(/\A[a-z][a-z0-9_-]*\z/)&&!@allowed.key?(step)&&['POST','PATCH','DELETE'].include?(method)&&route.match?(/\A\/v1\/[A-Za-z0-9_\/-]+\z/)&&!route.include?('//') @allowed[step.dup.freeze]=[method.dup.freeze,route.dup.freeze].freeze;manifest.concat([step,method,route]) end raise P::Refusal,'Only write workflows need a restart journal' if @allowed.empty? @header=['H','1',base,workspace,slug,job,input_fingerprint,P.digest(P.strings(manifest))].map{|value|value.dup.freeze}.freeze;P.strings(@header) begin @file=File.open(@lock_path,File::RDWR|File::CREAT|File::EXCL,0o600);@file.binmode;@owned=true rescue Errno::EEXIST raise P::Refusal,'This journal is locked; do not overlap jobs or steal a stale lock' end begin @owner=SecureRandom.hex(16).freeze;P.write_all(@file,@owner.b);@identity=@file.stat # Ruby's Windows fstat reports dev=0 while lstat reports the drive number. # Both expose the same exact inode. Retain it plus the initial path device; # compare like-for-like instead of treating the differing dev APIs as equal. named_identity=File.lstat(@lock_path);raise P::Refusal,'Lock identity did not bind' unless named_identity.ino==@identity.ino @path_device=named_identity.dev raise P::Refusal,'Choose a private regular journal file' if File.symlink?(@path) raise P::Refusal,'Journal missing: stop and reconcile lost state before starting a new logical job' if mode=='resume'&&!File.exist?(@path) raise P::Refusal,'Journal exists; use resume for the same logical job' if mode=='new'&&File.exist?(@path) if mode=='new' File.open(@path,File::WRONLY|File::CREAT|File::EXCL,0o600){|target|target.binmode;P.write_all(target,P::PREAMBLE+P.frame(@header))} end records=P.decode(File.binread(@path));raise P::Refusal,'Journal workspace/base/guide/job/input binding differs' if records.empty?||records[0]!=@header records.drop(1).each{|record|apply(record)} raise P::Refusal,'Saved intent lacks ACK; stop and reconcile before retry' if @intents.keys.any?{|step|!@saved.key?(step)} rescue Exception close;raise end end def apply(record) case record[0] when 'I' raise P::Refusal,'Invalid intent shape' unless record.length==6 _,step,method,route,fingerprint,key=record raise P::Refusal,'Invalid, future or repeated intent' unless step.match?(/\A[a-z][a-z0-9_-]*\z/)&&!@intents.key?(step)&&@allowed[step]==[method,route]&&fingerprint.match?(/\A[0-9A-F]{64}\z/)&&!@intents.keys.any?{|name|!@saved.key?(name)} raise P::Refusal,'Invalid persisted action key' unless (method=='POST'&&key.match?(/\A[0-9a-f]{32}\z/))||(method!='POST'&&key=='') @intents[step.dup.freeze]={'method'=>method.dup.freeze,'path'=>route.dup.freeze,'request_fingerprint'=>fingerprint.dup.freeze,'idempotency_key'=>key.dup.freeze}.freeze when 'A' raise P::Refusal,'Invalid ACK shape' unless record.length>=3 _,step,count,*pairs=record raise P::Refusal,'ACK without exactly one prior intent' unless count.match?(/\A(?:0|[1-9][0-9]*)\z/)&&pairs.length==2*count.to_i&&@intents.key?(step)&&!@saved.key?(step) names=pairs.each_slice(2).map(&:first) raise P::Refusal,'ACK fields must be unique sorted secret-free identifiers' unless names==names.uniq.sort&&names.all?{|name|name.match?(/\A[a-z][a-z0-9_]*\z/)&&!['api_key','exhibitday_api_key'].include?(name)} @saved[step.dup.freeze]=pairs.each_slice(2).to_h.transform_values{|value|value.dup.freeze}.freeze else raise P::Refusal,'Unknown journal transition' end end def require_active raise P::Refusal,'Journal is closed or IO outcome needs reconciliation' unless @owned&&@file&&!@tainted current=File.lstat(@lock_path) raise P::Refusal,'Journal lock replaced; stop without deleting it' unless current.dev==@path_device&¤t.ino==@identity.ino&&File.binread(@lock_path)==@owner.b end def append(record) require_active;raw=P.frame(record) begin File.open(@path,'ab'){|target|P.write_all(target,raw)} rescue Exception @tainted=true;raise end end def acknowledged(step);require_active;@saved.key?(step);end def saved(step) require_active;raise P::Refusal,'No acknowledged state exists' unless @saved.key?(step) @saved.fetch(step).transform_values(&:dup) end def begin_action(step,method,route,request_fingerprint) require_active;raise P::Refusal,'Never blindly repeat an action' if @intents.key?(step) record=['I',step,method,route,request_fingerprint,method=='POST'?SecureRandom.hex(16):''] previous=@intents.dup;begin;apply(record);ensure;@intents=previous;end append(record);apply(record);@intents.fetch(step).transform_values(&:dup) end def acknowledge(step,saved) require_active;record=['A',step,saved.length.to_s];saved.keys.sort.each{|name|record.concat([name,saved.fetch(name)])} previous=@saved.dup;begin;apply(record);P.strings(record);ensure;@saved=previous;end append(record);apply(record) end def close return unless @owned if @tainted;@file.close;@file=nil;@owned=false;return;end begin;require_active;rescue Exception;@file.close;@file=nil;@owned=false;raise;end @file.close;@file=nil;@owned=false;File.unlink(@lock_path) end end def journal_values(value) raise GuideJournalProtocol::Refusal,'Saved/fingerprint values must be exact strings' unless value.is_a?(Hash)&&value.all?{|name,item|name.is_a?(String)&&item.is_a?(String)} value.transform_values(&:dup) end def journal_acknowledge(job,step,saved);job.acknowledge(step,journal_values(saved));end def journal_acknowledged(job,step);job.acknowledged(step);end def journal_begin(job,step,method,path,request_fingerprint);job.begin_action(step,method,path,request_fingerprint);end def journal_fingerprint(value);GuideJournalProtocol.fingerprint(journal_values(value));end def journal_saved(job,step);job.saved(step);end def open_journal(path,base,workspace,slug,job,input_fingerprint,writes,mode);GuideJournal.new(path,base,workspace,slug,job,input_fingerprint,writes,mode);end def optional(name,fallback) value=ENV[name] value.nil? || value.empty? ? fallback : value end def positive_id(value) raise "Use a positive record ID" unless /\A[1-9][0-9]*\z/.match?(value) && Integer(value)<=9223372036854775807 value end def print_value(value) STDOUT.binmode.write((value.is_a?(String)?value:JSON.generate(value))+"\n") end def require_condition(value,message) raise message unless value==true end def required(name) value=ENV[name] raise "Set #{name}" if value.nil? || value.strip.empty? value end def response_status(value);value.fetch(:status).to_s;end def items(value) raise "Expected a JSON array" unless value.is_a?(Array) value end def single(value);rows=items(value);raise 'Expected exactly one selected record' unless rows.length==1;rows[0];end def text(value) return "" if value.nil? return value.to_s if value.is_a?(String)||value.is_a?(Integer)||value==true||value==false raise "Expected a scalar response value" end def main selected_event_id = positive_id(required('EXHIBITDAY_EVENT_ID')) desired_dates = [{'date' => '2030-01-15', 'start_time' => '09:00', 'end_time' => '17:00', 'timezone' => 'America/New_York', 'description' => 'Exhibit hours'}, {'date' => '2030-01-16', 'start_time' => '09:00', 'end_time' => '16:00', 'timezone' => 'America/New_York', 'description' => 'Final exhibit day'}] expected_dates = [{'date' => '2030-01-15', 'start_time' => '09:00:00', 'end_time' => '17:00:00', 'timezone' => 'America/New_York', 'description' => 'Exhibit hours'}, {'date' => '2030-01-16', 'start_time' => '09:00:00', 'end_time' => '16:00:00', 'timezone' => 'America/New_York', 'description' => 'Final exhibit day'}] journal_path = required('EXHIBITDAY_JOURNAL') stable_job_id = required('EXHIBITDAY_JOB_ID') job_mode = optional('EXHIBITDAY_JOB_MODE', 'resume') workspace_response = call('workspace_binding', {}, nil, nil) require_condition(equal(response_status(workspace_response), '200'), 'Expected the endpoint\'s documented HTTP200 acknowledgement.') owned_workspace = workspace_response.fetch(:body) owned_workspace_id = positive_id(text(field(owned_workspace, 'id'))) current_dates_response = call('read_group', {'event_id' => selected_event_id, 'filter_by_date_type_id' => '1', '$include_record_revision' => 'true'}, nil, nil) require_condition(equal(response_status(current_dates_response), '200'), 'Expected the endpoint\'s documented HTTP200 acknowledgement.') current_dates_page = current_dates_response.fetch(:body) require_condition(both(equal(text(field(current_dates_page, 'records_found')), '1'), both(equal(text(field(current_dates_page, 'total_records')), '1'), equal(field(current_dates_page, 'has_more'), false))), 'Expected one complete selected Dates group.') current_dates_group = single(field(current_dates_page, 'list_data')) require_condition(both(equal(text(field(current_dates_group, 'event_id')), selected_event_id), equal(text(field(current_dates_group, 'date_type_id')), '1')), 'The Dates group does not match this Event and Exhibit Hall type.') current_dates_revision = text(field(current_dates_group, 'record_revision')) require_condition(is_present(current_dates_revision), 'Read the actual selected group with its record_revision before replacing it.') input_fingerprint = journal_fingerprint({'workflow_contract_sha256' => '3422CE4F7C1283E1F77ACB98BE12123B5E2D0F078EB80BE01232C22F2941E85D', 'event_id' => selected_event_id, 'date_type_id' => '1', 'dates' => '[{"date":"2030-01-15","start_time":"09:00:00","end_time":"17:00:00","timezone":"America/New_York","description":"Exhibit hours"},{"date":"2030-01-16","start_time":"09:00:00","end_time":"16:00:00","timezone":"America/New_York","description":"Final exhibit day"}]'}) dates_job = open_journal(journal_path, 'https://api.exhibitday.com/v1', owned_workspace_id, 'dates-times-time-zones', stable_job_id, input_fingerprint, [['replace_group', 'PATCH', '/v1/events/dates']], job_mode) begin if journal_acknowledged(dates_job, 'replace_group') saved_dates = journal_saved(dates_job, 'replace_group') require_condition(both(equal(text(field(saved_dates, 'event_id')), selected_event_id), equal(text(field(saved_dates, 'date_type_id')), '1')), 'The saved ACK belongs to a different Event/group; stop and reconcile.') else dates_patch = {'event_id' => selected_event_id, 'date_type_id' => '1', 'dates' => desired_dates, 'expected_revision' => current_dates_revision} write_fingerprint = journal_fingerprint({'event_id' => selected_event_id, 'date_type_id' => '1', 'dates' => '[{"date":"2030-01-15","start_time":"09:00:00","end_time":"17:00:00","timezone":"America/New_York","description":"Exhibit hours"},{"date":"2030-01-16","start_time":"09:00:00","end_time":"16:00:00","timezone":"America/New_York","description":"Final exhibit day"}]', 'expected_revision' => current_dates_revision}) journal_begin(dates_job, 'replace_group', 'PATCH', '/v1/events/dates', write_fingerprint) saved_dates_response = call('replace_group', {}, dates_patch, nil) require_condition(equal(response_status(saved_dates_response), '200'), 'Expected the endpoint\'s documented HTTP200 acknowledgement.') dates_receipt = saved_dates_response.fetch(:body) saved_dates_revision = text(field(dates_receipt, 'record_revision')) require_condition(is_present(saved_dates_revision), 'A checked Dates save ACK requires its actual returned revision.') journal_acknowledge(dates_job, 'replace_group', {'event_id' => selected_event_id, 'date_type_id' => '1', 'record_revision' => saved_dates_revision}) end dates_readback_response = call('verify_group', {'event_id' => selected_event_id, 'filter_by_date_type_id' => '1'}, nil, nil) require_condition(equal(response_status(dates_readback_response), '200'), 'Expected the endpoint\'s documented HTTP200 acknowledgement.') dates_readback_page = dates_readback_response.fetch(:body) require_condition(both(equal(text(field(dates_readback_page, 'records_found')), '1'), both(equal(text(field(dates_readback_page, 'total_records')), '1'), equal(field(dates_readback_page, 'has_more'), false))), 'Readback must contain one complete selected group, without another page.') dates_readback_group = single(field(dates_readback_page, 'list_data')) require_condition(both(equal(text(field(dates_readback_group, 'event_id')), selected_event_id), equal(text(field(dates_readback_group, 'date_type_id')), '1')), 'Readback belongs to another Event or Dates group.') require_condition(deep_equal(field(dates_readback_group, 'dates'), expected_dates), 'The complete saved Dates list differs; review it instead of automatically restoring the example\'s dates.') print_value({'event_id' => selected_event_id, 'date_type_id' => '1', 'dates_verified' => 'true'}) ensure dates_job.close() end end main if $PROGRAM_NAME == __FILE__ ``` ```go // Go 1.18+; standard library only. Set EXHIBITDAY_API_KEY. package main import ( "bytes" "crypto/rand" "crypto/sha256" "encoding/hex" "regexp" "sort" "unicode/utf8" "encoding/json" "fmt" "io" "net/http" "net/url" "os" "strconv" "strings" "time" ) const base = "https://api.exhibitday.com/v1" const specification = "{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"read_group\":{\"method\":\"GET\",\"path\":\"/events/dates\"},\"replace_group\":{\"method\":\"PATCH\",\"path\":\"/events/dates\"},\"verify_group\":{\"method\":\"GET\",\"path\":\"/events/dates\"}}}" 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 }} var send = client.Do type result struct { status int; body any; headers http.Header; raw []byte } // 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 call(name string, query map[string]string, body any, key string) result { route := object(object(spec["requests"])[name]); method := text(route["method"]) headers := map[string]string{"Authorization": "Bearer " + apiKey, "Accept": "application/json"} if method == "POST" { if key == "" { panic("Persist a logical create key before sending POST") }; 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() } // 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 := method == "GET" 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 := send(request) if err != nil { if !resend { panic(apiError{0, "", "No response", true}) }; if attempt == 4 { panic(err) }; time.Sleep(time.Second*time.Duration(1<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 := resend && (response.StatusCode == 429 || response.StatusCode >= 500) if retry { if attempt == 4 { panic("Retry limit reached; check the outcome before starting a new create") } seconds := float64(int64(1)<= 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, raw} } panic("Retry limit reached") } func both(left,right bool)bool{return left&&right} func deep_equal(left,right any)bool{a,e:=json.Marshal(left);if e!=nil{panic(e)};b,e:=json.Marshal(right);if e!=nil{panic(e)};return string(a)==string(b)} func equal(left,right any)bool{switch a:=left.(type){case string:b,ok:=right.(string);return ok&&a==b;case bool:b,ok:=right.(bool);return ok&&a==b;case int64:b,ok:=right.(int64);return ok&&a==b};return left==nil&&right==nil} func field(value any,name string)any{obj,ok:=value.(map[string]any);if !ok{panic("Missing response object")};item,found:=obj[name];if !found{panic("Missing response field: "+name)};return item} func is_present(value string)bool{return value!=""} // Private client restart state only; no API transport or workflow interpreter. const journalPreamble = "EXHIBITDAY-GUIDE-JOURNAL 1\n" type journalRefusal struct{ message string } func (e journalRefusal) Error() string { return e.message } func journalNeed(ok bool, message string) { if !ok { panic(journalRefusal{message}) } } func journalMatch(value, pattern string) bool { return regexp.MustCompile("\\A(?:"+pattern+")\\z").MatchString(value) } func journalStrings(values []string) []byte { var output bytes.Buffer for _,value:=range values { journalNeed(utf8.ValidString(value),"Journal fields must be valid UTF8 strings"); output.WriteString(strconv.Itoa(len(value))+":");output.WriteString(value) } return output.Bytes() } func journalReadStrings(raw []byte) []string { values:=[]string{};offset:=0 for offset=0,"Incomplete journal string length");end:=offset+relative;text:=string(raw[offset:end]);journalNeed(journalMatch(text,"0|[1-9][0-9]*"),"Noncanonical journal string length");size,err:=strconv.ParseUint(text,10,64);offset=end+1;journalNeed(err==nil&&size<=uint64(len(raw)-offset),"Incomplete journal string");count:=int(size);value:=string(raw[offset:offset+count]);journalNeed(utf8.ValidString(value),"Invalid UTF8 journal field");values=append(values,value);offset+=count } return values } func journalDigest(raw []byte) string { hash:=sha256.Sum256(raw);return strings.ToUpper(hex.EncodeToString(hash[:])) } func journalFingerprint(pairs map[string]string) string { names:=make([]string,0,len(pairs));for name:=range pairs { names=append(names,name) };sort.Strings(names);values:=[]string{} for _,name:=range names { lower:=strings.ToLower(name);journalNeed(journalMatch(name,"[A-Za-z0-9_.-]+")&&lower!="api_key"&&lower!="exhibitday_api_key","Use explicit secret-free fingerprint names");values=append(values,name,pairs[name]) } return journalDigest(journalStrings(values)) } func journalFrame(values []string) []byte { raw:=journalStrings(values);header:=[]byte(strconv.Itoa(len(raw))+" "+journalDigest(raw)+"\n");result:=append(header,raw...);return append(result,'\n') } func journalDecode(raw []byte) [][]string { journalNeed(bytes.HasPrefix(raw,[]byte(journalPreamble)),"Unknown or incomplete journal version");offset:=len(journalPreamble);records:=[][]string{} for offset=0,"Incomplete frame header; reconcile before retry");end:=offset+relative;header:=string(raw[offset:end]);journalNeed(journalMatch(header,"(0|[1-9][0-9]*) [0-9A-F]{64}"),"Invalid frame header");fields:=strings.Split(header," ");size,err:=strconv.ParseUint(fields[0],10,64);offset=end+1;journalNeed(err==nil&&size0 { count,err:=file.Write(raw);if err!=nil{return err};if count<=0{return io.ErrShortWrite};raw=raw[count:] } return file.Sync() } func journalWriteFile(path string,flags int,raw []byte) (err error) { file,err:=os.OpenFile(path,flags,0600);if err!=nil{return err};defer func(){closed:=file.Close();if err==nil{err=closed}}();return journalWriteAll(file,raw) } func journalCopy(source map[string]string) map[string]string { copy:=map[string]string{};for name,value:=range source{copy[name]=value};return copy } func journalCopyStates(source map[string]map[string]string) map[string]map[string]string { copy:=map[string]map[string]string{};for name,value:=range source{copy[name]=journalCopy(value)};return copy } type guideJournal struct { path,lockPath,owner string header []string allowed map[string][2]string intents,savedValues map[string]map[string]string file *os.File identity os.FileInfo owned,tainted bool } func openGuideJournal(path,base,workspace,slug,job,inputFingerprint string,writes [][3]string,modes ...string) (result *guideJournal) { mode:="resume";journalNeed(len(modes)<=1,"Choose one local job mode");if len(modes)==1{mode=modes[0]};journalNeed(mode=="new"||mode=="resume","Choose new or resume for this local job") address,err:=url.Parse(base);journalNeed(err==nil&&address.Hostname()!=""&&(address.Scheme=="https"||address.Scheme=="http")&&address.User==nil&&address.RawQuery==""&&address.Fragment==""&&journalMatch(slug,"[a-z][a-z0-9-]*"),"Use actual API base and closed guide slug") journalNeed(strings.TrimSpace(job)!=""&&journalMatch(workspace,"[1-9][0-9]*")&&journalMatch(inputFingerprint,"[0-9A-F]{64}"),"Use actual workspace, stable explicit job ID and exact fingerprint") j:=&guideJournal{path:path,lockPath:path+".lock",allowed:map[string][2]string{},intents:map[string]map[string]string{},savedValues:map[string]map[string]string{}} manifest:=[]string{};for _,write:=range writes { step,method,route:=write[0],write[1],write[2];_,exists:=j.allowed[step];journalNeed(journalMatch(step,"[a-z][a-z0-9_-]*")&&!exists&&(method=="POST"||method=="PATCH"||method=="DELETE")&&journalMatch(route,"/v1/[A-Za-z0-9_/-]+")&&!strings.Contains(route,"//"),"Use a closed unique write manifest");j.allowed[step]=[2]string{method,route};manifest=append(manifest,step,method,route) } journalNeed(len(j.allowed)>0,"Only write workflows need a restart journal");j.header=[]string{"H","1",base,workspace,slug,job,inputFingerprint,journalDigest(journalStrings(manifest))};journalStrings(j.header) j.file,err=os.OpenFile(j.lockPath,os.O_RDWR|os.O_CREATE|os.O_EXCL,0600);if err!=nil { if os.IsExist(err){panic(journalRefusal{"This journal is locked; do not overlap jobs or steal a stale lock"})};panic(err) };j.owned=true defer func(){ if observed:=recover();observed!=nil { j.Close();panic(observed) } }() random:=make([]byte,16);if _,err=io.ReadFull(rand.Reader,random);err!=nil{panic(err)};j.owner=hex.EncodeToString(random);if err=journalWriteAll(j.file,[]byte(j.owner));err!=nil{panic(err)};j.identity,err=j.file.Stat();if err!=nil{panic(err)} info,err:=os.Lstat(path);if err!=nil&&!os.IsNotExist(err){panic(err)};exists:=err==nil;if exists{journalNeed(info.Mode()&os.ModeSymlink==0,"Choose a private regular journal file")};journalNeed(mode!="resume"||exists,"Journal missing: stop and reconcile lost state before starting a new logical job");journalNeed(mode!="new"||!exists,"Journal exists; use resume for the same logical job");if mode=="new"{raw:=append([]byte(journalPreamble),journalFrame(j.header)...);if err=journalWriteFile(path,os.O_WRONLY|os.O_CREATE|os.O_EXCL,raw);err!=nil{panic(err)}} raw,err:=os.ReadFile(path);if err!=nil{panic(err)};records:=journalDecode(raw);journalNeed(len(records)>0&&stringsEqual(records[0],j.header),"Journal workspace/base/guide/job/input binding differs");for _,record:=range records[1:]{j.apply(record)};for step:=range j.intents{_,ok:=j.savedValues[step];journalNeed(ok,"Saved intent lacks ACK; stop and reconcile before retry")};return j } func stringsEqual(left,right []string) bool { if len(left)!=len(right){return false};for i,value:=range left{if value!=right[i]{return false}};return true } func (j *guideJournal) apply(record []string) { journalNeed(len(record)>0,"Empty journal record") if record[0]=="I" { journalNeed(len(record)==6,"Invalid intent shape");step,method,route,fingerprint,key:=record[1],record[2],record[3],record[4],record[5];_,exists:=j.intents[step];expected,allowed:=j.allowed[step];pending:=false;for name:=range j.intents{if _,ok:=j.savedValues[name];!ok{pending=true}} journalNeed(journalMatch(step,"[a-z][a-z0-9_-]*")&&!exists&&allowed&&expected==[2]string{method,route}&&journalMatch(fingerprint,"[0-9A-F]{64}")&&!pending,"Invalid, future or repeated intent");journalNeed(method=="POST"&&journalMatch(key,"[0-9a-f]{32}")||method!="POST"&&key=="","Invalid persisted action key");j.intents[step]=map[string]string{"method":method,"path":route,"request_fingerprint":fingerprint,"idempotency_key":key} }else if record[0]=="A" { journalNeed(len(record)>=3,"Invalid ACK shape");step,text:=record[1],record[2];count,err:=strconv.ParseUint(text,10,64);_,prior:=j.intents[step];_,done:=j.savedValues[step];journalNeed(journalMatch(text,"0|[1-9][0-9]*")&&err==nil&&len(record)%2==1&&count==uint64((len(record)-3)/2)&&prior&&!done,"ACK without exactly one prior intent");names:=[]string{};for i:=3;i0&&value[0]!='0';for _,ch:=range value{valid=valid&&ch>='0'&&ch<='9'};id,err:=strconv.ParseInt(value,10,64);if !valid||err!=nil||id<=0{panic("Use a positive record ID")};return value} func print_value(value any){if result,ok:=value.(string);ok{fmt.Println(result);return};raw,err:=json.Marshal(value);if err!=nil{panic(err)};fmt.Println(string(raw))} func require_condition(value bool,message string){if !value{panic(message)}} func response_status(value result)string{return strconv.Itoa(value.status)} func items(value any)[]any{result,ok:=value.([]any);if !ok{panic("Expected a JSON array")};return result} func single(value any)any{rows:=items(value);if len(rows)!=1{panic("Expected exactly one selected record")};return rows[0]} func workflow() { selected_event_id := positive_id(required("EXHIBITDAY_EVENT_ID")) desired_dates := []any{map[string]any{"date": "2030-01-15", "start_time": "09:00", "end_time": "17:00", "timezone": "America/New_York", "description": "Exhibit hours"}, map[string]any{"date": "2030-01-16", "start_time": "09:00", "end_time": "16:00", "timezone": "America/New_York", "description": "Final exhibit day"}} expected_dates := []any{map[string]any{"date": "2030-01-15", "start_time": "09:00:00", "end_time": "17:00:00", "timezone": "America/New_York", "description": "Exhibit hours"}, map[string]any{"date": "2030-01-16", "start_time": "09:00:00", "end_time": "16:00:00", "timezone": "America/New_York", "description": "Final exhibit day"}} journal_path := required("EXHIBITDAY_JOURNAL") stable_job_id := required("EXHIBITDAY_JOB_ID") job_mode := optional("EXHIBITDAY_JOB_MODE", "resume") workspace_response := call("workspace_binding", map[string]string{}, nil, "") require_condition(equal(response_status(workspace_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement.") owned_workspace := workspace_response.body owned_workspace_id := positive_id(text(field(owned_workspace, "id"))) current_dates_response := call("read_group", map[string]string{"event_id": selected_event_id, "filter_by_date_type_id": "1", "$include_record_revision": "true"}, nil, "") require_condition(equal(response_status(current_dates_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement.") current_dates_page := current_dates_response.body require_condition(both(equal(text(field(current_dates_page, "records_found")), "1"), both(equal(text(field(current_dates_page, "total_records")), "1"), equal(field(current_dates_page, "has_more"), false))), "Expected one complete selected Dates group.") current_dates_group := single(field(current_dates_page, "list_data")) require_condition(both(equal(text(field(current_dates_group, "event_id")), selected_event_id), equal(text(field(current_dates_group, "date_type_id")), "1")), "The Dates group does not match this Event and Exhibit Hall type.") current_dates_revision := text(field(current_dates_group, "record_revision")) require_condition(is_present(current_dates_revision), "Read the actual selected group with its record_revision before replacing it.") input_fingerprint := journal_fingerprint(map[string]any{"workflow_contract_sha256": "3422CE4F7C1283E1F77ACB98BE12123B5E2D0F078EB80BE01232C22F2941E85D", "event_id": selected_event_id, "date_type_id": "1", "dates": "[{\"date\":\"2030-01-15\",\"start_time\":\"09:00:00\",\"end_time\":\"17:00:00\",\"timezone\":\"America/New_York\",\"description\":\"Exhibit hours\"},{\"date\":\"2030-01-16\",\"start_time\":\"09:00:00\",\"end_time\":\"16:00:00\",\"timezone\":\"America/New_York\",\"description\":\"Final exhibit day\"}]"}) func() { dates_job := open_journal(journal_path, "https://api.exhibitday.com/v1", owned_workspace_id, "dates-times-time-zones", stable_job_id, input_fingerprint, []any{[]any{"replace_group", "PATCH", "/v1/events/dates"}}, job_mode) defer dates_job.Close() if journal_acknowledged(dates_job, "replace_group") { saved_dates := journal_saved(dates_job, "replace_group") require_condition(both(equal(text(field(saved_dates, "event_id")), selected_event_id), equal(text(field(saved_dates, "date_type_id")), "1")), "The saved ACK belongs to a different Event/group; stop and reconcile.") } else { dates_patch := map[string]any{"event_id": selected_event_id, "date_type_id": "1", "dates": desired_dates, "expected_revision": current_dates_revision} write_fingerprint := journal_fingerprint(map[string]any{"event_id": selected_event_id, "date_type_id": "1", "dates": "[{\"date\":\"2030-01-15\",\"start_time\":\"09:00:00\",\"end_time\":\"17:00:00\",\"timezone\":\"America/New_York\",\"description\":\"Exhibit hours\"},{\"date\":\"2030-01-16\",\"start_time\":\"09:00:00\",\"end_time\":\"16:00:00\",\"timezone\":\"America/New_York\",\"description\":\"Final exhibit day\"}]", "expected_revision": current_dates_revision}) journal_begin(dates_job, "replace_group", "PATCH", "/v1/events/dates", write_fingerprint) saved_dates_response := call("replace_group", map[string]string{}, dates_patch, "") require_condition(equal(response_status(saved_dates_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement.") dates_receipt := saved_dates_response.body saved_dates_revision := text(field(dates_receipt, "record_revision")) require_condition(is_present(saved_dates_revision), "A checked Dates save ACK requires its actual returned revision.") journal_acknowledge(dates_job, "replace_group", map[string]any{"event_id": selected_event_id, "date_type_id": "1", "record_revision": saved_dates_revision}) } dates_readback_response := call("verify_group", map[string]string{"event_id": selected_event_id, "filter_by_date_type_id": "1"}, nil, "") require_condition(equal(response_status(dates_readback_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement.") dates_readback_page := dates_readback_response.body require_condition(both(equal(text(field(dates_readback_page, "records_found")), "1"), both(equal(text(field(dates_readback_page, "total_records")), "1"), equal(field(dates_readback_page, "has_more"), false))), "Readback must contain one complete selected group, without another page.") dates_readback_group := single(field(dates_readback_page, "list_data")) require_condition(both(equal(text(field(dates_readback_group, "event_id")), selected_event_id), equal(text(field(dates_readback_group, "date_type_id")), "1")), "Readback belongs to another Event or Dates group.") require_condition(deep_equal(field(dates_readback_group, "dates"), expected_dates), "The complete saved Dates list differs; review it instead of automatically restoring the example's dates.") print_value(map[string]any{"event_id": selected_event_id, "date_type_id": "1", "dates_verified": "true"}) }() } func header_key(value string)string{for _,ch:=range value{if ch<32||ch>126{panic("Use the API key as one ASCII header value without control characters")}};return value} func main(){apiKey=header_key(required("EXHIBITDAY_API_KEY"));if err:=json.Unmarshal([]byte(specification),&spec);err!=nil{panic(err)};workflow()} ``` #### Example response Response 200 — OK 304 — Not Modified 400 — Bad Request 401 — Unauthorized 404 — Not Found 409 — Conflict 429 — Too Many Requests 500 — Internal Server Error Example Successful request ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_data": [ { "event_id": 5001, "date_type_id": 1, "date_type": "Exhibit Hall", "dates": [ { "date": "2030-01-15", "start_time": "09:00:00", "end_time": "17:00:00", "timezone": "America/New_York", "description": "Exhibit hours" }, { "date": "2030-01-16", "start_time": "09:00:00", "end_time": "16:00:00", "timezone": "America/New_York", "description": "Final exhibit day" } ] } ] } ``` Note: The Exhibit Hall group as read after the save. It returns the two saved rows with their local times and time-zone label. Note: There is no response body. Keep using your cached response. ```json { "status_code": 400, "status": "Bad Request", "message": "HTTP method override is not supported.", "error_code": "invalid_request", "errors": [ "Send the documented HTTP method directly. X-HTTP-Method-Override cannot change a request's HTTP method." ], "error_params": [ "X-HTTP-Method-Override" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "No API key was provided. Send your key in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "missing_api_key", "errors": [ "Copy the key from Workspace Settings > API & Integrations > API Access in ExhibitDay." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "The API key is not valid. Check that you copied the whole key from Workspace Settings > API & Integrations > API Access, then send it in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "invalid_api_key", "errors": [ "Check that you sent the whole key. If it was regenerated, use the current key from Workspace Settings > API & Integrations > API Access." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "Access to the ExhibitDay API is not enabled for your workspace. Please contact support@exhibitday.com to enable API Access. Once access is enabled, send your key in the Authorization header as 'Bearer YOUR_API_KEY'.", "error_code": "api_access_disabled", "errors": [ "Nothing was read or changed." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "The API key is not valid for this request. Send your current key in the Authorization header as 'Bearer YOUR_API_KEY'.", "error_code": "invalid_api_key", "errors": [ "The API key is not valid for this request. Send your current key in the Authorization header as 'Bearer YOUR_API_KEY'." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "Access to the ExhibitDay API is not enabled for your workspace. Please contact support@exhibitday.com to enable API Access. Once access is enabled, send your key in the Authorization header as 'Bearer YOUR_API_KEY'.", "error_code": "api_access_disabled", "errors": [ "Access to the ExhibitDay API is not enabled for your workspace. Please contact support@exhibitday.com to enable API Access. Once access is enabled, send your key in the Authorization header as 'Bearer YOUR_API_KEY'." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 404, "status": "Not Found", "message": "Event not found. Invalid Event ID: 12345.", "error_code": "not_found", "errors": [ "Event not found. Invalid Event ID: 12345." ], "error_params": [ "event_id" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "The Event's Dates changed while they were being read. Send the GET request again.", "error_code": "record_changed", "errors": [ "The Event's Dates changed while they were being read. Send the GET request again." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 429, "status": "Too Many Requests", "message": "Error 429 - Too Many Requests", "error_code": "rate_limited", "errors": [ "Error 429 - Too Many Requests" ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "An unexpected error occurred. Please try again later." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` Note: Use the request_id from your own response when contacting support. ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "Check whether your change was saved before trying again." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` #### Things to keep in mind - Send dates and times in the Event's local schedule. - ExhibitDay stores the time-zone label you supply. - Handle UTC conversion and daylight-saving validation in your integration. - Use the two example dates only on a test Event. To use your own schedule, edit the desired dates and matching expected dates at the start of the program. List every Exhibit Hall row you want to keep and include seconds in the expected times. #### If a run stops - Keep the journal private. It records what the program tried to save and which save it confirmed. - To continue a run with no unresolved save, use `EXHIBITDAY_JOB_MODE=resume` with the same job ID, journal path and inputs. - A resumed run skips an acknowledged save and verifies the current group. It stops if a later edit changed the group. - If a save stops with a conflict, a lost response or a missing revision, check the Event's Exhibit Hall group in ExhibitDay before running the program again. - If you still need a change after checking the old run, use `EXHIBITDAY_JOB_MODE=new` with a new job ID and journal path. - Run only one copy per journal. - If a crash leaves a `.lock` file, make sure no copy using that journal is running or can start. Then remove the lock file and keep the journal. #### Related guides - [Create or Update Events from Your CRM](https://api.exhibitday.com/Help/V1?guide=event-setup-crm) - [Handle Errors and Retry Failed Requests](https://api.exhibitday.com/Help/V1?guide=errors-and-retries) ### Reserve Assets (Equipment and Materials) for an Event Guide page: https://api.exhibitday.com/Help/V1?guide=reserve-change-cancel-assets Reserve equipment or materials for an Event, change the reservation, and see what canceling would do. Example use case You need a display monitor for an Event and want to confirm it's available before reserving it. What you'll end up with A Capital Asset reservation marked checked, plus the current cancellation options. Before you start Have a workspace API key, an Event with editable Assets and an active Capital Asset your workspace owns and can reserve. Good to know Availability is advisory. The save checks permissions, stock and reservation policy again. #### At a glance Time to try About 15 minutes Effect on your data Creates and updates Endpoints 6 The program creates and updates one Asset reservation, reads the cancellation options and writes a private local journal. It leaves the reservation in place. - [`GET /v1/references/workspace_info`](https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-workspace_info) - [`GET /v1/assets/availability`](https://api.exhibitday.com/Help/V1?epf=5&topic=availability#get-v1-assets-availability) - [`POST /v1/assets/reservations`](https://api.exhibitday.com/Help/V1?epf=5&topic=reservations#post-v1-assets-reservations) - [`GET /v1/assets/reservations/info`](https://api.exhibitday.com/Help/V1?epf=5&topic=reservations#get-v1-assets-reservations-info) - [`PATCH /v1/assets/reservations`](https://api.exhibitday.com/Help/V1?epf=5&topic=reservations#patch-v1-assets-reservations) - [`GET /v1/assets/reservation_cancellation_inventory_options`](https://api.exhibitday.com/Help/V1?epf=5&topic=reservations#get-v1-assets-reservation_cancellation_inventory_options) #### How it works 1. Choose an Event, an owned Capital Asset and the two calendar dates. For a new reservation, the program checks availability before creating it. 2. It reads the saved reservation, then uses its revision to mark it checked. 3. It verifies the reservation and reads the cancellation options. The example does not send a cancellation. #### Reserve and verify the Asset #### Step 1: Confirm the workspace Read the workspace summary so you know where this key can make changes. ```bash curl -X GET "https://api.exhibitday.com/v1/references/workspace_info" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "id": 98765 } ``` **Check:** Confirm id is the workspace you intend to use. #### Step 2: Check availability for the dates Read availability for the owned Capital Asset before you try to reserve it. ```bash curl -X GET "https://api.exhibitday.com/v1/assets/availability?asset_id=12345&asset_type_id=1&start_date=2030-01-02&end_date=2030-01-04" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "asset_id": 12345, "asset_type_id": 1, "is_asset_owned_by_this_workspace": true, "start_date": "2030-01-02", "end_date": "2030-01-04", "is_advisory": true, "is_available_under_reservation_policy": true } ``` **Check:** Confirm the Asset and both dates. Availability is advisory and does not hold the Asset. #### Step 3: Reserve the Asset for the Event Send the Asset, Event and calendar dates once after availability allows the allocation. ```bash curl -X POST "https://api.exhibitday.com/v1/assets/reservations" -H "Authorization: Bearer YOUR_API_KEY" -H "Idempotency-Key: YOUR_PERSISTED_RESERVATION_KEY" -H "Content-Type: application/json" --data-binary "{\"asset_type_id\":1,\"asset_id\":12345,\"event_id\":45678,\"reservation_date\":\"2030-01-02\",\"return_date\":\"2030-01-04\",\"notes\":\"Display monitor for Spring Expo 2030\",\"notify_new_reservation\":false}" ``` Example response (shortened) ```json { "id": 23456, "asset_type_id": 1, "asset_id": 12345, "event_id": 45678, "is_asset_owned_by_this_workspace": true, "reservation_date": "2030-01-02", "return_date": "2030-01-04", "is_checked": false } ``` **Check:** Keep id and asset_type_id from the response. Verify the Event, Asset and dates. #### Step 4: Read the current reservation and its revision Get the saved reservation with its current revision before you mark it checked. ```bash curl -X GET "https://api.exhibitday.com/v1/assets/reservations/info?id=23456&asset_type_id=1&%24include_record_revision=true" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "id": 23456, "asset_type_id": 1, "asset_id": 12345, "event_id": 45678, "is_asset_owned_by_this_workspace": true, "reservation_date": "2030-01-02", "return_date": "2030-01-04", "is_checked": false, "record_revision": "COPY_RESERVATION_REVISION_FROM_YOUR_READ" } ``` **Check:** The revision below is a placeholder. Copy the returned record_revision from your own read before you send the PATCH. #### Step 5: Mark the reservation checked Set is_checked to true only if the reservation still has the revision you read. ```bash curl -X PATCH "https://api.exhibitday.com/v1/assets/reservations" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" --data-binary "{\"id\":23456,\"asset_type_id\":1,\"is_checked\":true,\"expected_revision\":\"COPY_RESERVATION_REVISION_FROM_YOUR_READ\",\"notify_reservation_update\":false}" ``` Example response (shortened) ```json { "status_code": 200, "status": "OK", "message": "Asset Reservation updated.", "errors": [], "record_revision": "NEW_RESERVATION_REVISION" } ``` **Check:** Confirm the update succeeded. If it conflicts or its result is uncertain, read the current reservation before deciding what to do. #### Step 6: Verify the updated reservation Read the same reservation again to confirm it is checked and its dates are unchanged. ```bash curl -X GET "https://api.exhibitday.com/v1/assets/reservations/info?id=23456&asset_type_id=1" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "id": 23456, "asset_type_id": 1, "asset_id": 12345, "event_id": 45678, "is_asset_owned_by_this_workspace": true, "reservation_date": "2030-01-02", "return_date": "2030-01-04", "is_checked": true } ``` **Check:** Confirm is_checked is true and the Asset, Event and dates still match. #### Step 7: Review the possible effects of canceling Read the current cancellation options for the verified reservation. ```bash curl -X GET "https://api.exhibitday.com/v1/assets/reservation_cancellation_inventory_options?id=23456&asset_type_id=1" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "reservation_id": 23456, "asset_id": 12345, "asset_type_id": 1, "can_cancel": true, "inventory_outcomes": [ { "value": "UndoOriginal", "label": "Undo Reservation (as if it never took place)", "effect": "The recorded check-out/return of this asset will be removed from inventory records" }, { "value": "KeepCapital", "label": "Unlink reservation from this event, but keep the asset reserved", "effect": "The asset will remain reserved for the original reservation period, but the reservation will no longer be tied to this event." } ] } ``` **Check:** Confirm reservation_id and read can_cancel and inventory_outcomes. This example stops after showing the options. **Note.** Cancellation affects inventory according to the option you choose. The program reads the options and leaves any cancellation decision to you. #### Choose reservation details | Option | What to send | | --- | --- | | Capital equipment | Use `asset_type_id=1` and provide a `return_date`. Keep the type with the reservation ID because the two types have separate ID spaces. | | Collateral tracked in quantities | Use `asset_type_id=2`, a positive whole-number `quantity` and an eligible `storage_location_id`. On create, omit `return_date` or send null if the return is unknown. | | Owned Capital for another purpose | Omit `event_id` and send plain-text `notes` explaining the purpose. Collateral and borrowed Assets require an Event. | | Optional Accessories | On create, omission uses the Asset's current defaults. A supplied `optional_accessories` list replaces the full selection. Send an empty array to clear it on update. | #### Try it #### Before running the example | Variable | What to put in it | Required? | | --- | --- | --- | | `EXHIBITDAY_API_KEY` | Your workspace API key. | Yes | | `EXHIBITDAY_EVENT_ID` | The Event to reserve for. | Yes | | `EXHIBITDAY_ASSET_ID` | The owned Capital Asset to reserve. | Yes | | `EXHIBITDAY_RESERVATION_DATE` | The start date in YYYY-MM-DD form. | Yes | | `EXHIBITDAY_RETURN_DATE` | The return date in YYYY-MM-DD form, on or after the start date. | Yes | | `EXHIBITDAY_JOB_ID` | A stable ID for this logical job. | Yes | | `EXHIBITDAY_JOURNAL` | A private local path for this job's journal. | Yes | | `EXHIBITDAY_JOB_MODE` | Use new for a new job, or resume (the default) to continue the same job. | No | **Careful.** This example changes data in your workspace. Use a test Event and Asset. #### Bash ``` export EXHIBITDAY_API_KEY='YOUR_API_KEY' export EXHIBITDAY_EVENT_ID='45678' export EXHIBITDAY_ASSET_ID='12345' export EXHIBITDAY_RESERVATION_DATE='2030-01-02' export EXHIBITDAY_RETURN_DATE='2030-01-04' export EXHIBITDAY_JOB_ID='monitor-reservation-01' export EXHIBITDAY_JOURNAL='/private/path/monitor-reservation-01.json' export EXHIBITDAY_JOB_MODE='new' ``` #### PowerShell ``` $env:EXHIBITDAY_API_KEY = 'YOUR_API_KEY' $env:EXHIBITDAY_EVENT_ID = '45678' $env:EXHIBITDAY_ASSET_ID = '12345' $env:EXHIBITDAY_RESERVATION_DATE = '2030-01-02' $env:EXHIBITDAY_RETURN_DATE = '2030-01-04' $env:EXHIBITDAY_JOB_ID = 'monitor-reservation-01' $env:EXHIBITDAY_JOURNAL = 'C:\private\path\monitor-reservation-01.json' $env:EXHIBITDAY_JOB_MODE = 'new' ``` Use your own Event and Asset IDs and dates. For a new job, choose a new private journal path and stable job ID. To continue that job, use the same values and set `EXHIBITDAY_JOB_MODE=resume`. Then copy the complete example program below in your language and run it. #### Complete example program Code Samples ```bash #!/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\"},\"availability\":{\"method\":\"GET\",\"path\":\"/assets/availability\"},\"create_reservation\":{\"method\":\"POST\",\"path\":\"/assets/reservations\"},\"read_reservation\":{\"method\":\"GET\",\"path\":\"/assets/reservations/info\"},\"mark_checked\":{\"method\":\"PATCH\",\"path\":\"/assets/reservations\"},\"verify_reservation\":{\"method\":\"GET\",\"path\":\"/assets/reservations/info\"},\"cancellation_options\":{\"method\":\"GET\",\"path\":\"/assets/reservation_cancellation_inventory_options\"}}}") API_KEY = os.environ["EXHIBITDAY_API_KEY"] if any(ord(char) < 32 or ord(char) > 126 for char in API_KEY): raise RuntimeError("Use the API key as one ASCII header value without control characters") if not API_KEY.strip(): raise RuntimeError("Set EXHIBITDAY_API_KEY") def decode_json(text): if SPEC["preserveNumbers"]: # Quote JSON NUMBER tokens, never text inside a JSON string, to keep CSV decimals exact. text = re.sub(r'"(?:\\.|[^"\\])*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?', lambda m: m[0] if m[0].startswith('"') else json.dumps(m[0]), text) return json.loads(text) from pathlib import Path # This terminal version uses curl for HTTP and Python's standard library for JSON/CSV. import subprocess import tempfile def transport(method, url, headers, data): with tempfile.TemporaryDirectory(prefix="exhibitday-guide-") as directory: folder = Path(directory) # curl may leave no output file for a valid bodyless304 response. (folder / "body").write_bytes(b"") command = ["curl", "--disable", "--silent", "--show-error", "--request", method, "--url", url, "--max-time", "30", "--dump-header", str(folder / "headers"), "--output", str(folder / "body"), "--write-out", "%{http_code}"] for name, value in headers.items(): command += ["--header", name + ": " + value] if data is not None: (folder / "request").write_bytes(data) command += ["--data-binary", "@" + str(folder / "request")] result = subprocess.run(command, capture_output=True, text=True) if result.returncode: raise urllib.error.URLError(result.stderr.strip()) response_headers = {} blocks = (folder / "headers").read_text(encoding="iso-8859-1").replace("\r\n", "\n").strip().split("\n\n") for line in blocks[-1].splitlines()[1:]: name, separator, value = line.partition(":") if separator: response_headers[name] = value.strip() return int(result.stdout), (folder / "body").read_bytes(), response_headers class ApiError(RuntimeError): """An API error response. Branch on error_code (and status), never on the message text. uncertain is True when a PATCH or DELETE got no response or a server error: it may or may not have been applied.""" def __init__(self, status, body, uncertain=False): self.status = status self.uncertain = uncertain self.error_code = body.get("error_code") if isinstance(body, dict) else None super().__init__(f"{body.get('error_code')} {body.get('error_params')}: {body.get('errors')} (request {body.get('request_id')})" if isinstance(body, dict) else "HTTP " + str(status) if status else "No response") def call(name, params=None, body=None, key=None): route = SPEC["requests"][name] headers = {"Authorization": "Bearer " + API_KEY, "Accept": "application/json"} if route["method"] == "POST": if not key: raise RuntimeError("Persist a logical create key before sending POST") headers["Idempotency-Key"] = key data = None if body is None else json.dumps(body).encode("utf-8") if data is not None: headers["Content-Type"] = "application/json" query = urllib.parse.urlencode(params or {}) url = BASE + route["path"] + ("?" + query if query else "") # Only GET has automatic retries in this workflow. A PATCH or DELETE that got no response or a # server error is never resent blindly: it may already have been applied, so the caller reads the record first. resend = route["method"] == "GET" for attempt in range(5): try: status, raw, response_headers = transport(route["method"], url, headers, data) except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException): if not resend: raise ApiError(0, None, uncertain=True) if attempt == 4: raise time.sleep(2 ** attempt) continue response_headers = {k.lower(): v for k, v in response_headers.items()} result = None if status != 304 and raw: try: result = decode_json(raw.decode("utf-8")) except (ValueError, UnicodeError): if status < 400: raise RuntimeError("Expected a JSON success response") if status >= 500 and not resend: raise ApiError(status, result, uncertain=True) retry = resend and (status == 429 or status >= 500) if retry: if attempt == 4: raise RuntimeError("Retry limit reached; check the request outcome before starting a new create") delay = response_headers.get("retry-after", str(2 ** attempt)) time.sleep(max(0, float(delay))) continue if status >= 400: raise ApiError(status, result) return {"status": status, "body": result, "headers": response_headers, "raw": raw} raise RuntimeError("Retry limit reached") def both(left,right): return left and right def 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] 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 offsetlen(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)-offset:raise JournalRefusal('Incomplete journal frame; reconcile before retry') payload=raw[offset:offset+size];offset+=size if raw[offset:offset+1]!=b'\n' or digest(payload).encode('ascii')!=match[2]:raise JournalRefusal('Journal integrity check failed; reconcile before retry') records.append(read_strings(payload));offset+=1 return records class Journal: def __init__(self,path,base,workspace,slug,job,input_fingerprint,writes,mode="resume"): self.path=Path(path);self.lock=Path(str(self.path)+'.lock');self.fd=None;self.owned=False;self.identity=None;self.tainted=False;self.intents={};self.saved_values={} address=urlsplit(base) if address.scheme not in ('https','http')or not address.netloc or address.username is not None or address.query or address.fragment or not re.fullmatch('[a-z][a-z0-9-]*',slug):raise JournalRefusal('Use the actual API base and closed guide slug') if not job.strip() or not re.fullmatch('[1-9][0-9]*',workspace) or not re.fullmatch('[0-9A-F]{64}',input_fingerprint):raise JournalRefusal('Use an actual workspace, explicit stable job ID and exact input fingerprint') if mode not in ("new","resume"):raise JournalRefusal("Choose new or resume for this local job") self.allowed={};manifest=[] for step,method,route in writes: if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.allowed or method not in ('POST','PATCH','DELETE')or not re.fullmatch('/v1/[A-Za-z0-9_/-]+',route)or'//'in route:raise JournalRefusal('Use a closed unique write manifest') self.allowed[step]=(method,route);manifest.extend((step,method,route)) if not self.allowed:raise JournalRefusal('Only write workflows need a restart journal') self.header=['H','1',base,workspace,slug,job,input_fingerprint,digest(strings(manifest))] strings(self.header) try: self.fd=os.open(self.lock,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600);self.owned=True except FileExistsError:raise JournalRefusal('This journal is locked; do not run overlapping jobs or steal a stale lock') try: self.owner=secrets.token_hex(16);self.identity=os.fstat(self.fd) if os.write(self.fd,self.owner.encode('ascii'))!=len(self.owner):raise OSError('Incomplete lock identity write') os.fsync(self.fd) if self.path.is_symlink():raise JournalRefusal('Choose a private regular journal file') if mode=="resume" and not self.path.exists():raise JournalRefusal("Journal missing: stop and reconcile lost state before starting a new logical job") if mode=="new" and self.path.exists():raise JournalRefusal("A journal already exists; use resume for the same logical job") if mode=="new": with open(self.path,'xb',buffering=0)as target: target.write(PREAMBLE+frame(self.header));os.fsync(target.fileno()) records=decode(self.path.read_bytes()) if not records or records[0]!=self.header:raise JournalRefusal('Journal workspace/base/guide/job/input binding differs') for record in records[1:]:self.apply(record) if any(step not in self.saved_values for step in self.intents):raise JournalRefusal('A saved before-send intent lacks an ACK; stop and reconcile its outcome before retry') except BaseException: self.close();raise def apply(self,record): if not record:raise JournalRefusal('Empty journal record') if record[0]=='I': if len(record)!=6:raise JournalRefusal('Invalid intent shape') _,step,method,path,request_fingerprint,key=record if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.intents or self.allowed.get(step)!=(method,path)or not re.fullmatch('[0-9A-F]{64}',request_fingerprint)or any(name not in self.saved_values for name in self.intents):raise JournalRefusal('Invalid, future or repeated journal intent') if method=='POST'and not re.fullmatch('[0-9a-f]{32}',key)or method!='POST'and key!='':raise JournalRefusal('Invalid persisted action key') self.intents[step]={'method':method,'path':path,'request_fingerprint':request_fingerprint,'idempotency_key':key} elif record[0]=='A': if len(record)<3:raise JournalRefusal('Invalid ACK shape') _,step,count,*pairs=record if not re.fullmatch('0|[1-9][0-9]*',count)or len(pairs)!=2*int(count)or step not in self.intents or step in self.saved_values:raise JournalRefusal('ACK without exactly one prior intent') names=pairs[::2] if names!=sorted(set(names))or any(not re.fullmatch('[a-z][a-z0-9_]*',name)or name in ('api_key','exhibitday_api_key')for name in names):raise JournalRefusal('ACK saved fields must be unique sorted secret-free identifiers') self.saved_values[step]=dict(zip(names,pairs[1::2])) else:raise JournalRefusal('Unknown journal transition') def append(self,record): # The reader commits state only after complete length/digest recognition. # A torn append is retained and refused, never silently truncated. self.require_active();raw=frame(record) try: with open(self.path,'ab',buffering=0)as target: view=memoryview(raw) while view: written=target.write(view) if not written:raise OSError('Journal write did not advance') view=view[written:] os.fsync(target.fileno()) except BaseException: self.tainted=True;raise def require_active(self): if not self.owned or self.fd is None or self.identity is None or self.tainted:raise JournalRefusal('The journal scope is closed or its IO outcome needs reconciliation') current=self.lock.stat(follow_symlinks=False) if current.st_dev!=self.identity.st_dev or current.st_ino!=self.identity.st_ino or self.lock.read_text(encoding='ascii')!=self.owner:raise JournalRefusal('The journal lock was replaced; stop without deleting it') def acknowledged(self,step): self.require_active();return step in self.saved_values def saved(self,step): self.require_active() if step not in self.saved_values:raise JournalRefusal('No acknowledged state exists for this step') return dict(self.saved_values[step]) def begin(self,step,method,path,request_fingerprint): self.require_active() if step in self.intents:raise JournalRefusal('Never blindly repeat an existing action intent') key=secrets.token_hex(16)if method=='POST'else'' record=['I',step,method,path,request_fingerprint,key] # Validate on an isolated state before touching the file. old=dict(self.intents) try:self.apply(record) finally:self.intents=old self.append(record);self.apply(record) return dict(self.intents[step]) def acknowledge(self,step,saved): self.require_active() record=['A',step,str(len(saved))] for name,value in sorted(saved.items()):record.extend((name,value)) old={name:dict(value)for name,value in self.saved_values.items()} try:self.apply(record);strings(record) finally:self.saved_values=old self.append(record);self.apply(record) def close(self): if self.owned: if self.tainted: os.close(self.fd);self.fd=None;self.owned=False return # Retain this lock after failed journal IO; manual reconciliation is required. try:self.require_active() except BaseException: os.close(self.fd);self.fd=None;self.owned=False;raise os.close(self.fd);self.fd=None;self.owned=False self.lock.unlink() def __enter__(self):return self def __exit__(self,*args):self.close() def journal_values(value): if not isinstance(value, dict) or any(not isinstance(k, str) or not isinstance(v, str) for k,v in value.items()): raise JournalRefusal('Saved/fingerprint values must be exact string fields') return dict(value) def journal_acknowledge(job, step, saved): job.acknowledge(step,journal_values(saved)) def journal_acknowledged(job, step): return job.acknowledged(step) def journal_begin(job, step, method, path, request_fingerprint): return job.begin(step,method,path,request_fingerprint) def journal_fingerprint(value): return fingerprint(journal_values(value)) def journal_saved(job, step): return job.saved(step) def 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 positive_id(value): if not re.fullmatch(r"[1-9][0-9]*", value) or int(value) > 9223372036854775807: raise RuntimeError("Use a positive record ID") return value def print_value(value): print(value if isinstance(value, str) else json.dumps(value, ensure_ascii=False)) def require_condition(value, message): if value is not True: raise RuntimeError(message) def required(name): value = os.environ.get(name) if value is None or not value.strip(): raise RuntimeError("Set " + name) return value def response_status(value): return str(value["status"]) def 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 validate_capital_reservation_dates(start, end): from datetime import date try: valid = all(re.fullmatch(r'[0-9]{4}-[0-9]{2}-[0-9]{2}', value) and date.fromisoformat(value) for value in (start, end)) except ValueError: valid = False if not valid or end < start: raise JournalRefusal('Use valid reservation and return dates in YYYY-MM-DD form, with return on or after reservation.') def main(): reserve_event_id = positive_id(required("EXHIBITDAY_EVENT_ID")) reserve_asset_id = positive_id(required("EXHIBITDAY_ASSET_ID")) reserve_start = required("EXHIBITDAY_RESERVATION_DATE") reserve_end = required("EXHIBITDAY_RETURN_DATE") reserve_journal_path = required("EXHIBITDAY_JOURNAL") reserve_job_id = required("EXHIBITDAY_JOB_ID") reserve_job_mode = optional("EXHIBITDAY_JOB_MODE", "resume") require_condition(either(equal(reserve_job_mode, "new"), equal(reserve_job_mode, "resume")), "Use exact new or resume for EXHIBITDAY_JOB_MODE.") validate_capital_reservation_dates(reserve_start, reserve_end) reserve_workspace_response = call("workspace_binding", {}, None, None) require_condition(equal(response_status(reserve_workspace_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") reserve_workspace = reserve_workspace_response["body"] reserve_workspace_id = positive_id(text(field(reserve_workspace, "id"))) reserve_input_fingerprint = journal_fingerprint({"workflow_contract_sha256": "2A835F55E124977C3B498E4C462F96FBF20CB76917E5A036A3D3B11327D77382", "asset_type_id": "1", "asset_id": reserve_asset_id, "event_id": reserve_event_id, "reservation_date": reserve_start, "return_date": reserve_end, "notes": "Display monitor for Spring Expo 2030", "notifications": "false"}) reserve_job = open_journal(reserve_journal_path, "https://api.exhibitday.com/v1", reserve_workspace_id, "reserve-change-cancel-assets", reserve_job_id, reserve_input_fingerprint, [["create_reservation", "POST", "/v1/assets/reservations"], ["mark_checked", "PATCH", "/v1/assets/reservations"]], reserve_job_mode) try: require_condition(either(not_value(journal_acknowledged(reserve_job, "mark_checked")), journal_acknowledged(reserve_job, "create_reservation")), "An update is acknowledged before its create. Stop and reconcile the journal.") reserve_id = "" if journal_acknowledged(reserve_job, "create_reservation"): reserve_created_saved = journal_saved(reserve_job, "create_reservation") reserve_id = positive_id(text(field(reserve_created_saved, "id"))) require_condition(both(both(equal(text(field(reserve_created_saved, "asset_type_id")), "1"), equal(text(field(reserve_created_saved, "asset_id")), reserve_asset_id)), equal(text(field(reserve_created_saved, "event_id")), reserve_event_id)), "The acknowledged create belongs to a different typed Asset or Event; do not create a replacement.") else: reserve_availability_response = call("availability", {"asset_id": reserve_asset_id, "asset_type_id": "1", "start_date": reserve_start, "end_date": reserve_end}, None, None) require_condition(equal(response_status(reserve_availability_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") reserve_availability_value = reserve_availability_response["body"] require_condition(both(both(both(both(both(equal(text(field(reserve_availability_value, "asset_id")), reserve_asset_id), equal(text(field(reserve_availability_value, "asset_type_id")), "1")), equal(text(field(reserve_availability_value, "start_date")), reserve_start)), equal(text(field(reserve_availability_value, "end_date")), reserve_end)), equal(field(reserve_availability_value, "is_asset_owned_by_this_workspace"), True)), equal(field(reserve_availability_value, "is_advisory"), True)), "Availability must describe this owned Capital Asset and exact requested calendar dates; it is advisory, not a reservation.") if not_value(equal(field(reserve_availability_value, "is_available_under_reservation_policy"), True)): print_value(reserve_availability_response["raw"].decode("utf-8")) require_condition(False, "No reservation was sent. Availability does not permit this new allocation; review the dates and policy before another decision.") reserve_create_fingerprint = journal_fingerprint({"asset_type_id": "1", "asset_id": reserve_asset_id, "event_id": reserve_event_id, "reservation_date": reserve_start, "return_date": reserve_end, "notes": "Display monitor for Spring Expo 2030", "notify_new_reservation": "false"}) reserve_create_intent = journal_begin(reserve_job, "create_reservation", "POST", "/v1/assets/reservations", reserve_create_fingerprint) reserve_create_response = call("create_reservation", {}, {"asset_type_id": "1", "asset_id": reserve_asset_id, "event_id": reserve_event_id, "reservation_date": reserve_start, "return_date": reserve_end, "notes": "Display monitor for Spring Expo 2030", "notify_new_reservation": False}, text(field(reserve_create_intent, "idempotency_key"))) require_condition(equal(response_status(reserve_create_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") reserve_created = reserve_create_response["body"] reserve_id = positive_id(text(field(reserve_created, "id"))) require_condition(both(both(both(both(both(both(both(both(equal(text(field(reserve_created, "id")), reserve_id), equal(text(field(reserve_created, "asset_type_id")), "1")), equal(text(field(reserve_created, "asset_id")), reserve_asset_id)), equal(text(field(reserve_created, "event_id")), reserve_event_id)), equal(field(reserve_created, "is_asset_owned_by_this_workspace"), True)), equal(text(field(reserve_created, "reservation_date")), reserve_start)), equal(text(field(reserve_created, "return_date")), reserve_end)), equal(text(field(reserve_created, "notes")), "Display monitor for Spring Expo 2030")), equal(field(reserve_created, "is_checked"), False)), "The reservation differs from the captured typed ID, owned Asset, Event, dates, notes or checked state. Review it before continuing; do not restore it automatically.") journal_acknowledge(reserve_job, "create_reservation", {"id": reserve_id, "asset_type_id": "1", "asset_id": reserve_asset_id, "event_id": reserve_event_id}) reserve_read_response = call("read_reservation", {"id": reserve_id, "asset_type_id": "1", "$include_record_revision": "true"}, None, None) require_condition(equal(response_status(reserve_read_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") reserve_current = reserve_read_response["body"] reserve_revision = text(field(reserve_current, "record_revision")) require_condition(is_present(reserve_revision), "The actual reservation Info read must include its record_revision.") if journal_acknowledged(reserve_job, "mark_checked"): reserve_update_saved = journal_saved(reserve_job, "mark_checked") require_condition(both(both(both(both(equal(text(field(reserve_update_saved, "id")), reserve_id), equal(text(field(reserve_update_saved, "asset_type_id")), "1")), equal(text(field(reserve_update_saved, "asset_id")), reserve_asset_id)), equal(text(field(reserve_update_saved, "event_id")), reserve_event_id)), equal(text(field(reserve_update_saved, "record_revision")), reserve_revision)), "The acknowledged update or current revision differs. Stop and review; do not restore earlier values.") require_condition(both(both(both(both(both(both(both(both(equal(text(field(reserve_current, "id")), reserve_id), equal(text(field(reserve_current, "asset_type_id")), "1")), equal(text(field(reserve_current, "asset_id")), reserve_asset_id)), equal(text(field(reserve_current, "event_id")), reserve_event_id)), equal(field(reserve_current, "is_asset_owned_by_this_workspace"), True)), equal(text(field(reserve_current, "reservation_date")), reserve_start)), equal(text(field(reserve_current, "return_date")), reserve_end)), equal(text(field(reserve_current, "notes")), "Display monitor for Spring Expo 2030")), equal(field(reserve_current, "is_checked"), True)), "The reservation differs from the captured typed ID, owned Asset, Event, dates, notes or checked state. Review it before continuing; do not restore it automatically.") else: require_condition(both(both(both(both(both(both(both(both(equal(text(field(reserve_current, "id")), reserve_id), equal(text(field(reserve_current, "asset_type_id")), "1")), equal(text(field(reserve_current, "asset_id")), reserve_asset_id)), equal(text(field(reserve_current, "event_id")), reserve_event_id)), equal(field(reserve_current, "is_asset_owned_by_this_workspace"), True)), equal(text(field(reserve_current, "reservation_date")), reserve_start)), equal(text(field(reserve_current, "return_date")), reserve_end)), equal(text(field(reserve_current, "notes")), "Display monitor for Spring Expo 2030")), equal(field(reserve_current, "is_checked"), False)), "The reservation differs from the captured typed ID, owned Asset, Event, dates, notes or checked state. Review it before continuing; do not restore it automatically.") reserve_patch = {"id": reserve_id, "asset_type_id": "1", "is_checked": True, "expected_revision": reserve_revision, "notify_reservation_update": False} reserve_patch_fingerprint = journal_fingerprint({"id": reserve_id, "asset_type_id": "1", "is_checked": "true", "expected_revision": reserve_revision, "notify_reservation_update": "false"}) journal_begin(reserve_job, "mark_checked", "PATCH", "/v1/assets/reservations", reserve_patch_fingerprint) reserve_patch_response = None try: reserve_patch_response = call("mark_checked", {}, reserve_patch, None) require_condition(reserve_patch_response["status"] == 200, "Expected HTTP200 for the selected conditional PATCH; read current values before another decision.") require_condition(is_present(text(field(reserve_patch_response["body"], "record_revision"))), "The conditional PATCH acknowledgement needs its actual record_revision.") except Exception as reserve_patch_response_failure: print_value(str(reserve_patch_response_failure)) reserve_failure_read_response = call("read_reservation", {"id": reserve_id, "asset_type_id": "1", "$include_record_revision": "true"}, None, None) require_condition(equal(response_status(reserve_failure_read_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") print_value(reserve_failure_read_response["raw"].decode("utf-8")) require_condition(False, "Review these actual current values and reconcile the saved pending PATCH before another write. The programme did not repeat or acknowledge the update.") require_condition(equal(response_status(reserve_patch_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") reserve_patch_receipt = reserve_patch_response["body"] reserve_after_revision = text(field(reserve_patch_receipt, "record_revision")) journal_acknowledge(reserve_job, "mark_checked", {"id": reserve_id, "asset_type_id": "1", "asset_id": reserve_asset_id, "event_id": reserve_event_id, "record_revision": reserve_after_revision}) reserve_verify_response = call("verify_reservation", {"id": reserve_id, "asset_type_id": "1"}, None, None) require_condition(equal(response_status(reserve_verify_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") reserve_verified = reserve_verify_response["body"] require_condition(both(both(both(both(both(both(both(both(equal(text(field(reserve_verified, "id")), reserve_id), equal(text(field(reserve_verified, "asset_type_id")), "1")), equal(text(field(reserve_verified, "asset_id")), reserve_asset_id)), equal(text(field(reserve_verified, "event_id")), reserve_event_id)), equal(field(reserve_verified, "is_asset_owned_by_this_workspace"), True)), equal(text(field(reserve_verified, "reservation_date")), reserve_start)), equal(text(field(reserve_verified, "return_date")), reserve_end)), equal(text(field(reserve_verified, "notes")), "Display monitor for Spring Expo 2030")), equal(field(reserve_verified, "is_checked"), True)), "The reservation differs from the captured typed ID, owned Asset, Event, dates, notes or checked state. Review it before continuing; do not restore it automatically.") reserve_options_response = call("cancellation_options", {"id": reserve_id, "asset_type_id": "1"}, None, None) require_condition(equal(response_status(reserve_options_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") reserve_options = reserve_options_response["body"] require_condition(both(both(equal(text(field(reserve_options, "reservation_id")), reserve_id), equal(text(field(reserve_options, "asset_id")), reserve_asset_id)), equal(text(field(reserve_options, "asset_type_id")), "1")), "The cancellation options describe a different typed reservation. No cancellation was sent.") print_value({"id": reserve_id, "asset_type_id": "1", "asset_id": reserve_asset_id, "event_id": reserve_event_id, "is_checked": field(reserve_verified, "is_checked"), "inventory_outcomes": field(reserve_options, "inventory_outcomes")}) finally: reserve_job.close() if __name__ == "__main__": main() EXHIBITDAY_PY ``` ```javascript // Server-side Node.js with fetch; built-in modules only. Set EXHIBITDAY_API_KEY. const BASE = "https://api.exhibitday.com/v1"; const SPEC = JSON.parse("{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"availability\":{\"method\":\"GET\",\"path\":\"/assets/availability\"},\"create_reservation\":{\"method\":\"POST\",\"path\":\"/assets/reservations\"},\"read_reservation\":{\"method\":\"GET\",\"path\":\"/assets/reservations/info\"},\"mark_checked\":{\"method\":\"PATCH\",\"path\":\"/assets/reservations\"},\"verify_reservation\":{\"method\":\"GET\",\"path\":\"/assets/reservations/info\"},\"cancellation_options\":{\"method\":\"GET\",\"path\":\"/assets/reservation_cancellation_inventory_options\"}}}"); const API_KEY = process.env.EXHIBITDAY_API_KEY; if (!API_KEY || !API_KEY.trim()) throw new Error("Set EXHIBITDAY_API_KEY"); if (/[^\x20-\x7e]/.test(API_KEY)) throw new Error("Use the API key as one ASCII header value without control characters"); 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, errors: result.errors, error_params: result.error_params, 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, key = null) { const route = SPEC.requests[name]; const headers = { Authorization: "Bearer " + API_KEY, Accept: "application/json" }; if (route.method === "POST") { if (!key) throw new Error("Persist a logical create key before sending POST"); headers["Idempotency-Key"] = key; } 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 : ""); // 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. const resend = route.method === "GET"; 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 = resend && (response.status === 429 || response.status >= 500); 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, raw }; } throw new Error("Retry limit reached"); } function both(left,right) { return left && right; } function either(left, right) { if (typeof left !== "boolean" || typeof right !== "boolean") throw new Error("Expected Boolean criteria"); return left || right; } function equal(left, right) { return typeof left === typeof right && left === right; } function field(value, name) { if (!value || Array.isArray(value) || typeof value !== "object" || !Object.hasOwn(value, name)) throw new Error("Missing response field: " + name); return value[name]; } function is_present(value) { return value !== null && value !== undefined && value !== ""; } 'use strict'; // Private client restart state. No HTTP or application dependency. const fs = require('node:fs'); const crypto = require('node:crypto'); const PREAMBLE = Buffer.from('EXHIBITDAY-GUIDE-JOURNAL 1\n', 'ascii'); class JournalRefusal extends Error {} function ascii(raw) { if (raw.some(value => value > 127)) throw new JournalRefusal('Journal framing must be canonical ASCII'); return raw.toString('ascii'); } function utf8(value) { if (typeof value !== 'string') throw new JournalRefusal('Journal fields are exact strings'); for (const unit of value) if (unit.length === 1 && unit.charCodeAt(0) >= 0xd800 && unit.charCodeAt(0) <= 0xdfff) throw new JournalRefusal('Invalid Unicode journal field'); return Buffer.from(value, 'utf8'); } function strings(values) { const parts = []; for (const value of values) { const raw = utf8(value); parts.push(Buffer.from(String(raw.length) + ':', 'ascii'), raw); } return Buffer.concat(parts); } function readStrings(raw) { const values = []; let offset = 0; while (offset < raw.length) { const end = raw.indexOf(58, offset); if (end < 0) throw new JournalRefusal('Incomplete journal string length'); const length = ascii(raw.subarray(offset, end)); if (!/^(0|[1-9][0-9]*)$/.test(length)) throw new JournalRefusal('Noncanonical journal string length'); const size = BigInt(length); offset = end + 1; if (size > BigInt(raw.length - offset)) throw new JournalRefusal('Incomplete journal string'); const count = Number(size); values.push(new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(raw.subarray(offset, offset + count))); offset += count; } return values; } function digest(raw) { return crypto.createHash('sha256').update(raw).digest('hex').toUpperCase(); } function fingerprint(pairs) { const values = []; for (const name of Object.keys(pairs).sort()) { if (!/^[A-Za-z0-9_.-]+$/.test(name) || ['api_key', 'exhibitday_api_key'].includes(name.toLowerCase())) throw new JournalRefusal('Use explicit secret-free fingerprint field names'); values.push(name, pairs[name]); } return digest(strings(values)); } function frame(values) { const raw = strings(values); return Buffer.concat([Buffer.from(String(raw.length) + ' ' + digest(raw) + '\n', 'ascii'), raw, Buffer.from('\n')]); } function decode(raw) { if (!raw.subarray(0, PREAMBLE.length).equals(PREAMBLE)) throw new JournalRefusal('Unknown or incomplete journal version'); let offset = PREAMBLE.length; const records = []; while (offset < raw.length) { const end = raw.indexOf(10, offset); if (end < 0) throw new JournalRefusal('Incomplete journal frame header; reconcile before retry'); const match = /^(0|[1-9][0-9]*) ([0-9A-F]{64})$/.exec(ascii(raw.subarray(offset, end))); if (!match) throw new JournalRefusal('Invalid journal frame header'); const size = BigInt(match[1]); offset = end + 1; if (size >= BigInt(raw.length - offset)) throw new JournalRefusal('Incomplete journal frame; reconcile before retry'); const count = Number(size), payload = raw.subarray(offset, offset + count); offset += count; if (raw[offset] !== 10 || digest(payload) !== match[2]) throw new JournalRefusal('Journal integrity check failed; reconcile before retry'); records.push(readStrings(payload)); offset++; } return records; } function writeAll(fd, raw) { let offset = 0; while (offset < raw.length) { const count = fs.writeSync(fd, raw, offset, raw.length - offset); if (!count) throw new Error('Journal write did not advance'); offset += count; } } function same(left, right) { return left.length === right.length && left.every((value, index) => value === right[index]); } class Journal { constructor(path, base, workspace, slug, job, inputFingerprint, writes, mode = 'resume') { this.path = path; this.lock = path + '.lock'; this.fd = null; this.owned = false; this.identity = null; this.tainted = false; this.intents = new Map(); this.savedValues = new Map(); this.allowed = new Map(); if (!['new', 'resume'].includes(mode)) throw new JournalRefusal('Choose new or resume for this local job'); const address = new URL(base); if (!['https:', 'http:'].includes(address.protocol) || !address.hostname || address.username || address.password || address.search || address.hash || !/^[a-z][a-z0-9-]*$/.test(slug)) throw new JournalRefusal('Use the actual API base and closed guide slug'); if (!job.trim() || !/^[1-9][0-9]*$/.test(workspace) || !/^[0-9A-F]{64}$/.test(inputFingerprint)) throw new JournalRefusal('Use an actual workspace, stable explicit job ID and exact input fingerprint'); const manifest = []; for (const [step, method, route] of writes) { if (!/^[a-z][a-z0-9_-]*$/.test(step) || this.allowed.has(step) || !['POST', 'PATCH', 'DELETE'].includes(method) || !/^\/v1\/[A-Za-z0-9_/-]+$/.test(route) || route.includes('//')) throw new JournalRefusal('Use a closed unique write manifest'); this.allowed.set(step, [method, route]); manifest.push(step, method, route); } if (!this.allowed.size) throw new JournalRefusal('Only write workflows need a restart journal'); this.header = ['H', '1', base, workspace, slug, job, inputFingerprint, digest(strings(manifest))]; strings(this.header); try { this.fd = fs.openSync(this.lock, 'wx', 0o600); this.owned = true; } catch (error) { if (error.code === 'EEXIST') throw new JournalRefusal('This journal is locked; do not overlap jobs or steal a stale lock'); throw error; } try { this.owner = crypto.randomBytes(16).toString('hex'); this.identity = fs.fstatSync(this.fd, { bigint: true }); writeAll(this.fd, Buffer.from(this.owner, 'ascii')); fs.fsyncSync(this.fd); let exists = true; try { if (fs.lstatSync(path).isSymbolicLink()) throw new JournalRefusal('Choose a private regular journal file'); } catch (error) { if (error.code === 'ENOENT') exists = false; else throw error; } if (mode === 'resume' && !exists) throw new JournalRefusal('Journal missing: stop and reconcile lost state before starting a new logical job'); if (mode === 'new' && exists) throw new JournalRefusal('Journal already exists; use resume for the same logical job'); if (mode === 'new') { const target = fs.openSync(path, 'wx', 0o600); try { writeAll(target, Buffer.concat([PREAMBLE, frame(this.header)])); fs.fsyncSync(target); } finally { fs.closeSync(target); } } const records = decode(fs.readFileSync(path)); if (!records.length || !same(records[0], this.header)) throw new JournalRefusal('Journal workspace/base/guide/job/input binding differs'); for (const record of records.slice(1)) this.apply(record); if ([...this.intents.keys()].some(step => !this.savedValues.has(step))) throw new JournalRefusal('Saved before-send intent lacks ACK; stop and reconcile before retry'); } catch (error) { this.close(); throw error; } } apply(record) { if (record[0] === 'I') { if (record.length !== 6) throw new JournalRefusal('Invalid intent shape'); const [, step, method, path, requestFingerprint, key] = record; if (!/^[a-z][a-z0-9_-]*$/.test(step) || this.intents.has(step) || !this.allowed.has(step) || !same(this.allowed.get(step), [method, path]) || !/^[0-9A-F]{64}$/.test(requestFingerprint) || [...this.intents.keys()].some(name => !this.savedValues.has(name))) throw new JournalRefusal('Invalid, future or repeated intent'); if ((method === 'POST' && !/^[0-9a-f]{32}$/.test(key)) || (method !== 'POST' && key !== '')) throw new JournalRefusal('Invalid persisted action key'); this.intents.set(step, { method, path, request_fingerprint: requestFingerprint, idempotency_key: key }); } else if (record[0] === 'A') { const [, step, count, ...pairs] = record; if (record.length < 3 || !/^(0|[1-9][0-9]*)$/.test(count) || BigInt(pairs.length) !== 2n * BigInt(count) || !this.intents.has(step) || this.savedValues.has(step)) throw new JournalRefusal('ACK without exactly one prior intent'); const names = pairs.filter((_, index) => index % 2 === 0); if (!same(names, [...new Set(names)].sort()) || names.some(name => !/^[a-z][a-z0-9_]*$/.test(name) || ['api_key', 'exhibitday_api_key'].includes(name))) throw new JournalRefusal('ACK fields must be unique sorted secret-free identifiers'); this.savedValues.set(step, Object.fromEntries(names.map((name, index) => [name, pairs[index * 2 + 1]]))); } else throw new JournalRefusal('Unknown journal transition'); } requireActive() { if (!this.owned || this.fd === null || this.identity === null || this.tainted) throw new JournalRefusal('Journal is closed or its IO outcome needs reconciliation'); const current = fs.lstatSync(this.lock, { bigint: true }); if (current.dev !== this.identity.dev || current.ino !== this.identity.ino || ascii(fs.readFileSync(this.lock)) !== this.owner) throw new JournalRefusal('Journal lock was replaced; stop without deleting it'); } append(record) { this.requireActive(); const raw = frame(record); let target; try { target = fs.openSync(this.path, 'a'); writeAll(target, raw); fs.fsyncSync(target); } catch (error) { this.tainted = true; throw error; } finally { if (target !== undefined) fs.closeSync(target); } } acknowledged(step) { this.requireActive(); return this.savedValues.has(step); } saved(step) { this.requireActive(); if (!this.savedValues.has(step)) throw new JournalRefusal('No acknowledged state exists'); return { ...this.savedValues.get(step) }; } begin(step, method, path, requestFingerprint) { this.requireActive(); if (this.intents.has(step)) throw new JournalRefusal('Never blindly repeat an existing action'); const key = method === 'POST' ? crypto.randomBytes(16).toString('hex') : '', record = ['I', step, method, path, requestFingerprint, key]; const old = new Map(this.intents); try { this.apply(record); } finally { this.intents = old; } this.append(record); this.apply(record); return { ...this.intents.get(step) }; } acknowledge(step, saved) { this.requireActive(); const names = Object.keys(saved).sort(), record = ['A', step, String(names.length)]; for (const name of names) record.push(name, saved[name]); const old = new Map(this.savedValues); try { this.apply(record); strings(record); } finally { this.savedValues = old; } this.append(record); this.apply(record); } close() { if (!this.owned) return; if (this.tainted) { fs.closeSync(this.fd); this.fd = null; this.owned = false; return; } try { this.requireActive(); } catch (error) { fs.closeSync(this.fd); this.fd = null; this.owned = false; throw error; } fs.closeSync(this.fd); this.fd = null; this.owned = false; fs.unlinkSync(this.lock); } } function journal_values(value) { if (!value || typeof value !== 'object' || Array.isArray(value) || Object.values(value).some(item=>typeof item!=='string')) throw new JournalRefusal('Saved/fingerprint values must be exact strings'); return {...value}; } function journal_acknowledge(job,step,saved) { job.acknowledge(step,journal_values(saved)); } function journal_acknowledged(job,step) { return job.acknowledged(step); } function journal_begin(job,step,method,path,requestFingerprint) { return job.begin(step,method,path,requestFingerprint); } function journal_fingerprint(value) { return fingerprint(journal_values(value)); } function journal_saved(job,step) { return job.saved(step); } function not_value(value) { if (typeof value !== "boolean") throw new Error("Expected a Boolean"); return !value; } function open_journal(path,base,workspace,slug,job,inputFingerprint,writes,mode) { return new Journal(path,base,workspace,slug,job,inputFingerprint,writes,mode); } function optional(name, fallback) { const value = process.env[name]; return value === undefined || value === "" ? fallback : value; } function positive_id(value) { if (!/^[1-9][0-9]*$/.test(value) || BigInt(value) > 9223372036854775807n) throw new Error("Use a positive record ID"); return value; } function print_value(value) { console.log(typeof value === "string" ? value : JSON.stringify(value)); } function require_condition(value, message) { if (value !== true) throw new Error(message); } function required(name) { const value = process.env[name]; if (value === undefined || !value.trim()) throw new Error("Set " + name); return value; } function response_status(value) { return String(value.status); } function text(value) { if (value === null || value === undefined) return ""; if (["string", "boolean", "bigint"].includes(typeof value)) return String(value); throw new Error("Expected a scalar response value"); } function validate_capital_reservation_dates(start, end) { const valid = value => { if (value.length !== 10 || !/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test(value) || value.startsWith('0000')) return false; const day = new Date(value + 'T00:00:00Z'); return !Number.isNaN(day.getTime()) && day.toISOString().slice(0, 10) === value; }; if (!valid(start) || !valid(end) || end < start) throw new JournalRefusal('Use valid reservation and return dates in YYYY-MM-DD form, with return on or after reservation.'); } async function main() { let reserve_event_id = positive_id(required("EXHIBITDAY_EVENT_ID")); let reserve_asset_id = positive_id(required("EXHIBITDAY_ASSET_ID")); let reserve_start = required("EXHIBITDAY_RESERVATION_DATE"); let reserve_end = required("EXHIBITDAY_RETURN_DATE"); let reserve_journal_path = required("EXHIBITDAY_JOURNAL"); let reserve_job_id = required("EXHIBITDAY_JOB_ID"); let reserve_job_mode = optional("EXHIBITDAY_JOB_MODE", "resume"); require_condition(either(equal(reserve_job_mode, "new"), equal(reserve_job_mode, "resume")), "Use exact new or resume for EXHIBITDAY_JOB_MODE."); validate_capital_reservation_dates(reserve_start, reserve_end); let reserve_workspace_response = await call("workspace_binding", {}, null, null); require_condition(equal(response_status(reserve_workspace_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); let reserve_workspace = reserve_workspace_response.body; let reserve_workspace_id = positive_id(text(field(reserve_workspace, "id"))); let reserve_input_fingerprint = journal_fingerprint({"workflow_contract_sha256": "2A835F55E124977C3B498E4C462F96FBF20CB76917E5A036A3D3B11327D77382", "asset_type_id": "1", "asset_id": reserve_asset_id, "event_id": reserve_event_id, "reservation_date": reserve_start, "return_date": reserve_end, "notes": "Display monitor for Spring Expo 2030", "notifications": "false"}); let reserve_job = open_journal(reserve_journal_path, "https://api.exhibitday.com/v1", reserve_workspace_id, "reserve-change-cancel-assets", reserve_job_id, reserve_input_fingerprint, [["create_reservation", "POST", "/v1/assets/reservations"], ["mark_checked", "PATCH", "/v1/assets/reservations"]], reserve_job_mode); try { require_condition(either(not_value(journal_acknowledged(reserve_job, "mark_checked")), journal_acknowledged(reserve_job, "create_reservation")), "An update is acknowledged before its create. Stop and reconcile the journal."); let reserve_id = ""; if (journal_acknowledged(reserve_job, "create_reservation")) { let reserve_created_saved = journal_saved(reserve_job, "create_reservation"); reserve_id = positive_id(text(field(reserve_created_saved, "id"))); require_condition(both(both(equal(text(field(reserve_created_saved, "asset_type_id")), "1"), equal(text(field(reserve_created_saved, "asset_id")), reserve_asset_id)), equal(text(field(reserve_created_saved, "event_id")), reserve_event_id)), "The acknowledged create belongs to a different typed Asset or Event; do not create a replacement."); } else { let reserve_availability_response = await call("availability", {"asset_id": reserve_asset_id, "asset_type_id": "1", "start_date": reserve_start, "end_date": reserve_end}, null, null); require_condition(equal(response_status(reserve_availability_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); let reserve_availability_value = reserve_availability_response.body; require_condition(both(both(both(both(both(equal(text(field(reserve_availability_value, "asset_id")), reserve_asset_id), equal(text(field(reserve_availability_value, "asset_type_id")), "1")), equal(text(field(reserve_availability_value, "start_date")), reserve_start)), equal(text(field(reserve_availability_value, "end_date")), reserve_end)), equal(field(reserve_availability_value, "is_asset_owned_by_this_workspace"), true)), equal(field(reserve_availability_value, "is_advisory"), true)), "Availability must describe this owned Capital Asset and exact requested calendar dates; it is advisory, not a reservation."); if (not_value(equal(field(reserve_availability_value, "is_available_under_reservation_policy"), true))) { print_value(reserve_availability_response.raw); require_condition(false, "No reservation was sent. Availability does not permit this new allocation; review the dates and policy before another decision."); } let reserve_create_fingerprint = journal_fingerprint({"asset_type_id": "1", "asset_id": reserve_asset_id, "event_id": reserve_event_id, "reservation_date": reserve_start, "return_date": reserve_end, "notes": "Display monitor for Spring Expo 2030", "notify_new_reservation": "false"}); let reserve_create_intent = journal_begin(reserve_job, "create_reservation", "POST", "/v1/assets/reservations", reserve_create_fingerprint); let reserve_create_response = await call("create_reservation", {}, {"asset_type_id": "1", "asset_id": reserve_asset_id, "event_id": reserve_event_id, "reservation_date": reserve_start, "return_date": reserve_end, "notes": "Display monitor for Spring Expo 2030", "notify_new_reservation": false}, text(field(reserve_create_intent, "idempotency_key"))); require_condition(equal(response_status(reserve_create_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); let reserve_created = reserve_create_response.body; reserve_id = positive_id(text(field(reserve_created, "id"))); require_condition(both(both(both(both(both(both(both(both(equal(text(field(reserve_created, "id")), reserve_id), equal(text(field(reserve_created, "asset_type_id")), "1")), equal(text(field(reserve_created, "asset_id")), reserve_asset_id)), equal(text(field(reserve_created, "event_id")), reserve_event_id)), equal(field(reserve_created, "is_asset_owned_by_this_workspace"), true)), equal(text(field(reserve_created, "reservation_date")), reserve_start)), equal(text(field(reserve_created, "return_date")), reserve_end)), equal(text(field(reserve_created, "notes")), "Display monitor for Spring Expo 2030")), equal(field(reserve_created, "is_checked"), false)), "The reservation differs from the captured typed ID, owned Asset, Event, dates, notes or checked state. Review it before continuing; do not restore it automatically."); journal_acknowledge(reserve_job, "create_reservation", {"id": reserve_id, "asset_type_id": "1", "asset_id": reserve_asset_id, "event_id": reserve_event_id}); } let reserve_read_response = await call("read_reservation", {"id": reserve_id, "asset_type_id": "1", "$include_record_revision": "true"}, null, null); require_condition(equal(response_status(reserve_read_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); let reserve_current = reserve_read_response.body; let reserve_revision = text(field(reserve_current, "record_revision")); require_condition(is_present(reserve_revision), "The actual reservation Info read must include its record_revision."); if (journal_acknowledged(reserve_job, "mark_checked")) { let reserve_update_saved = journal_saved(reserve_job, "mark_checked"); require_condition(both(both(both(both(equal(text(field(reserve_update_saved, "id")), reserve_id), equal(text(field(reserve_update_saved, "asset_type_id")), "1")), equal(text(field(reserve_update_saved, "asset_id")), reserve_asset_id)), equal(text(field(reserve_update_saved, "event_id")), reserve_event_id)), equal(text(field(reserve_update_saved, "record_revision")), reserve_revision)), "The acknowledged update or current revision differs. Stop and review; do not restore earlier values."); require_condition(both(both(both(both(both(both(both(both(equal(text(field(reserve_current, "id")), reserve_id), equal(text(field(reserve_current, "asset_type_id")), "1")), equal(text(field(reserve_current, "asset_id")), reserve_asset_id)), equal(text(field(reserve_current, "event_id")), reserve_event_id)), equal(field(reserve_current, "is_asset_owned_by_this_workspace"), true)), equal(text(field(reserve_current, "reservation_date")), reserve_start)), equal(text(field(reserve_current, "return_date")), reserve_end)), equal(text(field(reserve_current, "notes")), "Display monitor for Spring Expo 2030")), equal(field(reserve_current, "is_checked"), true)), "The reservation differs from the captured typed ID, owned Asset, Event, dates, notes or checked state. Review it before continuing; do not restore it automatically."); } else { require_condition(both(both(both(both(both(both(both(both(equal(text(field(reserve_current, "id")), reserve_id), equal(text(field(reserve_current, "asset_type_id")), "1")), equal(text(field(reserve_current, "asset_id")), reserve_asset_id)), equal(text(field(reserve_current, "event_id")), reserve_event_id)), equal(field(reserve_current, "is_asset_owned_by_this_workspace"), true)), equal(text(field(reserve_current, "reservation_date")), reserve_start)), equal(text(field(reserve_current, "return_date")), reserve_end)), equal(text(field(reserve_current, "notes")), "Display monitor for Spring Expo 2030")), equal(field(reserve_current, "is_checked"), false)), "The reservation differs from the captured typed ID, owned Asset, Event, dates, notes or checked state. Review it before continuing; do not restore it automatically."); let reserve_patch = {"id": reserve_id, "asset_type_id": "1", "is_checked": true, "expected_revision": reserve_revision, "notify_reservation_update": false}; let reserve_patch_fingerprint = journal_fingerprint({"id": reserve_id, "asset_type_id": "1", "is_checked": "true", "expected_revision": reserve_revision, "notify_reservation_update": "false"}); journal_begin(reserve_job, "mark_checked", "PATCH", "/v1/assets/reservations", reserve_patch_fingerprint); let reserve_patch_response = null; try { reserve_patch_response = await call("mark_checked", {}, reserve_patch, null); require_condition(reserve_patch_response.status == 200, "Expected HTTP200 for the selected conditional PATCH; read current values before another decision."); require_condition(is_present(text(field(reserve_patch_response.body, "record_revision"))), "The conditional PATCH acknowledgement needs its actual record_revision."); } catch (reserve_patch_response_failure) { print_value(String(reserve_patch_response_failure.message || reserve_patch_response_failure)); let reserve_failure_read_response = await call("read_reservation", {"id": reserve_id, "asset_type_id": "1", "$include_record_revision": "true"}, null, null); require_condition(equal(response_status(reserve_failure_read_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); print_value(reserve_failure_read_response.raw); require_condition(false, "Review these actual current values and reconcile the saved pending PATCH before another write. The programme did not repeat or acknowledge the update."); } require_condition(equal(response_status(reserve_patch_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); let reserve_patch_receipt = reserve_patch_response.body; let reserve_after_revision = text(field(reserve_patch_receipt, "record_revision")); journal_acknowledge(reserve_job, "mark_checked", {"id": reserve_id, "asset_type_id": "1", "asset_id": reserve_asset_id, "event_id": reserve_event_id, "record_revision": reserve_after_revision}); } let reserve_verify_response = await call("verify_reservation", {"id": reserve_id, "asset_type_id": "1"}, null, null); require_condition(equal(response_status(reserve_verify_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); let reserve_verified = reserve_verify_response.body; require_condition(both(both(both(both(both(both(both(both(equal(text(field(reserve_verified, "id")), reserve_id), equal(text(field(reserve_verified, "asset_type_id")), "1")), equal(text(field(reserve_verified, "asset_id")), reserve_asset_id)), equal(text(field(reserve_verified, "event_id")), reserve_event_id)), equal(field(reserve_verified, "is_asset_owned_by_this_workspace"), true)), equal(text(field(reserve_verified, "reservation_date")), reserve_start)), equal(text(field(reserve_verified, "return_date")), reserve_end)), equal(text(field(reserve_verified, "notes")), "Display monitor for Spring Expo 2030")), equal(field(reserve_verified, "is_checked"), true)), "The reservation differs from the captured typed ID, owned Asset, Event, dates, notes or checked state. Review it before continuing; do not restore it automatically."); let reserve_options_response = await call("cancellation_options", {"id": reserve_id, "asset_type_id": "1"}, null, null); require_condition(equal(response_status(reserve_options_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); let reserve_options = reserve_options_response.body; require_condition(both(both(equal(text(field(reserve_options, "reservation_id")), reserve_id), equal(text(field(reserve_options, "asset_id")), reserve_asset_id)), equal(text(field(reserve_options, "asset_type_id")), "1")), "The cancellation options describe a different typed reservation. No cancellation was sent."); print_value({"id": reserve_id, "asset_type_id": "1", "asset_id": reserve_asset_id, "event_id": reserve_event_id, "is_checked": field(reserve_verified, "is_checked"), "inventory_outcomes": field(reserve_options, "inventory_outcomes")}); } finally { reserve_job.close(); } } if (require.main === module) main().catch(error => { console.error(error.message); process.exitCode = 1; }); module.exports = { main }; ``` ```python # 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\"},\"availability\":{\"method\":\"GET\",\"path\":\"/assets/availability\"},\"create_reservation\":{\"method\":\"POST\",\"path\":\"/assets/reservations\"},\"read_reservation\":{\"method\":\"GET\",\"path\":\"/assets/reservations/info\"},\"mark_checked\":{\"method\":\"PATCH\",\"path\":\"/assets/reservations\"},\"verify_reservation\":{\"method\":\"GET\",\"path\":\"/assets/reservations/info\"},\"cancellation_options\":{\"method\":\"GET\",\"path\":\"/assets/reservation_cancellation_inventory_options\"}}}") 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) 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, key=None): route = SPEC["requests"][name] headers = {"Authorization": "Bearer " + API_KEY, "Accept": "application/json"} if route["method"] == "POST": if not key: raise RuntimeError("Persist a logical create key before sending POST") headers["Idempotency-Key"] = key data = None if body is None else json.dumps(body).encode("utf-8") if data is not None: headers["Content-Type"] = "application/json" query = urllib.parse.urlencode(params or {}) url = BASE + route["path"] + ("?" + query if query else "") # Only GET has automatic retries in this workflow. A PATCH or DELETE that got no response or a # server error is never resent blindly: it may already have been applied, so the caller reads the record first. resend = route["method"] == "GET" for attempt in range(5): try: status, raw, response_headers = transport(route["method"], url, headers, data) except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException): if not resend: raise ApiError(0, None, uncertain=True) if attempt == 4: raise time.sleep(2 ** attempt) continue response_headers = {k.lower(): v for k, v in response_headers.items()} result = None if status != 304 and raw: try: result = decode_json(raw.decode("utf-8")) except (ValueError, UnicodeError): if status < 400: raise RuntimeError("Expected a JSON success response") if status >= 500 and not resend: raise ApiError(status, result, uncertain=True) retry = resend and (status == 429 or status >= 500) if retry: if attempt == 4: raise RuntimeError("Retry limit reached; check the request outcome before starting a new create") delay = response_headers.get("retry-after", str(2 ** attempt)) time.sleep(max(0, float(delay))) continue if status >= 400: raise ApiError(status, result) return {"status": status, "body": result, "headers": response_headers, "raw": raw} raise RuntimeError("Retry limit reached") def both(left,right): return left and right def 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] 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 offsetlen(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)-offset:raise JournalRefusal('Incomplete journal frame; reconcile before retry') payload=raw[offset:offset+size];offset+=size if raw[offset:offset+1]!=b'\n' or digest(payload).encode('ascii')!=match[2]:raise JournalRefusal('Journal integrity check failed; reconcile before retry') records.append(read_strings(payload));offset+=1 return records class Journal: def __init__(self,path,base,workspace,slug,job,input_fingerprint,writes,mode="resume"): self.path=Path(path);self.lock=Path(str(self.path)+'.lock');self.fd=None;self.owned=False;self.identity=None;self.tainted=False;self.intents={};self.saved_values={} address=urlsplit(base) if address.scheme not in ('https','http')or not address.netloc or address.username is not None or address.query or address.fragment or not re.fullmatch('[a-z][a-z0-9-]*',slug):raise JournalRefusal('Use the actual API base and closed guide slug') if not job.strip() or not re.fullmatch('[1-9][0-9]*',workspace) or not re.fullmatch('[0-9A-F]{64}',input_fingerprint):raise JournalRefusal('Use an actual workspace, explicit stable job ID and exact input fingerprint') if mode not in ("new","resume"):raise JournalRefusal("Choose new or resume for this local job") self.allowed={};manifest=[] for step,method,route in writes: if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.allowed or method not in ('POST','PATCH','DELETE')or not re.fullmatch('/v1/[A-Za-z0-9_/-]+',route)or'//'in route:raise JournalRefusal('Use a closed unique write manifest') self.allowed[step]=(method,route);manifest.extend((step,method,route)) if not self.allowed:raise JournalRefusal('Only write workflows need a restart journal') self.header=['H','1',base,workspace,slug,job,input_fingerprint,digest(strings(manifest))] strings(self.header) try: self.fd=os.open(self.lock,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600);self.owned=True except FileExistsError:raise JournalRefusal('This journal is locked; do not run overlapping jobs or steal a stale lock') try: self.owner=secrets.token_hex(16);self.identity=os.fstat(self.fd) if os.write(self.fd,self.owner.encode('ascii'))!=len(self.owner):raise OSError('Incomplete lock identity write') os.fsync(self.fd) if self.path.is_symlink():raise JournalRefusal('Choose a private regular journal file') if mode=="resume" and not self.path.exists():raise JournalRefusal("Journal missing: stop and reconcile lost state before starting a new logical job") if mode=="new" and self.path.exists():raise JournalRefusal("A journal already exists; use resume for the same logical job") if mode=="new": with open(self.path,'xb',buffering=0)as target: target.write(PREAMBLE+frame(self.header));os.fsync(target.fileno()) records=decode(self.path.read_bytes()) if not records or records[0]!=self.header:raise JournalRefusal('Journal workspace/base/guide/job/input binding differs') for record in records[1:]:self.apply(record) if any(step not in self.saved_values for step in self.intents):raise JournalRefusal('A saved before-send intent lacks an ACK; stop and reconcile its outcome before retry') except BaseException: self.close();raise def apply(self,record): if not record:raise JournalRefusal('Empty journal record') if record[0]=='I': if len(record)!=6:raise JournalRefusal('Invalid intent shape') _,step,method,path,request_fingerprint,key=record if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.intents or self.allowed.get(step)!=(method,path)or not re.fullmatch('[0-9A-F]{64}',request_fingerprint)or any(name not in self.saved_values for name in self.intents):raise JournalRefusal('Invalid, future or repeated journal intent') if method=='POST'and not re.fullmatch('[0-9a-f]{32}',key)or method!='POST'and key!='':raise JournalRefusal('Invalid persisted action key') self.intents[step]={'method':method,'path':path,'request_fingerprint':request_fingerprint,'idempotency_key':key} elif record[0]=='A': if len(record)<3:raise JournalRefusal('Invalid ACK shape') _,step,count,*pairs=record if not re.fullmatch('0|[1-9][0-9]*',count)or len(pairs)!=2*int(count)or step not in self.intents or step in self.saved_values:raise JournalRefusal('ACK without exactly one prior intent') names=pairs[::2] if names!=sorted(set(names))or any(not re.fullmatch('[a-z][a-z0-9_]*',name)or name in ('api_key','exhibitday_api_key')for name in names):raise JournalRefusal('ACK saved fields must be unique sorted secret-free identifiers') self.saved_values[step]=dict(zip(names,pairs[1::2])) else:raise JournalRefusal('Unknown journal transition') def append(self,record): # The reader commits state only after complete length/digest recognition. # A torn append is retained and refused, never silently truncated. self.require_active();raw=frame(record) try: with open(self.path,'ab',buffering=0)as target: view=memoryview(raw) while view: written=target.write(view) if not written:raise OSError('Journal write did not advance') view=view[written:] os.fsync(target.fileno()) except BaseException: self.tainted=True;raise def require_active(self): if not self.owned or self.fd is None or self.identity is None or self.tainted:raise JournalRefusal('The journal scope is closed or its IO outcome needs reconciliation') current=self.lock.stat(follow_symlinks=False) if current.st_dev!=self.identity.st_dev or current.st_ino!=self.identity.st_ino or self.lock.read_text(encoding='ascii')!=self.owner:raise JournalRefusal('The journal lock was replaced; stop without deleting it') def acknowledged(self,step): self.require_active();return step in self.saved_values def saved(self,step): self.require_active() if step not in self.saved_values:raise JournalRefusal('No acknowledged state exists for this step') return dict(self.saved_values[step]) def begin(self,step,method,path,request_fingerprint): self.require_active() if step in self.intents:raise JournalRefusal('Never blindly repeat an existing action intent') key=secrets.token_hex(16)if method=='POST'else'' record=['I',step,method,path,request_fingerprint,key] # Validate on an isolated state before touching the file. old=dict(self.intents) try:self.apply(record) finally:self.intents=old self.append(record);self.apply(record) return dict(self.intents[step]) def acknowledge(self,step,saved): self.require_active() record=['A',step,str(len(saved))] for name,value in sorted(saved.items()):record.extend((name,value)) old={name:dict(value)for name,value in self.saved_values.items()} try:self.apply(record);strings(record) finally:self.saved_values=old self.append(record);self.apply(record) def close(self): if self.owned: if self.tainted: os.close(self.fd);self.fd=None;self.owned=False return # Retain this lock after failed journal IO; manual reconciliation is required. try:self.require_active() except BaseException: os.close(self.fd);self.fd=None;self.owned=False;raise os.close(self.fd);self.fd=None;self.owned=False self.lock.unlink() def __enter__(self):return self def __exit__(self,*args):self.close() def journal_values(value): if not isinstance(value, dict) or any(not isinstance(k, str) or not isinstance(v, str) for k,v in value.items()): raise JournalRefusal('Saved/fingerprint values must be exact string fields') return dict(value) def journal_acknowledge(job, step, saved): job.acknowledge(step,journal_values(saved)) def journal_acknowledged(job, step): return job.acknowledged(step) def journal_begin(job, step, method, path, request_fingerprint): return job.begin(step,method,path,request_fingerprint) def journal_fingerprint(value): return fingerprint(journal_values(value)) def journal_saved(job, step): return job.saved(step) def 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 positive_id(value): if not re.fullmatch(r"[1-9][0-9]*", value) or int(value) > 9223372036854775807: raise RuntimeError("Use a positive record ID") return value def print_value(value): print(value if isinstance(value, str) else json.dumps(value, ensure_ascii=False)) def require_condition(value, message): if value is not True: raise RuntimeError(message) def required(name): value = os.environ.get(name) if value is None or not value.strip(): raise RuntimeError("Set " + name) return value def response_status(value): return str(value["status"]) def 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 validate_capital_reservation_dates(start, end): from datetime import date try: valid = all(re.fullmatch(r'[0-9]{4}-[0-9]{2}-[0-9]{2}', value) and date.fromisoformat(value) for value in (start, end)) except ValueError: valid = False if not valid or end < start: raise JournalRefusal('Use valid reservation and return dates in YYYY-MM-DD form, with return on or after reservation.') def main(): reserve_event_id = positive_id(required("EXHIBITDAY_EVENT_ID")) reserve_asset_id = positive_id(required("EXHIBITDAY_ASSET_ID")) reserve_start = required("EXHIBITDAY_RESERVATION_DATE") reserve_end = required("EXHIBITDAY_RETURN_DATE") reserve_journal_path = required("EXHIBITDAY_JOURNAL") reserve_job_id = required("EXHIBITDAY_JOB_ID") reserve_job_mode = optional("EXHIBITDAY_JOB_MODE", "resume") require_condition(either(equal(reserve_job_mode, "new"), equal(reserve_job_mode, "resume")), "Use exact new or resume for EXHIBITDAY_JOB_MODE.") validate_capital_reservation_dates(reserve_start, reserve_end) reserve_workspace_response = call("workspace_binding", {}, None, None) require_condition(equal(response_status(reserve_workspace_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") reserve_workspace = reserve_workspace_response["body"] reserve_workspace_id = positive_id(text(field(reserve_workspace, "id"))) reserve_input_fingerprint = journal_fingerprint({"workflow_contract_sha256": "2A835F55E124977C3B498E4C462F96FBF20CB76917E5A036A3D3B11327D77382", "asset_type_id": "1", "asset_id": reserve_asset_id, "event_id": reserve_event_id, "reservation_date": reserve_start, "return_date": reserve_end, "notes": "Display monitor for Spring Expo 2030", "notifications": "false"}) reserve_job = open_journal(reserve_journal_path, "https://api.exhibitday.com/v1", reserve_workspace_id, "reserve-change-cancel-assets", reserve_job_id, reserve_input_fingerprint, [["create_reservation", "POST", "/v1/assets/reservations"], ["mark_checked", "PATCH", "/v1/assets/reservations"]], reserve_job_mode) try: require_condition(either(not_value(journal_acknowledged(reserve_job, "mark_checked")), journal_acknowledged(reserve_job, "create_reservation")), "An update is acknowledged before its create. Stop and reconcile the journal.") reserve_id = "" if journal_acknowledged(reserve_job, "create_reservation"): reserve_created_saved = journal_saved(reserve_job, "create_reservation") reserve_id = positive_id(text(field(reserve_created_saved, "id"))) require_condition(both(both(equal(text(field(reserve_created_saved, "asset_type_id")), "1"), equal(text(field(reserve_created_saved, "asset_id")), reserve_asset_id)), equal(text(field(reserve_created_saved, "event_id")), reserve_event_id)), "The acknowledged create belongs to a different typed Asset or Event; do not create a replacement.") else: reserve_availability_response = call("availability", {"asset_id": reserve_asset_id, "asset_type_id": "1", "start_date": reserve_start, "end_date": reserve_end}, None, None) require_condition(equal(response_status(reserve_availability_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") reserve_availability_value = reserve_availability_response["body"] require_condition(both(both(both(both(both(equal(text(field(reserve_availability_value, "asset_id")), reserve_asset_id), equal(text(field(reserve_availability_value, "asset_type_id")), "1")), equal(text(field(reserve_availability_value, "start_date")), reserve_start)), equal(text(field(reserve_availability_value, "end_date")), reserve_end)), equal(field(reserve_availability_value, "is_asset_owned_by_this_workspace"), True)), equal(field(reserve_availability_value, "is_advisory"), True)), "Availability must describe this owned Capital Asset and exact requested calendar dates; it is advisory, not a reservation.") if not_value(equal(field(reserve_availability_value, "is_available_under_reservation_policy"), True)): print_value(reserve_availability_response["raw"].decode("utf-8")) require_condition(False, "No reservation was sent. Availability does not permit this new allocation; review the dates and policy before another decision.") reserve_create_fingerprint = journal_fingerprint({"asset_type_id": "1", "asset_id": reserve_asset_id, "event_id": reserve_event_id, "reservation_date": reserve_start, "return_date": reserve_end, "notes": "Display monitor for Spring Expo 2030", "notify_new_reservation": "false"}) reserve_create_intent = journal_begin(reserve_job, "create_reservation", "POST", "/v1/assets/reservations", reserve_create_fingerprint) reserve_create_response = call("create_reservation", {}, {"asset_type_id": "1", "asset_id": reserve_asset_id, "event_id": reserve_event_id, "reservation_date": reserve_start, "return_date": reserve_end, "notes": "Display monitor for Spring Expo 2030", "notify_new_reservation": False}, text(field(reserve_create_intent, "idempotency_key"))) require_condition(equal(response_status(reserve_create_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") reserve_created = reserve_create_response["body"] reserve_id = positive_id(text(field(reserve_created, "id"))) require_condition(both(both(both(both(both(both(both(both(equal(text(field(reserve_created, "id")), reserve_id), equal(text(field(reserve_created, "asset_type_id")), "1")), equal(text(field(reserve_created, "asset_id")), reserve_asset_id)), equal(text(field(reserve_created, "event_id")), reserve_event_id)), equal(field(reserve_created, "is_asset_owned_by_this_workspace"), True)), equal(text(field(reserve_created, "reservation_date")), reserve_start)), equal(text(field(reserve_created, "return_date")), reserve_end)), equal(text(field(reserve_created, "notes")), "Display monitor for Spring Expo 2030")), equal(field(reserve_created, "is_checked"), False)), "The reservation differs from the captured typed ID, owned Asset, Event, dates, notes or checked state. Review it before continuing; do not restore it automatically.") journal_acknowledge(reserve_job, "create_reservation", {"id": reserve_id, "asset_type_id": "1", "asset_id": reserve_asset_id, "event_id": reserve_event_id}) reserve_read_response = call("read_reservation", {"id": reserve_id, "asset_type_id": "1", "$include_record_revision": "true"}, None, None) require_condition(equal(response_status(reserve_read_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") reserve_current = reserve_read_response["body"] reserve_revision = text(field(reserve_current, "record_revision")) require_condition(is_present(reserve_revision), "The actual reservation Info read must include its record_revision.") if journal_acknowledged(reserve_job, "mark_checked"): reserve_update_saved = journal_saved(reserve_job, "mark_checked") require_condition(both(both(both(both(equal(text(field(reserve_update_saved, "id")), reserve_id), equal(text(field(reserve_update_saved, "asset_type_id")), "1")), equal(text(field(reserve_update_saved, "asset_id")), reserve_asset_id)), equal(text(field(reserve_update_saved, "event_id")), reserve_event_id)), equal(text(field(reserve_update_saved, "record_revision")), reserve_revision)), "The acknowledged update or current revision differs. Stop and review; do not restore earlier values.") require_condition(both(both(both(both(both(both(both(both(equal(text(field(reserve_current, "id")), reserve_id), equal(text(field(reserve_current, "asset_type_id")), "1")), equal(text(field(reserve_current, "asset_id")), reserve_asset_id)), equal(text(field(reserve_current, "event_id")), reserve_event_id)), equal(field(reserve_current, "is_asset_owned_by_this_workspace"), True)), equal(text(field(reserve_current, "reservation_date")), reserve_start)), equal(text(field(reserve_current, "return_date")), reserve_end)), equal(text(field(reserve_current, "notes")), "Display monitor for Spring Expo 2030")), equal(field(reserve_current, "is_checked"), True)), "The reservation differs from the captured typed ID, owned Asset, Event, dates, notes or checked state. Review it before continuing; do not restore it automatically.") else: require_condition(both(both(both(both(both(both(both(both(equal(text(field(reserve_current, "id")), reserve_id), equal(text(field(reserve_current, "asset_type_id")), "1")), equal(text(field(reserve_current, "asset_id")), reserve_asset_id)), equal(text(field(reserve_current, "event_id")), reserve_event_id)), equal(field(reserve_current, "is_asset_owned_by_this_workspace"), True)), equal(text(field(reserve_current, "reservation_date")), reserve_start)), equal(text(field(reserve_current, "return_date")), reserve_end)), equal(text(field(reserve_current, "notes")), "Display monitor for Spring Expo 2030")), equal(field(reserve_current, "is_checked"), False)), "The reservation differs from the captured typed ID, owned Asset, Event, dates, notes or checked state. Review it before continuing; do not restore it automatically.") reserve_patch = {"id": reserve_id, "asset_type_id": "1", "is_checked": True, "expected_revision": reserve_revision, "notify_reservation_update": False} reserve_patch_fingerprint = journal_fingerprint({"id": reserve_id, "asset_type_id": "1", "is_checked": "true", "expected_revision": reserve_revision, "notify_reservation_update": "false"}) journal_begin(reserve_job, "mark_checked", "PATCH", "/v1/assets/reservations", reserve_patch_fingerprint) reserve_patch_response = None try: reserve_patch_response = call("mark_checked", {}, reserve_patch, None) require_condition(reserve_patch_response["status"] == 200, "Expected HTTP200 for the selected conditional PATCH; read current values before another decision.") require_condition(is_present(text(field(reserve_patch_response["body"], "record_revision"))), "The conditional PATCH acknowledgement needs its actual record_revision.") except Exception as reserve_patch_response_failure: print_value(str(reserve_patch_response_failure)) reserve_failure_read_response = call("read_reservation", {"id": reserve_id, "asset_type_id": "1", "$include_record_revision": "true"}, None, None) require_condition(equal(response_status(reserve_failure_read_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") print_value(reserve_failure_read_response["raw"].decode("utf-8")) require_condition(False, "Review these actual current values and reconcile the saved pending PATCH before another write. The programme did not repeat or acknowledge the update.") require_condition(equal(response_status(reserve_patch_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") reserve_patch_receipt = reserve_patch_response["body"] reserve_after_revision = text(field(reserve_patch_receipt, "record_revision")) journal_acknowledge(reserve_job, "mark_checked", {"id": reserve_id, "asset_type_id": "1", "asset_id": reserve_asset_id, "event_id": reserve_event_id, "record_revision": reserve_after_revision}) reserve_verify_response = call("verify_reservation", {"id": reserve_id, "asset_type_id": "1"}, None, None) require_condition(equal(response_status(reserve_verify_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") reserve_verified = reserve_verify_response["body"] require_condition(both(both(both(both(both(both(both(both(equal(text(field(reserve_verified, "id")), reserve_id), equal(text(field(reserve_verified, "asset_type_id")), "1")), equal(text(field(reserve_verified, "asset_id")), reserve_asset_id)), equal(text(field(reserve_verified, "event_id")), reserve_event_id)), equal(field(reserve_verified, "is_asset_owned_by_this_workspace"), True)), equal(text(field(reserve_verified, "reservation_date")), reserve_start)), equal(text(field(reserve_verified, "return_date")), reserve_end)), equal(text(field(reserve_verified, "notes")), "Display monitor for Spring Expo 2030")), equal(field(reserve_verified, "is_checked"), True)), "The reservation differs from the captured typed ID, owned Asset, Event, dates, notes or checked state. Review it before continuing; do not restore it automatically.") reserve_options_response = call("cancellation_options", {"id": reserve_id, "asset_type_id": "1"}, None, None) require_condition(equal(response_status(reserve_options_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") reserve_options = reserve_options_response["body"] require_condition(both(both(equal(text(field(reserve_options, "reservation_id")), reserve_id), equal(text(field(reserve_options, "asset_id")), reserve_asset_id)), equal(text(field(reserve_options, "asset_type_id")), "1")), "The cancellation options describe a different typed reservation. No cancellation was sent.") print_value({"id": reserve_id, "asset_type_id": "1", "asset_id": reserve_asset_id, "event_id": reserve_event_id, "is_checked": field(reserve_verified, "is_checked"), "inventory_outcomes": field(reserve_options, "inventory_outcomes")}) finally: reserve_job.close() if __name__ == "__main__": main() ``` ```csharp // .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\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"availability\":{\"method\":\"GET\",\"path\":\"/assets/availability\"},\"create_reservation\":{\"method\":\"POST\",\"path\":\"/assets/reservations\"},\"read_reservation\":{\"method\":\"GET\",\"path\":\"/assets/reservations/info\"},\"mark_checked\":{\"method\":\"PATCH\",\"path\":\"/assets/reservations\"},\"verify_reservation\":{\"method\":\"GET\",\"path\":\"/assets/reservations/info\"},\"cancellation_options\":{\"method\":\"GET\",\"path\":\"/assets/reservation_cancellation_inventory_options\"}}}"); static readonly string ApiKey = HeaderKey(Required("EXHIBITDAY_API_KEY")); static string HeaderKey(string value) { if(value.Any(c=>c<32||c>126))throw new Exception("Use the API key as one ASCII header value without control characters");return value; } static readonly HttpClient Client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false }) { Timeout = TimeSpan.FromSeconds(30) }; internal static Func> Send = request => Client.SendAsync(request); sealed class Result { public int Status; public JsonNode Body; public Dictionary Headers; public string Raw; } // 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(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 Call(string name, JsonObject query = null, JsonNode body = null, string key = null) { var route = Spec["requests"][name]; var method = Text(route["method"]); var headers = new Dictionary(StringComparer.OrdinalIgnoreCase) { ["Authorization"] = "Bearer " + ApiKey, ["Accept"] = "application/json" }; if (method == "POST") { if (string.IsNullOrEmpty(key)) throw new Exception("Persist a logical create key before sending POST"); headers["Idempotency-Key"] = key; } 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); // 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. var resend = method == "GET"; 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 Send(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 = resend && (status == 429 || status >= 500); 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, Raw = raw }; } } throw new Exception("Retry limit reached"); } static bool Both(bool left,bool right)=>left&&right; static JsonNode CopyNode(JsonNode value) => value?.DeepClone(); static bool Either(bool left,bool right) => left || right; static object Scalar(object value) { if(value is JsonValue json){if(json.TryGetValue(out var boolean))return boolean;if(json.TryGetValue(out var text))return text;return json.ToJsonString();}return value; } static bool Equal(object left,object right) => object.Equals(Scalar(left),Scalar(right)); static JsonNode Field(JsonNode value,string name) { if(value is not JsonObject obj || !obj.TryGetPropertyValue(name,out var item))throw new Exception("Missing response field: "+name);return item; } static bool IsPresent(string value) => value!=null && value!=""; public sealed class JournalRefusal : Exception { public JournalRefusal(string message) : base(message) {} } public static class JournalProtocol { public static readonly byte[] Preamble = Encoding.ASCII.GetBytes("EXHIBITDAY-GUIDE-JOURNAL 1\n"); static readonly UTF8Encoding Utf8 = new UTF8Encoding(false, true); static bool Match(string value,string pattern) => value != null && System.Text.RegularExpressions.Regex.IsMatch(value,"\\A(?:"+pattern+")\\z",System.Text.RegularExpressions.RegexOptions.CultureInvariant); public static bool Valid(string value,string pattern) => Match(value,pattern); static string Ascii(byte[] raw,int start,int count) { for(var i=start;i127)throw new JournalRefusal("Journal framing must be canonical ASCII");return Encoding.ASCII.GetString(raw,start,count); } public static byte[] Strings(IEnumerable values) { using var data=new MemoryStream(); foreach(var value in values){if(value==null)throw new JournalRefusal("Journal fields are exact strings");var item=Utf8.GetBytes(value);var prefix=Encoding.ASCII.GetBytes(item.Length.ToString(CultureInfo.InvariantCulture)+":");data.Write(prefix);data.Write(item);} return data.ToArray(); } public static List ReadStrings(byte[] raw) { var values=new List();var offset=0; while(offsetraw.Length-offset)throw new JournalRefusal("Incomplete journal string");values.Add(Utf8.GetString(raw,offset,(int)size));offset+=(int)size;} return values; } public static string Digest(byte[] raw)=>Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(raw)); public static string Fingerprint(IReadOnlyDictionary pairs) { var values=new List();foreach(var name in pairs.Keys.OrderBy(n=>n,StringComparer.Ordinal)){ if(!Match(name,"[A-Za-z0-9_.-]+")||new[]{"api_key","exhibitday_api_key"}.Contains(name.ToLowerInvariant()))throw new JournalRefusal("Use explicit secret-free fingerprint names");values.Add(name);values.Add(pairs[name]);} return Digest(Strings(values)); } public static byte[] Frame(IEnumerable values) { var payload=Strings(values);var header=Encoding.ASCII.GetBytes(payload.Length.ToString(CultureInfo.InvariantCulture)+" "+Digest(payload)+"\n"); using var data=new MemoryStream();data.Write(header);data.Write(payload);data.WriteByte(10);return data.ToArray(); } public static List> Decode(byte[] raw) { if(raw.Length>(); while(offset=raw.Length-offset)throw new JournalRefusal("Incomplete frame; reconcile before retry");var payload=raw.AsSpan(offset,(int)size).ToArray();offset+=(int)size; if(raw[offset]!=10||Digest(payload)!=split[1])throw new JournalRefusal("Journal integrity failed; reconcile before retry");records.Add(ReadStrings(payload));offset++;} return records; } } public sealed class Journal : IDisposable { readonly string path,lockPath,owner;readonly List header; readonly Dictionary allowed=new Dictionary(StringComparer.Ordinal); Dictionary> intents=new Dictionary>(StringComparer.Ordinal),savedValues=new Dictionary>(StringComparer.Ordinal); FileStream lockStream;bool owned,tainted;DateTime creation; static FileStream CreatePrivate(string target,FileAccess access,FileShare share) { var options=new FileStreamOptions{Mode=FileMode.CreateNew,Access=access,Share=share}; if(!OperatingSystem.IsWindows())options.UnixCreateMode=UnixFileMode.UserRead|UnixFileMode.UserWrite; return new FileStream(target,options); } public Journal(string path,string apiBase,string workspace,string slug,string job,string inputFingerprint,IEnumerable<(string Step,string Method,string Path)> writes,string mode="resume") { this.path=path;lockPath=path+".lock";owner=Convert.ToHexString(System.Security.Cryptography.RandomNumberGenerator.GetBytes(16)).ToLowerInvariant(); if(!Uri.TryCreate(apiBase,UriKind.Absolute,out var address)||address.Scheme!="https"&&address.Scheme!="http"||address.UserInfo.Length!=0||address.Query.Length!=0||address.Fragment.Length!=0||!JournalProtocol.Valid(slug,"[a-z][a-z0-9-]*"))throw new JournalRefusal("Use the actual API base and closed guide slug"); if(string.IsNullOrWhiteSpace(job)||!JournalProtocol.Valid(workspace,"[1-9][0-9]*")||!JournalProtocol.Valid(inputFingerprint,"[0-9A-F]{64}"))throw new JournalRefusal("Use actual workspace, stable explicit job ID and exact fingerprint"); if(mode!="new"&&mode!="resume")throw new JournalRefusal("Choose new or resume for this local job"); var manifest=new List();foreach(var write in writes){ if(!JournalProtocol.Valid(write.Step,"[a-z][a-z0-9_-]*")||allowed.ContainsKey(write.Step)||!new[]{"POST","PATCH","DELETE"}.Contains(write.Method)||!JournalProtocol.Valid(write.Path,"/v1/[A-Za-z0-9_/-]+")||write.Path.Contains("//"))throw new JournalRefusal("Use a closed unique write manifest"); allowed.Add(write.Step,(write.Method,write.Path));manifest.AddRange(new[]{write.Step,write.Method,write.Path});} if(allowed.Count==0)throw new JournalRefusal("Only write workflows need a restart journal"); header=new List{"H","1",apiBase,workspace,slug,job,inputFingerprint,JournalProtocol.Digest(JournalProtocol.Strings(manifest))};JournalProtocol.Strings(header); try{lockStream=CreatePrivate(lockPath,FileAccess.ReadWrite,FileShare.Read);owned=true;} catch(IOException)when(File.Exists(lockPath)){throw new JournalRefusal("This journal is locked; do not overlap jobs or steal a stale lock");} try{ var token=Encoding.ASCII.GetBytes(owner);lockStream.Write(token);lockStream.Flush(true);creation=File.GetCreationTimeUtc(lockPath); if(File.Exists(path)&&(File.GetAttributes(path)&FileAttributes.ReparsePoint)!=0)throw new JournalRefusal("Choose a private regular journal file"); if(mode=="resume"&&!File.Exists(path))throw new JournalRefusal("Journal missing: stop and reconcile lost state before starting a new logical job"); if(mode=="new"&&File.Exists(path))throw new JournalRefusal("Journal exists; use resume for the same logical job"); if(mode=="new"){using var output=CreatePrivate(path,FileAccess.Write,FileShare.None);output.Write(JournalProtocol.Preamble);output.Write(JournalProtocol.Frame(header));output.Flush(true);} var records=JournalProtocol.Decode(File.ReadAllBytes(path));if(records.Count==0||!records[0].SequenceEqual(header))throw new JournalRefusal("Journal workspace/base/guide/job/input binding differs"); foreach(var record in records.Skip(1))Apply(record);if(intents.Keys.Any(step=>!savedValues.ContainsKey(step)))throw new JournalRefusal("Saved intent lacks ACK; stop and reconcile before retry"); }catch{Dispose();throw;} } void Apply(IReadOnlyList record) { if(record.Count==0)throw new JournalRefusal("Empty journal record"); if(record[0]=="I"){ if(record.Count!=6)throw new JournalRefusal("Invalid intent shape");var step=record[1];var method=record[2];var route=record[3];var fingerprint=record[4];var key=record[5]; if(!JournalProtocol.Valid(step,"[a-z][a-z0-9_-]*")||intents.ContainsKey(step)||!allowed.TryGetValue(step,out var expected)||expected!=(method,route)||!JournalProtocol.Valid(fingerprint,"[0-9A-F]{64}")||intents.Keys.Any(name=>!savedValues.ContainsKey(name)))throw new JournalRefusal("Invalid, future or repeated intent"); if(method=="POST"&&!JournalProtocol.Valid(key,"[0-9a-f]{32}")||method!="POST"&&key!="")throw new JournalRefusal("Invalid persisted action key"); intents.Add(step,new Dictionary{{"method",method},{"path",route},{"request_fingerprint",fingerprint},{"idempotency_key",key}}); }else if(record[0]=="A"){ if(record.Count<3||!JournalProtocol.Valid(record[2],"0|[1-9][0-9]*")||!long.TryParse(record[2],NumberStyles.None,CultureInfo.InvariantCulture,out var count)||count!=(record.Count-3L)/2||record.Count%2!=1||!intents.ContainsKey(record[1])||savedValues.ContainsKey(record[1]))throw new JournalRefusal("ACK without exactly one prior intent"); var names=record.Skip(3).Where((_,index)=>index%2==0).ToArray(); if(!names.SequenceEqual(names.Distinct(StringComparer.Ordinal).OrderBy(name=>name,StringComparer.Ordinal))||names.Any(name=>!JournalProtocol.Valid(name,"[a-z][a-z0-9_]*")||name=="api_key"||name=="exhibitday_api_key"))throw new JournalRefusal("ACK fields must be unique sorted secret-free identifiers"); var saved=new Dictionary(StringComparer.Ordinal);for(var i=0;i record) { RequireActive();var raw=JournalProtocol.Frame(record); try{using var output=new FileStream(path,FileMode.Append,FileAccess.Write,FileShare.None);output.Write(raw);output.Flush(true);} catch{tainted=true;throw;} } public bool Acknowledged(string step){RequireActive();return savedValues.ContainsKey(step);} public Dictionary Saved(string step){RequireActive();if(!savedValues.ContainsKey(step))throw new JournalRefusal("No acknowledged state exists");return new Dictionary(savedValues[step],StringComparer.Ordinal);} public Dictionary Begin(string step,string method,string route,string requestFingerprint) { RequireActive();if(intents.ContainsKey(step))throw new JournalRefusal("Never blindly repeat an existing action"); var key=method=="POST"?Convert.ToHexString(System.Security.Cryptography.RandomNumberGenerator.GetBytes(16)).ToLowerInvariant():""; var record=new[]{"I",step,method,route,requestFingerprint,key};var previous=new Dictionary>(intents,StringComparer.Ordinal);try{Apply(record);}finally{intents=previous;} Append(record);Apply(record);return new Dictionary(intents[step],StringComparer.Ordinal); } public void Acknowledge(string step,IReadOnlyDictionary saved) { RequireActive();var record=new List{"A",step,saved.Count.ToString(CultureInfo.InvariantCulture)};foreach(var name in saved.Keys.OrderBy(name=>name,StringComparer.Ordinal))record.AddRange(new[]{name,saved[name]}); var previous=new Dictionary>(savedValues,StringComparer.Ordinal);try{Apply(record);JournalProtocol.Strings(record);}finally{savedValues=previous;} Append(record);Apply(record); } public void Dispose() { if(!owned)return;if(tainted){lockStream.Dispose();lockStream=null;owned=false;return;} try{RequireActive();}catch{lockStream.Dispose();lockStream=null;owned=false;throw;} lockStream.Dispose();lockStream=null;owned=false;File.Delete(lockPath); } } static Dictionary JournalValues(JsonNode value) { if(value is not JsonObject fields)throw new JournalRefusal("Saved/fingerprint values need an explicit object"); var result=new Dictionary(StringComparer.Ordinal); foreach(var field in fields){if(field.Value is not JsonValue item || !item.TryGetValue(out var text) || text==null)throw new JournalRefusal("Saved/fingerprint values must be exact strings");result.Add(field.Key,text);}return result; } static JsonObject JournalObject(IReadOnlyDictionary fields){var result=new JsonObject();foreach(var field in fields)result.Add(field.Key,JsonValue.Create(field.Value));return result;} static void JournalAcknowledge(Journal job,string step,JsonNode saved)=>job.Acknowledge(step,JournalValues(saved)); static bool JournalAcknowledged(Journal job,string step)=>job.Acknowledged(step); static JsonNode JournalBegin(Journal job,string step,string method,string path,string requestFingerprint)=>JournalObject(job.Begin(step,method,path,requestFingerprint)); static string JournalFingerprint(JsonNode value)=>JournalProtocol.Fingerprint(JournalValues(value)); static JsonNode JournalSaved(Journal job,string step)=>JournalObject(job.Saved(step)); static bool NotValue(bool value) => !value; static Journal OpenJournal(string path,string apiBase,string workspace,string slug,string job,string inputFingerprint,JsonNode manifest,string mode) { if(manifest is not JsonArray rows)throw new JournalRefusal("A closed write manifest is required");var writes=new List<(string,string,string)>(); foreach(var row in rows){if(row is not JsonArray fields || fields.Count!=3)throw new JournalRefusal("Each write must bind its step/method/path");var values=fields.Select(value=>value is JsonValue item&&item.TryGetValue(out var text)&&text!=null?text:throw new JournalRefusal("Manifest values are exact strings")).ToArray();writes.Add((values[0],values[1],values[2]));} return new Journal(path,apiBase,workspace,slug,job,inputFingerprint,writes,mode); } static string Optional(string name,string fallback) { var value=Environment.GetEnvironmentVariable(name);return value==null||value==""?fallback:value; } static string PositiveId(string value) { if(string.IsNullOrEmpty(value)||value[0]=='0'||!value.All(c=>c>='0'&&c<='9')||!long.TryParse(value,NumberStyles.None,CultureInfo.InvariantCulture,out var id)||id<=0)throw new Exception("Use a positive record ID");return value; } static void PrintValue(object value) => Console.WriteLine(value is string text ? text : JsonSerializer.Serialize(value)); static void RequireCondition(bool value,string message) { if(!value)throw new Exception(message); } static string ResponseStatus(Result value)=>value.Status.ToString(CultureInfo.InvariantCulture); static string Text(object value) => value==null?"":value is JsonNode node?Text(node):Convert.ToString(value,CultureInfo.InvariantCulture); static void ValidateCapitalReservationDates(string start, string end) { bool Valid(string value) => DateTime.TryParseExact(value, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var day) && value == day.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); if (!Valid(start) || !Valid(end) || string.CompareOrdinal(end, start) < 0) throw new JournalRefusal("Use valid reservation and return dates in YYYY-MM-DD form, with return on or after reservation."); } internal static async Task Run() { var reserve_event_id = PositiveId(Required("EXHIBITDAY_EVENT_ID")); var reserve_asset_id = PositiveId(Required("EXHIBITDAY_ASSET_ID")); var reserve_start = Required("EXHIBITDAY_RESERVATION_DATE"); var reserve_end = Required("EXHIBITDAY_RETURN_DATE"); var reserve_journal_path = Required("EXHIBITDAY_JOURNAL"); var reserve_job_id = Required("EXHIBITDAY_JOB_ID"); var reserve_job_mode = Optional("EXHIBITDAY_JOB_MODE", "resume"); RequireCondition(Either(Equal(reserve_job_mode, "new"), Equal(reserve_job_mode, "resume")), "Use exact new or resume for EXHIBITDAY_JOB_MODE."); ValidateCapitalReservationDates(reserve_start, reserve_end); var reserve_workspace_response = await Call("workspace_binding", new JsonObject { }, null, null); RequireCondition(Equal(ResponseStatus(reserve_workspace_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); var reserve_workspace = reserve_workspace_response.Body; var reserve_workspace_id = PositiveId(Text(Field(reserve_workspace, "id"))); var reserve_input_fingerprint = JournalFingerprint(new JsonObject { ["workflow_contract_sha256"] = "2A835F55E124977C3B498E4C462F96FBF20CB76917E5A036A3D3B11327D77382", ["asset_type_id"] = "1", ["asset_id"] = reserve_asset_id, ["event_id"] = reserve_event_id, ["reservation_date"] = reserve_start, ["return_date"] = reserve_end, ["notes"] = "Display monitor for Spring Expo 2030", ["notifications"] = "false" }); using (var reserve_job = OpenJournal(reserve_journal_path, "https://api.exhibitday.com/v1", reserve_workspace_id, "reserve-change-cancel-assets", reserve_job_id, reserve_input_fingerprint, new JsonArray(new JsonArray("create_reservation", "POST", "/v1/assets/reservations"), new JsonArray("mark_checked", "PATCH", "/v1/assets/reservations")), reserve_job_mode)) { RequireCondition(Either(NotValue(JournalAcknowledged(reserve_job, "mark_checked")), JournalAcknowledged(reserve_job, "create_reservation")), "An update is acknowledged before its create. Stop and reconcile the journal."); var reserve_id = ""; if (JournalAcknowledged(reserve_job, "create_reservation")) { var reserve_created_saved = JournalSaved(reserve_job, "create_reservation"); reserve_id = PositiveId(Text(Field(reserve_created_saved, "id"))); RequireCondition(Both(Both(Equal(Text(Field(reserve_created_saved, "asset_type_id")), "1"), Equal(Text(Field(reserve_created_saved, "asset_id")), reserve_asset_id)), Equal(Text(Field(reserve_created_saved, "event_id")), reserve_event_id)), "The acknowledged create belongs to a different typed Asset or Event; do not create a replacement."); } else { var reserve_availability_response = await Call("availability", new JsonObject { ["asset_id"] = reserve_asset_id, ["asset_type_id"] = "1", ["start_date"] = reserve_start, ["end_date"] = reserve_end }, null, null); RequireCondition(Equal(ResponseStatus(reserve_availability_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); var reserve_availability_value = reserve_availability_response.Body; RequireCondition(Both(Both(Both(Both(Both(Equal(Text(Field(reserve_availability_value, "asset_id")), reserve_asset_id), Equal(Text(Field(reserve_availability_value, "asset_type_id")), "1")), Equal(Text(Field(reserve_availability_value, "start_date")), reserve_start)), Equal(Text(Field(reserve_availability_value, "end_date")), reserve_end)), Equal(Field(reserve_availability_value, "is_asset_owned_by_this_workspace"), true)), Equal(Field(reserve_availability_value, "is_advisory"), true)), "Availability must describe this owned Capital Asset and exact requested calendar dates; it is advisory, not a reservation."); if (NotValue(Equal(Field(reserve_availability_value, "is_available_under_reservation_policy"), true))) { PrintValue(reserve_availability_response.Raw); RequireCondition(false, "No reservation was sent. Availability does not permit this new allocation; review the dates and policy before another decision."); } var reserve_create_fingerprint = JournalFingerprint(new JsonObject { ["asset_type_id"] = "1", ["asset_id"] = reserve_asset_id, ["event_id"] = reserve_event_id, ["reservation_date"] = reserve_start, ["return_date"] = reserve_end, ["notes"] = "Display monitor for Spring Expo 2030", ["notify_new_reservation"] = "false" }); var reserve_create_intent = JournalBegin(reserve_job, "create_reservation", "POST", "/v1/assets/reservations", reserve_create_fingerprint); var reserve_create_response = await Call("create_reservation", new JsonObject { }, new JsonObject { ["asset_type_id"] = "1", ["asset_id"] = reserve_asset_id, ["event_id"] = reserve_event_id, ["reservation_date"] = reserve_start, ["return_date"] = reserve_end, ["notes"] = "Display monitor for Spring Expo 2030", ["notify_new_reservation"] = false }, Text(Field(reserve_create_intent, "idempotency_key"))); RequireCondition(Equal(ResponseStatus(reserve_create_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); var reserve_created = reserve_create_response.Body; reserve_id = PositiveId(Text(Field(reserve_created, "id"))); RequireCondition(Both(Both(Both(Both(Both(Both(Both(Both(Equal(Text(Field(reserve_created, "id")), reserve_id), Equal(Text(Field(reserve_created, "asset_type_id")), "1")), Equal(Text(Field(reserve_created, "asset_id")), reserve_asset_id)), Equal(Text(Field(reserve_created, "event_id")), reserve_event_id)), Equal(Field(reserve_created, "is_asset_owned_by_this_workspace"), true)), Equal(Text(Field(reserve_created, "reservation_date")), reserve_start)), Equal(Text(Field(reserve_created, "return_date")), reserve_end)), Equal(Text(Field(reserve_created, "notes")), "Display monitor for Spring Expo 2030")), Equal(Field(reserve_created, "is_checked"), false)), "The reservation differs from the captured typed ID, owned Asset, Event, dates, notes or checked state. Review it before continuing; do not restore it automatically."); JournalAcknowledge(reserve_job, "create_reservation", new JsonObject { ["id"] = reserve_id, ["asset_type_id"] = "1", ["asset_id"] = reserve_asset_id, ["event_id"] = reserve_event_id }); } var reserve_read_response = await Call("read_reservation", new JsonObject { ["id"] = reserve_id, ["asset_type_id"] = "1", ["$include_record_revision"] = "true" }, null, null); RequireCondition(Equal(ResponseStatus(reserve_read_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); var reserve_current = reserve_read_response.Body; var reserve_revision = Text(Field(reserve_current, "record_revision")); RequireCondition(IsPresent(reserve_revision), "The actual reservation Info read must include its record_revision."); if (JournalAcknowledged(reserve_job, "mark_checked")) { var reserve_update_saved = JournalSaved(reserve_job, "mark_checked"); RequireCondition(Both(Both(Both(Both(Equal(Text(Field(reserve_update_saved, "id")), reserve_id), Equal(Text(Field(reserve_update_saved, "asset_type_id")), "1")), Equal(Text(Field(reserve_update_saved, "asset_id")), reserve_asset_id)), Equal(Text(Field(reserve_update_saved, "event_id")), reserve_event_id)), Equal(Text(Field(reserve_update_saved, "record_revision")), reserve_revision)), "The acknowledged update or current revision differs. Stop and review; do not restore earlier values."); RequireCondition(Both(Both(Both(Both(Both(Both(Both(Both(Equal(Text(Field(reserve_current, "id")), reserve_id), Equal(Text(Field(reserve_current, "asset_type_id")), "1")), Equal(Text(Field(reserve_current, "asset_id")), reserve_asset_id)), Equal(Text(Field(reserve_current, "event_id")), reserve_event_id)), Equal(Field(reserve_current, "is_asset_owned_by_this_workspace"), true)), Equal(Text(Field(reserve_current, "reservation_date")), reserve_start)), Equal(Text(Field(reserve_current, "return_date")), reserve_end)), Equal(Text(Field(reserve_current, "notes")), "Display monitor for Spring Expo 2030")), Equal(Field(reserve_current, "is_checked"), true)), "The reservation differs from the captured typed ID, owned Asset, Event, dates, notes or checked state. Review it before continuing; do not restore it automatically."); } else { RequireCondition(Both(Both(Both(Both(Both(Both(Both(Both(Equal(Text(Field(reserve_current, "id")), reserve_id), Equal(Text(Field(reserve_current, "asset_type_id")), "1")), Equal(Text(Field(reserve_current, "asset_id")), reserve_asset_id)), Equal(Text(Field(reserve_current, "event_id")), reserve_event_id)), Equal(Field(reserve_current, "is_asset_owned_by_this_workspace"), true)), Equal(Text(Field(reserve_current, "reservation_date")), reserve_start)), Equal(Text(Field(reserve_current, "return_date")), reserve_end)), Equal(Text(Field(reserve_current, "notes")), "Display monitor for Spring Expo 2030")), Equal(Field(reserve_current, "is_checked"), false)), "The reservation differs from the captured typed ID, owned Asset, Event, dates, notes or checked state. Review it before continuing; do not restore it automatically."); var reserve_patch = new JsonObject { ["id"] = reserve_id, ["asset_type_id"] = "1", ["is_checked"] = true, ["expected_revision"] = reserve_revision, ["notify_reservation_update"] = false }; var reserve_patch_fingerprint = JournalFingerprint(new JsonObject { ["id"] = reserve_id, ["asset_type_id"] = "1", ["is_checked"] = "true", ["expected_revision"] = reserve_revision, ["notify_reservation_update"] = "false" }); JournalBegin(reserve_job, "mark_checked", "PATCH", "/v1/assets/reservations", reserve_patch_fingerprint); Result reserve_patch_response = null; try { reserve_patch_response = await Call("mark_checked", new JsonObject { }, reserve_patch, null); RequireCondition(reserve_patch_response.Status == 200, "Expected HTTP200 for the selected conditional PATCH; read current values before another decision."); RequireCondition(IsPresent(Text(Field(reserve_patch_response.Body, "record_revision"))), "The conditional PATCH acknowledgement needs its actual record_revision."); } catch (Exception reserve_patch_response_failure) { PrintValue(reserve_patch_response_failure.Message); var reserve_failure_read_response = await Call("read_reservation", new JsonObject { ["id"] = reserve_id, ["asset_type_id"] = "1", ["$include_record_revision"] = "true" }, null, null); RequireCondition(Equal(ResponseStatus(reserve_failure_read_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); PrintValue(reserve_failure_read_response.Raw); RequireCondition(false, "Review these actual current values and reconcile the saved pending PATCH before another write. The programme did not repeat or acknowledge the update."); } RequireCondition(Equal(ResponseStatus(reserve_patch_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); var reserve_patch_receipt = reserve_patch_response.Body; var reserve_after_revision = Text(Field(reserve_patch_receipt, "record_revision")); JournalAcknowledge(reserve_job, "mark_checked", new JsonObject { ["id"] = reserve_id, ["asset_type_id"] = "1", ["asset_id"] = reserve_asset_id, ["event_id"] = reserve_event_id, ["record_revision"] = reserve_after_revision }); } var reserve_verify_response = await Call("verify_reservation", new JsonObject { ["id"] = reserve_id, ["asset_type_id"] = "1" }, null, null); RequireCondition(Equal(ResponseStatus(reserve_verify_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); var reserve_verified = reserve_verify_response.Body; RequireCondition(Both(Both(Both(Both(Both(Both(Both(Both(Equal(Text(Field(reserve_verified, "id")), reserve_id), Equal(Text(Field(reserve_verified, "asset_type_id")), "1")), Equal(Text(Field(reserve_verified, "asset_id")), reserve_asset_id)), Equal(Text(Field(reserve_verified, "event_id")), reserve_event_id)), Equal(Field(reserve_verified, "is_asset_owned_by_this_workspace"), true)), Equal(Text(Field(reserve_verified, "reservation_date")), reserve_start)), Equal(Text(Field(reserve_verified, "return_date")), reserve_end)), Equal(Text(Field(reserve_verified, "notes")), "Display monitor for Spring Expo 2030")), Equal(Field(reserve_verified, "is_checked"), true)), "The reservation differs from the captured typed ID, owned Asset, Event, dates, notes or checked state. Review it before continuing; do not restore it automatically."); var reserve_options_response = await Call("cancellation_options", new JsonObject { ["id"] = reserve_id, ["asset_type_id"] = "1" }, null, null); RequireCondition(Equal(ResponseStatus(reserve_options_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); var reserve_options = reserve_options_response.Body; RequireCondition(Both(Both(Equal(Text(Field(reserve_options, "reservation_id")), reserve_id), Equal(Text(Field(reserve_options, "asset_id")), reserve_asset_id)), Equal(Text(Field(reserve_options, "asset_type_id")), "1")), "The cancellation options describe a different typed reservation. No cancellation was sent."); PrintValue(new JsonObject { ["id"] = reserve_id, ["asset_type_id"] = "1", ["asset_id"] = reserve_asset_id, ["event_id"] = reserve_event_id, ["is_checked"] = CopyNode(Field(reserve_verified, "is_checked")), ["inventory_outcomes"] = CopyNode(Field(reserve_options, "inventory_outcomes")) }); } } static Task Main() => Run(); } ``` ```java // 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 SPEC = JSON.fromJson("{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"availability\":{\"method\":\"GET\",\"path\":\"/assets/availability\"},\"create_reservation\":{\"method\":\"POST\",\"path\":\"/assets/reservations\"},\"read_reservation\":{\"method\":\"GET\",\"path\":\"/assets/reservations/info\"},\"mark_checked\":{\"method\":\"PATCH\",\"path\":\"/assets/reservations\"},\"verify_reservation\":{\"method\":\"GET\",\"path\":\"/assets/reservations/info\"},\"cancellation_options\":{\"method\":\"GET\",\"path\":\"/assets/reservation_cancellation_inventory_options\"}}}", Map.class); static final String API_KEY = headerKey(required("EXHIBITDAY_API_KEY")); static String headerKey(String value){if(value.chars().anyMatch(c->c<32||c>126))throw new IllegalArgumentException("Use the API key as one ASCII header value without control characters");return value;} static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).followRedirects(HttpClient.Redirect.NEVER).build(); interface RequestSender { HttpResponse send(HttpRequest request)throws IOException,InterruptedException; } static RequestSender SEND=request->CLIENT.send(request,HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); static class Result { int status; Object body; Map headers; String raw; Result(int s, Object b, Map h,String r) {status=s;body=b;headers=h;raw=r;} } // 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 obj(Object value) {return value==null?new LinkedHashMap<>(): (Map)value;} @SuppressWarnings("unchecked") static List list(Object value) {return value==null?Collections.emptyList():(List)value;} static Map map(Object... pairs) {Map result=new LinkedHashMap<>();for(int i=0;i query,Object body,String key) { Map route=obj(obj(SPEC.get("requests")).get(name));String method=text(route.get("method")); Map headers=map("Authorization","Bearer " + API_KEY,"Accept","application/json"); if(method.equals("POST")){if(key==null||key.isEmpty())throw new IllegalArgumentException("Persist a logical create key before sending POST");headers.put("Idempotency-Key",key);} 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); // 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. boolean resend=method.equals("GET"); 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 response; try {response=SEND.send(request.build());} 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();Object parsed=null; if(status!=304&&!response.body().isEmpty()) { try {parsed=JSON.fromJson(response.body(),Object.class);} catch(RuntimeException error){if(status<400)throw new IllegalStateException("Expected a JSON success response",error);} } Map 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=resend&&(status==429||status>=500); 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,response.body()); } throw new IllegalStateException("Retry limit reached"); } static boolean both(boolean left,boolean right){return left&&right;} static boolean either(boolean left,boolean right){return left||right;} static boolean equal(Object left,Object right){return Objects.equals(left,right);} static Object field(Object value,String name){if(!(value instanceof Map)||!obj(value).containsKey(name))throw new IllegalStateException("Missing response field: "+name);return obj(value).get(name);} static boolean is_present(String value){return value!=null&&!value.isEmpty();} // Private client restart state only. No transport, application or JSON interpreter. static final class Journal implements AutoCloseable { public static final class Refusal extends IllegalStateException { Refusal(String message){super(message);} } public static final byte[] PREAMBLE="EXHIBITDAY-GUIDE-JOURNAL 1\n".getBytes(StandardCharsets.US_ASCII); static boolean valid(String value,String pattern){return value!=null&&value.matches(pattern);} static byte[] utf8(String value)throws java.nio.charset.CharacterCodingException { if(value==null)throw new Refusal("Journal fields are exact strings"); java.nio.ByteBuffer encoded=StandardCharsets.UTF_8.newEncoder().onMalformedInput(java.nio.charset.CodingErrorAction.REPORT).onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT).encode(java.nio.CharBuffer.wrap(value));byte[] raw=new byte[encoded.remaining()];encoded.get(raw);return raw; } static String ascii(byte[] raw,int start,int count){for(int i=start;i127)throw new Refusal("Journal framing must be canonical ASCII");return new String(raw,start,count,StandardCharsets.US_ASCII);} public static byte[] strings(Collection values)throws IOException { ByteArrayOutputStream output=new ByteArrayOutputStream();for(String value:values){byte[] raw=utf8(value);output.write((raw.length+":").getBytes(StandardCharsets.US_ASCII));output.write(raw);}return output.toByteArray(); } static int find(byte[] raw,int offset,int value){for(int i=offset;i readStrings(byte[] raw)throws IOException { List values=new ArrayList<>();int offset=0; while(offset0)throw new Refusal("Incomplete journal string");int count=size.intValueExact(); values.add(StandardCharsets.UTF_8.newDecoder().onMalformedInput(java.nio.charset.CodingErrorAction.REPORT).onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT).decode(java.nio.ByteBuffer.wrap(raw,offset,count)).toString());offset+=count;} return values; } public static String digest(byte[] raw){try{byte[] hash=java.security.MessageDigest.getInstance("SHA-256").digest(raw);StringBuilder text=new StringBuilder();for(byte item:hash)text.append(String.format(Locale.ROOT,"%02X",item&255));return text.toString();}catch(java.security.NoSuchAlgorithmException error){throw new IllegalStateException(error);}} public static String fingerprint(Map pairs)throws IOException { List values=new ArrayList<>();for(String name:new TreeSet<>(pairs.keySet())){if(!valid(name,"[A-Za-z0-9_.-]+")||Arrays.asList("api_key","exhibitday_api_key").contains(name.toLowerCase(Locale.ROOT)))throw new Refusal("Use explicit secret-free fingerprint names");values.add(name);values.add(pairs.get(name));}return digest(strings(values)); } public static byte[] frame(Collection values)throws IOException {byte[] payload=strings(values);ByteArrayOutputStream output=new ByteArrayOutputStream();output.write((payload.length+" "+digest(payload)+"\n").getBytes(StandardCharsets.US_ASCII));output.write(payload);output.write(10);return output.toByteArray();} public static List> decode(byte[] raw)throws IOException { if(raw.length> records=new ArrayList<>(); while(offset=0)throw new Refusal("Incomplete frame; reconcile before retry");int count=size.intValueExact();byte[] payload=Arrays.copyOfRange(raw,offset,offset+count);offset+=count; if(raw[offset]!=10||!digest(payload).equals(fields[1]))throw new Refusal("Journal integrity failed; reconcile before retry");records.add(readStrings(payload));offset++;}return records; } static void writeAll(java.nio.channels.FileChannel target,byte[] raw)throws IOException {java.nio.ByteBuffer data=java.nio.ByteBuffer.wrap(raw);while(data.hasRemaining())if(target.write(data)<=0)throw new IOException("Journal write did not advance");} static java.nio.channels.FileChannel createPrivate(Path path,OpenOption... options)throws IOException { java.nio.file.attribute.FileAttribute[] attributes=FileSystems.getDefault().supportedFileAttributeViews().contains("posix")?new java.nio.file.attribute.FileAttribute[]{java.nio.file.attribute.PosixFilePermissions.asFileAttribute(java.nio.file.attribute.PosixFilePermissions.fromString("rw-------"))}:new java.nio.file.attribute.FileAttribute[0]; return java.nio.channels.FileChannel.open(path,new HashSet<>(Arrays.asList(options)),attributes); } final Path path,lockPath;final String owner;final List header; final Map> allowed=new LinkedHashMap<>();Map> intents=new LinkedHashMap<>(),savedValues=new LinkedHashMap<>(); java.nio.channels.FileChannel lock;boolean owned,tainted;Object fileKey;java.nio.file.attribute.FileTime creation; public Journal(Path path,String apiBase,String workspace,String slug,String job,String inputFingerprint,List> writes)throws IOException {this(path,apiBase,workspace,slug,job,inputFingerprint,writes,"resume");} public Journal(Path path,String apiBase,String workspace,String slug,String job,String inputFingerprint,List> writes,String mode)throws IOException { this.path=path;lockPath=Path.of(path.toString()+".lock");byte[] random=new byte[16];new java.security.SecureRandom().nextBytes(random);StringBuilder token=new StringBuilder();for(byte item:random)token.append(String.format(Locale.ROOT,"%02x",item&255));owner=token.toString(); URI address=URI.create(apiBase);if(!Arrays.asList("https","http").contains(address.getScheme())||address.getHost()==null||address.getUserInfo()!=null||address.getRawQuery()!=null||address.getRawFragment()!=null||!valid(slug,"[a-z][a-z0-9-]*"))throw new Refusal("Use actual API base and closed guide slug"); if(job==null||job.trim().isEmpty()||!valid(workspace,"[1-9][0-9]*")||!valid(inputFingerprint,"[0-9A-F]{64}"))throw new Refusal("Use actual workspace, stable explicit job ID and exact fingerprint"); if(!Arrays.asList("new","resume").contains(mode))throw new Refusal("Choose new or resume for this local job"); List manifest=new ArrayList<>();for(List item:writes){if(item.size()!=3)throw new Refusal("Invalid write manifest shape");String step=item.get(0),method=item.get(1),route=item.get(2); if(!valid(step,"[a-z][a-z0-9_-]*")||allowed.containsKey(step)||!Arrays.asList("POST","PATCH","DELETE").contains(method)||!valid(route,"/v1/[A-Za-z0-9_/-]+")||route.contains("//"))throw new Refusal("Use a closed unique write manifest");allowed.put(step,List.of(method,route));manifest.addAll(item);} if(allowed.isEmpty())throw new Refusal("Only write workflows need a restart journal");header=List.of("H","1",apiBase,workspace,slug,job,inputFingerprint,digest(strings(manifest)));strings(header); try{lock=createPrivate(lockPath,StandardOpenOption.CREATE_NEW,StandardOpenOption.READ,StandardOpenOption.WRITE);owned=true;}catch(FileAlreadyExistsException error){throw new Refusal("This journal is locked; do not overlap jobs or steal a stale lock");} try{writeAll(lock,owner.getBytes(StandardCharsets.US_ASCII));lock.force(true);java.nio.file.attribute.BasicFileAttributes identity=Files.readAttributes(lockPath,java.nio.file.attribute.BasicFileAttributes.class,LinkOption.NOFOLLOW_LINKS);fileKey=identity.fileKey();creation=identity.creationTime(); if(Files.isSymbolicLink(path))throw new Refusal("Choose a private regular journal file"); if(mode.equals("resume")&&!Files.exists(path))throw new Refusal("Journal missing: stop and reconcile lost state before starting a new logical job"); if(mode.equals("new")&&Files.exists(path))throw new Refusal("Journal exists; use resume for the same logical job"); if(mode.equals("new")){try(java.nio.channels.FileChannel target=createPrivate(path,StandardOpenOption.CREATE_NEW,StandardOpenOption.WRITE)){writeAll(target,PREAMBLE);writeAll(target,frame(header));target.force(true);}} List> records=decode(Files.readAllBytes(path));if(records.isEmpty()||!records.get(0).equals(header))throw new Refusal("Journal workspace/base/guide/job/input binding differs");for(List record:records.subList(1,records.size()))apply(record); if(intents.keySet().stream().anyMatch(step->!savedValues.containsKey(step)))throw new Refusal("Saved intent lacks ACK; stop and reconcile before retry"); }catch(IOException|RuntimeException error){close();throw error;} } void apply(List record){ if(record.isEmpty())throw new Refusal("Empty journal record"); if(record.get(0).equals("I")){ if(record.size()!=6)throw new Refusal("Invalid intent shape");String step=record.get(1),method=record.get(2),route=record.get(3),fingerprint=record.get(4),key=record.get(5); if(!valid(step,"[a-z][a-z0-9_-]*")||intents.containsKey(step)||!List.of(method,route).equals(allowed.get(step))||!valid(fingerprint,"[0-9A-F]{64}")||intents.keySet().stream().anyMatch(name->!savedValues.containsKey(name)))throw new Refusal("Invalid, future or repeated intent"); if(method.equals("POST")&&!valid(key,"[0-9a-f]{32}")||!method.equals("POST")&&!key.isEmpty())throw new Refusal("Invalid persisted action key");intents.put(step,new LinkedHashMap<>(Map.of("method",method,"path",route,"request_fingerprint",fingerprint,"idempotency_key",key))); }else if(record.get(0).equals("A")){ if(record.size()<3||!valid(record.get(2),"0|[1-9][0-9]*")||!new java.math.BigInteger(record.get(2)).multiply(java.math.BigInteger.TWO).equals(java.math.BigInteger.valueOf(record.size()-3))||!intents.containsKey(record.get(1))||savedValues.containsKey(record.get(1)))throw new Refusal("ACK without exactly one prior intent"); List names=new ArrayList<>();for(int i=3;i(new TreeSet<>(names)))||names.stream().anyMatch(name->!valid(name,"[a-z][a-z0-9_]*")||name.equals("api_key")||name.equals("exhibitday_api_key")))throw new Refusal("ACK fields must be unique sorted secret-free identifiers"); Map saved=new LinkedHashMap<>();for(int i=0;i record)throws IOException {requireActive();byte[] raw=frame(record);try(java.nio.channels.FileChannel target=java.nio.channels.FileChannel.open(path,StandardOpenOption.WRITE,StandardOpenOption.APPEND)){writeAll(target,raw);target.force(true);}catch(IOException|RuntimeException error){tainted=true;throw error;}} public boolean acknowledged(String step)throws IOException{requireActive();return savedValues.containsKey(step);} public Map saved(String step)throws IOException{requireActive();if(!savedValues.containsKey(step))throw new Refusal("No acknowledged state exists");return new LinkedHashMap<>(savedValues.get(step));} public Map begin(String step,String method,String route,String requestFingerprint)throws IOException { requireActive();if(intents.containsKey(step))throw new Refusal("Never blindly repeat an existing action");String key="";if(method.equals("POST")){byte[] bytes=new byte[16];new java.security.SecureRandom().nextBytes(bytes);StringBuilder text=new StringBuilder();for(byte item:bytes)text.append(String.format(Locale.ROOT,"%02x",item&255));key=text.toString();} List record=List.of("I",step,method,route,requestFingerprint,key);Map> previous=new LinkedHashMap<>(intents);try{apply(record);}finally{intents=previous;}append(record);apply(record);return new LinkedHashMap<>(intents.get(step)); } public void acknowledge(String step,Map saved)throws IOException { requireActive();List record=new ArrayList<>(List.of("A",step,Integer.toString(saved.size())));for(String name:new TreeSet<>(saved.keySet())){record.add(name);record.add(saved.get(name));} Map> previous=new LinkedHashMap<>(savedValues);try{apply(record);strings(record);}finally{savedValues=previous;}append(record);apply(record); } public void close()throws IOException { if(!owned)return;if(tainted){lock.close();lock=null;owned=false;return;} try{requireActive();}catch(IOException|RuntimeException error){lock.close();lock=null;owned=false;throw error;}lock.close();lock=null;owned=false;Files.delete(lockPath); } } static Map journal_values(Object value){if(!(value instanceof Map))throw new Journal.Refusal("Saved/fingerprint values need an explicit object");Map result=new LinkedHashMap<>();for(Map.Entry field:((Map)value).entrySet()){if(!(field.getKey() instanceof String)||!(field.getValue() instanceof String))throw new Journal.Refusal("Saved/fingerprint values must be exact strings");result.put((String)field.getKey(),(String)field.getValue());}return result;} static void journal_acknowledge(Journal job,String step,Object saved)throws IOException{job.acknowledge(step,journal_values(saved));} static boolean journal_acknowledged(Journal job,String step)throws IOException{return job.acknowledged(step);} static Object journal_begin(Journal job,String step,String method,String path,String requestFingerprint)throws IOException{return new LinkedHashMap(job.begin(step,method,path,requestFingerprint));} static String journal_fingerprint(Object value)throws IOException{return Journal.fingerprint(journal_values(value));} static Object journal_saved(Journal job,String step)throws IOException{return new LinkedHashMap(job.saved(step));} static boolean not_value(boolean value){return !value;} static Journal open_journal(String path,String base,String workspace,String slug,String job,String inputFingerprint,Object manifest,String mode)throws IOException { if(!(manifest instanceof List))throw new Journal.Refusal("A closed write manifest is required");List> writes=new ArrayList<>();for(Object row:(List)manifest){if(!(row instanceof List)||((List)row).size()!=3)throw new Journal.Refusal("Each write must bind step/method/path");List fields=new ArrayList<>();for(Object value:(List)row){if(!(value instanceof String))throw new Journal.Refusal("Manifest values are exact strings");fields.add((String)value);}writes.add(fields);}return new Journal(Path.of(path),base,workspace,slug,job,inputFingerprint,writes,mode); } static String optional(String name,String fallback){String value=System.getenv(name);return value==null||value.isEmpty()?fallback:value;} static String positive_id(String value){try{if(value==null||!value.matches("[1-9][0-9]*")||Long.parseLong(value)<=0)throw new IllegalArgumentException();return value;}catch(RuntimeException error){throw new IllegalArgumentException("Use a positive record ID");}} static void print_value(Object value){try{String text=value instanceof String?(String)value:JSON.toJson(value);System.out.write((text+"\n").getBytes(StandardCharsets.UTF_8));}catch(IOException error){throw new UncheckedIOException(error);}} static void require_condition(boolean value,String message){if(!value)throw new IllegalStateException(message);} static String response_status(Result value){return Integer.toString(value.status);} static void validate_capital_reservation_dates(String start, String end) throws IOException { boolean valid = start.matches("[0-9]{4}-[0-9]{2}-[0-9]{2}") && end.matches("[0-9]{4}-[0-9]{2}-[0-9]{2}"); try { valid = valid && LocalDate.parse(start).getYear() > 0 && LocalDate.parse(end).getYear() > 0; } catch (java.time.format.DateTimeParseException error) { valid = false; } if (!valid || end.compareTo(start) < 0) throw new Journal.Refusal("Use valid reservation and return dates in YYYY-MM-DD form, with return on or after reservation."); } static void run()throws Exception { String reserve_event_id = positive_id(required("EXHIBITDAY_EVENT_ID")); String reserve_asset_id = positive_id(required("EXHIBITDAY_ASSET_ID")); String reserve_start = required("EXHIBITDAY_RESERVATION_DATE"); String reserve_end = required("EXHIBITDAY_RETURN_DATE"); String reserve_journal_path = required("EXHIBITDAY_JOURNAL"); String reserve_job_id = required("EXHIBITDAY_JOB_ID"); String reserve_job_mode = optional("EXHIBITDAY_JOB_MODE", "resume"); require_condition(either(equal(reserve_job_mode, "new"), equal(reserve_job_mode, "resume")), "Use exact new or resume for EXHIBITDAY_JOB_MODE."); validate_capital_reservation_dates(reserve_start, reserve_end); Result reserve_workspace_response = call("workspace_binding", map(), null, null); require_condition(equal(response_status(reserve_workspace_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); Object reserve_workspace = reserve_workspace_response.body; String reserve_workspace_id = positive_id(text(field(reserve_workspace, "id"))); String reserve_input_fingerprint = journal_fingerprint(map("workflow_contract_sha256", "2A835F55E124977C3B498E4C462F96FBF20CB76917E5A036A3D3B11327D77382", "asset_type_id", "1", "asset_id", reserve_asset_id, "event_id", reserve_event_id, "reservation_date", reserve_start, "return_date", reserve_end, "notes", "Display monitor for Spring Expo 2030", "notifications", "false")); try (Journal reserve_job = open_journal(reserve_journal_path, "https://api.exhibitday.com/v1", reserve_workspace_id, "reserve-change-cancel-assets", reserve_job_id, reserve_input_fingerprint, Arrays.asList(Arrays.asList("create_reservation", "POST", "/v1/assets/reservations"), Arrays.asList("mark_checked", "PATCH", "/v1/assets/reservations")), reserve_job_mode)) { require_condition(either(not_value(journal_acknowledged(reserve_job, "mark_checked")), journal_acknowledged(reserve_job, "create_reservation")), "An update is acknowledged before its create. Stop and reconcile the journal."); String reserve_id = ""; if (journal_acknowledged(reserve_job, "create_reservation")) { Object reserve_created_saved = journal_saved(reserve_job, "create_reservation"); reserve_id = positive_id(text(field(reserve_created_saved, "id"))); require_condition(both(both(equal(text(field(reserve_created_saved, "asset_type_id")), "1"), equal(text(field(reserve_created_saved, "asset_id")), reserve_asset_id)), equal(text(field(reserve_created_saved, "event_id")), reserve_event_id)), "The acknowledged create belongs to a different typed Asset or Event; do not create a replacement."); } else { Result reserve_availability_response = call("availability", map("asset_id", reserve_asset_id, "asset_type_id", "1", "start_date", reserve_start, "end_date", reserve_end), null, null); require_condition(equal(response_status(reserve_availability_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); Object reserve_availability_value = reserve_availability_response.body; require_condition(both(both(both(both(both(equal(text(field(reserve_availability_value, "asset_id")), reserve_asset_id), equal(text(field(reserve_availability_value, "asset_type_id")), "1")), equal(text(field(reserve_availability_value, "start_date")), reserve_start)), equal(text(field(reserve_availability_value, "end_date")), reserve_end)), equal(field(reserve_availability_value, "is_asset_owned_by_this_workspace"), true)), equal(field(reserve_availability_value, "is_advisory"), true)), "Availability must describe this owned Capital Asset and exact requested calendar dates; it is advisory, not a reservation."); if (not_value(equal(field(reserve_availability_value, "is_available_under_reservation_policy"), true))) { print_value(reserve_availability_response.raw); require_condition(false, "No reservation was sent. Availability does not permit this new allocation; review the dates and policy before another decision."); } String reserve_create_fingerprint = journal_fingerprint(map("asset_type_id", "1", "asset_id", reserve_asset_id, "event_id", reserve_event_id, "reservation_date", reserve_start, "return_date", reserve_end, "notes", "Display monitor for Spring Expo 2030", "notify_new_reservation", "false")); Object reserve_create_intent = journal_begin(reserve_job, "create_reservation", "POST", "/v1/assets/reservations", reserve_create_fingerprint); Result reserve_create_response = call("create_reservation", map(), map("asset_type_id", "1", "asset_id", reserve_asset_id, "event_id", reserve_event_id, "reservation_date", reserve_start, "return_date", reserve_end, "notes", "Display monitor for Spring Expo 2030", "notify_new_reservation", false), text(field(reserve_create_intent, "idempotency_key"))); require_condition(equal(response_status(reserve_create_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); Object reserve_created = reserve_create_response.body; reserve_id = positive_id(text(field(reserve_created, "id"))); require_condition(both(both(both(both(both(both(both(both(equal(text(field(reserve_created, "id")), reserve_id), equal(text(field(reserve_created, "asset_type_id")), "1")), equal(text(field(reserve_created, "asset_id")), reserve_asset_id)), equal(text(field(reserve_created, "event_id")), reserve_event_id)), equal(field(reserve_created, "is_asset_owned_by_this_workspace"), true)), equal(text(field(reserve_created, "reservation_date")), reserve_start)), equal(text(field(reserve_created, "return_date")), reserve_end)), equal(text(field(reserve_created, "notes")), "Display monitor for Spring Expo 2030")), equal(field(reserve_created, "is_checked"), false)), "The reservation differs from the captured typed ID, owned Asset, Event, dates, notes or checked state. Review it before continuing; do not restore it automatically."); journal_acknowledge(reserve_job, "create_reservation", map("id", reserve_id, "asset_type_id", "1", "asset_id", reserve_asset_id, "event_id", reserve_event_id)); } Result reserve_read_response = call("read_reservation", map("id", reserve_id, "asset_type_id", "1", "$include_record_revision", "true"), null, null); require_condition(equal(response_status(reserve_read_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); Object reserve_current = reserve_read_response.body; String reserve_revision = text(field(reserve_current, "record_revision")); require_condition(is_present(reserve_revision), "The actual reservation Info read must include its record_revision."); if (journal_acknowledged(reserve_job, "mark_checked")) { Object reserve_update_saved = journal_saved(reserve_job, "mark_checked"); require_condition(both(both(both(both(equal(text(field(reserve_update_saved, "id")), reserve_id), equal(text(field(reserve_update_saved, "asset_type_id")), "1")), equal(text(field(reserve_update_saved, "asset_id")), reserve_asset_id)), equal(text(field(reserve_update_saved, "event_id")), reserve_event_id)), equal(text(field(reserve_update_saved, "record_revision")), reserve_revision)), "The acknowledged update or current revision differs. Stop and review; do not restore earlier values."); require_condition(both(both(both(both(both(both(both(both(equal(text(field(reserve_current, "id")), reserve_id), equal(text(field(reserve_current, "asset_type_id")), "1")), equal(text(field(reserve_current, "asset_id")), reserve_asset_id)), equal(text(field(reserve_current, "event_id")), reserve_event_id)), equal(field(reserve_current, "is_asset_owned_by_this_workspace"), true)), equal(text(field(reserve_current, "reservation_date")), reserve_start)), equal(text(field(reserve_current, "return_date")), reserve_end)), equal(text(field(reserve_current, "notes")), "Display monitor for Spring Expo 2030")), equal(field(reserve_current, "is_checked"), true)), "The reservation differs from the captured typed ID, owned Asset, Event, dates, notes or checked state. Review it before continuing; do not restore it automatically."); } else { require_condition(both(both(both(both(both(both(both(both(equal(text(field(reserve_current, "id")), reserve_id), equal(text(field(reserve_current, "asset_type_id")), "1")), equal(text(field(reserve_current, "asset_id")), reserve_asset_id)), equal(text(field(reserve_current, "event_id")), reserve_event_id)), equal(field(reserve_current, "is_asset_owned_by_this_workspace"), true)), equal(text(field(reserve_current, "reservation_date")), reserve_start)), equal(text(field(reserve_current, "return_date")), reserve_end)), equal(text(field(reserve_current, "notes")), "Display monitor for Spring Expo 2030")), equal(field(reserve_current, "is_checked"), false)), "The reservation differs from the captured typed ID, owned Asset, Event, dates, notes or checked state. Review it before continuing; do not restore it automatically."); Object reserve_patch = map("id", reserve_id, "asset_type_id", "1", "is_checked", true, "expected_revision", reserve_revision, "notify_reservation_update", false); String reserve_patch_fingerprint = journal_fingerprint(map("id", reserve_id, "asset_type_id", "1", "is_checked", "true", "expected_revision", reserve_revision, "notify_reservation_update", "false")); journal_begin(reserve_job, "mark_checked", "PATCH", "/v1/assets/reservations", reserve_patch_fingerprint); Result reserve_patch_response = null; try { reserve_patch_response = call("mark_checked", map(), reserve_patch, null); require_condition(reserve_patch_response.status == 200, "Expected HTTP200 for the selected conditional PATCH; read current values before another decision."); require_condition(is_present(text(field(reserve_patch_response.body, "record_revision"))), "The conditional PATCH acknowledgement needs its actual record_revision."); } catch (Exception reserve_patch_response_failure) { print_value(reserve_patch_response_failure.getMessage()); Result reserve_failure_read_response = call("read_reservation", map("id", reserve_id, "asset_type_id", "1", "$include_record_revision", "true"), null, null); require_condition(equal(response_status(reserve_failure_read_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); print_value(reserve_failure_read_response.raw); require_condition(false, "Review these actual current values and reconcile the saved pending PATCH before another write. The programme did not repeat or acknowledge the update."); } require_condition(equal(response_status(reserve_patch_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); Object reserve_patch_receipt = reserve_patch_response.body; String reserve_after_revision = text(field(reserve_patch_receipt, "record_revision")); journal_acknowledge(reserve_job, "mark_checked", map("id", reserve_id, "asset_type_id", "1", "asset_id", reserve_asset_id, "event_id", reserve_event_id, "record_revision", reserve_after_revision)); } Result reserve_verify_response = call("verify_reservation", map("id", reserve_id, "asset_type_id", "1"), null, null); require_condition(equal(response_status(reserve_verify_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); Object reserve_verified = reserve_verify_response.body; require_condition(both(both(both(both(both(both(both(both(equal(text(field(reserve_verified, "id")), reserve_id), equal(text(field(reserve_verified, "asset_type_id")), "1")), equal(text(field(reserve_verified, "asset_id")), reserve_asset_id)), equal(text(field(reserve_verified, "event_id")), reserve_event_id)), equal(field(reserve_verified, "is_asset_owned_by_this_workspace"), true)), equal(text(field(reserve_verified, "reservation_date")), reserve_start)), equal(text(field(reserve_verified, "return_date")), reserve_end)), equal(text(field(reserve_verified, "notes")), "Display monitor for Spring Expo 2030")), equal(field(reserve_verified, "is_checked"), true)), "The reservation differs from the captured typed ID, owned Asset, Event, dates, notes or checked state. Review it before continuing; do not restore it automatically."); Result reserve_options_response = call("cancellation_options", map("id", reserve_id, "asset_type_id", "1"), null, null); require_condition(equal(response_status(reserve_options_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); Object reserve_options = reserve_options_response.body; require_condition(both(both(equal(text(field(reserve_options, "reservation_id")), reserve_id), equal(text(field(reserve_options, "asset_id")), reserve_asset_id)), equal(text(field(reserve_options, "asset_type_id")), "1")), "The cancellation options describe a different typed reservation. No cancellation was sent."); print_value(map("id", reserve_id, "asset_type_id", "1", "asset_id", reserve_asset_id, "event_id", reserve_event_id, "is_checked", field(reserve_verified, "is_checked"), "inventory_outcomes", field(reserve_options, "inventory_outcomes"))); } } public static void main(String[] args)throws Exception {run();} } ``` ```php $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, ?string $key = null): array { global $spec, $apiKey, $transport; $route = $spec['requests'][$name]; $headers = ['Authorization' => 'Bearer ' . $apiKey, 'Accept' => 'application/json']; if ($route['method'] === 'POST') { if ($key === null || $key === '') throw new RuntimeException('Persist a logical create key before sending POST'); $headers['Idempotency-Key'] = $key; // 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); // 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 = 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 = $resend && ($status === 429 || $status >= 500); 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, 'raw' => $raw]; } throw new RuntimeException('Retry limit reached'); } $transport = Closure::fromCallable('nativeTransport'); function both(bool $left,bool $right):bool{return $left&&$right;} function either(bool $left,bool $right):bool{return $left||$right;} function equal(mixed $left,mixed $right):bool{return $left===$right;} function field(mixed $value,string $name):mixed{if(!is_array($value)||!array_key_exists($name,$value))throw new RuntimeException("Missing response field: ".$name);return $value[$name];} function is_present(?string $value):bool{return $value!==null&&$value!=="";} final class JournalRefusal extends RuntimeException {} final class JournalProtocol { public const PREAMBLE="EXHIBITDAY-GUIDE-JOURNAL 1\n"; public static function utf8(mixed $value):string {if(!is_string($value)||preg_match('//u',$value)!==1)throw new JournalRefusal('Journal fields must be exact valid UTF8 strings');return$value;} public static function strings(array $values):string {$raw='';foreach($values as$value){$item=self::utf8($value);$raw.=strlen($item).':'.$item;}return$raw;} private static function length(string $text,int $remaining):int {if(!preg_match('/\A(?:0|[1-9][0-9]*)\z/',$text))throw new JournalRefusal('Noncanonical string length');$maximum=(string)$remaining;if(strlen($text)>strlen($maximum)||(strlen($text)===strlen($maximum)&&strcmp($text,$maximum)>0))throw new JournalRefusal('Incomplete journal string/frame');return(int)$text;} public static function readStrings(string $raw):array {$values=[];$offset=0;while($offset=strlen($raw)-$offset)throw new JournalRefusal('Incomplete frame; reconcile before retry');$payload=substr($raw,$offset,$size);$offset+=$size;if($raw[$offset]!=="\n"||self::digest($payload)!==$match[2])throw new JournalRefusal('Journal integrity failed; reconcile before retry');$records[]=self::readStrings($payload);$offset++;}return$records;} public static function writeAll($file,string $raw):void {$offset=0;while($offsetpath=$path;$this->lockPath=$path.'.lock';$this->owner=bin2hex(random_bytes(16));$address=parse_url($base); if($address===false||!in_array($address['scheme']??null,['https','http'],true)||!isset($address['host'])||isset($address['user'])||isset($address['pass'])||isset($address['query'])||isset($address['fragment'])||!preg_match('/\A[a-z][a-z0-9-]*\z/',$slug))throw new JournalRefusal('Use actual API base and closed guide slug'); if(trim($job)===''||!preg_match('/\A[1-9][0-9]*\z/',$workspace)||!preg_match('/\A[0-9A-F]{64}\z/',$inputFingerprint))throw new JournalRefusal('Use actual workspace, stable explicit job ID and exact fingerprint'); if(!in_array($mode,['new','resume'],true))throw new JournalRefusal('Choose new or resume for this local job'); $manifest=[];foreach($writes as$write){if(!is_array($write)||!array_is_list($write)||count($write)!==3)throw new JournalRefusal('Invalid write manifest');[$step,$method,$route]=$write; if(!is_string($step)||!preg_match('/\A[a-z][a-z0-9_-]*\z/',$step)||isset($this->allowed[$step])||!in_array($method,['POST','PATCH','DELETE'],true)||!is_string($route)||!preg_match('~\A/v1/[A-Za-z0-9_/-]+\z~',$route)||str_contains($route,'//'))throw new JournalRefusal('Use a closed unique write manifest');$this->allowed[$step]=[$method,$route];array_push($manifest,$step,$method,$route);} if($this->allowed===[])throw new JournalRefusal('Only write workflows need restart journal');$this->header=['H','1',$base,$workspace,$slug,$job,$inputFingerprint,JournalProtocol::digest(JournalProtocol::strings($manifest))];JournalProtocol::strings($this->header); $this->file=JournalProtocol::createPrivate($this->lockPath);$this->owned=true; try{ JournalProtocol::writeAll($this->file,$this->owner);$identity=fstat($this->file);if($identity===false)throw new JournalRefusal('Cannot bind acquired lock identity');$this->identity=$identity; clearstatcache(true,$path);if(is_link($path))throw new JournalRefusal('Choose private regular journal file'); $exists=file_exists($path);if($mode==='resume'&&!$exists)throw new JournalRefusal('Journal missing: stop and reconcile lost state before starting a new logical job');if($mode==='new'&&$exists)throw new JournalRefusal('Journal exists; use resume for the same logical job'); if($mode==='new'){$target=JournalProtocol::createPrivate($path);try{JournalProtocol::writeAll($target,JournalProtocol::PREAMBLE.JournalProtocol::frame($this->header));}finally{fclose($target);}} $raw=file_get_contents($path);if($raw===false)throw new JournalRefusal('Cannot read journal');$records=JournalProtocol::decode($raw);if($records===[]||$records[0]!==$this->header)throw new JournalRefusal('Journal workspace/base/guide/job/input binding differs');foreach(array_slice($records,1)as$record)$this->apply($record); if(array_diff(array_keys($this->intents),array_keys($this->savedValues))!==[])throw new JournalRefusal('Saved intent lacks ACK; stop and reconcile before retry'); }catch(Throwable $error){$this->close();throw$error;} } private function apply(array $record):void { if(($record[0]??null)==='I'){ if(count($record)!==6)throw new JournalRefusal('Invalid intent shape');[,$step,$method,$route,$fingerprint,$key]=$record; if(!preg_match('/\A[a-z][a-z0-9_-]*\z/',$step)||isset($this->intents[$step])||($this->allowed[$step]??null)!==[$method,$route]||!preg_match('/\A[0-9A-F]{64}\z/',$fingerprint)||array_diff(array_keys($this->intents),array_keys($this->savedValues))!==[])throw new JournalRefusal('Invalid, future or repeated intent'); if(($method==='POST'&&!preg_match('/\A[0-9a-f]{32}\z/',$key))||($method!=='POST'&&$key!==''))throw new JournalRefusal('Invalid persisted action key');$this->intents[$step]=['method'=>$method,'path'=>$route,'request_fingerprint'=>$fingerprint,'idempotency_key'=>$key]; }elseif(($record[0]??null)==='A'){ if(count($record)<3)throw new JournalRefusal('Invalid ACK shape');[,$step,$count]=$record;$pairs=array_slice($record,3); if(!preg_match('/\A(?:0|[1-9][0-9]*)\z/',$count)||(string)intdiv(count($pairs),2)!==$count||count($pairs)%2!==0||!isset($this->intents[$step])||isset($this->savedValues[$step]))throw new JournalRefusal('ACK without exactly one prior intent'); $names=[];for($i=0;$i$name){if(!preg_match('/\A[a-z][a-z0-9_]*\z/',$name)||in_array($name,['api_key','exhibitday_api_key'],true))throw new JournalRefusal('Use secret-free ACK field names');$saved[$name]=$pairs[$i*2+1];}$this->savedValues[$step]=$saved; }else throw new JournalRefusal('Unknown journal transition'); } private function requireActive():void { if(!$this->owned||$this->file===null||$this->tainted)throw new JournalRefusal('Journal closed or IO outcome needs reconciliation');clearstatcache(true,$this->lockPath);$current=@lstat($this->lockPath);$token=@file_get_contents($this->lockPath); if($current===false||($current['dev']??null)!==($this->identity['dev']??null)||($current['ino']??null)!==($this->identity['ino']??null)||$token!==$this->owner)throw new JournalRefusal('Journal lock replaced; stop without deleting it'); } private function append(array $record):void { $this->requireActive();$raw=JournalProtocol::frame($record);$target=null; try{$target=@fopen($this->path,'ab');if($target===false)throw new JournalRefusal('Cannot append journal; stop and reconcile');JournalProtocol::writeAll($target,$raw);}catch(Throwable $error){$this->tainted=true;throw$error;}finally{if(is_resource($target))fclose($target);} } public function acknowledged(string $step):bool{$this->requireActive();return isset($this->savedValues[$step]);} public function saved(string $step):array{$this->requireActive();if(!isset($this->savedValues[$step]))throw new JournalRefusal('No acknowledged state exists');return$this->savedValues[$step];} public function beginAction(string $step,string $method,string $route,string $requestFingerprint):array { $this->requireActive();if(isset($this->intents[$step]))throw new JournalRefusal('Never blindly repeat an existing action');$key=$method==='POST'?bin2hex(random_bytes(16)):'';$record=['I',$step,$method,$route,$requestFingerprint,$key];$previous=$this->intents;try{$this->apply($record);}finally{$this->intents=$previous;}$this->append($record);$this->apply($record);return$this->intents[$step]; } public function acknowledge(string $step,array $saved):void { $this->requireActive();$record=['A',$step,(string)count($saved)];$names=array_keys($saved);sort($names,SORT_STRING);foreach($names as$name){$record[]=$name;$record[]=$saved[$name];}$previous=$this->savedValues;try{$this->apply($record);JournalProtocol::strings($record);}finally{$this->savedValues=$previous;}$this->append($record);$this->apply($record); } public function close():void { if(!$this->owned)return;if($this->tainted){fclose($this->file);$this->file=null;$this->owned=false;return;} try{$this->requireActive();}catch(Throwable $error){fclose($this->file);$this->file=null;$this->owned=false;throw$error;}fclose($this->file);$this->file=null;$this->owned=false;if(!unlink($this->lockPath))throw new JournalRefusal('Could not release owned journal lock'); } } function journal_values(mixed $value):array{if(!is_object($value))throw new JournalRefusal('Saved/fingerprint values need an explicit object');$result=get_object_vars($value);foreach($result as$name=>$item)if(!is_string($name)||!is_string($item))throw new JournalRefusal('Saved/fingerprint values must be exact strings');return$result;} function journal_acknowledge(GuideJournal $job,string $step,mixed $saved):void{$job->acknowledge($step,journal_values($saved));} function journal_acknowledged(GuideJournal $job,string $step):bool{return $job->acknowledged($step);} function journal_begin(GuideJournal $job,string $step,string $method,string $path,string $requestFingerprint):array{return $job->beginAction($step,$method,$path,$requestFingerprint);} function journal_fingerprint(mixed $value):string{return JournalProtocol::fingerprint(journal_values($value));} function journal_saved(GuideJournal $job,string $step):array{return $job->saved($step);} function not_value(bool $value):bool{return !$value;} function open_journal(string $path,string $base,string $workspace,string $slug,string $job,string $inputFingerprint,array $writes,string $mode):GuideJournal{return new GuideJournal($path,$base,$workspace,$slug,$job,$inputFingerprint,$writes,$mode);} function positive_id(string $value):string{if(!preg_match("/^[1-9][0-9]*$/D",$value)||strlen($value)>19||(strlen($value)===19&&strcmp($value,"9223372036854775807")>0))throw new RuntimeException("Use a positive record ID");return $value;} function print_value(mixed $value):void{echo (is_string($value)?$value:json_encode($value,JSON_THROW_ON_ERROR))."\n";} function require_condition(bool $value,string $message):void{if(!$value)throw new RuntimeException($message);} function response_status(array $value):string{return(string)$value["status"];} function text(mixed $value):string{if($value===null)return "";if(is_string($value))return $value;if(is_bool($value))return $value?"true":"false";if(is_int($value))return (string)$value;throw new RuntimeException("Expected a scalar response value");} function validate_capital_reservation_dates(string $start, string $end): void { foreach ([$start, $end] as $value) { if (!preg_match('/\A([0-9]{4})-([0-9]{2})-([0-9]{2})\z/', $value, $parts) || !checkdate((int)$parts[2], (int)$parts[3], (int)$parts[1])) throw new JournalRefusal('Use valid reservation and return dates in YYYY-MM-DD form, with return on or after reservation.'); } if (strcmp($end, $start) < 0) throw new JournalRefusal('Use valid reservation and return dates in YYYY-MM-DD form, with return on or after reservation.'); } function main():void { $reserve_event_id = positive_id(required('EXHIBITDAY_EVENT_ID')); $reserve_asset_id = positive_id(required('EXHIBITDAY_ASSET_ID')); $reserve_start = required('EXHIBITDAY_RESERVATION_DATE'); $reserve_end = required('EXHIBITDAY_RETURN_DATE'); $reserve_journal_path = required('EXHIBITDAY_JOURNAL'); $reserve_job_id = required('EXHIBITDAY_JOB_ID'); $reserve_job_mode = optional('EXHIBITDAY_JOB_MODE', 'resume'); require_condition(either(equal($reserve_job_mode, 'new'), equal($reserve_job_mode, 'resume')), 'Use exact new or resume for EXHIBITDAY_JOB_MODE.'); validate_capital_reservation_dates($reserve_start, $reserve_end); $reserve_workspace_response = call('workspace_binding', [], null, null); require_condition(equal(response_status($reserve_workspace_response), '200'), 'Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.'); $reserve_workspace = $reserve_workspace_response["body"]; $reserve_workspace_id = positive_id(text(field($reserve_workspace, 'id'))); $reserve_input_fingerprint = journal_fingerprint((object)['workflow_contract_sha256' => '2A835F55E124977C3B498E4C462F96FBF20CB76917E5A036A3D3B11327D77382', 'asset_type_id' => '1', 'asset_id' => $reserve_asset_id, 'event_id' => $reserve_event_id, 'reservation_date' => $reserve_start, 'return_date' => $reserve_end, 'notes' => 'Display monitor for Spring Expo 2030', 'notifications' => 'false']); $reserve_job = open_journal($reserve_journal_path, 'https://api.exhibitday.com/v1', $reserve_workspace_id, 'reserve-change-cancel-assets', $reserve_job_id, $reserve_input_fingerprint, [['create_reservation', 'POST', '/v1/assets/reservations'], ['mark_checked', 'PATCH', '/v1/assets/reservations']], $reserve_job_mode); try { require_condition(either(not_value(journal_acknowledged($reserve_job, 'mark_checked')), journal_acknowledged($reserve_job, 'create_reservation')), 'An update is acknowledged before its create. Stop and reconcile the journal.'); $reserve_id = ''; if (journal_acknowledged($reserve_job, 'create_reservation')) { $reserve_created_saved = journal_saved($reserve_job, 'create_reservation'); $reserve_id = positive_id(text(field($reserve_created_saved, 'id'))); require_condition(both(both(equal(text(field($reserve_created_saved, 'asset_type_id')), '1'), equal(text(field($reserve_created_saved, 'asset_id')), $reserve_asset_id)), equal(text(field($reserve_created_saved, 'event_id')), $reserve_event_id)), 'The acknowledged create belongs to a different typed Asset or Event; do not create a replacement.'); } else { $reserve_availability_response = call('availability', ['asset_id' => $reserve_asset_id, 'asset_type_id' => '1', 'start_date' => $reserve_start, 'end_date' => $reserve_end], null, null); require_condition(equal(response_status($reserve_availability_response), '200'), 'Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.'); $reserve_availability_value = $reserve_availability_response["body"]; require_condition(both(both(both(both(both(equal(text(field($reserve_availability_value, 'asset_id')), $reserve_asset_id), equal(text(field($reserve_availability_value, 'asset_type_id')), '1')), equal(text(field($reserve_availability_value, 'start_date')), $reserve_start)), equal(text(field($reserve_availability_value, 'end_date')), $reserve_end)), equal(field($reserve_availability_value, 'is_asset_owned_by_this_workspace'), true)), equal(field($reserve_availability_value, 'is_advisory'), true)), 'Availability must describe this owned Capital Asset and exact requested calendar dates; it is advisory, not a reservation.'); if (not_value(equal(field($reserve_availability_value, 'is_available_under_reservation_policy'), true))) { print_value($reserve_availability_response["raw"]); require_condition(false, 'No reservation was sent. Availability does not permit this new allocation; review the dates and policy before another decision.'); } $reserve_create_fingerprint = journal_fingerprint((object)['asset_type_id' => '1', 'asset_id' => $reserve_asset_id, 'event_id' => $reserve_event_id, 'reservation_date' => $reserve_start, 'return_date' => $reserve_end, 'notes' => 'Display monitor for Spring Expo 2030', 'notify_new_reservation' => 'false']); $reserve_create_intent = journal_begin($reserve_job, 'create_reservation', 'POST', '/v1/assets/reservations', $reserve_create_fingerprint); $reserve_create_response = call('create_reservation', [], (object)['asset_type_id' => '1', 'asset_id' => $reserve_asset_id, 'event_id' => $reserve_event_id, 'reservation_date' => $reserve_start, 'return_date' => $reserve_end, 'notes' => 'Display monitor for Spring Expo 2030', 'notify_new_reservation' => false], text(field($reserve_create_intent, 'idempotency_key'))); require_condition(equal(response_status($reserve_create_response), '200'), 'Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.'); $reserve_created = $reserve_create_response["body"]; $reserve_id = positive_id(text(field($reserve_created, 'id'))); require_condition(both(both(both(both(both(both(both(both(equal(text(field($reserve_created, 'id')), $reserve_id), equal(text(field($reserve_created, 'asset_type_id')), '1')), equal(text(field($reserve_created, 'asset_id')), $reserve_asset_id)), equal(text(field($reserve_created, 'event_id')), $reserve_event_id)), equal(field($reserve_created, 'is_asset_owned_by_this_workspace'), true)), equal(text(field($reserve_created, 'reservation_date')), $reserve_start)), equal(text(field($reserve_created, 'return_date')), $reserve_end)), equal(text(field($reserve_created, 'notes')), 'Display monitor for Spring Expo 2030')), equal(field($reserve_created, 'is_checked'), false)), 'The reservation differs from the captured typed ID, owned Asset, Event, dates, notes or checked state. Review it before continuing; do not restore it automatically.'); journal_acknowledge($reserve_job, 'create_reservation', (object)['id' => $reserve_id, 'asset_type_id' => '1', 'asset_id' => $reserve_asset_id, 'event_id' => $reserve_event_id]); } $reserve_read_response = call('read_reservation', ['id' => $reserve_id, 'asset_type_id' => '1', '$include_record_revision' => 'true'], null, null); require_condition(equal(response_status($reserve_read_response), '200'), 'Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.'); $reserve_current = $reserve_read_response["body"]; $reserve_revision = text(field($reserve_current, 'record_revision')); require_condition(is_present($reserve_revision), 'The actual reservation Info read must include its record_revision.'); if (journal_acknowledged($reserve_job, 'mark_checked')) { $reserve_update_saved = journal_saved($reserve_job, 'mark_checked'); require_condition(both(both(both(both(equal(text(field($reserve_update_saved, 'id')), $reserve_id), equal(text(field($reserve_update_saved, 'asset_type_id')), '1')), equal(text(field($reserve_update_saved, 'asset_id')), $reserve_asset_id)), equal(text(field($reserve_update_saved, 'event_id')), $reserve_event_id)), equal(text(field($reserve_update_saved, 'record_revision')), $reserve_revision)), 'The acknowledged update or current revision differs. Stop and review; do not restore earlier values.'); require_condition(both(both(both(both(both(both(both(both(equal(text(field($reserve_current, 'id')), $reserve_id), equal(text(field($reserve_current, 'asset_type_id')), '1')), equal(text(field($reserve_current, 'asset_id')), $reserve_asset_id)), equal(text(field($reserve_current, 'event_id')), $reserve_event_id)), equal(field($reserve_current, 'is_asset_owned_by_this_workspace'), true)), equal(text(field($reserve_current, 'reservation_date')), $reserve_start)), equal(text(field($reserve_current, 'return_date')), $reserve_end)), equal(text(field($reserve_current, 'notes')), 'Display monitor for Spring Expo 2030')), equal(field($reserve_current, 'is_checked'), true)), 'The reservation differs from the captured typed ID, owned Asset, Event, dates, notes or checked state. Review it before continuing; do not restore it automatically.'); } else { require_condition(both(both(both(both(both(both(both(both(equal(text(field($reserve_current, 'id')), $reserve_id), equal(text(field($reserve_current, 'asset_type_id')), '1')), equal(text(field($reserve_current, 'asset_id')), $reserve_asset_id)), equal(text(field($reserve_current, 'event_id')), $reserve_event_id)), equal(field($reserve_current, 'is_asset_owned_by_this_workspace'), true)), equal(text(field($reserve_current, 'reservation_date')), $reserve_start)), equal(text(field($reserve_current, 'return_date')), $reserve_end)), equal(text(field($reserve_current, 'notes')), 'Display monitor for Spring Expo 2030')), equal(field($reserve_current, 'is_checked'), false)), 'The reservation differs from the captured typed ID, owned Asset, Event, dates, notes or checked state. Review it before continuing; do not restore it automatically.'); $reserve_patch = (object)['id' => $reserve_id, 'asset_type_id' => '1', 'is_checked' => true, 'expected_revision' => $reserve_revision, 'notify_reservation_update' => false]; $reserve_patch_fingerprint = journal_fingerprint((object)['id' => $reserve_id, 'asset_type_id' => '1', 'is_checked' => 'true', 'expected_revision' => $reserve_revision, 'notify_reservation_update' => 'false']); journal_begin($reserve_job, 'mark_checked', 'PATCH', '/v1/assets/reservations', $reserve_patch_fingerprint); $reserve_patch_response = null; try { $reserve_patch_response = call('mark_checked', [], $reserve_patch, null); require_condition($reserve_patch_response["status"] == 200, 'Expected HTTP200 for the selected conditional PATCH; read current values before another decision.'); require_condition(is_present(text(field($reserve_patch_response["body"], 'record_revision'))), 'The conditional PATCH acknowledgement needs its actual record_revision.'); } catch (\Throwable $reserve_patch_response_failure) { print_value($reserve_patch_response_failure->getMessage()); $reserve_failure_read_response = call('read_reservation', ['id' => $reserve_id, 'asset_type_id' => '1', '$include_record_revision' => 'true'], null, null); require_condition(equal(response_status($reserve_failure_read_response), '200'), 'Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.'); print_value($reserve_failure_read_response["raw"]); require_condition(false, 'Review these actual current values and reconcile the saved pending PATCH before another write. The programme did not repeat or acknowledge the update.'); } require_condition(equal(response_status($reserve_patch_response), '200'), 'Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.'); $reserve_patch_receipt = $reserve_patch_response["body"]; $reserve_after_revision = text(field($reserve_patch_receipt, 'record_revision')); journal_acknowledge($reserve_job, 'mark_checked', (object)['id' => $reserve_id, 'asset_type_id' => '1', 'asset_id' => $reserve_asset_id, 'event_id' => $reserve_event_id, 'record_revision' => $reserve_after_revision]); } $reserve_verify_response = call('verify_reservation', ['id' => $reserve_id, 'asset_type_id' => '1'], null, null); require_condition(equal(response_status($reserve_verify_response), '200'), 'Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.'); $reserve_verified = $reserve_verify_response["body"]; require_condition(both(both(both(both(both(both(both(both(equal(text(field($reserve_verified, 'id')), $reserve_id), equal(text(field($reserve_verified, 'asset_type_id')), '1')), equal(text(field($reserve_verified, 'asset_id')), $reserve_asset_id)), equal(text(field($reserve_verified, 'event_id')), $reserve_event_id)), equal(field($reserve_verified, 'is_asset_owned_by_this_workspace'), true)), equal(text(field($reserve_verified, 'reservation_date')), $reserve_start)), equal(text(field($reserve_verified, 'return_date')), $reserve_end)), equal(text(field($reserve_verified, 'notes')), 'Display monitor for Spring Expo 2030')), equal(field($reserve_verified, 'is_checked'), true)), 'The reservation differs from the captured typed ID, owned Asset, Event, dates, notes or checked state. Review it before continuing; do not restore it automatically.'); $reserve_options_response = call('cancellation_options', ['id' => $reserve_id, 'asset_type_id' => '1'], null, null); require_condition(equal(response_status($reserve_options_response), '200'), 'Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.'); $reserve_options = $reserve_options_response["body"]; require_condition(both(both(equal(text(field($reserve_options, 'reservation_id')), $reserve_id), equal(text(field($reserve_options, 'asset_id')), $reserve_asset_id)), equal(text(field($reserve_options, 'asset_type_id')), '1')), 'The cancellation options describe a different typed reservation. No cancellation was sent.'); print_value((object)['id' => $reserve_id, 'asset_type_id' => '1', 'asset_id' => $reserve_asset_id, 'event_id' => $reserve_event_id, 'is_checked' => field($reserve_verified, 'is_checked'), 'inventory_outcomes' => field($reserve_options, 'inventory_outcomes')]); } finally { $reserve_job->close(); } } if (realpath($_SERVER['SCRIPT_FILENAME'] ?? '') === __FILE__) main(); ``` ```ruby # 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":true,"requests":{"workspace_binding":{"method":"GET","path":"/references/workspace_info"},"availability":{"method":"GET","path":"/assets/availability"},"create_reservation":{"method":"POST","path":"/assets/reservations"},"read_reservation":{"method":"GET","path":"/assets/reservations/info"},"mark_checked":{"method":"PATCH","path":"/assets/reservations"},"verify_reservation":{"method":"GET","path":"/assets/reservations/info"},"cancellation_options":{"method":"GET","path":"/assets/reservation_cancellation_inventory_options"}}}') API_KEY = ENV.fetch('EXHIBITDAY_API_KEY') raise 'Use the API key as one ASCII header value without control characters' if API_KEY.each_codepoint.any?{|point|point<32||point>126} 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, 'DELETE' => Net::HTTP::Delete }.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, key = nil) route = SPEC.fetch('requests').fetch(name) headers = { 'Authorization' => 'Bearer ' + API_KEY, 'Accept' => 'application/json' } if route.fetch('method') == 'POST' headers['Idempotency-Key'] = key || raise('Persist a logical create key before sending POST') # 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) # 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.fetch('method') == 'GET' 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 = resend && (status == 429 || (500..599).cover?(status)) 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, raw: raw } end raise 'Retry limit reached' end def both(left,right);left&&right;end def either(left,right) raise "Expected Boolean criteria" unless [true,false].include?(left) && [true,false].include?(right) left || right end def equal(left,right) left.class==right.class && left==right end def field(value,name) raise "Missing response field: #{name}" unless value.is_a?(Hash) && value.key?(name) value.fetch(name) end def is_present(value) !value.nil? && value!="" end require 'digest' require 'securerandom' require 'uri' # Private client restart state, with no transport or application dependency. module GuideJournalProtocol PREAMBLE="EXHIBITDAY-GUIDE-JOURNAL 1\n".b.freeze class Refusal < StandardError; end def self.utf8(value) raise Refusal,'Journal fields are exact strings' unless value.is_a?(String)&&value.valid_encoding? raw=value.encode(Encoding::UTF_8) raise Refusal,'Invalid UTF8 journal field' unless raw.valid_encoding? raw.b end def self.strings(values) values.map{|value|raw=utf8(value);raw.bytesize.to_s.b+':'.b+raw}.join.b end def self.read_strings(raw) values=[];offset=0 while offsetraw.bytesize-offset value=raw.byteslice(offset,size).dup.force_encoding(Encoding::UTF_8);raise Refusal,'Invalid UTF8 string' unless value.valid_encoding? values<=raw.bytesize-offset payload=raw.byteslice(offset,size);offset+=size raise Refusal,'Journal integrity failed; reconcile before retry' unless raw.getbyte(offset)==10&&digest(payload)==match[2] records<0 offset+=written end file.flush;file.fsync end end class GuideJournal P=GuideJournalProtocol def initialize(path,base,workspace,slug,job,input_fingerprint,writes,mode='resume') @path=path.dup;@lock_path=path+'.lock';@file=nil;@owned=false;@tainted=false;@intents={};@saved={};@allowed={} address=URI(base) raise P::Refusal,'Use actual API base and closed guide slug' unless ['https','http'].include?(address.scheme)&&address.host&&address.userinfo.nil?&&address.query.nil?&&address.fragment.nil?&&slug.match?(/\A[a-z][a-z0-9-]*\z/) raise P::Refusal,'Use actual workspace, stable explicit job ID and exact fingerprint' unless !job.strip.empty?&&workspace.match?(/\A[1-9][0-9]*\z/)&&input_fingerprint.match?(/\A[0-9A-F]{64}\z/) raise P::Refusal,'Choose new or resume for this local job' unless ['new','resume'].include?(mode) manifest=[] writes.each do|step,method,route| raise P::Refusal,'Use closed unique write manifest' unless step.match?(/\A[a-z][a-z0-9_-]*\z/)&&!@allowed.key?(step)&&['POST','PATCH','DELETE'].include?(method)&&route.match?(/\A\/v1\/[A-Za-z0-9_\/-]+\z/)&&!route.include?('//') @allowed[step.dup.freeze]=[method.dup.freeze,route.dup.freeze].freeze;manifest.concat([step,method,route]) end raise P::Refusal,'Only write workflows need a restart journal' if @allowed.empty? @header=['H','1',base,workspace,slug,job,input_fingerprint,P.digest(P.strings(manifest))].map{|value|value.dup.freeze}.freeze;P.strings(@header) begin @file=File.open(@lock_path,File::RDWR|File::CREAT|File::EXCL,0o600);@file.binmode;@owned=true rescue Errno::EEXIST raise P::Refusal,'This journal is locked; do not overlap jobs or steal a stale lock' end begin @owner=SecureRandom.hex(16).freeze;P.write_all(@file,@owner.b);@identity=@file.stat # Ruby's Windows fstat reports dev=0 while lstat reports the drive number. # Both expose the same exact inode. Retain it plus the initial path device; # compare like-for-like instead of treating the differing dev APIs as equal. named_identity=File.lstat(@lock_path);raise P::Refusal,'Lock identity did not bind' unless named_identity.ino==@identity.ino @path_device=named_identity.dev raise P::Refusal,'Choose a private regular journal file' if File.symlink?(@path) raise P::Refusal,'Journal missing: stop and reconcile lost state before starting a new logical job' if mode=='resume'&&!File.exist?(@path) raise P::Refusal,'Journal exists; use resume for the same logical job' if mode=='new'&&File.exist?(@path) if mode=='new' File.open(@path,File::WRONLY|File::CREAT|File::EXCL,0o600){|target|target.binmode;P.write_all(target,P::PREAMBLE+P.frame(@header))} end records=P.decode(File.binread(@path));raise P::Refusal,'Journal workspace/base/guide/job/input binding differs' if records.empty?||records[0]!=@header records.drop(1).each{|record|apply(record)} raise P::Refusal,'Saved intent lacks ACK; stop and reconcile before retry' if @intents.keys.any?{|step|!@saved.key?(step)} rescue Exception close;raise end end def apply(record) case record[0] when 'I' raise P::Refusal,'Invalid intent shape' unless record.length==6 _,step,method,route,fingerprint,key=record raise P::Refusal,'Invalid, future or repeated intent' unless step.match?(/\A[a-z][a-z0-9_-]*\z/)&&!@intents.key?(step)&&@allowed[step]==[method,route]&&fingerprint.match?(/\A[0-9A-F]{64}\z/)&&!@intents.keys.any?{|name|!@saved.key?(name)} raise P::Refusal,'Invalid persisted action key' unless (method=='POST'&&key.match?(/\A[0-9a-f]{32}\z/))||(method!='POST'&&key=='') @intents[step.dup.freeze]={'method'=>method.dup.freeze,'path'=>route.dup.freeze,'request_fingerprint'=>fingerprint.dup.freeze,'idempotency_key'=>key.dup.freeze}.freeze when 'A' raise P::Refusal,'Invalid ACK shape' unless record.length>=3 _,step,count,*pairs=record raise P::Refusal,'ACK without exactly one prior intent' unless count.match?(/\A(?:0|[1-9][0-9]*)\z/)&&pairs.length==2*count.to_i&&@intents.key?(step)&&!@saved.key?(step) names=pairs.each_slice(2).map(&:first) raise P::Refusal,'ACK fields must be unique sorted secret-free identifiers' unless names==names.uniq.sort&&names.all?{|name|name.match?(/\A[a-z][a-z0-9_]*\z/)&&!['api_key','exhibitday_api_key'].include?(name)} @saved[step.dup.freeze]=pairs.each_slice(2).to_h.transform_values{|value|value.dup.freeze}.freeze else raise P::Refusal,'Unknown journal transition' end end def require_active raise P::Refusal,'Journal is closed or IO outcome needs reconciliation' unless @owned&&@file&&!@tainted current=File.lstat(@lock_path) raise P::Refusal,'Journal lock replaced; stop without deleting it' unless current.dev==@path_device&¤t.ino==@identity.ino&&File.binread(@lock_path)==@owner.b end def append(record) require_active;raw=P.frame(record) begin File.open(@path,'ab'){|target|P.write_all(target,raw)} rescue Exception @tainted=true;raise end end def acknowledged(step);require_active;@saved.key?(step);end def saved(step) require_active;raise P::Refusal,'No acknowledged state exists' unless @saved.key?(step) @saved.fetch(step).transform_values(&:dup) end def begin_action(step,method,route,request_fingerprint) require_active;raise P::Refusal,'Never blindly repeat an action' if @intents.key?(step) record=['I',step,method,route,request_fingerprint,method=='POST'?SecureRandom.hex(16):''] previous=@intents.dup;begin;apply(record);ensure;@intents=previous;end append(record);apply(record);@intents.fetch(step).transform_values(&:dup) end def acknowledge(step,saved) require_active;record=['A',step,saved.length.to_s];saved.keys.sort.each{|name|record.concat([name,saved.fetch(name)])} previous=@saved.dup;begin;apply(record);P.strings(record);ensure;@saved=previous;end append(record);apply(record) end def close return unless @owned if @tainted;@file.close;@file=nil;@owned=false;return;end begin;require_active;rescue Exception;@file.close;@file=nil;@owned=false;raise;end @file.close;@file=nil;@owned=false;File.unlink(@lock_path) end end def journal_values(value) raise GuideJournalProtocol::Refusal,'Saved/fingerprint values must be exact strings' unless value.is_a?(Hash)&&value.all?{|name,item|name.is_a?(String)&&item.is_a?(String)} value.transform_values(&:dup) end def journal_acknowledge(job,step,saved);job.acknowledge(step,journal_values(saved));end def journal_acknowledged(job,step);job.acknowledged(step);end def journal_begin(job,step,method,path,request_fingerprint);job.begin_action(step,method,path,request_fingerprint);end def journal_fingerprint(value);GuideJournalProtocol.fingerprint(journal_values(value));end def journal_saved(job,step);job.saved(step);end def not_value(value) raise "Expected a Boolean" unless value==true || value==false !value end def open_journal(path,base,workspace,slug,job,input_fingerprint,writes,mode);GuideJournal.new(path,base,workspace,slug,job,input_fingerprint,writes,mode);end def optional(name,fallback) value=ENV[name] value.nil? || value.empty? ? fallback : value end def positive_id(value) raise "Use a positive record ID" unless /\A[1-9][0-9]*\z/.match?(value) && Integer(value)<=9223372036854775807 value end def print_value(value) STDOUT.binmode.write((value.is_a?(String)?value:JSON.generate(value))+"\n") end def require_condition(value,message) raise message unless value==true end def required(name) value=ENV[name] raise "Set #{name}" if value.nil? || value.strip.empty? value end def response_status(value);value.fetch(:status).to_s;end def text(value) return "" if value.nil? return value.to_s if value.is_a?(String)||value.is_a?(Integer)||value==true||value==false raise "Expected a scalar response value" end def validate_capital_reservation_dates(start_date, end_date) valid = [start_date, end_date].all? do |value| parts = /\A([0-9]{4})-([0-9]{2})-([0-9]{2})\z/.match(value) parts && parts[1].to_i > 0 && Date.valid_date?(*parts.captures.map(&:to_i), Date::GREGORIAN) end raise GuideJournalProtocol::Refusal, 'Use valid reservation and return dates in YYYY-MM-DD form, with return on or after reservation.' unless valid && end_date >= start_date end def main reserve_event_id = positive_id(required('EXHIBITDAY_EVENT_ID')) reserve_asset_id = positive_id(required('EXHIBITDAY_ASSET_ID')) reserve_start = required('EXHIBITDAY_RESERVATION_DATE') reserve_end = required('EXHIBITDAY_RETURN_DATE') reserve_journal_path = required('EXHIBITDAY_JOURNAL') reserve_job_id = required('EXHIBITDAY_JOB_ID') reserve_job_mode = optional('EXHIBITDAY_JOB_MODE', 'resume') require_condition(either(equal(reserve_job_mode, 'new'), equal(reserve_job_mode, 'resume')), 'Use exact new or resume for EXHIBITDAY_JOB_MODE.') validate_capital_reservation_dates(reserve_start, reserve_end) reserve_workspace_response = call('workspace_binding', {}, nil, nil) require_condition(equal(response_status(reserve_workspace_response), '200'), 'Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.') reserve_workspace = reserve_workspace_response.fetch(:body) reserve_workspace_id = positive_id(text(field(reserve_workspace, 'id'))) reserve_input_fingerprint = journal_fingerprint({'workflow_contract_sha256' => '2A835F55E124977C3B498E4C462F96FBF20CB76917E5A036A3D3B11327D77382', 'asset_type_id' => '1', 'asset_id' => reserve_asset_id, 'event_id' => reserve_event_id, 'reservation_date' => reserve_start, 'return_date' => reserve_end, 'notes' => 'Display monitor for Spring Expo 2030', 'notifications' => 'false'}) reserve_job = open_journal(reserve_journal_path, 'https://api.exhibitday.com/v1', reserve_workspace_id, 'reserve-change-cancel-assets', reserve_job_id, reserve_input_fingerprint, [['create_reservation', 'POST', '/v1/assets/reservations'], ['mark_checked', 'PATCH', '/v1/assets/reservations']], reserve_job_mode) begin require_condition(either(not_value(journal_acknowledged(reserve_job, 'mark_checked')), journal_acknowledged(reserve_job, 'create_reservation')), 'An update is acknowledged before its create. Stop and reconcile the journal.') reserve_id = '' if journal_acknowledged(reserve_job, 'create_reservation') reserve_created_saved = journal_saved(reserve_job, 'create_reservation') reserve_id = positive_id(text(field(reserve_created_saved, 'id'))) require_condition(both(both(equal(text(field(reserve_created_saved, 'asset_type_id')), '1'), equal(text(field(reserve_created_saved, 'asset_id')), reserve_asset_id)), equal(text(field(reserve_created_saved, 'event_id')), reserve_event_id)), 'The acknowledged create belongs to a different typed Asset or Event; do not create a replacement.') else reserve_availability_response = call('availability', {'asset_id' => reserve_asset_id, 'asset_type_id' => '1', 'start_date' => reserve_start, 'end_date' => reserve_end}, nil, nil) require_condition(equal(response_status(reserve_availability_response), '200'), 'Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.') reserve_availability_value = reserve_availability_response.fetch(:body) require_condition(both(both(both(both(both(equal(text(field(reserve_availability_value, 'asset_id')), reserve_asset_id), equal(text(field(reserve_availability_value, 'asset_type_id')), '1')), equal(text(field(reserve_availability_value, 'start_date')), reserve_start)), equal(text(field(reserve_availability_value, 'end_date')), reserve_end)), equal(field(reserve_availability_value, 'is_asset_owned_by_this_workspace'), true)), equal(field(reserve_availability_value, 'is_advisory'), true)), 'Availability must describe this owned Capital Asset and exact requested calendar dates; it is advisory, not a reservation.') if not_value(equal(field(reserve_availability_value, 'is_available_under_reservation_policy'), true)) print_value(reserve_availability_response.fetch(:raw)) require_condition(false, 'No reservation was sent. Availability does not permit this new allocation; review the dates and policy before another decision.') end reserve_create_fingerprint = journal_fingerprint({'asset_type_id' => '1', 'asset_id' => reserve_asset_id, 'event_id' => reserve_event_id, 'reservation_date' => reserve_start, 'return_date' => reserve_end, 'notes' => 'Display monitor for Spring Expo 2030', 'notify_new_reservation' => 'false'}) reserve_create_intent = journal_begin(reserve_job, 'create_reservation', 'POST', '/v1/assets/reservations', reserve_create_fingerprint) reserve_create_response = call('create_reservation', {}, {'asset_type_id' => '1', 'asset_id' => reserve_asset_id, 'event_id' => reserve_event_id, 'reservation_date' => reserve_start, 'return_date' => reserve_end, 'notes' => 'Display monitor for Spring Expo 2030', 'notify_new_reservation' => false}, text(field(reserve_create_intent, 'idempotency_key'))) require_condition(equal(response_status(reserve_create_response), '200'), 'Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.') reserve_created = reserve_create_response.fetch(:body) reserve_id = positive_id(text(field(reserve_created, 'id'))) require_condition(both(both(both(both(both(both(both(both(equal(text(field(reserve_created, 'id')), reserve_id), equal(text(field(reserve_created, 'asset_type_id')), '1')), equal(text(field(reserve_created, 'asset_id')), reserve_asset_id)), equal(text(field(reserve_created, 'event_id')), reserve_event_id)), equal(field(reserve_created, 'is_asset_owned_by_this_workspace'), true)), equal(text(field(reserve_created, 'reservation_date')), reserve_start)), equal(text(field(reserve_created, 'return_date')), reserve_end)), equal(text(field(reserve_created, 'notes')), 'Display monitor for Spring Expo 2030')), equal(field(reserve_created, 'is_checked'), false)), 'The reservation differs from the captured typed ID, owned Asset, Event, dates, notes or checked state. Review it before continuing; do not restore it automatically.') journal_acknowledge(reserve_job, 'create_reservation', {'id' => reserve_id, 'asset_type_id' => '1', 'asset_id' => reserve_asset_id, 'event_id' => reserve_event_id}) end reserve_read_response = call('read_reservation', {'id' => reserve_id, 'asset_type_id' => '1', '$include_record_revision' => 'true'}, nil, nil) require_condition(equal(response_status(reserve_read_response), '200'), 'Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.') reserve_current = reserve_read_response.fetch(:body) reserve_revision = text(field(reserve_current, 'record_revision')) require_condition(is_present(reserve_revision), 'The actual reservation Info read must include its record_revision.') if journal_acknowledged(reserve_job, 'mark_checked') reserve_update_saved = journal_saved(reserve_job, 'mark_checked') require_condition(both(both(both(both(equal(text(field(reserve_update_saved, 'id')), reserve_id), equal(text(field(reserve_update_saved, 'asset_type_id')), '1')), equal(text(field(reserve_update_saved, 'asset_id')), reserve_asset_id)), equal(text(field(reserve_update_saved, 'event_id')), reserve_event_id)), equal(text(field(reserve_update_saved, 'record_revision')), reserve_revision)), 'The acknowledged update or current revision differs. Stop and review; do not restore earlier values.') require_condition(both(both(both(both(both(both(both(both(equal(text(field(reserve_current, 'id')), reserve_id), equal(text(field(reserve_current, 'asset_type_id')), '1')), equal(text(field(reserve_current, 'asset_id')), reserve_asset_id)), equal(text(field(reserve_current, 'event_id')), reserve_event_id)), equal(field(reserve_current, 'is_asset_owned_by_this_workspace'), true)), equal(text(field(reserve_current, 'reservation_date')), reserve_start)), equal(text(field(reserve_current, 'return_date')), reserve_end)), equal(text(field(reserve_current, 'notes')), 'Display monitor for Spring Expo 2030')), equal(field(reserve_current, 'is_checked'), true)), 'The reservation differs from the captured typed ID, owned Asset, Event, dates, notes or checked state. Review it before continuing; do not restore it automatically.') else require_condition(both(both(both(both(both(both(both(both(equal(text(field(reserve_current, 'id')), reserve_id), equal(text(field(reserve_current, 'asset_type_id')), '1')), equal(text(field(reserve_current, 'asset_id')), reserve_asset_id)), equal(text(field(reserve_current, 'event_id')), reserve_event_id)), equal(field(reserve_current, 'is_asset_owned_by_this_workspace'), true)), equal(text(field(reserve_current, 'reservation_date')), reserve_start)), equal(text(field(reserve_current, 'return_date')), reserve_end)), equal(text(field(reserve_current, 'notes')), 'Display monitor for Spring Expo 2030')), equal(field(reserve_current, 'is_checked'), false)), 'The reservation differs from the captured typed ID, owned Asset, Event, dates, notes or checked state. Review it before continuing; do not restore it automatically.') reserve_patch = {'id' => reserve_id, 'asset_type_id' => '1', 'is_checked' => true, 'expected_revision' => reserve_revision, 'notify_reservation_update' => false} reserve_patch_fingerprint = journal_fingerprint({'id' => reserve_id, 'asset_type_id' => '1', 'is_checked' => 'true', 'expected_revision' => reserve_revision, 'notify_reservation_update' => 'false'}) journal_begin(reserve_job, 'mark_checked', 'PATCH', '/v1/assets/reservations', reserve_patch_fingerprint) reserve_patch_response = nil begin reserve_patch_response = call('mark_checked', {}, reserve_patch, nil) require_condition(reserve_patch_response.fetch(:status) == 200, 'Expected HTTP200 for the selected conditional PATCH; read current values before another decision.') require_condition(is_present(text(field(reserve_patch_response.fetch(:body), 'record_revision'))), 'The conditional PATCH acknowledgement needs its actual record_revision.') rescue StandardError => reserve_patch_response_failure print_value(reserve_patch_response_failure.message) reserve_failure_read_response = call('read_reservation', {'id' => reserve_id, 'asset_type_id' => '1', '$include_record_revision' => 'true'}, nil, nil) require_condition(equal(response_status(reserve_failure_read_response), '200'), 'Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.') print_value(reserve_failure_read_response.fetch(:raw)) require_condition(false, 'Review these actual current values and reconcile the saved pending PATCH before another write. The programme did not repeat or acknowledge the update.') end require_condition(equal(response_status(reserve_patch_response), '200'), 'Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.') reserve_patch_receipt = reserve_patch_response.fetch(:body) reserve_after_revision = text(field(reserve_patch_receipt, 'record_revision')) journal_acknowledge(reserve_job, 'mark_checked', {'id' => reserve_id, 'asset_type_id' => '1', 'asset_id' => reserve_asset_id, 'event_id' => reserve_event_id, 'record_revision' => reserve_after_revision}) end reserve_verify_response = call('verify_reservation', {'id' => reserve_id, 'asset_type_id' => '1'}, nil, nil) require_condition(equal(response_status(reserve_verify_response), '200'), 'Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.') reserve_verified = reserve_verify_response.fetch(:body) require_condition(both(both(both(both(both(both(both(both(equal(text(field(reserve_verified, 'id')), reserve_id), equal(text(field(reserve_verified, 'asset_type_id')), '1')), equal(text(field(reserve_verified, 'asset_id')), reserve_asset_id)), equal(text(field(reserve_verified, 'event_id')), reserve_event_id)), equal(field(reserve_verified, 'is_asset_owned_by_this_workspace'), true)), equal(text(field(reserve_verified, 'reservation_date')), reserve_start)), equal(text(field(reserve_verified, 'return_date')), reserve_end)), equal(text(field(reserve_verified, 'notes')), 'Display monitor for Spring Expo 2030')), equal(field(reserve_verified, 'is_checked'), true)), 'The reservation differs from the captured typed ID, owned Asset, Event, dates, notes or checked state. Review it before continuing; do not restore it automatically.') reserve_options_response = call('cancellation_options', {'id' => reserve_id, 'asset_type_id' => '1'}, nil, nil) require_condition(equal(response_status(reserve_options_response), '200'), 'Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.') reserve_options = reserve_options_response.fetch(:body) require_condition(both(both(equal(text(field(reserve_options, 'reservation_id')), reserve_id), equal(text(field(reserve_options, 'asset_id')), reserve_asset_id)), equal(text(field(reserve_options, 'asset_type_id')), '1')), 'The cancellation options describe a different typed reservation. No cancellation was sent.') print_value({'id' => reserve_id, 'asset_type_id' => '1', 'asset_id' => reserve_asset_id, 'event_id' => reserve_event_id, 'is_checked' => field(reserve_verified, 'is_checked'), 'inventory_outcomes' => field(reserve_options, 'inventory_outcomes')}) ensure reserve_job.close() end end main if $PROGRAM_NAME == __FILE__ ``` ```go // Go 1.18+; standard library only. Set EXHIBITDAY_API_KEY. package main import ( "bytes" "crypto/rand" "crypto/sha256" "encoding/hex" "regexp" "sort" "unicode/utf8" "encoding/json" "fmt" "io" "net/http" "net/url" "os" "strconv" "strings" "time" ) const base = "https://api.exhibitday.com/v1" const specification = "{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"availability\":{\"method\":\"GET\",\"path\":\"/assets/availability\"},\"create_reservation\":{\"method\":\"POST\",\"path\":\"/assets/reservations\"},\"read_reservation\":{\"method\":\"GET\",\"path\":\"/assets/reservations/info\"},\"mark_checked\":{\"method\":\"PATCH\",\"path\":\"/assets/reservations\"},\"verify_reservation\":{\"method\":\"GET\",\"path\":\"/assets/reservations/info\"},\"cancellation_options\":{\"method\":\"GET\",\"path\":\"/assets/reservation_cancellation_inventory_options\"}}}" 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 }} var send = client.Do type result struct { status int; body any; headers http.Header; raw []byte } // 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 call(name string, query map[string]string, body any, key string) result { route := object(object(spec["requests"])[name]); method := text(route["method"]) headers := map[string]string{"Authorization": "Bearer " + apiKey, "Accept": "application/json"} if method == "POST" { if key == "" { panic("Persist a logical create key before sending POST") }; 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() } // 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 := method == "GET" 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 := send(request) if err != nil { if !resend { panic(apiError{0, "", "No response", true}) }; if attempt == 4 { panic(err) }; time.Sleep(time.Second*time.Duration(1<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 := resend && (response.StatusCode == 429 || response.StatusCode >= 500) if retry { if attempt == 4 { panic("Retry limit reached; check the outcome before starting a new create") } seconds := float64(int64(1)<= 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, raw} } panic("Retry limit reached") } func both(left,right bool)bool{return left&&right} func either(left,right bool)bool{return left||right} func equal(left,right any)bool{switch a:=left.(type){case string:b,ok:=right.(string);return ok&&a==b;case bool:b,ok:=right.(bool);return ok&&a==b;case int64:b,ok:=right.(int64);return ok&&a==b};return left==nil&&right==nil} func field(value any,name string)any{obj,ok:=value.(map[string]any);if !ok{panic("Missing response object")};item,found:=obj[name];if !found{panic("Missing response field: "+name)};return item} func is_present(value string)bool{return value!=""} // Private client restart state only; no API transport or workflow interpreter. const journalPreamble = "EXHIBITDAY-GUIDE-JOURNAL 1\n" type journalRefusal struct{ message string } func (e journalRefusal) Error() string { return e.message } func journalNeed(ok bool, message string) { if !ok { panic(journalRefusal{message}) } } func journalMatch(value, pattern string) bool { return regexp.MustCompile("\\A(?:"+pattern+")\\z").MatchString(value) } func journalStrings(values []string) []byte { var output bytes.Buffer for _,value:=range values { journalNeed(utf8.ValidString(value),"Journal fields must be valid UTF8 strings"); output.WriteString(strconv.Itoa(len(value))+":");output.WriteString(value) } return output.Bytes() } func journalReadStrings(raw []byte) []string { values:=[]string{};offset:=0 for offset=0,"Incomplete journal string length");end:=offset+relative;text:=string(raw[offset:end]);journalNeed(journalMatch(text,"0|[1-9][0-9]*"),"Noncanonical journal string length");size,err:=strconv.ParseUint(text,10,64);offset=end+1;journalNeed(err==nil&&size<=uint64(len(raw)-offset),"Incomplete journal string");count:=int(size);value:=string(raw[offset:offset+count]);journalNeed(utf8.ValidString(value),"Invalid UTF8 journal field");values=append(values,value);offset+=count } return values } func journalDigest(raw []byte) string { hash:=sha256.Sum256(raw);return strings.ToUpper(hex.EncodeToString(hash[:])) } func journalFingerprint(pairs map[string]string) string { names:=make([]string,0,len(pairs));for name:=range pairs { names=append(names,name) };sort.Strings(names);values:=[]string{} for _,name:=range names { lower:=strings.ToLower(name);journalNeed(journalMatch(name,"[A-Za-z0-9_.-]+")&&lower!="api_key"&&lower!="exhibitday_api_key","Use explicit secret-free fingerprint names");values=append(values,name,pairs[name]) } return journalDigest(journalStrings(values)) } func journalFrame(values []string) []byte { raw:=journalStrings(values);header:=[]byte(strconv.Itoa(len(raw))+" "+journalDigest(raw)+"\n");result:=append(header,raw...);return append(result,'\n') } func journalDecode(raw []byte) [][]string { journalNeed(bytes.HasPrefix(raw,[]byte(journalPreamble)),"Unknown or incomplete journal version");offset:=len(journalPreamble);records:=[][]string{} for offset=0,"Incomplete frame header; reconcile before retry");end:=offset+relative;header:=string(raw[offset:end]);journalNeed(journalMatch(header,"(0|[1-9][0-9]*) [0-9A-F]{64}"),"Invalid frame header");fields:=strings.Split(header," ");size,err:=strconv.ParseUint(fields[0],10,64);offset=end+1;journalNeed(err==nil&&size0 { count,err:=file.Write(raw);if err!=nil{return err};if count<=0{return io.ErrShortWrite};raw=raw[count:] } return file.Sync() } func journalWriteFile(path string,flags int,raw []byte) (err error) { file,err:=os.OpenFile(path,flags,0600);if err!=nil{return err};defer func(){closed:=file.Close();if err==nil{err=closed}}();return journalWriteAll(file,raw) } func journalCopy(source map[string]string) map[string]string { copy:=map[string]string{};for name,value:=range source{copy[name]=value};return copy } func journalCopyStates(source map[string]map[string]string) map[string]map[string]string { copy:=map[string]map[string]string{};for name,value:=range source{copy[name]=journalCopy(value)};return copy } type guideJournal struct { path,lockPath,owner string header []string allowed map[string][2]string intents,savedValues map[string]map[string]string file *os.File identity os.FileInfo owned,tainted bool } func openGuideJournal(path,base,workspace,slug,job,inputFingerprint string,writes [][3]string,modes ...string) (result *guideJournal) { mode:="resume";journalNeed(len(modes)<=1,"Choose one local job mode");if len(modes)==1{mode=modes[0]};journalNeed(mode=="new"||mode=="resume","Choose new or resume for this local job") address,err:=url.Parse(base);journalNeed(err==nil&&address.Hostname()!=""&&(address.Scheme=="https"||address.Scheme=="http")&&address.User==nil&&address.RawQuery==""&&address.Fragment==""&&journalMatch(slug,"[a-z][a-z0-9-]*"),"Use actual API base and closed guide slug") journalNeed(strings.TrimSpace(job)!=""&&journalMatch(workspace,"[1-9][0-9]*")&&journalMatch(inputFingerprint,"[0-9A-F]{64}"),"Use actual workspace, stable explicit job ID and exact fingerprint") j:=&guideJournal{path:path,lockPath:path+".lock",allowed:map[string][2]string{},intents:map[string]map[string]string{},savedValues:map[string]map[string]string{}} manifest:=[]string{};for _,write:=range writes { step,method,route:=write[0],write[1],write[2];_,exists:=j.allowed[step];journalNeed(journalMatch(step,"[a-z][a-z0-9_-]*")&&!exists&&(method=="POST"||method=="PATCH"||method=="DELETE")&&journalMatch(route,"/v1/[A-Za-z0-9_/-]+")&&!strings.Contains(route,"//"),"Use a closed unique write manifest");j.allowed[step]=[2]string{method,route};manifest=append(manifest,step,method,route) } journalNeed(len(j.allowed)>0,"Only write workflows need a restart journal");j.header=[]string{"H","1",base,workspace,slug,job,inputFingerprint,journalDigest(journalStrings(manifest))};journalStrings(j.header) j.file,err=os.OpenFile(j.lockPath,os.O_RDWR|os.O_CREATE|os.O_EXCL,0600);if err!=nil { if os.IsExist(err){panic(journalRefusal{"This journal is locked; do not overlap jobs or steal a stale lock"})};panic(err) };j.owned=true defer func(){ if observed:=recover();observed!=nil { j.Close();panic(observed) } }() random:=make([]byte,16);if _,err=io.ReadFull(rand.Reader,random);err!=nil{panic(err)};j.owner=hex.EncodeToString(random);if err=journalWriteAll(j.file,[]byte(j.owner));err!=nil{panic(err)};j.identity,err=j.file.Stat();if err!=nil{panic(err)} info,err:=os.Lstat(path);if err!=nil&&!os.IsNotExist(err){panic(err)};exists:=err==nil;if exists{journalNeed(info.Mode()&os.ModeSymlink==0,"Choose a private regular journal file")};journalNeed(mode!="resume"||exists,"Journal missing: stop and reconcile lost state before starting a new logical job");journalNeed(mode!="new"||!exists,"Journal exists; use resume for the same logical job");if mode=="new"{raw:=append([]byte(journalPreamble),journalFrame(j.header)...);if err=journalWriteFile(path,os.O_WRONLY|os.O_CREATE|os.O_EXCL,raw);err!=nil{panic(err)}} raw,err:=os.ReadFile(path);if err!=nil{panic(err)};records:=journalDecode(raw);journalNeed(len(records)>0&&stringsEqual(records[0],j.header),"Journal workspace/base/guide/job/input binding differs");for _,record:=range records[1:]{j.apply(record)};for step:=range j.intents{_,ok:=j.savedValues[step];journalNeed(ok,"Saved intent lacks ACK; stop and reconcile before retry")};return j } func stringsEqual(left,right []string) bool { if len(left)!=len(right){return false};for i,value:=range left{if value!=right[i]{return false}};return true } func (j *guideJournal) apply(record []string) { journalNeed(len(record)>0,"Empty journal record") if record[0]=="I" { journalNeed(len(record)==6,"Invalid intent shape");step,method,route,fingerprint,key:=record[1],record[2],record[3],record[4],record[5];_,exists:=j.intents[step];expected,allowed:=j.allowed[step];pending:=false;for name:=range j.intents{if _,ok:=j.savedValues[name];!ok{pending=true}} journalNeed(journalMatch(step,"[a-z][a-z0-9_-]*")&&!exists&&allowed&&expected==[2]string{method,route}&&journalMatch(fingerprint,"[0-9A-F]{64}")&&!pending,"Invalid, future or repeated intent");journalNeed(method=="POST"&&journalMatch(key,"[0-9a-f]{32}")||method!="POST"&&key=="","Invalid persisted action key");j.intents[step]=map[string]string{"method":method,"path":route,"request_fingerprint":fingerprint,"idempotency_key":key} }else if record[0]=="A" { journalNeed(len(record)>=3,"Invalid ACK shape");step,text:=record[1],record[2];count,err:=strconv.ParseUint(text,10,64);_,prior:=j.intents[step];_,done:=j.savedValues[step];journalNeed(journalMatch(text,"0|[1-9][0-9]*")&&err==nil&&len(record)%2==1&&count==uint64((len(record)-3)/2)&&prior&&!done,"ACK without exactly one prior intent");names:=[]string{};for i:=3;i0&&value[0]!='0';for _,ch:=range value{valid=valid&&ch>='0'&&ch<='9'};id,err:=strconv.ParseInt(value,10,64);if !valid||err!=nil||id<=0{panic("Use a positive record ID")};return value} func print_value(value any){if result,ok:=value.(string);ok{fmt.Println(result);return};raw,err:=json.Marshal(value);if err!=nil{panic(err)};fmt.Println(string(raw))} func require_condition(value bool,message string){if !value{panic(message)}} func response_status(value result)string{return strconv.Itoa(value.status)} func validate_capital_reservation_dates(start, end string) { valid := func(value string) bool { const format = "2006-01-02" day, err := time.Parse(format, value) return err == nil && day.Year() > 0 && day.Format(format) == value } journalNeed(valid(start) && valid(end) && end >= start, "Use valid reservation and return dates in YYYY-MM-DD form, with return on or after reservation.") } func workflow() { reserve_event_id := positive_id(required("EXHIBITDAY_EVENT_ID")) reserve_asset_id := positive_id(required("EXHIBITDAY_ASSET_ID")) reserve_start := required("EXHIBITDAY_RESERVATION_DATE") reserve_end := required("EXHIBITDAY_RETURN_DATE") reserve_journal_path := required("EXHIBITDAY_JOURNAL") reserve_job_id := required("EXHIBITDAY_JOB_ID") reserve_job_mode := optional("EXHIBITDAY_JOB_MODE", "resume") require_condition(either(equal(reserve_job_mode, "new"), equal(reserve_job_mode, "resume")), "Use exact new or resume for EXHIBITDAY_JOB_MODE.") validate_capital_reservation_dates(reserve_start, reserve_end) reserve_workspace_response := call("workspace_binding", map[string]string{}, nil, "") require_condition(equal(response_status(reserve_workspace_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") reserve_workspace := reserve_workspace_response.body reserve_workspace_id := positive_id(text(field(reserve_workspace, "id"))) reserve_input_fingerprint := journal_fingerprint(map[string]any{"workflow_contract_sha256": "2A835F55E124977C3B498E4C462F96FBF20CB76917E5A036A3D3B11327D77382", "asset_type_id": "1", "asset_id": reserve_asset_id, "event_id": reserve_event_id, "reservation_date": reserve_start, "return_date": reserve_end, "notes": "Display monitor for Spring Expo 2030", "notifications": "false"}) func() { reserve_job := open_journal(reserve_journal_path, "https://api.exhibitday.com/v1", reserve_workspace_id, "reserve-change-cancel-assets", reserve_job_id, reserve_input_fingerprint, []any{[]any{"create_reservation", "POST", "/v1/assets/reservations"}, []any{"mark_checked", "PATCH", "/v1/assets/reservations"}}, reserve_job_mode) defer reserve_job.Close() require_condition(either(not_value(journal_acknowledged(reserve_job, "mark_checked")), journal_acknowledged(reserve_job, "create_reservation")), "An update is acknowledged before its create. Stop and reconcile the journal.") reserve_id := "" if journal_acknowledged(reserve_job, "create_reservation") { reserve_created_saved := journal_saved(reserve_job, "create_reservation") reserve_id = positive_id(text(field(reserve_created_saved, "id"))) require_condition(both(both(equal(text(field(reserve_created_saved, "asset_type_id")), "1"), equal(text(field(reserve_created_saved, "asset_id")), reserve_asset_id)), equal(text(field(reserve_created_saved, "event_id")), reserve_event_id)), "The acknowledged create belongs to a different typed Asset or Event; do not create a replacement.") } else { reserve_availability_response := call("availability", map[string]string{"asset_id": reserve_asset_id, "asset_type_id": "1", "start_date": reserve_start, "end_date": reserve_end}, nil, "") require_condition(equal(response_status(reserve_availability_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") reserve_availability_value := reserve_availability_response.body require_condition(both(both(both(both(both(equal(text(field(reserve_availability_value, "asset_id")), reserve_asset_id), equal(text(field(reserve_availability_value, "asset_type_id")), "1")), equal(text(field(reserve_availability_value, "start_date")), reserve_start)), equal(text(field(reserve_availability_value, "end_date")), reserve_end)), equal(field(reserve_availability_value, "is_asset_owned_by_this_workspace"), true)), equal(field(reserve_availability_value, "is_advisory"), true)), "Availability must describe this owned Capital Asset and exact requested calendar dates; it is advisory, not a reservation.") if not_value(equal(field(reserve_availability_value, "is_available_under_reservation_policy"), true)) { print_value(string(reserve_availability_response.raw)) require_condition(false, "No reservation was sent. Availability does not permit this new allocation; review the dates and policy before another decision.") } reserve_create_fingerprint := journal_fingerprint(map[string]any{"asset_type_id": "1", "asset_id": reserve_asset_id, "event_id": reserve_event_id, "reservation_date": reserve_start, "return_date": reserve_end, "notes": "Display monitor for Spring Expo 2030", "notify_new_reservation": "false"}) reserve_create_intent := journal_begin(reserve_job, "create_reservation", "POST", "/v1/assets/reservations", reserve_create_fingerprint) reserve_create_response := call("create_reservation", map[string]string{}, map[string]any{"asset_type_id": "1", "asset_id": reserve_asset_id, "event_id": reserve_event_id, "reservation_date": reserve_start, "return_date": reserve_end, "notes": "Display monitor for Spring Expo 2030", "notify_new_reservation": false}, text(field(reserve_create_intent, "idempotency_key"))) require_condition(equal(response_status(reserve_create_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") reserve_created := reserve_create_response.body reserve_id = positive_id(text(field(reserve_created, "id"))) require_condition(both(both(both(both(both(both(both(both(equal(text(field(reserve_created, "id")), reserve_id), equal(text(field(reserve_created, "asset_type_id")), "1")), equal(text(field(reserve_created, "asset_id")), reserve_asset_id)), equal(text(field(reserve_created, "event_id")), reserve_event_id)), equal(field(reserve_created, "is_asset_owned_by_this_workspace"), true)), equal(text(field(reserve_created, "reservation_date")), reserve_start)), equal(text(field(reserve_created, "return_date")), reserve_end)), equal(text(field(reserve_created, "notes")), "Display monitor for Spring Expo 2030")), equal(field(reserve_created, "is_checked"), false)), "The reservation differs from the captured typed ID, owned Asset, Event, dates, notes or checked state. Review it before continuing; do not restore it automatically.") journal_acknowledge(reserve_job, "create_reservation", map[string]any{"id": reserve_id, "asset_type_id": "1", "asset_id": reserve_asset_id, "event_id": reserve_event_id}) } reserve_read_response := call("read_reservation", map[string]string{"id": reserve_id, "asset_type_id": "1", "$include_record_revision": "true"}, nil, "") require_condition(equal(response_status(reserve_read_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") reserve_current := reserve_read_response.body reserve_revision := text(field(reserve_current, "record_revision")) require_condition(is_present(reserve_revision), "The actual reservation Info read must include its record_revision.") if journal_acknowledged(reserve_job, "mark_checked") { reserve_update_saved := journal_saved(reserve_job, "mark_checked") require_condition(both(both(both(both(equal(text(field(reserve_update_saved, "id")), reserve_id), equal(text(field(reserve_update_saved, "asset_type_id")), "1")), equal(text(field(reserve_update_saved, "asset_id")), reserve_asset_id)), equal(text(field(reserve_update_saved, "event_id")), reserve_event_id)), equal(text(field(reserve_update_saved, "record_revision")), reserve_revision)), "The acknowledged update or current revision differs. Stop and review; do not restore earlier values.") require_condition(both(both(both(both(both(both(both(both(equal(text(field(reserve_current, "id")), reserve_id), equal(text(field(reserve_current, "asset_type_id")), "1")), equal(text(field(reserve_current, "asset_id")), reserve_asset_id)), equal(text(field(reserve_current, "event_id")), reserve_event_id)), equal(field(reserve_current, "is_asset_owned_by_this_workspace"), true)), equal(text(field(reserve_current, "reservation_date")), reserve_start)), equal(text(field(reserve_current, "return_date")), reserve_end)), equal(text(field(reserve_current, "notes")), "Display monitor for Spring Expo 2030")), equal(field(reserve_current, "is_checked"), true)), "The reservation differs from the captured typed ID, owned Asset, Event, dates, notes or checked state. Review it before continuing; do not restore it automatically.") } else { require_condition(both(both(both(both(both(both(both(both(equal(text(field(reserve_current, "id")), reserve_id), equal(text(field(reserve_current, "asset_type_id")), "1")), equal(text(field(reserve_current, "asset_id")), reserve_asset_id)), equal(text(field(reserve_current, "event_id")), reserve_event_id)), equal(field(reserve_current, "is_asset_owned_by_this_workspace"), true)), equal(text(field(reserve_current, "reservation_date")), reserve_start)), equal(text(field(reserve_current, "return_date")), reserve_end)), equal(text(field(reserve_current, "notes")), "Display monitor for Spring Expo 2030")), equal(field(reserve_current, "is_checked"), false)), "The reservation differs from the captured typed ID, owned Asset, Event, dates, notes or checked state. Review it before continuing; do not restore it automatically.") reserve_patch := map[string]any{"id": reserve_id, "asset_type_id": "1", "is_checked": true, "expected_revision": reserve_revision, "notify_reservation_update": false} reserve_patch_fingerprint := journal_fingerprint(map[string]any{"id": reserve_id, "asset_type_id": "1", "is_checked": "true", "expected_revision": reserve_revision, "notify_reservation_update": "false"}) journal_begin(reserve_job, "mark_checked", "PATCH", "/v1/assets/reservations", reserve_patch_fingerprint) reserve_patch_response := result{} var reserve_patch_response_failure any func() { defer func() { reserve_patch_response_failure = recover() }() reserve_patch_response = call("mark_checked", map[string]string{}, reserve_patch, "") require_condition(reserve_patch_response.status == 200, "Expected HTTP200 for the selected conditional PATCH; read current values before another decision.") require_condition(is_present(text(field(reserve_patch_response.body, "record_revision"))), "The conditional PATCH acknowledgement needs its actual record_revision.") }() if reserve_patch_response_failure != nil { print_value(fmt.Sprint(reserve_patch_response_failure)) reserve_failure_read_response := call("read_reservation", map[string]string{"id": reserve_id, "asset_type_id": "1", "$include_record_revision": "true"}, nil, "") require_condition(equal(response_status(reserve_failure_read_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") print_value(string(reserve_failure_read_response.raw)) require_condition(false, "Review these actual current values and reconcile the saved pending PATCH before another write. The programme did not repeat or acknowledge the update.") } require_condition(equal(response_status(reserve_patch_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") reserve_patch_receipt := reserve_patch_response.body reserve_after_revision := text(field(reserve_patch_receipt, "record_revision")) journal_acknowledge(reserve_job, "mark_checked", map[string]any{"id": reserve_id, "asset_type_id": "1", "asset_id": reserve_asset_id, "event_id": reserve_event_id, "record_revision": reserve_after_revision}) } reserve_verify_response := call("verify_reservation", map[string]string{"id": reserve_id, "asset_type_id": "1"}, nil, "") require_condition(equal(response_status(reserve_verify_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") reserve_verified := reserve_verify_response.body require_condition(both(both(both(both(both(both(both(both(equal(text(field(reserve_verified, "id")), reserve_id), equal(text(field(reserve_verified, "asset_type_id")), "1")), equal(text(field(reserve_verified, "asset_id")), reserve_asset_id)), equal(text(field(reserve_verified, "event_id")), reserve_event_id)), equal(field(reserve_verified, "is_asset_owned_by_this_workspace"), true)), equal(text(field(reserve_verified, "reservation_date")), reserve_start)), equal(text(field(reserve_verified, "return_date")), reserve_end)), equal(text(field(reserve_verified, "notes")), "Display monitor for Spring Expo 2030")), equal(field(reserve_verified, "is_checked"), true)), "The reservation differs from the captured typed ID, owned Asset, Event, dates, notes or checked state. Review it before continuing; do not restore it automatically.") reserve_options_response := call("cancellation_options", map[string]string{"id": reserve_id, "asset_type_id": "1"}, nil, "") require_condition(equal(response_status(reserve_options_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") reserve_options := reserve_options_response.body require_condition(both(both(equal(text(field(reserve_options, "reservation_id")), reserve_id), equal(text(field(reserve_options, "asset_id")), reserve_asset_id)), equal(text(field(reserve_options, "asset_type_id")), "1")), "The cancellation options describe a different typed reservation. No cancellation was sent.") print_value(map[string]any{"id": reserve_id, "asset_type_id": "1", "asset_id": reserve_asset_id, "event_id": reserve_event_id, "is_checked": field(reserve_verified, "is_checked"), "inventory_outcomes": field(reserve_options, "inventory_outcomes")}) }() } func header_key(value string)string{for _,ch:=range value{if ch<32||ch>126{panic("Use the API key as one ASCII header value without control characters")}};return value} func main(){apiKey=header_key(required("EXHIBITDAY_API_KEY"));if err:=json.Unmarshal([]byte(specification),&spec);err!=nil{panic(err)};workflow()} ``` #### Example response Response 200 — OK 304 — Not Modified 400 — Bad Request 401 — Unauthorized 404 — Not Found 409 — Conflict 429 — Too Many Requests 500 — Internal Server Error Example Successful request ```json { "id": 23456, "asset_type_id": 1, "asset_id": 12345, "asset_name": "Display monitor", "is_asset_owned_by_this_workspace": true, "event_id": 45678, "event_name": "Spring Expo 2030", "reservation_date": "2030-01-02", "return_date": "2030-01-04", "storage_location_id": null, "storage_location_name": null, "quantity": 1, "quantity_adjustment": null, "is_quantity_editable": true, "notes": "Display monitor for Spring Expo 2030", "shipping_logistics_id": 1, "is_flagged": false, "is_starred": false, "is_checked": true, "asset_reservation_created_timestamp": "2030-01-01T12:00:00Z", "optional_accessories": [], "logistical_records": [], "attachments": [] } ``` Note: The reservation as read after it was marked checked. The program then reads the cancellation options and leaves the reservation in place. Note: There is no response body. Keep using your cached response. ```json { "status_code": 400, "status": "Bad Request", "message": "HTTP method override is not supported.", "error_code": "invalid_request", "errors": [ "Send the documented HTTP method directly. X-HTTP-Method-Override cannot change a request's HTTP method." ], "error_params": [ "X-HTTP-Method-Override" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "No API key was provided. Send your key in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "missing_api_key", "errors": [ "Copy the key from Workspace Settings > API & Integrations > API Access in ExhibitDay." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "The API key is not valid. Check that you copied the whole key from Workspace Settings > API & Integrations > API Access, then send it in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "invalid_api_key", "errors": [ "Check that you sent the whole key. If it was regenerated, use the current key from Workspace Settings > API & Integrations > API Access." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "Access to the ExhibitDay API is not enabled for your workspace. Please contact support@exhibitday.com to enable API Access. Once access is enabled, send your key in the Authorization header as 'Bearer YOUR_API_KEY'.", "error_code": "api_access_disabled", "errors": [ "Nothing was read or changed." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 404, "status": "Not Found", "message": "Asset Reservation not found. Invalid Asset Reservation ID: 12345.", "error_code": "not_found", "errors": [ "Asset Reservation not found. Invalid Asset Reservation ID: 12345." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "The record was being changed while it was read, so no record_revision could be issued. Read it again.", "error_code": "record_changed", "errors": [ "The record was being changed while it was read, so no record_revision could be issued. Read it again." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "This reservation changed while it was being read. Read it again; no data was changed.", "error_code": "record_changed", "errors": [ "This reservation changed while it was being read. Read it again; no data was changed." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 429, "status": "Too Many Requests", "message": "Error 429 - Too Many Requests", "error_code": "rate_limited", "errors": [ "Error 429 - Too Many Requests" ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "An unexpected error occurred. Please try again later." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` Note: Use the request_id from your own response when contacting support. ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "Check whether your change was saved before trying again." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` #### Things to keep in mind - Capital availability uses inclusive calendar dates and the Asset's reservation policy. Collateral availability uses dated stock deductions and scheduled returns. An earlier reservation does not make an archived or no-longer-shared Asset eligible for a new allocation. - On update, omission keeps the saved value. A Collateral `return_date` of null makes the return unknown. Use `new_event_id` for an allowed move. Moving or extending a reservation can require current eligibility again. - The example sends both notification flags as false. The API defaults to true for eligible notifications. If you choose to [cancel the reservation](https://api.exhibitday.com/Help/V1?epf=5&topic=reservations#post-v1-assets-cancel_reservation), select from the current inventory options. Cancellation does not support an Idempotency-Key. After an uncertain response, check the reservation and inventory before deciding whether to repeat it. #### If a run stops - Keep the journal private. It records what the program tried to save and which save it confirmed. - To continue a run with no unresolved save, use `EXHIBITDAY_JOB_MODE=resume` with the same job ID, journal path and inputs. - A resumed run skips an acknowledged create and reads the saved reservation. A failed or uncertain PATCH triggers one current read and then stops, keeping the pending change in the journal. - If a save stops with a lost response, check the saved reservation and its Event in ExhibitDay before running the program again. - If you still need a change after checking the old run, use `EXHIBITDAY_JOB_MODE=new` with a new job ID and journal path. - Run only one copy per journal. - If a crash leaves a `.lock` file, make sure no copy using that journal is running or can start. Then remove the lock file and keep the journal. #### Related guides - [Update Collateral Stock After a Delivery or Recount](https://api.exhibitday.com/Help/V1?guide=collateral-inventory-storage) - [Avoid Overwriting Someone Else's Changes](https://api.exhibitday.com/Help/V1?guide=update-records-safely) - [Handle Errors and Retry Failed Requests](https://api.exhibitday.com/Help/V1?guide=errors-and-retries) ### Update Collateral Stock After a Delivery or Recount Guide page: https://api.exhibitday.com/Help/V1?guide=collateral-inventory-storage Record a stock delivery or recount for Collateral at a Storage Location. Example use case A delivery contains 120 brochures. A later recount shows there were 118. What you'll end up with One stock adjustment at the selected Storage Location, with the received count or your corrected count after a recount. Before you start Have a workspace API key that can edit manual inventory, an Active Collateral item you own, and a Storage Location in your workspace. Good to know The program records the delivery first. If you supply a recount quantity, it corrects the same adjustment in a separate save. #### At a glance Time to try About 10 minutes Effect on your data Creates and updates Endpoints 4 The program records one stock adjustment and corrects it when you supply a recount quantity. It writes a private local journal. - [`GET /v1/references/workspace_info`](https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-workspace_info) - [`POST /v1/assets/inventory_adjustments`](https://api.exhibitday.com/Help/V1?epf=5&topic=inventory-adjustments#post-v1-assets-inventory_adjustments) - [`GET /v1/assets/inventory_adjustments/info`](https://api.exhibitday.com/Help/V1?epf=5&topic=inventory-adjustments#get-v1-assets-inventory_adjustments-info) - [`PATCH /v1/assets/inventory_adjustments`](https://api.exhibitday.com/Help/V1?epf=5&topic=inventory-adjustments#patch-v1-assets-inventory_adjustments) #### How it works 1. Choose an Active Collateral item and a Storage Location in your workspace. Supply the quantity received and, if you have one, the corrected count. 2. The program records the delivery. With a recount quantity, it reads the saved revision and corrects that same adjustment. 3. It verifies the saved increase and prints the adjustment ID and quantity. #### Record and verify the stock adjustment These requests show a delivery of 120 and a recount of 118. Without a recount quantity, the program skips the revision read and correction in Steps 3 and 4, then verifies the received quantity in Step 5. **Manual example.** If you need IDs, find an [Active Collateral item](https://api.exhibitday.com/Help/V1?epf=5#get-v1-assets) and a [Storage Location](https://api.exhibitday.com/Help/V1?epf=5&topic=storage-locations#get-v1-assets-storage_locations) in your workspace. The program starts with the IDs you supply. `curl -X GET "https://api.exhibitday.com/v1/assets?filter_by_asset_type_id=2&filter_by_asset_status_id=1" -H "Authorization: Bearer YOUR_API_KEY"` `curl -X GET "https://api.exhibitday.com/v1/assets/storage_locations" -H "Authorization: Bearer YOUR_API_KEY"` **Check:** The item is Collateral and belongs to your workspace, and the Storage Location belongs to your workspace. #### Step 1: Confirm the workspace Check where the key will make changes so you can confirm the workspace. ```bash curl -X GET "https://api.exhibitday.com/v1/references/workspace_info" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "id": 98765 } ``` **Check:** Confirm id is the workspace you intended to use. #### Step 2: Record the stock delivery Create one adjustment for the 120 brochures received at the selected location. ```bash curl -X POST "https://api.exhibitday.com/v1/assets/inventory_adjustments" -H "Authorization: Bearer YOUR_API_KEY" -H "Idempotency-Key: YOUR_PERSISTED_ADJUSTMENT_KEY" -H "Content-Type: application/json" --data-binary "{\"asset_id\":1234,\"storage_location_id\":2345,\"quantity\":120,\"is_increase\":true,\"description\":\"Brochures received for Annual Expo\"}" ``` Example response (shortened) ```json { "id": 3456, "asset_id": 1234, "storage_location_id": 2345, "quantity_adjustment": 120, "quantity": 120, "is_increase": true, "description": "Brochures received for Annual Expo" } ``` **Check:** Confirm the item, location and increase. Keep the returned adjustment id. #### Step 3: Read the adjustment and its revision Read the saved adjustment so the correction can check for intervening changes. ```bash curl -X GET "https://api.exhibitday.com/v1/assets/inventory_adjustments/info?id=3456&%24include_record_revision=true" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "id": 3456, "asset_id": 1234, "storage_location_id": 2345, "quantity_adjustment": 120, "quantity": 120, "is_increase": true, "description": "Brochures received for Annual Expo", "record_revision": "COPY_ADJUSTMENT_REVISION_FROM_YOUR_READ" } ``` **Check:** Confirm the same adjustment, Asset and location. Keep its record_revision for the PATCH. #### Step 4: Correct the increase after a recount Set the same adjustment's quantity to 118 using the revision from your read. ```bash curl -X PATCH "https://api.exhibitday.com/v1/assets/inventory_adjustments" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" --data-binary "{\"id\":3456,\"quantity\":118,\"expected_revision\":\"COPY_ADJUSTMENT_REVISION_FROM_YOUR_READ\"}" ``` Example response (shortened) ```json { "status_code": 200, "status": "OK", "message": "Inventory Adjustment updated.", "errors": [], "record_revision": "NEW_ADJUSTMENT_REVISION" } ``` **Check:** Look for the returned record_revision. The PATCH identifies the adjustment by id and leaves the Asset and location out. #### Step 5: Verify the corrected stock movement Read the adjustment normally to confirm the saved increase. ```bash curl -X GET "https://api.exhibitday.com/v1/assets/inventory_adjustments/info?id=3456" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "id": 3456, "asset_id": 1234, "storage_location_id": 2345, "quantity_adjustment": 118, "quantity": 118, "is_increase": true, "description": "Brochures received for Annual Expo" } ``` **Check:** Confirm the same ID, item and location with an increase of 118. This is a stock movement. Use availability for the stock balance. **Note.** A lost response can leave the outcome uncertain. Review the adjustment and inventory before deciding whether to send another request. #### Try it #### Before running the example | Variable | What to put in it | Required? | | --- | --- | --- | | `EXHIBITDAY_API_KEY` | Your workspace API key. | Yes | | `EXHIBITDAY_ASSET_ID` | The ID of an Active Collateral item in your workspace. | Yes | | `EXHIBITDAY_STORAGE_LOCATION_ID` | The ID of the Storage Location where you received the stock. | Yes | | `EXHIBITDAY_RECEIVED_QUANTITY` | The number of items received, a whole number greater than zero. | Yes | | `EXHIBITDAY_RECOUNT_QUANTITY` | The corrected count after a recount, a whole number greater than zero. Leave it unset to skip the correction. | No | | `EXHIBITDAY_JOB_ID` | A stable ID for this logical change. | Yes | | `EXHIBITDAY_JOURNAL` | A private local path for this job's journal. | Yes | | `EXHIBITDAY_JOB_MODE` | Use new for a genuinely new job or resume with the existing journal. The default is resume. | No | **Careful.** This example changes data in your workspace. Use a test Collateral item and Storage Location. #### Bash ``` export EXHIBITDAY_API_KEY='YOUR_API_KEY' export EXHIBITDAY_ASSET_ID='1234' export EXHIBITDAY_STORAGE_LOCATION_ID='2345' export EXHIBITDAY_RECEIVED_QUANTITY='120' export EXHIBITDAY_RECOUNT_QUANTITY='118' export EXHIBITDAY_JOB_ID='brochure-delivery-01' export EXHIBITDAY_JOURNAL='/private/path/brochure-delivery-01.json' export EXHIBITDAY_JOB_MODE='new' ``` #### PowerShell ``` $env:EXHIBITDAY_API_KEY = 'YOUR_API_KEY' $env:EXHIBITDAY_ASSET_ID = '1234' $env:EXHIBITDAY_STORAGE_LOCATION_ID = '2345' $env:EXHIBITDAY_RECEIVED_QUANTITY = '120' $env:EXHIBITDAY_RECOUNT_QUANTITY = '118' $env:EXHIBITDAY_JOB_ID = 'brochure-delivery-01' $env:EXHIBITDAY_JOURNAL = 'C:\private\path\brochure-delivery-01.json' $env:EXHIBITDAY_JOB_MODE = 'new' ``` Use your own Collateral and Storage Location IDs and quantities. Then copy the complete example program below in your language and run it. For a new job, choose a new private journal path and stable job ID. To continue that job, use the same values and set `EXHIBITDAY_JOB_MODE=resume`. #### Complete example program Code Samples ```bash #!/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_adjustment\":{\"method\":\"POST\",\"path\":\"/assets/inventory_adjustments\"},\"read_adjustment\":{\"method\":\"GET\",\"path\":\"/assets/inventory_adjustments/info\"},\"correct_count\":{\"method\":\"PATCH\",\"path\":\"/assets/inventory_adjustments\"},\"verify_adjustment\":{\"method\":\"GET\",\"path\":\"/assets/inventory_adjustments/info\"}}}") API_KEY = os.environ["EXHIBITDAY_API_KEY"] if any(ord(char) < 32 or ord(char) > 126 for char in API_KEY): raise RuntimeError("Use the API key as one ASCII header value without control characters") if not API_KEY.strip(): raise RuntimeError("Set EXHIBITDAY_API_KEY") def decode_json(text): if SPEC["preserveNumbers"]: # Quote JSON NUMBER tokens, never text inside a JSON string, to keep CSV decimals exact. text = re.sub(r'"(?:\\.|[^"\\])*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?', lambda m: m[0] if m[0].startswith('"') else json.dumps(m[0]), text) return json.loads(text) from pathlib import Path # This terminal version uses curl for HTTP and Python's standard library for JSON/CSV. import subprocess import tempfile def transport(method, url, headers, data): with tempfile.TemporaryDirectory(prefix="exhibitday-guide-") as directory: folder = Path(directory) # curl may leave no output file for a valid bodyless304 response. (folder / "body").write_bytes(b"") command = ["curl", "--disable", "--silent", "--show-error", "--request", method, "--url", url, "--max-time", "30", "--dump-header", str(folder / "headers"), "--output", str(folder / "body"), "--write-out", "%{http_code}"] for name, value in headers.items(): command += ["--header", name + ": " + value] if data is not None: (folder / "request").write_bytes(data) command += ["--data-binary", "@" + str(folder / "request")] result = subprocess.run(command, capture_output=True, text=True) if result.returncode: raise urllib.error.URLError(result.stderr.strip()) response_headers = {} blocks = (folder / "headers").read_text(encoding="iso-8859-1").replace("\r\n", "\n").strip().split("\n\n") for line in blocks[-1].splitlines()[1:]: name, separator, value = line.partition(":") if separator: response_headers[name] = value.strip() return int(result.stdout), (folder / "body").read_bytes(), response_headers class ApiError(RuntimeError): """An API error response. Branch on error_code (and status), never on the message text. uncertain is True when a PATCH or DELETE got no response or a server error: it may or may not have been applied.""" def __init__(self, status, body, uncertain=False): self.status = status self.uncertain = uncertain self.error_code = body.get("error_code") if isinstance(body, dict) else None super().__init__(f"{body.get('error_code')} {body.get('error_params')}: {body.get('errors')} (request {body.get('request_id')})" if isinstance(body, dict) else "HTTP " + str(status) if status else "No response") def call(name, params=None, body=None, key=None): route = SPEC["requests"][name] headers = {"Authorization": "Bearer " + API_KEY, "Accept": "application/json"} if route["method"] == "POST": if not key: raise RuntimeError("Persist a logical create key before sending POST") headers["Idempotency-Key"] = key data = None if body is None else json.dumps(body).encode("utf-8") if data is not None: headers["Content-Type"] = "application/json" query = urllib.parse.urlencode(params or {}) url = BASE + route["path"] + ("?" + query if query else "") # Only GET has automatic retries in this workflow. A PATCH or DELETE that got no response or a # server error is never resent blindly: it may already have been applied, so the caller reads the record first. resend = route["method"] == "GET" for attempt in range(5): try: status, raw, response_headers = transport(route["method"], url, headers, data) except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException): if not resend: raise ApiError(0, None, uncertain=True) if attempt == 4: raise time.sleep(2 ** attempt) continue response_headers = {k.lower(): v for k, v in response_headers.items()} result = None if status != 304 and raw: try: result = decode_json(raw.decode("utf-8")) except (ValueError, UnicodeError): if status < 400: raise RuntimeError("Expected a JSON success response") if status >= 500 and not resend: raise ApiError(status, result, uncertain=True) retry = resend and (status == 429 or status >= 500) if retry: if attempt == 4: raise RuntimeError("Retry limit reached; check the request outcome before starting a new create") delay = response_headers.get("retry-after", str(2 ** attempt)) time.sleep(max(0, float(delay))) continue if status >= 400: raise ApiError(status, result) return {"status": status, "body": result, "headers": response_headers, "raw": raw} raise RuntimeError("Retry limit reached") def both(left,right): return left and right def bounded_whole_number(value, name, maximum): if not re.fullmatch(r"0|[1-9][0-9]*", value) or len(value)>len(maximum) or (len(value)==len(maximum) and value>maximum): raise RuntimeError(name+" must be a whole number from 0 through "+maximum) return value 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] 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 offsetlen(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)-offset:raise JournalRefusal('Incomplete journal frame; reconcile before retry') payload=raw[offset:offset+size];offset+=size if raw[offset:offset+1]!=b'\n' or digest(payload).encode('ascii')!=match[2]:raise JournalRefusal('Journal integrity check failed; reconcile before retry') records.append(read_strings(payload));offset+=1 return records class Journal: def __init__(self,path,base,workspace,slug,job,input_fingerprint,writes,mode="resume"): self.path=Path(path);self.lock=Path(str(self.path)+'.lock');self.fd=None;self.owned=False;self.identity=None;self.tainted=False;self.intents={};self.saved_values={} address=urlsplit(base) if address.scheme not in ('https','http')or not address.netloc or address.username is not None or address.query or address.fragment or not re.fullmatch('[a-z][a-z0-9-]*',slug):raise JournalRefusal('Use the actual API base and closed guide slug') if not job.strip() or not re.fullmatch('[1-9][0-9]*',workspace) or not re.fullmatch('[0-9A-F]{64}',input_fingerprint):raise JournalRefusal('Use an actual workspace, explicit stable job ID and exact input fingerprint') if mode not in ("new","resume"):raise JournalRefusal("Choose new or resume for this local job") self.allowed={};manifest=[] for step,method,route in writes: if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.allowed or method not in ('POST','PATCH','DELETE')or not re.fullmatch('/v1/[A-Za-z0-9_/-]+',route)or'//'in route:raise JournalRefusal('Use a closed unique write manifest') self.allowed[step]=(method,route);manifest.extend((step,method,route)) if not self.allowed:raise JournalRefusal('Only write workflows need a restart journal') self.header=['H','1',base,workspace,slug,job,input_fingerprint,digest(strings(manifest))] strings(self.header) try: self.fd=os.open(self.lock,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600);self.owned=True except FileExistsError:raise JournalRefusal('This journal is locked; do not run overlapping jobs or steal a stale lock') try: self.owner=secrets.token_hex(16);self.identity=os.fstat(self.fd) if os.write(self.fd,self.owner.encode('ascii'))!=len(self.owner):raise OSError('Incomplete lock identity write') os.fsync(self.fd) if self.path.is_symlink():raise JournalRefusal('Choose a private regular journal file') if mode=="resume" and not self.path.exists():raise JournalRefusal("Journal missing: stop and reconcile lost state before starting a new logical job") if mode=="new" and self.path.exists():raise JournalRefusal("A journal already exists; use resume for the same logical job") if mode=="new": with open(self.path,'xb',buffering=0)as target: target.write(PREAMBLE+frame(self.header));os.fsync(target.fileno()) records=decode(self.path.read_bytes()) if not records or records[0]!=self.header:raise JournalRefusal('Journal workspace/base/guide/job/input binding differs') for record in records[1:]:self.apply(record) if any(step not in self.saved_values for step in self.intents):raise JournalRefusal('A saved before-send intent lacks an ACK; stop and reconcile its outcome before retry') except BaseException: self.close();raise def apply(self,record): if not record:raise JournalRefusal('Empty journal record') if record[0]=='I': if len(record)!=6:raise JournalRefusal('Invalid intent shape') _,step,method,path,request_fingerprint,key=record if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.intents or self.allowed.get(step)!=(method,path)or not re.fullmatch('[0-9A-F]{64}',request_fingerprint)or any(name not in self.saved_values for name in self.intents):raise JournalRefusal('Invalid, future or repeated journal intent') if method=='POST'and not re.fullmatch('[0-9a-f]{32}',key)or method!='POST'and key!='':raise JournalRefusal('Invalid persisted action key') self.intents[step]={'method':method,'path':path,'request_fingerprint':request_fingerprint,'idempotency_key':key} elif record[0]=='A': if len(record)<3:raise JournalRefusal('Invalid ACK shape') _,step,count,*pairs=record if not re.fullmatch('0|[1-9][0-9]*',count)or len(pairs)!=2*int(count)or step not in self.intents or step in self.saved_values:raise JournalRefusal('ACK without exactly one prior intent') names=pairs[::2] if names!=sorted(set(names))or any(not re.fullmatch('[a-z][a-z0-9_]*',name)or name in ('api_key','exhibitday_api_key')for name in names):raise JournalRefusal('ACK saved fields must be unique sorted secret-free identifiers') self.saved_values[step]=dict(zip(names,pairs[1::2])) else:raise JournalRefusal('Unknown journal transition') def append(self,record): # The reader commits state only after complete length/digest recognition. # A torn append is retained and refused, never silently truncated. self.require_active();raw=frame(record) try: with open(self.path,'ab',buffering=0)as target: view=memoryview(raw) while view: written=target.write(view) if not written:raise OSError('Journal write did not advance') view=view[written:] os.fsync(target.fileno()) except BaseException: self.tainted=True;raise def require_active(self): if not self.owned or self.fd is None or self.identity is None or self.tainted:raise JournalRefusal('The journal scope is closed or its IO outcome needs reconciliation') current=self.lock.stat(follow_symlinks=False) if current.st_dev!=self.identity.st_dev or current.st_ino!=self.identity.st_ino or self.lock.read_text(encoding='ascii')!=self.owner:raise JournalRefusal('The journal lock was replaced; stop without deleting it') def acknowledged(self,step): self.require_active();return step in self.saved_values def saved(self,step): self.require_active() if step not in self.saved_values:raise JournalRefusal('No acknowledged state exists for this step') return dict(self.saved_values[step]) def begin(self,step,method,path,request_fingerprint): self.require_active() if step in self.intents:raise JournalRefusal('Never blindly repeat an existing action intent') key=secrets.token_hex(16)if method=='POST'else'' record=['I',step,method,path,request_fingerprint,key] # Validate on an isolated state before touching the file. old=dict(self.intents) try:self.apply(record) finally:self.intents=old self.append(record);self.apply(record) return dict(self.intents[step]) def acknowledge(self,step,saved): self.require_active() record=['A',step,str(len(saved))] for name,value in sorted(saved.items()):record.extend((name,value)) old={name:dict(value)for name,value in self.saved_values.items()} try:self.apply(record);strings(record) finally:self.saved_values=old self.append(record);self.apply(record) def close(self): if self.owned: if self.tainted: os.close(self.fd);self.fd=None;self.owned=False return # Retain this lock after failed journal IO; manual reconciliation is required. try:self.require_active() except BaseException: os.close(self.fd);self.fd=None;self.owned=False;raise os.close(self.fd);self.fd=None;self.owned=False self.lock.unlink() def __enter__(self):return self def __exit__(self,*args):self.close() def journal_values(value): if not isinstance(value, dict) or any(not isinstance(k, str) or not isinstance(v, str) for k,v in value.items()): raise JournalRefusal('Saved/fingerprint values must be exact string fields') return dict(value) def journal_acknowledge(job, step, saved): job.acknowledge(step,journal_values(saved)) def journal_acknowledged(job, step): return job.acknowledged(step) def journal_begin(job, step, method, path, request_fingerprint): return job.begin(step,method,path,request_fingerprint) def journal_fingerprint(value): return fingerprint(journal_values(value)) def journal_saved(job, step): return job.saved(step) def 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 positive_id(value): if not re.fullmatch(r"[1-9][0-9]*", value) or int(value) > 9223372036854775807: raise RuntimeError("Use a positive record ID") return value def print_value(value): print(value if isinstance(value, str) else json.dumps(value, ensure_ascii=False)) def require_condition(value, message): if value is not True: raise RuntimeError(message) def required(name): value = os.environ.get(name) if value is None or not value.strip(): raise RuntimeError("Set " + name) return value def response_status(value): return str(value["status"]) def 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(): inventory_asset_id = positive_id(required("EXHIBITDAY_ASSET_ID")) inventory_location_id = positive_id(required("EXHIBITDAY_STORAGE_LOCATION_ID")) inventory_journal_path = required("EXHIBITDAY_JOURNAL") inventory_job_id = required("EXHIBITDAY_JOB_ID") inventory_job_mode = optional("EXHIBITDAY_JOB_MODE", "resume") require_condition(either(equal(inventory_job_mode, "new"), equal(inventory_job_mode, "resume")), "Use exact new or resume for EXHIBITDAY_JOB_MODE.") inventory_received = bounded_whole_number(required("EXHIBITDAY_RECEIVED_QUANTITY"), "EXHIBITDAY_RECEIVED_QUANTITY", "2147483647") require_condition(not_value(equal(inventory_received, "0")), "EXHIBITDAY_RECEIVED_QUANTITY must be greater than zero.") inventory_recount = optional("EXHIBITDAY_RECOUNT_QUANTITY", "") inventory_expected = inventory_received if not_value(equal(inventory_recount, "")): inventory_recount = bounded_whole_number(inventory_recount, "EXHIBITDAY_RECOUNT_QUANTITY", "2147483647") require_condition(not_value(equal(inventory_recount, "0")), "EXHIBITDAY_RECOUNT_QUANTITY must be greater than zero.") inventory_expected = inventory_recount inventory_workspace_response = call("workspace_binding", {}, None, None) require_condition(equal(response_status(inventory_workspace_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") inventory_workspace = inventory_workspace_response["body"] inventory_workspace_id = positive_id(text(field(inventory_workspace, "id"))) inventory_input_fingerprint = journal_fingerprint({"workflow_contract_sha256": "F9CCD36E69D6E5A76E22B460D9FB853A89937E942238AAD7DF5A63BE8EA9F49D", "asset_id": inventory_asset_id, "storage_location_id": inventory_location_id, "create_quantity": inventory_received, "correct_quantity": inventory_recount}) inventory_job = open_journal(inventory_journal_path, "https://api.exhibitday.com/v1", inventory_workspace_id, "collateral-inventory-storage", inventory_job_id, inventory_input_fingerprint, [["create_adjustment", "POST", "/v1/assets/inventory_adjustments"], ["correct_count", "PATCH", "/v1/assets/inventory_adjustments"]], inventory_job_mode) try: require_condition(either(not_value(journal_acknowledged(inventory_job, "correct_count")), journal_acknowledged(inventory_job, "create_adjustment")), "A correction is acknowledged before its create. Stop and reconcile the journal.") require_condition(either(not_value(journal_acknowledged(inventory_job, "correct_count")), not_value(equal(inventory_recount, ""))), "This journal records a correction without a recount quantity. Stop and reconcile.") inventory_adjustment_id = "" if journal_acknowledged(inventory_job, "create_adjustment"): inventory_created_saved = journal_saved(inventory_job, "create_adjustment") inventory_adjustment_id = positive_id(text(field(inventory_created_saved, "id"))) require_condition(both(equal(text(field(inventory_created_saved, "asset_id")), inventory_asset_id), equal(text(field(inventory_created_saved, "storage_location_id")), inventory_location_id)), "The saved adjustment belongs to different inventory or storage; do not create a replacement.") else: inventory_create_fingerprint = journal_fingerprint({"asset_id": inventory_asset_id, "storage_location_id": inventory_location_id, "quantity": inventory_received, "is_increase": "true", "description": "Brochures received for Annual Expo"}) inventory_create_intent = journal_begin(inventory_job, "create_adjustment", "POST", "/v1/assets/inventory_adjustments", inventory_create_fingerprint) inventory_create_response = call("create_adjustment", {}, {"asset_id": inventory_asset_id, "storage_location_id": inventory_location_id, "quantity": inventory_received, "is_increase": True, "description": "Brochures received for Annual Expo"}, text(field(inventory_create_intent, "idempotency_key"))) require_condition(equal(response_status(inventory_create_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") inventory_created = inventory_create_response["body"] inventory_adjustment_id = positive_id(text(field(inventory_created, "id"))) require_condition(both(both(equal(text(field(inventory_created, "id")), inventory_adjustment_id), equal(text(field(inventory_created, "asset_id")), inventory_asset_id)), both(equal(text(field(inventory_created, "storage_location_id")), inventory_location_id), both(both(equal(text(field(inventory_created, "quantity_adjustment")), inventory_received), equal(text(field(inventory_created, "quantity")), inventory_received)), equal(field(inventory_created, "is_increase"), True)))), "The create acknowledgement differs from this item, location or stock increase. Keep pending state and reconcile.") journal_acknowledge(inventory_job, "create_adjustment", {"id": inventory_adjustment_id, "asset_id": inventory_asset_id, "storage_location_id": inventory_location_id}) if not_value(equal(inventory_recount, "")): inventory_read_response = call("read_adjustment", {"id": inventory_adjustment_id, "$include_record_revision": "true"}, None, None) require_condition(equal(response_status(inventory_read_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") inventory_current = inventory_read_response["body"] if journal_acknowledged(inventory_job, "correct_count"): inventory_corrected_saved = journal_saved(inventory_job, "correct_count") require_condition(both(equal(text(field(inventory_corrected_saved, "id")), inventory_adjustment_id), both(equal(text(field(inventory_corrected_saved, "asset_id")), inventory_asset_id), both(equal(text(field(inventory_corrected_saved, "storage_location_id")), inventory_location_id), equal(text(field(inventory_corrected_saved, "quantity")), inventory_recount)))), "The acknowledged correction differs from this record or quantity; stop and reconcile.") require_condition(both(both(equal(text(field(inventory_current, "id")), inventory_adjustment_id), equal(text(field(inventory_current, "asset_id")), inventory_asset_id)), both(equal(text(field(inventory_current, "storage_location_id")), inventory_location_id), both(both(equal(text(field(inventory_current, "quantity_adjustment")), inventory_recount), equal(text(field(inventory_current, "quantity")), inventory_recount)), equal(field(inventory_current, "is_increase"), True)))), "The acknowledged adjustment is now missing, rebound or changed; do not silently restore it.") else: require_condition(both(both(equal(text(field(inventory_current, "id")), inventory_adjustment_id), equal(text(field(inventory_current, "asset_id")), inventory_asset_id)), both(equal(text(field(inventory_current, "storage_location_id")), inventory_location_id), both(both(equal(text(field(inventory_current, "quantity_adjustment")), inventory_received), equal(text(field(inventory_current, "quantity")), inventory_received)), equal(field(inventory_current, "is_increase"), True)))), "The saved adjustment is no longer the expected stock increase. Review it before any correction.") inventory_revision = text(field(inventory_current, "record_revision")) require_condition(is_present(inventory_revision), "The inventory read must return its actual record_revision before correction.") inventory_patch = {"id": inventory_adjustment_id, "quantity": inventory_recount, "expected_revision": inventory_revision} inventory_patch_fingerprint = journal_fingerprint({"id": inventory_adjustment_id, "quantity": inventory_recount, "expected_revision": inventory_revision}) journal_begin(inventory_job, "correct_count", "PATCH", "/v1/assets/inventory_adjustments", inventory_patch_fingerprint) inventory_patch_response = call("correct_count", {}, inventory_patch, None) require_condition(equal(response_status(inventory_patch_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") inventory_patch_receipt = inventory_patch_response["body"] inventory_after_revision = text(field(inventory_patch_receipt, "record_revision")) require_condition(is_present(inventory_after_revision), "A checked correction acknowledgement requires its returned record_revision.") journal_acknowledge(inventory_job, "correct_count", {"id": inventory_adjustment_id, "asset_id": inventory_asset_id, "storage_location_id": inventory_location_id, "quantity": inventory_recount, "record_revision": inventory_after_revision}) inventory_verify_response = call("verify_adjustment", {"id": inventory_adjustment_id}, None, None) require_condition(equal(response_status(inventory_verify_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") inventory_verified = inventory_verify_response["body"] require_condition(both(both(equal(text(field(inventory_verified, "id")), inventory_adjustment_id), equal(text(field(inventory_verified, "asset_id")), inventory_asset_id)), both(equal(text(field(inventory_verified, "storage_location_id")), inventory_location_id), both(both(equal(text(field(inventory_verified, "quantity_adjustment")), inventory_expected), equal(text(field(inventory_verified, "quantity")), inventory_expected)), equal(field(inventory_verified, "is_increase"), True)))), "The final adjustment does not match the acknowledged record, location and stock increase. Reconcile; do not add another adjustment or undo it automatically.") print_value({"id": inventory_adjustment_id, "asset_id": inventory_asset_id, "storage_location_id": inventory_location_id, "quantity": inventory_expected}) finally: inventory_job.close() if __name__ == "__main__": main() EXHIBITDAY_PY ``` ```javascript // Server-side Node.js with fetch; built-in modules only. Set EXHIBITDAY_API_KEY. const BASE = "https://api.exhibitday.com/v1"; const SPEC = JSON.parse("{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"create_adjustment\":{\"method\":\"POST\",\"path\":\"/assets/inventory_adjustments\"},\"read_adjustment\":{\"method\":\"GET\",\"path\":\"/assets/inventory_adjustments/info\"},\"correct_count\":{\"method\":\"PATCH\",\"path\":\"/assets/inventory_adjustments\"},\"verify_adjustment\":{\"method\":\"GET\",\"path\":\"/assets/inventory_adjustments/info\"}}}"); const API_KEY = process.env.EXHIBITDAY_API_KEY; if (!API_KEY || !API_KEY.trim()) throw new Error("Set EXHIBITDAY_API_KEY"); if (/[^\x20-\x7e]/.test(API_KEY)) throw new Error("Use the API key as one ASCII header value without control characters"); 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, errors: result.errors, error_params: result.error_params, 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, key = null) { const route = SPEC.requests[name]; const headers = { Authorization: "Bearer " + API_KEY, Accept: "application/json" }; if (route.method === "POST") { if (!key) throw new Error("Persist a logical create key before sending POST"); headers["Idempotency-Key"] = key; } 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 : ""); // 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. const resend = route.method === "GET"; 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 = resend && (response.status === 429 || response.status >= 500); 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, raw }; } throw new Error("Retry limit reached"); } function both(left,right) { return left && right; } function bounded_whole_number(value,name,maximum) { if (!/^(?:0|[1-9][0-9]*)(?![\s\S])/.test(value) || value.length>maximum.length || (value.length===maximum.length && value>maximum)) throw new Error(name+" must be a whole number from 0 through "+maximum); return value; } function either(left, right) { if (typeof left !== "boolean" || typeof right !== "boolean") throw new Error("Expected Boolean criteria"); return left || right; } function equal(left, right) { return typeof left === typeof right && left === right; } function field(value, name) { if (!value || Array.isArray(value) || typeof value !== "object" || !Object.hasOwn(value, name)) throw new Error("Missing response field: " + name); return value[name]; } function is_present(value) { return value !== null && value !== undefined && value !== ""; } 'use strict'; // Private client restart state. No HTTP or application dependency. const fs = require('node:fs'); const crypto = require('node:crypto'); const PREAMBLE = Buffer.from('EXHIBITDAY-GUIDE-JOURNAL 1\n', 'ascii'); class JournalRefusal extends Error {} function ascii(raw) { if (raw.some(value => value > 127)) throw new JournalRefusal('Journal framing must be canonical ASCII'); return raw.toString('ascii'); } function utf8(value) { if (typeof value !== 'string') throw new JournalRefusal('Journal fields are exact strings'); for (const unit of value) if (unit.length === 1 && unit.charCodeAt(0) >= 0xd800 && unit.charCodeAt(0) <= 0xdfff) throw new JournalRefusal('Invalid Unicode journal field'); return Buffer.from(value, 'utf8'); } function strings(values) { const parts = []; for (const value of values) { const raw = utf8(value); parts.push(Buffer.from(String(raw.length) + ':', 'ascii'), raw); } return Buffer.concat(parts); } function readStrings(raw) { const values = []; let offset = 0; while (offset < raw.length) { const end = raw.indexOf(58, offset); if (end < 0) throw new JournalRefusal('Incomplete journal string length'); const length = ascii(raw.subarray(offset, end)); if (!/^(0|[1-9][0-9]*)$/.test(length)) throw new JournalRefusal('Noncanonical journal string length'); const size = BigInt(length); offset = end + 1; if (size > BigInt(raw.length - offset)) throw new JournalRefusal('Incomplete journal string'); const count = Number(size); values.push(new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(raw.subarray(offset, offset + count))); offset += count; } return values; } function digest(raw) { return crypto.createHash('sha256').update(raw).digest('hex').toUpperCase(); } function fingerprint(pairs) { const values = []; for (const name of Object.keys(pairs).sort()) { if (!/^[A-Za-z0-9_.-]+$/.test(name) || ['api_key', 'exhibitday_api_key'].includes(name.toLowerCase())) throw new JournalRefusal('Use explicit secret-free fingerprint field names'); values.push(name, pairs[name]); } return digest(strings(values)); } function frame(values) { const raw = strings(values); return Buffer.concat([Buffer.from(String(raw.length) + ' ' + digest(raw) + '\n', 'ascii'), raw, Buffer.from('\n')]); } function decode(raw) { if (!raw.subarray(0, PREAMBLE.length).equals(PREAMBLE)) throw new JournalRefusal('Unknown or incomplete journal version'); let offset = PREAMBLE.length; const records = []; while (offset < raw.length) { const end = raw.indexOf(10, offset); if (end < 0) throw new JournalRefusal('Incomplete journal frame header; reconcile before retry'); const match = /^(0|[1-9][0-9]*) ([0-9A-F]{64})$/.exec(ascii(raw.subarray(offset, end))); if (!match) throw new JournalRefusal('Invalid journal frame header'); const size = BigInt(match[1]); offset = end + 1; if (size >= BigInt(raw.length - offset)) throw new JournalRefusal('Incomplete journal frame; reconcile before retry'); const count = Number(size), payload = raw.subarray(offset, offset + count); offset += count; if (raw[offset] !== 10 || digest(payload) !== match[2]) throw new JournalRefusal('Journal integrity check failed; reconcile before retry'); records.push(readStrings(payload)); offset++; } return records; } function writeAll(fd, raw) { let offset = 0; while (offset < raw.length) { const count = fs.writeSync(fd, raw, offset, raw.length - offset); if (!count) throw new Error('Journal write did not advance'); offset += count; } } function same(left, right) { return left.length === right.length && left.every((value, index) => value === right[index]); } class Journal { constructor(path, base, workspace, slug, job, inputFingerprint, writes, mode = 'resume') { this.path = path; this.lock = path + '.lock'; this.fd = null; this.owned = false; this.identity = null; this.tainted = false; this.intents = new Map(); this.savedValues = new Map(); this.allowed = new Map(); if (!['new', 'resume'].includes(mode)) throw new JournalRefusal('Choose new or resume for this local job'); const address = new URL(base); if (!['https:', 'http:'].includes(address.protocol) || !address.hostname || address.username || address.password || address.search || address.hash || !/^[a-z][a-z0-9-]*$/.test(slug)) throw new JournalRefusal('Use the actual API base and closed guide slug'); if (!job.trim() || !/^[1-9][0-9]*$/.test(workspace) || !/^[0-9A-F]{64}$/.test(inputFingerprint)) throw new JournalRefusal('Use an actual workspace, stable explicit job ID and exact input fingerprint'); const manifest = []; for (const [step, method, route] of writes) { if (!/^[a-z][a-z0-9_-]*$/.test(step) || this.allowed.has(step) || !['POST', 'PATCH', 'DELETE'].includes(method) || !/^\/v1\/[A-Za-z0-9_/-]+$/.test(route) || route.includes('//')) throw new JournalRefusal('Use a closed unique write manifest'); this.allowed.set(step, [method, route]); manifest.push(step, method, route); } if (!this.allowed.size) throw new JournalRefusal('Only write workflows need a restart journal'); this.header = ['H', '1', base, workspace, slug, job, inputFingerprint, digest(strings(manifest))]; strings(this.header); try { this.fd = fs.openSync(this.lock, 'wx', 0o600); this.owned = true; } catch (error) { if (error.code === 'EEXIST') throw new JournalRefusal('This journal is locked; do not overlap jobs or steal a stale lock'); throw error; } try { this.owner = crypto.randomBytes(16).toString('hex'); this.identity = fs.fstatSync(this.fd, { bigint: true }); writeAll(this.fd, Buffer.from(this.owner, 'ascii')); fs.fsyncSync(this.fd); let exists = true; try { if (fs.lstatSync(path).isSymbolicLink()) throw new JournalRefusal('Choose a private regular journal file'); } catch (error) { if (error.code === 'ENOENT') exists = false; else throw error; } if (mode === 'resume' && !exists) throw new JournalRefusal('Journal missing: stop and reconcile lost state before starting a new logical job'); if (mode === 'new' && exists) throw new JournalRefusal('Journal already exists; use resume for the same logical job'); if (mode === 'new') { const target = fs.openSync(path, 'wx', 0o600); try { writeAll(target, Buffer.concat([PREAMBLE, frame(this.header)])); fs.fsyncSync(target); } finally { fs.closeSync(target); } } const records = decode(fs.readFileSync(path)); if (!records.length || !same(records[0], this.header)) throw new JournalRefusal('Journal workspace/base/guide/job/input binding differs'); for (const record of records.slice(1)) this.apply(record); if ([...this.intents.keys()].some(step => !this.savedValues.has(step))) throw new JournalRefusal('Saved before-send intent lacks ACK; stop and reconcile before retry'); } catch (error) { this.close(); throw error; } } apply(record) { if (record[0] === 'I') { if (record.length !== 6) throw new JournalRefusal('Invalid intent shape'); const [, step, method, path, requestFingerprint, key] = record; if (!/^[a-z][a-z0-9_-]*$/.test(step) || this.intents.has(step) || !this.allowed.has(step) || !same(this.allowed.get(step), [method, path]) || !/^[0-9A-F]{64}$/.test(requestFingerprint) || [...this.intents.keys()].some(name => !this.savedValues.has(name))) throw new JournalRefusal('Invalid, future or repeated intent'); if ((method === 'POST' && !/^[0-9a-f]{32}$/.test(key)) || (method !== 'POST' && key !== '')) throw new JournalRefusal('Invalid persisted action key'); this.intents.set(step, { method, path, request_fingerprint: requestFingerprint, idempotency_key: key }); } else if (record[0] === 'A') { const [, step, count, ...pairs] = record; if (record.length < 3 || !/^(0|[1-9][0-9]*)$/.test(count) || BigInt(pairs.length) !== 2n * BigInt(count) || !this.intents.has(step) || this.savedValues.has(step)) throw new JournalRefusal('ACK without exactly one prior intent'); const names = pairs.filter((_, index) => index % 2 === 0); if (!same(names, [...new Set(names)].sort()) || names.some(name => !/^[a-z][a-z0-9_]*$/.test(name) || ['api_key', 'exhibitday_api_key'].includes(name))) throw new JournalRefusal('ACK fields must be unique sorted secret-free identifiers'); this.savedValues.set(step, Object.fromEntries(names.map((name, index) => [name, pairs[index * 2 + 1]]))); } else throw new JournalRefusal('Unknown journal transition'); } requireActive() { if (!this.owned || this.fd === null || this.identity === null || this.tainted) throw new JournalRefusal('Journal is closed or its IO outcome needs reconciliation'); const current = fs.lstatSync(this.lock, { bigint: true }); if (current.dev !== this.identity.dev || current.ino !== this.identity.ino || ascii(fs.readFileSync(this.lock)) !== this.owner) throw new JournalRefusal('Journal lock was replaced; stop without deleting it'); } append(record) { this.requireActive(); const raw = frame(record); let target; try { target = fs.openSync(this.path, 'a'); writeAll(target, raw); fs.fsyncSync(target); } catch (error) { this.tainted = true; throw error; } finally { if (target !== undefined) fs.closeSync(target); } } acknowledged(step) { this.requireActive(); return this.savedValues.has(step); } saved(step) { this.requireActive(); if (!this.savedValues.has(step)) throw new JournalRefusal('No acknowledged state exists'); return { ...this.savedValues.get(step) }; } begin(step, method, path, requestFingerprint) { this.requireActive(); if (this.intents.has(step)) throw new JournalRefusal('Never blindly repeat an existing action'); const key = method === 'POST' ? crypto.randomBytes(16).toString('hex') : '', record = ['I', step, method, path, requestFingerprint, key]; const old = new Map(this.intents); try { this.apply(record); } finally { this.intents = old; } this.append(record); this.apply(record); return { ...this.intents.get(step) }; } acknowledge(step, saved) { this.requireActive(); const names = Object.keys(saved).sort(), record = ['A', step, String(names.length)]; for (const name of names) record.push(name, saved[name]); const old = new Map(this.savedValues); try { this.apply(record); strings(record); } finally { this.savedValues = old; } this.append(record); this.apply(record); } close() { if (!this.owned) return; if (this.tainted) { fs.closeSync(this.fd); this.fd = null; this.owned = false; return; } try { this.requireActive(); } catch (error) { fs.closeSync(this.fd); this.fd = null; this.owned = false; throw error; } fs.closeSync(this.fd); this.fd = null; this.owned = false; fs.unlinkSync(this.lock); } } function journal_values(value) { if (!value || typeof value !== 'object' || Array.isArray(value) || Object.values(value).some(item=>typeof item!=='string')) throw new JournalRefusal('Saved/fingerprint values must be exact strings'); return {...value}; } function journal_acknowledge(job,step,saved) { job.acknowledge(step,journal_values(saved)); } function journal_acknowledged(job,step) { return job.acknowledged(step); } function journal_begin(job,step,method,path,requestFingerprint) { return job.begin(step,method,path,requestFingerprint); } function journal_fingerprint(value) { return fingerprint(journal_values(value)); } function journal_saved(job,step) { return job.saved(step); } function not_value(value) { if (typeof value !== "boolean") throw new Error("Expected a Boolean"); return !value; } function open_journal(path,base,workspace,slug,job,inputFingerprint,writes,mode) { return new Journal(path,base,workspace,slug,job,inputFingerprint,writes,mode); } function optional(name, fallback) { const value = process.env[name]; return value === undefined || value === "" ? fallback : value; } function positive_id(value) { if (!/^[1-9][0-9]*$/.test(value) || BigInt(value) > 9223372036854775807n) throw new Error("Use a positive record ID"); return value; } function print_value(value) { console.log(typeof value === "string" ? value : JSON.stringify(value)); } function require_condition(value, message) { if (value !== true) throw new Error(message); } function required(name) { const value = process.env[name]; if (value === undefined || !value.trim()) throw new Error("Set " + name); return value; } function response_status(value) { return String(value.status); } function text(value) { if (value === null || value === undefined) return ""; if (["string", "boolean", "bigint"].includes(typeof value)) return String(value); throw new Error("Expected a scalar response value"); } async function main() { let inventory_asset_id = positive_id(required("EXHIBITDAY_ASSET_ID")); let inventory_location_id = positive_id(required("EXHIBITDAY_STORAGE_LOCATION_ID")); let inventory_journal_path = required("EXHIBITDAY_JOURNAL"); let inventory_job_id = required("EXHIBITDAY_JOB_ID"); let inventory_job_mode = optional("EXHIBITDAY_JOB_MODE", "resume"); require_condition(either(equal(inventory_job_mode, "new"), equal(inventory_job_mode, "resume")), "Use exact new or resume for EXHIBITDAY_JOB_MODE."); let inventory_received = bounded_whole_number(required("EXHIBITDAY_RECEIVED_QUANTITY"), "EXHIBITDAY_RECEIVED_QUANTITY", "2147483647"); require_condition(not_value(equal(inventory_received, "0")), "EXHIBITDAY_RECEIVED_QUANTITY must be greater than zero."); let inventory_recount = optional("EXHIBITDAY_RECOUNT_QUANTITY", ""); let inventory_expected = inventory_received; if (not_value(equal(inventory_recount, ""))) { inventory_recount = bounded_whole_number(inventory_recount, "EXHIBITDAY_RECOUNT_QUANTITY", "2147483647"); require_condition(not_value(equal(inventory_recount, "0")), "EXHIBITDAY_RECOUNT_QUANTITY must be greater than zero."); inventory_expected = inventory_recount; } let inventory_workspace_response = await call("workspace_binding", {}, null, null); require_condition(equal(response_status(inventory_workspace_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); let inventory_workspace = inventory_workspace_response.body; let inventory_workspace_id = positive_id(text(field(inventory_workspace, "id"))); let inventory_input_fingerprint = journal_fingerprint({"workflow_contract_sha256": "F9CCD36E69D6E5A76E22B460D9FB853A89937E942238AAD7DF5A63BE8EA9F49D", "asset_id": inventory_asset_id, "storage_location_id": inventory_location_id, "create_quantity": inventory_received, "correct_quantity": inventory_recount}); let inventory_job = open_journal(inventory_journal_path, "https://api.exhibitday.com/v1", inventory_workspace_id, "collateral-inventory-storage", inventory_job_id, inventory_input_fingerprint, [["create_adjustment", "POST", "/v1/assets/inventory_adjustments"], ["correct_count", "PATCH", "/v1/assets/inventory_adjustments"]], inventory_job_mode); try { require_condition(either(not_value(journal_acknowledged(inventory_job, "correct_count")), journal_acknowledged(inventory_job, "create_adjustment")), "A correction is acknowledged before its create. Stop and reconcile the journal."); require_condition(either(not_value(journal_acknowledged(inventory_job, "correct_count")), not_value(equal(inventory_recount, ""))), "This journal records a correction without a recount quantity. Stop and reconcile."); let inventory_adjustment_id = ""; if (journal_acknowledged(inventory_job, "create_adjustment")) { let inventory_created_saved = journal_saved(inventory_job, "create_adjustment"); inventory_adjustment_id = positive_id(text(field(inventory_created_saved, "id"))); require_condition(both(equal(text(field(inventory_created_saved, "asset_id")), inventory_asset_id), equal(text(field(inventory_created_saved, "storage_location_id")), inventory_location_id)), "The saved adjustment belongs to different inventory or storage; do not create a replacement."); } else { let inventory_create_fingerprint = journal_fingerprint({"asset_id": inventory_asset_id, "storage_location_id": inventory_location_id, "quantity": inventory_received, "is_increase": "true", "description": "Brochures received for Annual Expo"}); let inventory_create_intent = journal_begin(inventory_job, "create_adjustment", "POST", "/v1/assets/inventory_adjustments", inventory_create_fingerprint); let inventory_create_response = await call("create_adjustment", {}, {"asset_id": inventory_asset_id, "storage_location_id": inventory_location_id, "quantity": inventory_received, "is_increase": true, "description": "Brochures received for Annual Expo"}, text(field(inventory_create_intent, "idempotency_key"))); require_condition(equal(response_status(inventory_create_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); let inventory_created = inventory_create_response.body; inventory_adjustment_id = positive_id(text(field(inventory_created, "id"))); require_condition(both(both(equal(text(field(inventory_created, "id")), inventory_adjustment_id), equal(text(field(inventory_created, "asset_id")), inventory_asset_id)), both(equal(text(field(inventory_created, "storage_location_id")), inventory_location_id), both(both(equal(text(field(inventory_created, "quantity_adjustment")), inventory_received), equal(text(field(inventory_created, "quantity")), inventory_received)), equal(field(inventory_created, "is_increase"), true)))), "The create acknowledgement differs from this item, location or stock increase. Keep pending state and reconcile."); journal_acknowledge(inventory_job, "create_adjustment", {"id": inventory_adjustment_id, "asset_id": inventory_asset_id, "storage_location_id": inventory_location_id}); } if (not_value(equal(inventory_recount, ""))) { let inventory_read_response = await call("read_adjustment", {"id": inventory_adjustment_id, "$include_record_revision": "true"}, null, null); require_condition(equal(response_status(inventory_read_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); let inventory_current = inventory_read_response.body; if (journal_acknowledged(inventory_job, "correct_count")) { let inventory_corrected_saved = journal_saved(inventory_job, "correct_count"); require_condition(both(equal(text(field(inventory_corrected_saved, "id")), inventory_adjustment_id), both(equal(text(field(inventory_corrected_saved, "asset_id")), inventory_asset_id), both(equal(text(field(inventory_corrected_saved, "storage_location_id")), inventory_location_id), equal(text(field(inventory_corrected_saved, "quantity")), inventory_recount)))), "The acknowledged correction differs from this record or quantity; stop and reconcile."); require_condition(both(both(equal(text(field(inventory_current, "id")), inventory_adjustment_id), equal(text(field(inventory_current, "asset_id")), inventory_asset_id)), both(equal(text(field(inventory_current, "storage_location_id")), inventory_location_id), both(both(equal(text(field(inventory_current, "quantity_adjustment")), inventory_recount), equal(text(field(inventory_current, "quantity")), inventory_recount)), equal(field(inventory_current, "is_increase"), true)))), "The acknowledged adjustment is now missing, rebound or changed; do not silently restore it."); } else { require_condition(both(both(equal(text(field(inventory_current, "id")), inventory_adjustment_id), equal(text(field(inventory_current, "asset_id")), inventory_asset_id)), both(equal(text(field(inventory_current, "storage_location_id")), inventory_location_id), both(both(equal(text(field(inventory_current, "quantity_adjustment")), inventory_received), equal(text(field(inventory_current, "quantity")), inventory_received)), equal(field(inventory_current, "is_increase"), true)))), "The saved adjustment is no longer the expected stock increase. Review it before any correction."); let inventory_revision = text(field(inventory_current, "record_revision")); require_condition(is_present(inventory_revision), "The inventory read must return its actual record_revision before correction."); let inventory_patch = {"id": inventory_adjustment_id, "quantity": inventory_recount, "expected_revision": inventory_revision}; let inventory_patch_fingerprint = journal_fingerprint({"id": inventory_adjustment_id, "quantity": inventory_recount, "expected_revision": inventory_revision}); journal_begin(inventory_job, "correct_count", "PATCH", "/v1/assets/inventory_adjustments", inventory_patch_fingerprint); let inventory_patch_response = await call("correct_count", {}, inventory_patch, null); require_condition(equal(response_status(inventory_patch_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); let inventory_patch_receipt = inventory_patch_response.body; let inventory_after_revision = text(field(inventory_patch_receipt, "record_revision")); require_condition(is_present(inventory_after_revision), "A checked correction acknowledgement requires its returned record_revision."); journal_acknowledge(inventory_job, "correct_count", {"id": inventory_adjustment_id, "asset_id": inventory_asset_id, "storage_location_id": inventory_location_id, "quantity": inventory_recount, "record_revision": inventory_after_revision}); } } let inventory_verify_response = await call("verify_adjustment", {"id": inventory_adjustment_id}, null, null); require_condition(equal(response_status(inventory_verify_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); let inventory_verified = inventory_verify_response.body; require_condition(both(both(equal(text(field(inventory_verified, "id")), inventory_adjustment_id), equal(text(field(inventory_verified, "asset_id")), inventory_asset_id)), both(equal(text(field(inventory_verified, "storage_location_id")), inventory_location_id), both(both(equal(text(field(inventory_verified, "quantity_adjustment")), inventory_expected), equal(text(field(inventory_verified, "quantity")), inventory_expected)), equal(field(inventory_verified, "is_increase"), true)))), "The final adjustment does not match the acknowledged record, location and stock increase. Reconcile; do not add another adjustment or undo it automatically."); print_value({"id": inventory_adjustment_id, "asset_id": inventory_asset_id, "storage_location_id": inventory_location_id, "quantity": inventory_expected}); } finally { inventory_job.close(); } } if (require.main === module) main().catch(error => { console.error(error.message); process.exitCode = 1; }); module.exports = { main }; ``` ```python # 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_adjustment\":{\"method\":\"POST\",\"path\":\"/assets/inventory_adjustments\"},\"read_adjustment\":{\"method\":\"GET\",\"path\":\"/assets/inventory_adjustments/info\"},\"correct_count\":{\"method\":\"PATCH\",\"path\":\"/assets/inventory_adjustments\"},\"verify_adjustment\":{\"method\":\"GET\",\"path\":\"/assets/inventory_adjustments/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) 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, key=None): route = SPEC["requests"][name] headers = {"Authorization": "Bearer " + API_KEY, "Accept": "application/json"} if route["method"] == "POST": if not key: raise RuntimeError("Persist a logical create key before sending POST") headers["Idempotency-Key"] = key data = None if body is None else json.dumps(body).encode("utf-8") if data is not None: headers["Content-Type"] = "application/json" query = urllib.parse.urlencode(params or {}) url = BASE + route["path"] + ("?" + query if query else "") # Only GET has automatic retries in this workflow. A PATCH or DELETE that got no response or a # server error is never resent blindly: it may already have been applied, so the caller reads the record first. resend = route["method"] == "GET" for attempt in range(5): try: status, raw, response_headers = transport(route["method"], url, headers, data) except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException): if not resend: raise ApiError(0, None, uncertain=True) if attempt == 4: raise time.sleep(2 ** attempt) continue response_headers = {k.lower(): v for k, v in response_headers.items()} result = None if status != 304 and raw: try: result = decode_json(raw.decode("utf-8")) except (ValueError, UnicodeError): if status < 400: raise RuntimeError("Expected a JSON success response") if status >= 500 and not resend: raise ApiError(status, result, uncertain=True) retry = resend and (status == 429 or status >= 500) if retry: if attempt == 4: raise RuntimeError("Retry limit reached; check the request outcome before starting a new create") delay = response_headers.get("retry-after", str(2 ** attempt)) time.sleep(max(0, float(delay))) continue if status >= 400: raise ApiError(status, result) return {"status": status, "body": result, "headers": response_headers, "raw": raw} raise RuntimeError("Retry limit reached") def both(left,right): return left and right def bounded_whole_number(value, name, maximum): if not re.fullmatch(r"0|[1-9][0-9]*", value) or len(value)>len(maximum) or (len(value)==len(maximum) and value>maximum): raise RuntimeError(name+" must be a whole number from 0 through "+maximum) return value 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] 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 offsetlen(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)-offset:raise JournalRefusal('Incomplete journal frame; reconcile before retry') payload=raw[offset:offset+size];offset+=size if raw[offset:offset+1]!=b'\n' or digest(payload).encode('ascii')!=match[2]:raise JournalRefusal('Journal integrity check failed; reconcile before retry') records.append(read_strings(payload));offset+=1 return records class Journal: def __init__(self,path,base,workspace,slug,job,input_fingerprint,writes,mode="resume"): self.path=Path(path);self.lock=Path(str(self.path)+'.lock');self.fd=None;self.owned=False;self.identity=None;self.tainted=False;self.intents={};self.saved_values={} address=urlsplit(base) if address.scheme not in ('https','http')or not address.netloc or address.username is not None or address.query or address.fragment or not re.fullmatch('[a-z][a-z0-9-]*',slug):raise JournalRefusal('Use the actual API base and closed guide slug') if not job.strip() or not re.fullmatch('[1-9][0-9]*',workspace) or not re.fullmatch('[0-9A-F]{64}',input_fingerprint):raise JournalRefusal('Use an actual workspace, explicit stable job ID and exact input fingerprint') if mode not in ("new","resume"):raise JournalRefusal("Choose new or resume for this local job") self.allowed={};manifest=[] for step,method,route in writes: if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.allowed or method not in ('POST','PATCH','DELETE')or not re.fullmatch('/v1/[A-Za-z0-9_/-]+',route)or'//'in route:raise JournalRefusal('Use a closed unique write manifest') self.allowed[step]=(method,route);manifest.extend((step,method,route)) if not self.allowed:raise JournalRefusal('Only write workflows need a restart journal') self.header=['H','1',base,workspace,slug,job,input_fingerprint,digest(strings(manifest))] strings(self.header) try: self.fd=os.open(self.lock,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600);self.owned=True except FileExistsError:raise JournalRefusal('This journal is locked; do not run overlapping jobs or steal a stale lock') try: self.owner=secrets.token_hex(16);self.identity=os.fstat(self.fd) if os.write(self.fd,self.owner.encode('ascii'))!=len(self.owner):raise OSError('Incomplete lock identity write') os.fsync(self.fd) if self.path.is_symlink():raise JournalRefusal('Choose a private regular journal file') if mode=="resume" and not self.path.exists():raise JournalRefusal("Journal missing: stop and reconcile lost state before starting a new logical job") if mode=="new" and self.path.exists():raise JournalRefusal("A journal already exists; use resume for the same logical job") if mode=="new": with open(self.path,'xb',buffering=0)as target: target.write(PREAMBLE+frame(self.header));os.fsync(target.fileno()) records=decode(self.path.read_bytes()) if not records or records[0]!=self.header:raise JournalRefusal('Journal workspace/base/guide/job/input binding differs') for record in records[1:]:self.apply(record) if any(step not in self.saved_values for step in self.intents):raise JournalRefusal('A saved before-send intent lacks an ACK; stop and reconcile its outcome before retry') except BaseException: self.close();raise def apply(self,record): if not record:raise JournalRefusal('Empty journal record') if record[0]=='I': if len(record)!=6:raise JournalRefusal('Invalid intent shape') _,step,method,path,request_fingerprint,key=record if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.intents or self.allowed.get(step)!=(method,path)or not re.fullmatch('[0-9A-F]{64}',request_fingerprint)or any(name not in self.saved_values for name in self.intents):raise JournalRefusal('Invalid, future or repeated journal intent') if method=='POST'and not re.fullmatch('[0-9a-f]{32}',key)or method!='POST'and key!='':raise JournalRefusal('Invalid persisted action key') self.intents[step]={'method':method,'path':path,'request_fingerprint':request_fingerprint,'idempotency_key':key} elif record[0]=='A': if len(record)<3:raise JournalRefusal('Invalid ACK shape') _,step,count,*pairs=record if not re.fullmatch('0|[1-9][0-9]*',count)or len(pairs)!=2*int(count)or step not in self.intents or step in self.saved_values:raise JournalRefusal('ACK without exactly one prior intent') names=pairs[::2] if names!=sorted(set(names))or any(not re.fullmatch('[a-z][a-z0-9_]*',name)or name in ('api_key','exhibitday_api_key')for name in names):raise JournalRefusal('ACK saved fields must be unique sorted secret-free identifiers') self.saved_values[step]=dict(zip(names,pairs[1::2])) else:raise JournalRefusal('Unknown journal transition') def append(self,record): # The reader commits state only after complete length/digest recognition. # A torn append is retained and refused, never silently truncated. self.require_active();raw=frame(record) try: with open(self.path,'ab',buffering=0)as target: view=memoryview(raw) while view: written=target.write(view) if not written:raise OSError('Journal write did not advance') view=view[written:] os.fsync(target.fileno()) except BaseException: self.tainted=True;raise def require_active(self): if not self.owned or self.fd is None or self.identity is None or self.tainted:raise JournalRefusal('The journal scope is closed or its IO outcome needs reconciliation') current=self.lock.stat(follow_symlinks=False) if current.st_dev!=self.identity.st_dev or current.st_ino!=self.identity.st_ino or self.lock.read_text(encoding='ascii')!=self.owner:raise JournalRefusal('The journal lock was replaced; stop without deleting it') def acknowledged(self,step): self.require_active();return step in self.saved_values def saved(self,step): self.require_active() if step not in self.saved_values:raise JournalRefusal('No acknowledged state exists for this step') return dict(self.saved_values[step]) def begin(self,step,method,path,request_fingerprint): self.require_active() if step in self.intents:raise JournalRefusal('Never blindly repeat an existing action intent') key=secrets.token_hex(16)if method=='POST'else'' record=['I',step,method,path,request_fingerprint,key] # Validate on an isolated state before touching the file. old=dict(self.intents) try:self.apply(record) finally:self.intents=old self.append(record);self.apply(record) return dict(self.intents[step]) def acknowledge(self,step,saved): self.require_active() record=['A',step,str(len(saved))] for name,value in sorted(saved.items()):record.extend((name,value)) old={name:dict(value)for name,value in self.saved_values.items()} try:self.apply(record);strings(record) finally:self.saved_values=old self.append(record);self.apply(record) def close(self): if self.owned: if self.tainted: os.close(self.fd);self.fd=None;self.owned=False return # Retain this lock after failed journal IO; manual reconciliation is required. try:self.require_active() except BaseException: os.close(self.fd);self.fd=None;self.owned=False;raise os.close(self.fd);self.fd=None;self.owned=False self.lock.unlink() def __enter__(self):return self def __exit__(self,*args):self.close() def journal_values(value): if not isinstance(value, dict) or any(not isinstance(k, str) or not isinstance(v, str) for k,v in value.items()): raise JournalRefusal('Saved/fingerprint values must be exact string fields') return dict(value) def journal_acknowledge(job, step, saved): job.acknowledge(step,journal_values(saved)) def journal_acknowledged(job, step): return job.acknowledged(step) def journal_begin(job, step, method, path, request_fingerprint): return job.begin(step,method,path,request_fingerprint) def journal_fingerprint(value): return fingerprint(journal_values(value)) def journal_saved(job, step): return job.saved(step) def 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 positive_id(value): if not re.fullmatch(r"[1-9][0-9]*", value) or int(value) > 9223372036854775807: raise RuntimeError("Use a positive record ID") return value def print_value(value): print(value if isinstance(value, str) else json.dumps(value, ensure_ascii=False)) def require_condition(value, message): if value is not True: raise RuntimeError(message) def required(name): value = os.environ.get(name) if value is None or not value.strip(): raise RuntimeError("Set " + name) return value def response_status(value): return str(value["status"]) def 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(): inventory_asset_id = positive_id(required("EXHIBITDAY_ASSET_ID")) inventory_location_id = positive_id(required("EXHIBITDAY_STORAGE_LOCATION_ID")) inventory_journal_path = required("EXHIBITDAY_JOURNAL") inventory_job_id = required("EXHIBITDAY_JOB_ID") inventory_job_mode = optional("EXHIBITDAY_JOB_MODE", "resume") require_condition(either(equal(inventory_job_mode, "new"), equal(inventory_job_mode, "resume")), "Use exact new or resume for EXHIBITDAY_JOB_MODE.") inventory_received = bounded_whole_number(required("EXHIBITDAY_RECEIVED_QUANTITY"), "EXHIBITDAY_RECEIVED_QUANTITY", "2147483647") require_condition(not_value(equal(inventory_received, "0")), "EXHIBITDAY_RECEIVED_QUANTITY must be greater than zero.") inventory_recount = optional("EXHIBITDAY_RECOUNT_QUANTITY", "") inventory_expected = inventory_received if not_value(equal(inventory_recount, "")): inventory_recount = bounded_whole_number(inventory_recount, "EXHIBITDAY_RECOUNT_QUANTITY", "2147483647") require_condition(not_value(equal(inventory_recount, "0")), "EXHIBITDAY_RECOUNT_QUANTITY must be greater than zero.") inventory_expected = inventory_recount inventory_workspace_response = call("workspace_binding", {}, None, None) require_condition(equal(response_status(inventory_workspace_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") inventory_workspace = inventory_workspace_response["body"] inventory_workspace_id = positive_id(text(field(inventory_workspace, "id"))) inventory_input_fingerprint = journal_fingerprint({"workflow_contract_sha256": "F9CCD36E69D6E5A76E22B460D9FB853A89937E942238AAD7DF5A63BE8EA9F49D", "asset_id": inventory_asset_id, "storage_location_id": inventory_location_id, "create_quantity": inventory_received, "correct_quantity": inventory_recount}) inventory_job = open_journal(inventory_journal_path, "https://api.exhibitday.com/v1", inventory_workspace_id, "collateral-inventory-storage", inventory_job_id, inventory_input_fingerprint, [["create_adjustment", "POST", "/v1/assets/inventory_adjustments"], ["correct_count", "PATCH", "/v1/assets/inventory_adjustments"]], inventory_job_mode) try: require_condition(either(not_value(journal_acknowledged(inventory_job, "correct_count")), journal_acknowledged(inventory_job, "create_adjustment")), "A correction is acknowledged before its create. Stop and reconcile the journal.") require_condition(either(not_value(journal_acknowledged(inventory_job, "correct_count")), not_value(equal(inventory_recount, ""))), "This journal records a correction without a recount quantity. Stop and reconcile.") inventory_adjustment_id = "" if journal_acknowledged(inventory_job, "create_adjustment"): inventory_created_saved = journal_saved(inventory_job, "create_adjustment") inventory_adjustment_id = positive_id(text(field(inventory_created_saved, "id"))) require_condition(both(equal(text(field(inventory_created_saved, "asset_id")), inventory_asset_id), equal(text(field(inventory_created_saved, "storage_location_id")), inventory_location_id)), "The saved adjustment belongs to different inventory or storage; do not create a replacement.") else: inventory_create_fingerprint = journal_fingerprint({"asset_id": inventory_asset_id, "storage_location_id": inventory_location_id, "quantity": inventory_received, "is_increase": "true", "description": "Brochures received for Annual Expo"}) inventory_create_intent = journal_begin(inventory_job, "create_adjustment", "POST", "/v1/assets/inventory_adjustments", inventory_create_fingerprint) inventory_create_response = call("create_adjustment", {}, {"asset_id": inventory_asset_id, "storage_location_id": inventory_location_id, "quantity": inventory_received, "is_increase": True, "description": "Brochures received for Annual Expo"}, text(field(inventory_create_intent, "idempotency_key"))) require_condition(equal(response_status(inventory_create_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") inventory_created = inventory_create_response["body"] inventory_adjustment_id = positive_id(text(field(inventory_created, "id"))) require_condition(both(both(equal(text(field(inventory_created, "id")), inventory_adjustment_id), equal(text(field(inventory_created, "asset_id")), inventory_asset_id)), both(equal(text(field(inventory_created, "storage_location_id")), inventory_location_id), both(both(equal(text(field(inventory_created, "quantity_adjustment")), inventory_received), equal(text(field(inventory_created, "quantity")), inventory_received)), equal(field(inventory_created, "is_increase"), True)))), "The create acknowledgement differs from this item, location or stock increase. Keep pending state and reconcile.") journal_acknowledge(inventory_job, "create_adjustment", {"id": inventory_adjustment_id, "asset_id": inventory_asset_id, "storage_location_id": inventory_location_id}) if not_value(equal(inventory_recount, "")): inventory_read_response = call("read_adjustment", {"id": inventory_adjustment_id, "$include_record_revision": "true"}, None, None) require_condition(equal(response_status(inventory_read_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") inventory_current = inventory_read_response["body"] if journal_acknowledged(inventory_job, "correct_count"): inventory_corrected_saved = journal_saved(inventory_job, "correct_count") require_condition(both(equal(text(field(inventory_corrected_saved, "id")), inventory_adjustment_id), both(equal(text(field(inventory_corrected_saved, "asset_id")), inventory_asset_id), both(equal(text(field(inventory_corrected_saved, "storage_location_id")), inventory_location_id), equal(text(field(inventory_corrected_saved, "quantity")), inventory_recount)))), "The acknowledged correction differs from this record or quantity; stop and reconcile.") require_condition(both(both(equal(text(field(inventory_current, "id")), inventory_adjustment_id), equal(text(field(inventory_current, "asset_id")), inventory_asset_id)), both(equal(text(field(inventory_current, "storage_location_id")), inventory_location_id), both(both(equal(text(field(inventory_current, "quantity_adjustment")), inventory_recount), equal(text(field(inventory_current, "quantity")), inventory_recount)), equal(field(inventory_current, "is_increase"), True)))), "The acknowledged adjustment is now missing, rebound or changed; do not silently restore it.") else: require_condition(both(both(equal(text(field(inventory_current, "id")), inventory_adjustment_id), equal(text(field(inventory_current, "asset_id")), inventory_asset_id)), both(equal(text(field(inventory_current, "storage_location_id")), inventory_location_id), both(both(equal(text(field(inventory_current, "quantity_adjustment")), inventory_received), equal(text(field(inventory_current, "quantity")), inventory_received)), equal(field(inventory_current, "is_increase"), True)))), "The saved adjustment is no longer the expected stock increase. Review it before any correction.") inventory_revision = text(field(inventory_current, "record_revision")) require_condition(is_present(inventory_revision), "The inventory read must return its actual record_revision before correction.") inventory_patch = {"id": inventory_adjustment_id, "quantity": inventory_recount, "expected_revision": inventory_revision} inventory_patch_fingerprint = journal_fingerprint({"id": inventory_adjustment_id, "quantity": inventory_recount, "expected_revision": inventory_revision}) journal_begin(inventory_job, "correct_count", "PATCH", "/v1/assets/inventory_adjustments", inventory_patch_fingerprint) inventory_patch_response = call("correct_count", {}, inventory_patch, None) require_condition(equal(response_status(inventory_patch_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") inventory_patch_receipt = inventory_patch_response["body"] inventory_after_revision = text(field(inventory_patch_receipt, "record_revision")) require_condition(is_present(inventory_after_revision), "A checked correction acknowledgement requires its returned record_revision.") journal_acknowledge(inventory_job, "correct_count", {"id": inventory_adjustment_id, "asset_id": inventory_asset_id, "storage_location_id": inventory_location_id, "quantity": inventory_recount, "record_revision": inventory_after_revision}) inventory_verify_response = call("verify_adjustment", {"id": inventory_adjustment_id}, None, None) require_condition(equal(response_status(inventory_verify_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") inventory_verified = inventory_verify_response["body"] require_condition(both(both(equal(text(field(inventory_verified, "id")), inventory_adjustment_id), equal(text(field(inventory_verified, "asset_id")), inventory_asset_id)), both(equal(text(field(inventory_verified, "storage_location_id")), inventory_location_id), both(both(equal(text(field(inventory_verified, "quantity_adjustment")), inventory_expected), equal(text(field(inventory_verified, "quantity")), inventory_expected)), equal(field(inventory_verified, "is_increase"), True)))), "The final adjustment does not match the acknowledged record, location and stock increase. Reconcile; do not add another adjustment or undo it automatically.") print_value({"id": inventory_adjustment_id, "asset_id": inventory_asset_id, "storage_location_id": inventory_location_id, "quantity": inventory_expected}) finally: inventory_job.close() if __name__ == "__main__": main() ``` ```csharp // .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\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"create_adjustment\":{\"method\":\"POST\",\"path\":\"/assets/inventory_adjustments\"},\"read_adjustment\":{\"method\":\"GET\",\"path\":\"/assets/inventory_adjustments/info\"},\"correct_count\":{\"method\":\"PATCH\",\"path\":\"/assets/inventory_adjustments\"},\"verify_adjustment\":{\"method\":\"GET\",\"path\":\"/assets/inventory_adjustments/info\"}}}"); static readonly string ApiKey = HeaderKey(Required("EXHIBITDAY_API_KEY")); static string HeaderKey(string value) { if(value.Any(c=>c<32||c>126))throw new Exception("Use the API key as one ASCII header value without control characters");return value; } static readonly HttpClient Client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false }) { Timeout = TimeSpan.FromSeconds(30) }; internal static Func> Send = request => Client.SendAsync(request); sealed class Result { public int Status; public JsonNode Body; public Dictionary Headers; public string Raw; } // 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(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 Call(string name, JsonObject query = null, JsonNode body = null, string key = null) { var route = Spec["requests"][name]; var method = Text(route["method"]); var headers = new Dictionary(StringComparer.OrdinalIgnoreCase) { ["Authorization"] = "Bearer " + ApiKey, ["Accept"] = "application/json" }; if (method == "POST") { if (string.IsNullOrEmpty(key)) throw new Exception("Persist a logical create key before sending POST"); headers["Idempotency-Key"] = key; } 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); // 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. var resend = method == "GET"; 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 Send(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 = resend && (status == 429 || status >= 500); 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, Raw = raw }; } } throw new Exception("Retry limit reached"); } static bool Both(bool left,bool right)=>left&&right; static string BoundedWholeNumber(string value,string name,string maximum) { if(string.IsNullOrEmpty(value)||(value.Length>1&&value[0]=='0')||!value.All(c=>c>='0'&&c<='9')||value.Length>maximum.Length||(value.Length==maximum.Length&&string.CompareOrdinal(value,maximum)>0))throw new Exception(name+" must be a whole number from 0 through "+maximum);return value; } static bool Either(bool left,bool right) => left || right; static object Scalar(object value) { if(value is JsonValue json){if(json.TryGetValue(out var boolean))return boolean;if(json.TryGetValue(out var text))return text;return json.ToJsonString();}return value; } static bool Equal(object left,object right) => object.Equals(Scalar(left),Scalar(right)); static JsonNode Field(JsonNode value,string name) { if(value is not JsonObject obj || !obj.TryGetPropertyValue(name,out var item))throw new Exception("Missing response field: "+name);return item; } static bool IsPresent(string value) => value!=null && value!=""; public sealed class JournalRefusal : Exception { public JournalRefusal(string message) : base(message) {} } public static class JournalProtocol { public static readonly byte[] Preamble = Encoding.ASCII.GetBytes("EXHIBITDAY-GUIDE-JOURNAL 1\n"); static readonly UTF8Encoding Utf8 = new UTF8Encoding(false, true); static bool Match(string value,string pattern) => value != null && System.Text.RegularExpressions.Regex.IsMatch(value,"\\A(?:"+pattern+")\\z",System.Text.RegularExpressions.RegexOptions.CultureInvariant); public static bool Valid(string value,string pattern) => Match(value,pattern); static string Ascii(byte[] raw,int start,int count) { for(var i=start;i127)throw new JournalRefusal("Journal framing must be canonical ASCII");return Encoding.ASCII.GetString(raw,start,count); } public static byte[] Strings(IEnumerable values) { using var data=new MemoryStream(); foreach(var value in values){if(value==null)throw new JournalRefusal("Journal fields are exact strings");var item=Utf8.GetBytes(value);var prefix=Encoding.ASCII.GetBytes(item.Length.ToString(CultureInfo.InvariantCulture)+":");data.Write(prefix);data.Write(item);} return data.ToArray(); } public static List ReadStrings(byte[] raw) { var values=new List();var offset=0; while(offsetraw.Length-offset)throw new JournalRefusal("Incomplete journal string");values.Add(Utf8.GetString(raw,offset,(int)size));offset+=(int)size;} return values; } public static string Digest(byte[] raw)=>Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(raw)); public static string Fingerprint(IReadOnlyDictionary pairs) { var values=new List();foreach(var name in pairs.Keys.OrderBy(n=>n,StringComparer.Ordinal)){ if(!Match(name,"[A-Za-z0-9_.-]+")||new[]{"api_key","exhibitday_api_key"}.Contains(name.ToLowerInvariant()))throw new JournalRefusal("Use explicit secret-free fingerprint names");values.Add(name);values.Add(pairs[name]);} return Digest(Strings(values)); } public static byte[] Frame(IEnumerable values) { var payload=Strings(values);var header=Encoding.ASCII.GetBytes(payload.Length.ToString(CultureInfo.InvariantCulture)+" "+Digest(payload)+"\n"); using var data=new MemoryStream();data.Write(header);data.Write(payload);data.WriteByte(10);return data.ToArray(); } public static List> Decode(byte[] raw) { if(raw.Length>(); while(offset=raw.Length-offset)throw new JournalRefusal("Incomplete frame; reconcile before retry");var payload=raw.AsSpan(offset,(int)size).ToArray();offset+=(int)size; if(raw[offset]!=10||Digest(payload)!=split[1])throw new JournalRefusal("Journal integrity failed; reconcile before retry");records.Add(ReadStrings(payload));offset++;} return records; } } public sealed class Journal : IDisposable { readonly string path,lockPath,owner;readonly List header; readonly Dictionary allowed=new Dictionary(StringComparer.Ordinal); Dictionary> intents=new Dictionary>(StringComparer.Ordinal),savedValues=new Dictionary>(StringComparer.Ordinal); FileStream lockStream;bool owned,tainted;DateTime creation; static FileStream CreatePrivate(string target,FileAccess access,FileShare share) { var options=new FileStreamOptions{Mode=FileMode.CreateNew,Access=access,Share=share}; if(!OperatingSystem.IsWindows())options.UnixCreateMode=UnixFileMode.UserRead|UnixFileMode.UserWrite; return new FileStream(target,options); } public Journal(string path,string apiBase,string workspace,string slug,string job,string inputFingerprint,IEnumerable<(string Step,string Method,string Path)> writes,string mode="resume") { this.path=path;lockPath=path+".lock";owner=Convert.ToHexString(System.Security.Cryptography.RandomNumberGenerator.GetBytes(16)).ToLowerInvariant(); if(!Uri.TryCreate(apiBase,UriKind.Absolute,out var address)||address.Scheme!="https"&&address.Scheme!="http"||address.UserInfo.Length!=0||address.Query.Length!=0||address.Fragment.Length!=0||!JournalProtocol.Valid(slug,"[a-z][a-z0-9-]*"))throw new JournalRefusal("Use the actual API base and closed guide slug"); if(string.IsNullOrWhiteSpace(job)||!JournalProtocol.Valid(workspace,"[1-9][0-9]*")||!JournalProtocol.Valid(inputFingerprint,"[0-9A-F]{64}"))throw new JournalRefusal("Use actual workspace, stable explicit job ID and exact fingerprint"); if(mode!="new"&&mode!="resume")throw new JournalRefusal("Choose new or resume for this local job"); var manifest=new List();foreach(var write in writes){ if(!JournalProtocol.Valid(write.Step,"[a-z][a-z0-9_-]*")||allowed.ContainsKey(write.Step)||!new[]{"POST","PATCH","DELETE"}.Contains(write.Method)||!JournalProtocol.Valid(write.Path,"/v1/[A-Za-z0-9_/-]+")||write.Path.Contains("//"))throw new JournalRefusal("Use a closed unique write manifest"); allowed.Add(write.Step,(write.Method,write.Path));manifest.AddRange(new[]{write.Step,write.Method,write.Path});} if(allowed.Count==0)throw new JournalRefusal("Only write workflows need a restart journal"); header=new List{"H","1",apiBase,workspace,slug,job,inputFingerprint,JournalProtocol.Digest(JournalProtocol.Strings(manifest))};JournalProtocol.Strings(header); try{lockStream=CreatePrivate(lockPath,FileAccess.ReadWrite,FileShare.Read);owned=true;} catch(IOException)when(File.Exists(lockPath)){throw new JournalRefusal("This journal is locked; do not overlap jobs or steal a stale lock");} try{ var token=Encoding.ASCII.GetBytes(owner);lockStream.Write(token);lockStream.Flush(true);creation=File.GetCreationTimeUtc(lockPath); if(File.Exists(path)&&(File.GetAttributes(path)&FileAttributes.ReparsePoint)!=0)throw new JournalRefusal("Choose a private regular journal file"); if(mode=="resume"&&!File.Exists(path))throw new JournalRefusal("Journal missing: stop and reconcile lost state before starting a new logical job"); if(mode=="new"&&File.Exists(path))throw new JournalRefusal("Journal exists; use resume for the same logical job"); if(mode=="new"){using var output=CreatePrivate(path,FileAccess.Write,FileShare.None);output.Write(JournalProtocol.Preamble);output.Write(JournalProtocol.Frame(header));output.Flush(true);} var records=JournalProtocol.Decode(File.ReadAllBytes(path));if(records.Count==0||!records[0].SequenceEqual(header))throw new JournalRefusal("Journal workspace/base/guide/job/input binding differs"); foreach(var record in records.Skip(1))Apply(record);if(intents.Keys.Any(step=>!savedValues.ContainsKey(step)))throw new JournalRefusal("Saved intent lacks ACK; stop and reconcile before retry"); }catch{Dispose();throw;} } void Apply(IReadOnlyList record) { if(record.Count==0)throw new JournalRefusal("Empty journal record"); if(record[0]=="I"){ if(record.Count!=6)throw new JournalRefusal("Invalid intent shape");var step=record[1];var method=record[2];var route=record[3];var fingerprint=record[4];var key=record[5]; if(!JournalProtocol.Valid(step,"[a-z][a-z0-9_-]*")||intents.ContainsKey(step)||!allowed.TryGetValue(step,out var expected)||expected!=(method,route)||!JournalProtocol.Valid(fingerprint,"[0-9A-F]{64}")||intents.Keys.Any(name=>!savedValues.ContainsKey(name)))throw new JournalRefusal("Invalid, future or repeated intent"); if(method=="POST"&&!JournalProtocol.Valid(key,"[0-9a-f]{32}")||method!="POST"&&key!="")throw new JournalRefusal("Invalid persisted action key"); intents.Add(step,new Dictionary{{"method",method},{"path",route},{"request_fingerprint",fingerprint},{"idempotency_key",key}}); }else if(record[0]=="A"){ if(record.Count<3||!JournalProtocol.Valid(record[2],"0|[1-9][0-9]*")||!long.TryParse(record[2],NumberStyles.None,CultureInfo.InvariantCulture,out var count)||count!=(record.Count-3L)/2||record.Count%2!=1||!intents.ContainsKey(record[1])||savedValues.ContainsKey(record[1]))throw new JournalRefusal("ACK without exactly one prior intent"); var names=record.Skip(3).Where((_,index)=>index%2==0).ToArray(); if(!names.SequenceEqual(names.Distinct(StringComparer.Ordinal).OrderBy(name=>name,StringComparer.Ordinal))||names.Any(name=>!JournalProtocol.Valid(name,"[a-z][a-z0-9_]*")||name=="api_key"||name=="exhibitday_api_key"))throw new JournalRefusal("ACK fields must be unique sorted secret-free identifiers"); var saved=new Dictionary(StringComparer.Ordinal);for(var i=0;i record) { RequireActive();var raw=JournalProtocol.Frame(record); try{using var output=new FileStream(path,FileMode.Append,FileAccess.Write,FileShare.None);output.Write(raw);output.Flush(true);} catch{tainted=true;throw;} } public bool Acknowledged(string step){RequireActive();return savedValues.ContainsKey(step);} public Dictionary Saved(string step){RequireActive();if(!savedValues.ContainsKey(step))throw new JournalRefusal("No acknowledged state exists");return new Dictionary(savedValues[step],StringComparer.Ordinal);} public Dictionary Begin(string step,string method,string route,string requestFingerprint) { RequireActive();if(intents.ContainsKey(step))throw new JournalRefusal("Never blindly repeat an existing action"); var key=method=="POST"?Convert.ToHexString(System.Security.Cryptography.RandomNumberGenerator.GetBytes(16)).ToLowerInvariant():""; var record=new[]{"I",step,method,route,requestFingerprint,key};var previous=new Dictionary>(intents,StringComparer.Ordinal);try{Apply(record);}finally{intents=previous;} Append(record);Apply(record);return new Dictionary(intents[step],StringComparer.Ordinal); } public void Acknowledge(string step,IReadOnlyDictionary saved) { RequireActive();var record=new List{"A",step,saved.Count.ToString(CultureInfo.InvariantCulture)};foreach(var name in saved.Keys.OrderBy(name=>name,StringComparer.Ordinal))record.AddRange(new[]{name,saved[name]}); var previous=new Dictionary>(savedValues,StringComparer.Ordinal);try{Apply(record);JournalProtocol.Strings(record);}finally{savedValues=previous;} Append(record);Apply(record); } public void Dispose() { if(!owned)return;if(tainted){lockStream.Dispose();lockStream=null;owned=false;return;} try{RequireActive();}catch{lockStream.Dispose();lockStream=null;owned=false;throw;} lockStream.Dispose();lockStream=null;owned=false;File.Delete(lockPath); } } static Dictionary JournalValues(JsonNode value) { if(value is not JsonObject fields)throw new JournalRefusal("Saved/fingerprint values need an explicit object"); var result=new Dictionary(StringComparer.Ordinal); foreach(var field in fields){if(field.Value is not JsonValue item || !item.TryGetValue(out var text) || text==null)throw new JournalRefusal("Saved/fingerprint values must be exact strings");result.Add(field.Key,text);}return result; } static JsonObject JournalObject(IReadOnlyDictionary fields){var result=new JsonObject();foreach(var field in fields)result.Add(field.Key,JsonValue.Create(field.Value));return result;} static void JournalAcknowledge(Journal job,string step,JsonNode saved)=>job.Acknowledge(step,JournalValues(saved)); static bool JournalAcknowledged(Journal job,string step)=>job.Acknowledged(step); static JsonNode JournalBegin(Journal job,string step,string method,string path,string requestFingerprint)=>JournalObject(job.Begin(step,method,path,requestFingerprint)); static string JournalFingerprint(JsonNode value)=>JournalProtocol.Fingerprint(JournalValues(value)); static JsonNode JournalSaved(Journal job,string step)=>JournalObject(job.Saved(step)); static bool NotValue(bool value) => !value; static Journal OpenJournal(string path,string apiBase,string workspace,string slug,string job,string inputFingerprint,JsonNode manifest,string mode) { if(manifest is not JsonArray rows)throw new JournalRefusal("A closed write manifest is required");var writes=new List<(string,string,string)>(); foreach(var row in rows){if(row is not JsonArray fields || fields.Count!=3)throw new JournalRefusal("Each write must bind its step/method/path");var values=fields.Select(value=>value is JsonValue item&&item.TryGetValue(out var text)&&text!=null?text:throw new JournalRefusal("Manifest values are exact strings")).ToArray();writes.Add((values[0],values[1],values[2]));} return new Journal(path,apiBase,workspace,slug,job,inputFingerprint,writes,mode); } static string Optional(string name,string fallback) { var value=Environment.GetEnvironmentVariable(name);return value==null||value==""?fallback:value; } static string PositiveId(string value) { if(string.IsNullOrEmpty(value)||value[0]=='0'||!value.All(c=>c>='0'&&c<='9')||!long.TryParse(value,NumberStyles.None,CultureInfo.InvariantCulture,out var id)||id<=0)throw new Exception("Use a positive record ID");return value; } static void PrintValue(object value) => Console.WriteLine(value is string text ? text : JsonSerializer.Serialize(value)); static void RequireCondition(bool value,string message) { if(!value)throw new Exception(message); } static string ResponseStatus(Result value)=>value.Status.ToString(CultureInfo.InvariantCulture); static string Text(object value) => value==null?"":value is JsonNode node?Text(node):Convert.ToString(value,CultureInfo.InvariantCulture); internal static async Task Run() { var inventory_asset_id = PositiveId(Required("EXHIBITDAY_ASSET_ID")); var inventory_location_id = PositiveId(Required("EXHIBITDAY_STORAGE_LOCATION_ID")); var inventory_journal_path = Required("EXHIBITDAY_JOURNAL"); var inventory_job_id = Required("EXHIBITDAY_JOB_ID"); var inventory_job_mode = Optional("EXHIBITDAY_JOB_MODE", "resume"); RequireCondition(Either(Equal(inventory_job_mode, "new"), Equal(inventory_job_mode, "resume")), "Use exact new or resume for EXHIBITDAY_JOB_MODE."); var inventory_received = BoundedWholeNumber(Required("EXHIBITDAY_RECEIVED_QUANTITY"), "EXHIBITDAY_RECEIVED_QUANTITY", "2147483647"); RequireCondition(NotValue(Equal(inventory_received, "0")), "EXHIBITDAY_RECEIVED_QUANTITY must be greater than zero."); var inventory_recount = Optional("EXHIBITDAY_RECOUNT_QUANTITY", ""); var inventory_expected = inventory_received; if (NotValue(Equal(inventory_recount, ""))) { inventory_recount = BoundedWholeNumber(inventory_recount, "EXHIBITDAY_RECOUNT_QUANTITY", "2147483647"); RequireCondition(NotValue(Equal(inventory_recount, "0")), "EXHIBITDAY_RECOUNT_QUANTITY must be greater than zero."); inventory_expected = inventory_recount; } var inventory_workspace_response = await Call("workspace_binding", new JsonObject { }, null, null); RequireCondition(Equal(ResponseStatus(inventory_workspace_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); var inventory_workspace = inventory_workspace_response.Body; var inventory_workspace_id = PositiveId(Text(Field(inventory_workspace, "id"))); var inventory_input_fingerprint = JournalFingerprint(new JsonObject { ["workflow_contract_sha256"] = "F9CCD36E69D6E5A76E22B460D9FB853A89937E942238AAD7DF5A63BE8EA9F49D", ["asset_id"] = inventory_asset_id, ["storage_location_id"] = inventory_location_id, ["create_quantity"] = inventory_received, ["correct_quantity"] = inventory_recount }); using (var inventory_job = OpenJournal(inventory_journal_path, "https://api.exhibitday.com/v1", inventory_workspace_id, "collateral-inventory-storage", inventory_job_id, inventory_input_fingerprint, new JsonArray(new JsonArray("create_adjustment", "POST", "/v1/assets/inventory_adjustments"), new JsonArray("correct_count", "PATCH", "/v1/assets/inventory_adjustments")), inventory_job_mode)) { RequireCondition(Either(NotValue(JournalAcknowledged(inventory_job, "correct_count")), JournalAcknowledged(inventory_job, "create_adjustment")), "A correction is acknowledged before its create. Stop and reconcile the journal."); RequireCondition(Either(NotValue(JournalAcknowledged(inventory_job, "correct_count")), NotValue(Equal(inventory_recount, ""))), "This journal records a correction without a recount quantity. Stop and reconcile."); var inventory_adjustment_id = ""; if (JournalAcknowledged(inventory_job, "create_adjustment")) { var inventory_created_saved = JournalSaved(inventory_job, "create_adjustment"); inventory_adjustment_id = PositiveId(Text(Field(inventory_created_saved, "id"))); RequireCondition(Both(Equal(Text(Field(inventory_created_saved, "asset_id")), inventory_asset_id), Equal(Text(Field(inventory_created_saved, "storage_location_id")), inventory_location_id)), "The saved adjustment belongs to different inventory or storage; do not create a replacement."); } else { var inventory_create_fingerprint = JournalFingerprint(new JsonObject { ["asset_id"] = inventory_asset_id, ["storage_location_id"] = inventory_location_id, ["quantity"] = inventory_received, ["is_increase"] = "true", ["description"] = "Brochures received for Annual Expo" }); var inventory_create_intent = JournalBegin(inventory_job, "create_adjustment", "POST", "/v1/assets/inventory_adjustments", inventory_create_fingerprint); var inventory_create_response = await Call("create_adjustment", new JsonObject { }, new JsonObject { ["asset_id"] = inventory_asset_id, ["storage_location_id"] = inventory_location_id, ["quantity"] = inventory_received, ["is_increase"] = true, ["description"] = "Brochures received for Annual Expo" }, Text(Field(inventory_create_intent, "idempotency_key"))); RequireCondition(Equal(ResponseStatus(inventory_create_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); var inventory_created = inventory_create_response.Body; inventory_adjustment_id = PositiveId(Text(Field(inventory_created, "id"))); RequireCondition(Both(Both(Equal(Text(Field(inventory_created, "id")), inventory_adjustment_id), Equal(Text(Field(inventory_created, "asset_id")), inventory_asset_id)), Both(Equal(Text(Field(inventory_created, "storage_location_id")), inventory_location_id), Both(Both(Equal(Text(Field(inventory_created, "quantity_adjustment")), inventory_received), Equal(Text(Field(inventory_created, "quantity")), inventory_received)), Equal(Field(inventory_created, "is_increase"), true)))), "The create acknowledgement differs from this item, location or stock increase. Keep pending state and reconcile."); JournalAcknowledge(inventory_job, "create_adjustment", new JsonObject { ["id"] = inventory_adjustment_id, ["asset_id"] = inventory_asset_id, ["storage_location_id"] = inventory_location_id }); } if (NotValue(Equal(inventory_recount, ""))) { var inventory_read_response = await Call("read_adjustment", new JsonObject { ["id"] = inventory_adjustment_id, ["$include_record_revision"] = "true" }, null, null); RequireCondition(Equal(ResponseStatus(inventory_read_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); var inventory_current = inventory_read_response.Body; if (JournalAcknowledged(inventory_job, "correct_count")) { var inventory_corrected_saved = JournalSaved(inventory_job, "correct_count"); RequireCondition(Both(Equal(Text(Field(inventory_corrected_saved, "id")), inventory_adjustment_id), Both(Equal(Text(Field(inventory_corrected_saved, "asset_id")), inventory_asset_id), Both(Equal(Text(Field(inventory_corrected_saved, "storage_location_id")), inventory_location_id), Equal(Text(Field(inventory_corrected_saved, "quantity")), inventory_recount)))), "The acknowledged correction differs from this record or quantity; stop and reconcile."); RequireCondition(Both(Both(Equal(Text(Field(inventory_current, "id")), inventory_adjustment_id), Equal(Text(Field(inventory_current, "asset_id")), inventory_asset_id)), Both(Equal(Text(Field(inventory_current, "storage_location_id")), inventory_location_id), Both(Both(Equal(Text(Field(inventory_current, "quantity_adjustment")), inventory_recount), Equal(Text(Field(inventory_current, "quantity")), inventory_recount)), Equal(Field(inventory_current, "is_increase"), true)))), "The acknowledged adjustment is now missing, rebound or changed; do not silently restore it."); } else { RequireCondition(Both(Both(Equal(Text(Field(inventory_current, "id")), inventory_adjustment_id), Equal(Text(Field(inventory_current, "asset_id")), inventory_asset_id)), Both(Equal(Text(Field(inventory_current, "storage_location_id")), inventory_location_id), Both(Both(Equal(Text(Field(inventory_current, "quantity_adjustment")), inventory_received), Equal(Text(Field(inventory_current, "quantity")), inventory_received)), Equal(Field(inventory_current, "is_increase"), true)))), "The saved adjustment is no longer the expected stock increase. Review it before any correction."); var inventory_revision = Text(Field(inventory_current, "record_revision")); RequireCondition(IsPresent(inventory_revision), "The inventory read must return its actual record_revision before correction."); var inventory_patch = new JsonObject { ["id"] = inventory_adjustment_id, ["quantity"] = inventory_recount, ["expected_revision"] = inventory_revision }; var inventory_patch_fingerprint = JournalFingerprint(new JsonObject { ["id"] = inventory_adjustment_id, ["quantity"] = inventory_recount, ["expected_revision"] = inventory_revision }); JournalBegin(inventory_job, "correct_count", "PATCH", "/v1/assets/inventory_adjustments", inventory_patch_fingerprint); var inventory_patch_response = await Call("correct_count", new JsonObject { }, inventory_patch, null); RequireCondition(Equal(ResponseStatus(inventory_patch_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); var inventory_patch_receipt = inventory_patch_response.Body; var inventory_after_revision = Text(Field(inventory_patch_receipt, "record_revision")); RequireCondition(IsPresent(inventory_after_revision), "A checked correction acknowledgement requires its returned record_revision."); JournalAcknowledge(inventory_job, "correct_count", new JsonObject { ["id"] = inventory_adjustment_id, ["asset_id"] = inventory_asset_id, ["storage_location_id"] = inventory_location_id, ["quantity"] = inventory_recount, ["record_revision"] = inventory_after_revision }); } } var inventory_verify_response = await Call("verify_adjustment", new JsonObject { ["id"] = inventory_adjustment_id }, null, null); RequireCondition(Equal(ResponseStatus(inventory_verify_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); var inventory_verified = inventory_verify_response.Body; RequireCondition(Both(Both(Equal(Text(Field(inventory_verified, "id")), inventory_adjustment_id), Equal(Text(Field(inventory_verified, "asset_id")), inventory_asset_id)), Both(Equal(Text(Field(inventory_verified, "storage_location_id")), inventory_location_id), Both(Both(Equal(Text(Field(inventory_verified, "quantity_adjustment")), inventory_expected), Equal(Text(Field(inventory_verified, "quantity")), inventory_expected)), Equal(Field(inventory_verified, "is_increase"), true)))), "The final adjustment does not match the acknowledged record, location and stock increase. Reconcile; do not add another adjustment or undo it automatically."); PrintValue(new JsonObject { ["id"] = inventory_adjustment_id, ["asset_id"] = inventory_asset_id, ["storage_location_id"] = inventory_location_id, ["quantity"] = inventory_expected }); } } static Task Main() => Run(); } ``` ```java // 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 SPEC = JSON.fromJson("{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"create_adjustment\":{\"method\":\"POST\",\"path\":\"/assets/inventory_adjustments\"},\"read_adjustment\":{\"method\":\"GET\",\"path\":\"/assets/inventory_adjustments/info\"},\"correct_count\":{\"method\":\"PATCH\",\"path\":\"/assets/inventory_adjustments\"},\"verify_adjustment\":{\"method\":\"GET\",\"path\":\"/assets/inventory_adjustments/info\"}}}", Map.class); static final String API_KEY = headerKey(required("EXHIBITDAY_API_KEY")); static String headerKey(String value){if(value.chars().anyMatch(c->c<32||c>126))throw new IllegalArgumentException("Use the API key as one ASCII header value without control characters");return value;} static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).followRedirects(HttpClient.Redirect.NEVER).build(); interface RequestSender { HttpResponse send(HttpRequest request)throws IOException,InterruptedException; } static RequestSender SEND=request->CLIENT.send(request,HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); static class Result { int status; Object body; Map headers; String raw; Result(int s, Object b, Map h,String r) {status=s;body=b;headers=h;raw=r;} } // 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 obj(Object value) {return value==null?new LinkedHashMap<>(): (Map)value;} @SuppressWarnings("unchecked") static List list(Object value) {return value==null?Collections.emptyList():(List)value;} static Map map(Object... pairs) {Map result=new LinkedHashMap<>();for(int i=0;i query,Object body,String key) { Map route=obj(obj(SPEC.get("requests")).get(name));String method=text(route.get("method")); Map headers=map("Authorization","Bearer " + API_KEY,"Accept","application/json"); if(method.equals("POST")){if(key==null||key.isEmpty())throw new IllegalArgumentException("Persist a logical create key before sending POST");headers.put("Idempotency-Key",key);} 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); // 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. boolean resend=method.equals("GET"); 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 response; try {response=SEND.send(request.build());} 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();Object parsed=null; if(status!=304&&!response.body().isEmpty()) { try {parsed=JSON.fromJson(response.body(),Object.class);} catch(RuntimeException error){if(status<400)throw new IllegalStateException("Expected a JSON success response",error);} } Map 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=resend&&(status==429||status>=500); 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,response.body()); } throw new IllegalStateException("Retry limit reached"); } static boolean both(boolean left,boolean right){return left&&right;} static String bounded_whole_number(String value,String name,String maximum){if(!value.matches("0|[1-9][0-9]*")||value.length()>maximum.length()||(value.length()==maximum.length()&&value.compareTo(maximum)>0))throw new IllegalArgumentException(name+" must be a whole number from 0 through "+maximum);return value;} static boolean either(boolean left,boolean right){return left||right;} static boolean equal(Object left,Object right){return Objects.equals(left,right);} static Object field(Object value,String name){if(!(value instanceof Map)||!obj(value).containsKey(name))throw new IllegalStateException("Missing response field: "+name);return obj(value).get(name);} static boolean is_present(String value){return value!=null&&!value.isEmpty();} // Private client restart state only. No transport, application or JSON interpreter. static final class Journal implements AutoCloseable { public static final class Refusal extends IllegalStateException { Refusal(String message){super(message);} } public static final byte[] PREAMBLE="EXHIBITDAY-GUIDE-JOURNAL 1\n".getBytes(StandardCharsets.US_ASCII); static boolean valid(String value,String pattern){return value!=null&&value.matches(pattern);} static byte[] utf8(String value)throws java.nio.charset.CharacterCodingException { if(value==null)throw new Refusal("Journal fields are exact strings"); java.nio.ByteBuffer encoded=StandardCharsets.UTF_8.newEncoder().onMalformedInput(java.nio.charset.CodingErrorAction.REPORT).onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT).encode(java.nio.CharBuffer.wrap(value));byte[] raw=new byte[encoded.remaining()];encoded.get(raw);return raw; } static String ascii(byte[] raw,int start,int count){for(int i=start;i127)throw new Refusal("Journal framing must be canonical ASCII");return new String(raw,start,count,StandardCharsets.US_ASCII);} public static byte[] strings(Collection values)throws IOException { ByteArrayOutputStream output=new ByteArrayOutputStream();for(String value:values){byte[] raw=utf8(value);output.write((raw.length+":").getBytes(StandardCharsets.US_ASCII));output.write(raw);}return output.toByteArray(); } static int find(byte[] raw,int offset,int value){for(int i=offset;i readStrings(byte[] raw)throws IOException { List values=new ArrayList<>();int offset=0; while(offset0)throw new Refusal("Incomplete journal string");int count=size.intValueExact(); values.add(StandardCharsets.UTF_8.newDecoder().onMalformedInput(java.nio.charset.CodingErrorAction.REPORT).onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT).decode(java.nio.ByteBuffer.wrap(raw,offset,count)).toString());offset+=count;} return values; } public static String digest(byte[] raw){try{byte[] hash=java.security.MessageDigest.getInstance("SHA-256").digest(raw);StringBuilder text=new StringBuilder();for(byte item:hash)text.append(String.format(Locale.ROOT,"%02X",item&255));return text.toString();}catch(java.security.NoSuchAlgorithmException error){throw new IllegalStateException(error);}} public static String fingerprint(Map pairs)throws IOException { List values=new ArrayList<>();for(String name:new TreeSet<>(pairs.keySet())){if(!valid(name,"[A-Za-z0-9_.-]+")||Arrays.asList("api_key","exhibitday_api_key").contains(name.toLowerCase(Locale.ROOT)))throw new Refusal("Use explicit secret-free fingerprint names");values.add(name);values.add(pairs.get(name));}return digest(strings(values)); } public static byte[] frame(Collection values)throws IOException {byte[] payload=strings(values);ByteArrayOutputStream output=new ByteArrayOutputStream();output.write((payload.length+" "+digest(payload)+"\n").getBytes(StandardCharsets.US_ASCII));output.write(payload);output.write(10);return output.toByteArray();} public static List> decode(byte[] raw)throws IOException { if(raw.length> records=new ArrayList<>(); while(offset=0)throw new Refusal("Incomplete frame; reconcile before retry");int count=size.intValueExact();byte[] payload=Arrays.copyOfRange(raw,offset,offset+count);offset+=count; if(raw[offset]!=10||!digest(payload).equals(fields[1]))throw new Refusal("Journal integrity failed; reconcile before retry");records.add(readStrings(payload));offset++;}return records; } static void writeAll(java.nio.channels.FileChannel target,byte[] raw)throws IOException {java.nio.ByteBuffer data=java.nio.ByteBuffer.wrap(raw);while(data.hasRemaining())if(target.write(data)<=0)throw new IOException("Journal write did not advance");} static java.nio.channels.FileChannel createPrivate(Path path,OpenOption... options)throws IOException { java.nio.file.attribute.FileAttribute[] attributes=FileSystems.getDefault().supportedFileAttributeViews().contains("posix")?new java.nio.file.attribute.FileAttribute[]{java.nio.file.attribute.PosixFilePermissions.asFileAttribute(java.nio.file.attribute.PosixFilePermissions.fromString("rw-------"))}:new java.nio.file.attribute.FileAttribute[0]; return java.nio.channels.FileChannel.open(path,new HashSet<>(Arrays.asList(options)),attributes); } final Path path,lockPath;final String owner;final List header; final Map> allowed=new LinkedHashMap<>();Map> intents=new LinkedHashMap<>(),savedValues=new LinkedHashMap<>(); java.nio.channels.FileChannel lock;boolean owned,tainted;Object fileKey;java.nio.file.attribute.FileTime creation; public Journal(Path path,String apiBase,String workspace,String slug,String job,String inputFingerprint,List> writes)throws IOException {this(path,apiBase,workspace,slug,job,inputFingerprint,writes,"resume");} public Journal(Path path,String apiBase,String workspace,String slug,String job,String inputFingerprint,List> writes,String mode)throws IOException { this.path=path;lockPath=Path.of(path.toString()+".lock");byte[] random=new byte[16];new java.security.SecureRandom().nextBytes(random);StringBuilder token=new StringBuilder();for(byte item:random)token.append(String.format(Locale.ROOT,"%02x",item&255));owner=token.toString(); URI address=URI.create(apiBase);if(!Arrays.asList("https","http").contains(address.getScheme())||address.getHost()==null||address.getUserInfo()!=null||address.getRawQuery()!=null||address.getRawFragment()!=null||!valid(slug,"[a-z][a-z0-9-]*"))throw new Refusal("Use actual API base and closed guide slug"); if(job==null||job.trim().isEmpty()||!valid(workspace,"[1-9][0-9]*")||!valid(inputFingerprint,"[0-9A-F]{64}"))throw new Refusal("Use actual workspace, stable explicit job ID and exact fingerprint"); if(!Arrays.asList("new","resume").contains(mode))throw new Refusal("Choose new or resume for this local job"); List manifest=new ArrayList<>();for(List item:writes){if(item.size()!=3)throw new Refusal("Invalid write manifest shape");String step=item.get(0),method=item.get(1),route=item.get(2); if(!valid(step,"[a-z][a-z0-9_-]*")||allowed.containsKey(step)||!Arrays.asList("POST","PATCH","DELETE").contains(method)||!valid(route,"/v1/[A-Za-z0-9_/-]+")||route.contains("//"))throw new Refusal("Use a closed unique write manifest");allowed.put(step,List.of(method,route));manifest.addAll(item);} if(allowed.isEmpty())throw new Refusal("Only write workflows need a restart journal");header=List.of("H","1",apiBase,workspace,slug,job,inputFingerprint,digest(strings(manifest)));strings(header); try{lock=createPrivate(lockPath,StandardOpenOption.CREATE_NEW,StandardOpenOption.READ,StandardOpenOption.WRITE);owned=true;}catch(FileAlreadyExistsException error){throw new Refusal("This journal is locked; do not overlap jobs or steal a stale lock");} try{writeAll(lock,owner.getBytes(StandardCharsets.US_ASCII));lock.force(true);java.nio.file.attribute.BasicFileAttributes identity=Files.readAttributes(lockPath,java.nio.file.attribute.BasicFileAttributes.class,LinkOption.NOFOLLOW_LINKS);fileKey=identity.fileKey();creation=identity.creationTime(); if(Files.isSymbolicLink(path))throw new Refusal("Choose a private regular journal file"); if(mode.equals("resume")&&!Files.exists(path))throw new Refusal("Journal missing: stop and reconcile lost state before starting a new logical job"); if(mode.equals("new")&&Files.exists(path))throw new Refusal("Journal exists; use resume for the same logical job"); if(mode.equals("new")){try(java.nio.channels.FileChannel target=createPrivate(path,StandardOpenOption.CREATE_NEW,StandardOpenOption.WRITE)){writeAll(target,PREAMBLE);writeAll(target,frame(header));target.force(true);}} List> records=decode(Files.readAllBytes(path));if(records.isEmpty()||!records.get(0).equals(header))throw new Refusal("Journal workspace/base/guide/job/input binding differs");for(List record:records.subList(1,records.size()))apply(record); if(intents.keySet().stream().anyMatch(step->!savedValues.containsKey(step)))throw new Refusal("Saved intent lacks ACK; stop and reconcile before retry"); }catch(IOException|RuntimeException error){close();throw error;} } void apply(List record){ if(record.isEmpty())throw new Refusal("Empty journal record"); if(record.get(0).equals("I")){ if(record.size()!=6)throw new Refusal("Invalid intent shape");String step=record.get(1),method=record.get(2),route=record.get(3),fingerprint=record.get(4),key=record.get(5); if(!valid(step,"[a-z][a-z0-9_-]*")||intents.containsKey(step)||!List.of(method,route).equals(allowed.get(step))||!valid(fingerprint,"[0-9A-F]{64}")||intents.keySet().stream().anyMatch(name->!savedValues.containsKey(name)))throw new Refusal("Invalid, future or repeated intent"); if(method.equals("POST")&&!valid(key,"[0-9a-f]{32}")||!method.equals("POST")&&!key.isEmpty())throw new Refusal("Invalid persisted action key");intents.put(step,new LinkedHashMap<>(Map.of("method",method,"path",route,"request_fingerprint",fingerprint,"idempotency_key",key))); }else if(record.get(0).equals("A")){ if(record.size()<3||!valid(record.get(2),"0|[1-9][0-9]*")||!new java.math.BigInteger(record.get(2)).multiply(java.math.BigInteger.TWO).equals(java.math.BigInteger.valueOf(record.size()-3))||!intents.containsKey(record.get(1))||savedValues.containsKey(record.get(1)))throw new Refusal("ACK without exactly one prior intent"); List names=new ArrayList<>();for(int i=3;i(new TreeSet<>(names)))||names.stream().anyMatch(name->!valid(name,"[a-z][a-z0-9_]*")||name.equals("api_key")||name.equals("exhibitday_api_key")))throw new Refusal("ACK fields must be unique sorted secret-free identifiers"); Map saved=new LinkedHashMap<>();for(int i=0;i record)throws IOException {requireActive();byte[] raw=frame(record);try(java.nio.channels.FileChannel target=java.nio.channels.FileChannel.open(path,StandardOpenOption.WRITE,StandardOpenOption.APPEND)){writeAll(target,raw);target.force(true);}catch(IOException|RuntimeException error){tainted=true;throw error;}} public boolean acknowledged(String step)throws IOException{requireActive();return savedValues.containsKey(step);} public Map saved(String step)throws IOException{requireActive();if(!savedValues.containsKey(step))throw new Refusal("No acknowledged state exists");return new LinkedHashMap<>(savedValues.get(step));} public Map begin(String step,String method,String route,String requestFingerprint)throws IOException { requireActive();if(intents.containsKey(step))throw new Refusal("Never blindly repeat an existing action");String key="";if(method.equals("POST")){byte[] bytes=new byte[16];new java.security.SecureRandom().nextBytes(bytes);StringBuilder text=new StringBuilder();for(byte item:bytes)text.append(String.format(Locale.ROOT,"%02x",item&255));key=text.toString();} List record=List.of("I",step,method,route,requestFingerprint,key);Map> previous=new LinkedHashMap<>(intents);try{apply(record);}finally{intents=previous;}append(record);apply(record);return new LinkedHashMap<>(intents.get(step)); } public void acknowledge(String step,Map saved)throws IOException { requireActive();List record=new ArrayList<>(List.of("A",step,Integer.toString(saved.size())));for(String name:new TreeSet<>(saved.keySet())){record.add(name);record.add(saved.get(name));} Map> previous=new LinkedHashMap<>(savedValues);try{apply(record);strings(record);}finally{savedValues=previous;}append(record);apply(record); } public void close()throws IOException { if(!owned)return;if(tainted){lock.close();lock=null;owned=false;return;} try{requireActive();}catch(IOException|RuntimeException error){lock.close();lock=null;owned=false;throw error;}lock.close();lock=null;owned=false;Files.delete(lockPath); } } static Map journal_values(Object value){if(!(value instanceof Map))throw new Journal.Refusal("Saved/fingerprint values need an explicit object");Map result=new LinkedHashMap<>();for(Map.Entry field:((Map)value).entrySet()){if(!(field.getKey() instanceof String)||!(field.getValue() instanceof String))throw new Journal.Refusal("Saved/fingerprint values must be exact strings");result.put((String)field.getKey(),(String)field.getValue());}return result;} static void journal_acknowledge(Journal job,String step,Object saved)throws IOException{job.acknowledge(step,journal_values(saved));} static boolean journal_acknowledged(Journal job,String step)throws IOException{return job.acknowledged(step);} static Object journal_begin(Journal job,String step,String method,String path,String requestFingerprint)throws IOException{return new LinkedHashMap(job.begin(step,method,path,requestFingerprint));} static String journal_fingerprint(Object value)throws IOException{return Journal.fingerprint(journal_values(value));} static Object journal_saved(Journal job,String step)throws IOException{return new LinkedHashMap(job.saved(step));} static boolean not_value(boolean value){return !value;} static Journal open_journal(String path,String base,String workspace,String slug,String job,String inputFingerprint,Object manifest,String mode)throws IOException { if(!(manifest instanceof List))throw new Journal.Refusal("A closed write manifest is required");List> writes=new ArrayList<>();for(Object row:(List)manifest){if(!(row instanceof List)||((List)row).size()!=3)throw new Journal.Refusal("Each write must bind step/method/path");List fields=new ArrayList<>();for(Object value:(List)row){if(!(value instanceof String))throw new Journal.Refusal("Manifest values are exact strings");fields.add((String)value);}writes.add(fields);}return new Journal(Path.of(path),base,workspace,slug,job,inputFingerprint,writes,mode); } static String optional(String name,String fallback){String value=System.getenv(name);return value==null||value.isEmpty()?fallback:value;} static String positive_id(String value){try{if(value==null||!value.matches("[1-9][0-9]*")||Long.parseLong(value)<=0)throw new IllegalArgumentException();return value;}catch(RuntimeException error){throw new IllegalArgumentException("Use a positive record ID");}} static void print_value(Object value){try{String text=value instanceof String?(String)value:JSON.toJson(value);System.out.write((text+"\n").getBytes(StandardCharsets.UTF_8));}catch(IOException error){throw new UncheckedIOException(error);}} static void require_condition(boolean value,String message){if(!value)throw new IllegalStateException(message);} static String response_status(Result value){return Integer.toString(value.status);} static void run()throws Exception { String inventory_asset_id = positive_id(required("EXHIBITDAY_ASSET_ID")); String inventory_location_id = positive_id(required("EXHIBITDAY_STORAGE_LOCATION_ID")); String inventory_journal_path = required("EXHIBITDAY_JOURNAL"); String inventory_job_id = required("EXHIBITDAY_JOB_ID"); String inventory_job_mode = optional("EXHIBITDAY_JOB_MODE", "resume"); require_condition(either(equal(inventory_job_mode, "new"), equal(inventory_job_mode, "resume")), "Use exact new or resume for EXHIBITDAY_JOB_MODE."); String inventory_received = bounded_whole_number(required("EXHIBITDAY_RECEIVED_QUANTITY"), "EXHIBITDAY_RECEIVED_QUANTITY", "2147483647"); require_condition(not_value(equal(inventory_received, "0")), "EXHIBITDAY_RECEIVED_QUANTITY must be greater than zero."); String inventory_recount = optional("EXHIBITDAY_RECOUNT_QUANTITY", ""); String inventory_expected = inventory_received; if (not_value(equal(inventory_recount, ""))) { inventory_recount = bounded_whole_number(inventory_recount, "EXHIBITDAY_RECOUNT_QUANTITY", "2147483647"); require_condition(not_value(equal(inventory_recount, "0")), "EXHIBITDAY_RECOUNT_QUANTITY must be greater than zero."); inventory_expected = inventory_recount; } Result inventory_workspace_response = call("workspace_binding", map(), null, null); require_condition(equal(response_status(inventory_workspace_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); Object inventory_workspace = inventory_workspace_response.body; String inventory_workspace_id = positive_id(text(field(inventory_workspace, "id"))); String inventory_input_fingerprint = journal_fingerprint(map("workflow_contract_sha256", "F9CCD36E69D6E5A76E22B460D9FB853A89937E942238AAD7DF5A63BE8EA9F49D", "asset_id", inventory_asset_id, "storage_location_id", inventory_location_id, "create_quantity", inventory_received, "correct_quantity", inventory_recount)); try (Journal inventory_job = open_journal(inventory_journal_path, "https://api.exhibitday.com/v1", inventory_workspace_id, "collateral-inventory-storage", inventory_job_id, inventory_input_fingerprint, Arrays.asList(Arrays.asList("create_adjustment", "POST", "/v1/assets/inventory_adjustments"), Arrays.asList("correct_count", "PATCH", "/v1/assets/inventory_adjustments")), inventory_job_mode)) { require_condition(either(not_value(journal_acknowledged(inventory_job, "correct_count")), journal_acknowledged(inventory_job, "create_adjustment")), "A correction is acknowledged before its create. Stop and reconcile the journal."); require_condition(either(not_value(journal_acknowledged(inventory_job, "correct_count")), not_value(equal(inventory_recount, ""))), "This journal records a correction without a recount quantity. Stop and reconcile."); String inventory_adjustment_id = ""; if (journal_acknowledged(inventory_job, "create_adjustment")) { Object inventory_created_saved = journal_saved(inventory_job, "create_adjustment"); inventory_adjustment_id = positive_id(text(field(inventory_created_saved, "id"))); require_condition(both(equal(text(field(inventory_created_saved, "asset_id")), inventory_asset_id), equal(text(field(inventory_created_saved, "storage_location_id")), inventory_location_id)), "The saved adjustment belongs to different inventory or storage; do not create a replacement."); } else { String inventory_create_fingerprint = journal_fingerprint(map("asset_id", inventory_asset_id, "storage_location_id", inventory_location_id, "quantity", inventory_received, "is_increase", "true", "description", "Brochures received for Annual Expo")); Object inventory_create_intent = journal_begin(inventory_job, "create_adjustment", "POST", "/v1/assets/inventory_adjustments", inventory_create_fingerprint); Result inventory_create_response = call("create_adjustment", map(), map("asset_id", inventory_asset_id, "storage_location_id", inventory_location_id, "quantity", inventory_received, "is_increase", true, "description", "Brochures received for Annual Expo"), text(field(inventory_create_intent, "idempotency_key"))); require_condition(equal(response_status(inventory_create_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); Object inventory_created = inventory_create_response.body; inventory_adjustment_id = positive_id(text(field(inventory_created, "id"))); require_condition(both(both(equal(text(field(inventory_created, "id")), inventory_adjustment_id), equal(text(field(inventory_created, "asset_id")), inventory_asset_id)), both(equal(text(field(inventory_created, "storage_location_id")), inventory_location_id), both(both(equal(text(field(inventory_created, "quantity_adjustment")), inventory_received), equal(text(field(inventory_created, "quantity")), inventory_received)), equal(field(inventory_created, "is_increase"), true)))), "The create acknowledgement differs from this item, location or stock increase. Keep pending state and reconcile."); journal_acknowledge(inventory_job, "create_adjustment", map("id", inventory_adjustment_id, "asset_id", inventory_asset_id, "storage_location_id", inventory_location_id)); } if (not_value(equal(inventory_recount, ""))) { Result inventory_read_response = call("read_adjustment", map("id", inventory_adjustment_id, "$include_record_revision", "true"), null, null); require_condition(equal(response_status(inventory_read_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); Object inventory_current = inventory_read_response.body; if (journal_acknowledged(inventory_job, "correct_count")) { Object inventory_corrected_saved = journal_saved(inventory_job, "correct_count"); require_condition(both(equal(text(field(inventory_corrected_saved, "id")), inventory_adjustment_id), both(equal(text(field(inventory_corrected_saved, "asset_id")), inventory_asset_id), both(equal(text(field(inventory_corrected_saved, "storage_location_id")), inventory_location_id), equal(text(field(inventory_corrected_saved, "quantity")), inventory_recount)))), "The acknowledged correction differs from this record or quantity; stop and reconcile."); require_condition(both(both(equal(text(field(inventory_current, "id")), inventory_adjustment_id), equal(text(field(inventory_current, "asset_id")), inventory_asset_id)), both(equal(text(field(inventory_current, "storage_location_id")), inventory_location_id), both(both(equal(text(field(inventory_current, "quantity_adjustment")), inventory_recount), equal(text(field(inventory_current, "quantity")), inventory_recount)), equal(field(inventory_current, "is_increase"), true)))), "The acknowledged adjustment is now missing, rebound or changed; do not silently restore it."); } else { require_condition(both(both(equal(text(field(inventory_current, "id")), inventory_adjustment_id), equal(text(field(inventory_current, "asset_id")), inventory_asset_id)), both(equal(text(field(inventory_current, "storage_location_id")), inventory_location_id), both(both(equal(text(field(inventory_current, "quantity_adjustment")), inventory_received), equal(text(field(inventory_current, "quantity")), inventory_received)), equal(field(inventory_current, "is_increase"), true)))), "The saved adjustment is no longer the expected stock increase. Review it before any correction."); String inventory_revision = text(field(inventory_current, "record_revision")); require_condition(is_present(inventory_revision), "The inventory read must return its actual record_revision before correction."); Object inventory_patch = map("id", inventory_adjustment_id, "quantity", inventory_recount, "expected_revision", inventory_revision); String inventory_patch_fingerprint = journal_fingerprint(map("id", inventory_adjustment_id, "quantity", inventory_recount, "expected_revision", inventory_revision)); journal_begin(inventory_job, "correct_count", "PATCH", "/v1/assets/inventory_adjustments", inventory_patch_fingerprint); Result inventory_patch_response = call("correct_count", map(), inventory_patch, null); require_condition(equal(response_status(inventory_patch_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); Object inventory_patch_receipt = inventory_patch_response.body; String inventory_after_revision = text(field(inventory_patch_receipt, "record_revision")); require_condition(is_present(inventory_after_revision), "A checked correction acknowledgement requires its returned record_revision."); journal_acknowledge(inventory_job, "correct_count", map("id", inventory_adjustment_id, "asset_id", inventory_asset_id, "storage_location_id", inventory_location_id, "quantity", inventory_recount, "record_revision", inventory_after_revision)); } } Result inventory_verify_response = call("verify_adjustment", map("id", inventory_adjustment_id), null, null); require_condition(equal(response_status(inventory_verify_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome."); Object inventory_verified = inventory_verify_response.body; require_condition(both(both(equal(text(field(inventory_verified, "id")), inventory_adjustment_id), equal(text(field(inventory_verified, "asset_id")), inventory_asset_id)), both(equal(text(field(inventory_verified, "storage_location_id")), inventory_location_id), both(both(equal(text(field(inventory_verified, "quantity_adjustment")), inventory_expected), equal(text(field(inventory_verified, "quantity")), inventory_expected)), equal(field(inventory_verified, "is_increase"), true)))), "The final adjustment does not match the acknowledged record, location and stock increase. Reconcile; do not add another adjustment or undo it automatically."); print_value(map("id", inventory_adjustment_id, "asset_id", inventory_asset_id, "storage_location_id", inventory_location_id, "quantity", inventory_expected)); } } public static void main(String[] args)throws Exception {run();} } ``` ```php $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, ?string $key = null): array { global $spec, $apiKey, $transport; $route = $spec['requests'][$name]; $headers = ['Authorization' => 'Bearer ' . $apiKey, 'Accept' => 'application/json']; if ($route['method'] === 'POST') { if ($key === null || $key === '') throw new RuntimeException('Persist a logical create key before sending POST'); $headers['Idempotency-Key'] = $key; // 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); // 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 = 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 = $resend && ($status === 429 || $status >= 500); 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, 'raw' => $raw]; } throw new RuntimeException('Retry limit reached'); } $transport = Closure::fromCallable('nativeTransport'); function both(bool $left,bool $right):bool{return $left&&$right;} function bounded_whole_number(string $value,string $name,string $maximum):string{if(!preg_match("/^(?:0|[1-9][0-9]*)$/D",$value)||strlen($value)>strlen($maximum)||(strlen($value)===strlen($maximum)&&strcmp($value,$maximum)>0))throw new RuntimeException($name." must be a whole number from 0 through ".$maximum);return $value;} function either(bool $left,bool $right):bool{return $left||$right;} function equal(mixed $left,mixed $right):bool{return $left===$right;} function field(mixed $value,string $name):mixed{if(!is_array($value)||!array_key_exists($name,$value))throw new RuntimeException("Missing response field: ".$name);return $value[$name];} function is_present(?string $value):bool{return $value!==null&&$value!=="";} final class JournalRefusal extends RuntimeException {} final class JournalProtocol { public const PREAMBLE="EXHIBITDAY-GUIDE-JOURNAL 1\n"; public static function utf8(mixed $value):string {if(!is_string($value)||preg_match('//u',$value)!==1)throw new JournalRefusal('Journal fields must be exact valid UTF8 strings');return$value;} public static function strings(array $values):string {$raw='';foreach($values as$value){$item=self::utf8($value);$raw.=strlen($item).':'.$item;}return$raw;} private static function length(string $text,int $remaining):int {if(!preg_match('/\A(?:0|[1-9][0-9]*)\z/',$text))throw new JournalRefusal('Noncanonical string length');$maximum=(string)$remaining;if(strlen($text)>strlen($maximum)||(strlen($text)===strlen($maximum)&&strcmp($text,$maximum)>0))throw new JournalRefusal('Incomplete journal string/frame');return(int)$text;} public static function readStrings(string $raw):array {$values=[];$offset=0;while($offset=strlen($raw)-$offset)throw new JournalRefusal('Incomplete frame; reconcile before retry');$payload=substr($raw,$offset,$size);$offset+=$size;if($raw[$offset]!=="\n"||self::digest($payload)!==$match[2])throw new JournalRefusal('Journal integrity failed; reconcile before retry');$records[]=self::readStrings($payload);$offset++;}return$records;} public static function writeAll($file,string $raw):void {$offset=0;while($offsetpath=$path;$this->lockPath=$path.'.lock';$this->owner=bin2hex(random_bytes(16));$address=parse_url($base); if($address===false||!in_array($address['scheme']??null,['https','http'],true)||!isset($address['host'])||isset($address['user'])||isset($address['pass'])||isset($address['query'])||isset($address['fragment'])||!preg_match('/\A[a-z][a-z0-9-]*\z/',$slug))throw new JournalRefusal('Use actual API base and closed guide slug'); if(trim($job)===''||!preg_match('/\A[1-9][0-9]*\z/',$workspace)||!preg_match('/\A[0-9A-F]{64}\z/',$inputFingerprint))throw new JournalRefusal('Use actual workspace, stable explicit job ID and exact fingerprint'); if(!in_array($mode,['new','resume'],true))throw new JournalRefusal('Choose new or resume for this local job'); $manifest=[];foreach($writes as$write){if(!is_array($write)||!array_is_list($write)||count($write)!==3)throw new JournalRefusal('Invalid write manifest');[$step,$method,$route]=$write; if(!is_string($step)||!preg_match('/\A[a-z][a-z0-9_-]*\z/',$step)||isset($this->allowed[$step])||!in_array($method,['POST','PATCH','DELETE'],true)||!is_string($route)||!preg_match('~\A/v1/[A-Za-z0-9_/-]+\z~',$route)||str_contains($route,'//'))throw new JournalRefusal('Use a closed unique write manifest');$this->allowed[$step]=[$method,$route];array_push($manifest,$step,$method,$route);} if($this->allowed===[])throw new JournalRefusal('Only write workflows need restart journal');$this->header=['H','1',$base,$workspace,$slug,$job,$inputFingerprint,JournalProtocol::digest(JournalProtocol::strings($manifest))];JournalProtocol::strings($this->header); $this->file=JournalProtocol::createPrivate($this->lockPath);$this->owned=true; try{ JournalProtocol::writeAll($this->file,$this->owner);$identity=fstat($this->file);if($identity===false)throw new JournalRefusal('Cannot bind acquired lock identity');$this->identity=$identity; clearstatcache(true,$path);if(is_link($path))throw new JournalRefusal('Choose private regular journal file'); $exists=file_exists($path);if($mode==='resume'&&!$exists)throw new JournalRefusal('Journal missing: stop and reconcile lost state before starting a new logical job');if($mode==='new'&&$exists)throw new JournalRefusal('Journal exists; use resume for the same logical job'); if($mode==='new'){$target=JournalProtocol::createPrivate($path);try{JournalProtocol::writeAll($target,JournalProtocol::PREAMBLE.JournalProtocol::frame($this->header));}finally{fclose($target);}} $raw=file_get_contents($path);if($raw===false)throw new JournalRefusal('Cannot read journal');$records=JournalProtocol::decode($raw);if($records===[]||$records[0]!==$this->header)throw new JournalRefusal('Journal workspace/base/guide/job/input binding differs');foreach(array_slice($records,1)as$record)$this->apply($record); if(array_diff(array_keys($this->intents),array_keys($this->savedValues))!==[])throw new JournalRefusal('Saved intent lacks ACK; stop and reconcile before retry'); }catch(Throwable $error){$this->close();throw$error;} } private function apply(array $record):void { if(($record[0]??null)==='I'){ if(count($record)!==6)throw new JournalRefusal('Invalid intent shape');[,$step,$method,$route,$fingerprint,$key]=$record; if(!preg_match('/\A[a-z][a-z0-9_-]*\z/',$step)||isset($this->intents[$step])||($this->allowed[$step]??null)!==[$method,$route]||!preg_match('/\A[0-9A-F]{64}\z/',$fingerprint)||array_diff(array_keys($this->intents),array_keys($this->savedValues))!==[])throw new JournalRefusal('Invalid, future or repeated intent'); if(($method==='POST'&&!preg_match('/\A[0-9a-f]{32}\z/',$key))||($method!=='POST'&&$key!==''))throw new JournalRefusal('Invalid persisted action key');$this->intents[$step]=['method'=>$method,'path'=>$route,'request_fingerprint'=>$fingerprint,'idempotency_key'=>$key]; }elseif(($record[0]??null)==='A'){ if(count($record)<3)throw new JournalRefusal('Invalid ACK shape');[,$step,$count]=$record;$pairs=array_slice($record,3); if(!preg_match('/\A(?:0|[1-9][0-9]*)\z/',$count)||(string)intdiv(count($pairs),2)!==$count||count($pairs)%2!==0||!isset($this->intents[$step])||isset($this->savedValues[$step]))throw new JournalRefusal('ACK without exactly one prior intent'); $names=[];for($i=0;$i$name){if(!preg_match('/\A[a-z][a-z0-9_]*\z/',$name)||in_array($name,['api_key','exhibitday_api_key'],true))throw new JournalRefusal('Use secret-free ACK field names');$saved[$name]=$pairs[$i*2+1];}$this->savedValues[$step]=$saved; }else throw new JournalRefusal('Unknown journal transition'); } private function requireActive():void { if(!$this->owned||$this->file===null||$this->tainted)throw new JournalRefusal('Journal closed or IO outcome needs reconciliation');clearstatcache(true,$this->lockPath);$current=@lstat($this->lockPath);$token=@file_get_contents($this->lockPath); if($current===false||($current['dev']??null)!==($this->identity['dev']??null)||($current['ino']??null)!==($this->identity['ino']??null)||$token!==$this->owner)throw new JournalRefusal('Journal lock replaced; stop without deleting it'); } private function append(array $record):void { $this->requireActive();$raw=JournalProtocol::frame($record);$target=null; try{$target=@fopen($this->path,'ab');if($target===false)throw new JournalRefusal('Cannot append journal; stop and reconcile');JournalProtocol::writeAll($target,$raw);}catch(Throwable $error){$this->tainted=true;throw$error;}finally{if(is_resource($target))fclose($target);} } public function acknowledged(string $step):bool{$this->requireActive();return isset($this->savedValues[$step]);} public function saved(string $step):array{$this->requireActive();if(!isset($this->savedValues[$step]))throw new JournalRefusal('No acknowledged state exists');return$this->savedValues[$step];} public function beginAction(string $step,string $method,string $route,string $requestFingerprint):array { $this->requireActive();if(isset($this->intents[$step]))throw new JournalRefusal('Never blindly repeat an existing action');$key=$method==='POST'?bin2hex(random_bytes(16)):'';$record=['I',$step,$method,$route,$requestFingerprint,$key];$previous=$this->intents;try{$this->apply($record);}finally{$this->intents=$previous;}$this->append($record);$this->apply($record);return$this->intents[$step]; } public function acknowledge(string $step,array $saved):void { $this->requireActive();$record=['A',$step,(string)count($saved)];$names=array_keys($saved);sort($names,SORT_STRING);foreach($names as$name){$record[]=$name;$record[]=$saved[$name];}$previous=$this->savedValues;try{$this->apply($record);JournalProtocol::strings($record);}finally{$this->savedValues=$previous;}$this->append($record);$this->apply($record); } public function close():void { if(!$this->owned)return;if($this->tainted){fclose($this->file);$this->file=null;$this->owned=false;return;} try{$this->requireActive();}catch(Throwable $error){fclose($this->file);$this->file=null;$this->owned=false;throw$error;}fclose($this->file);$this->file=null;$this->owned=false;if(!unlink($this->lockPath))throw new JournalRefusal('Could not release owned journal lock'); } } function journal_values(mixed $value):array{if(!is_object($value))throw new JournalRefusal('Saved/fingerprint values need an explicit object');$result=get_object_vars($value);foreach($result as$name=>$item)if(!is_string($name)||!is_string($item))throw new JournalRefusal('Saved/fingerprint values must be exact strings');return$result;} function journal_acknowledge(GuideJournal $job,string $step,mixed $saved):void{$job->acknowledge($step,journal_values($saved));} function journal_acknowledged(GuideJournal $job,string $step):bool{return $job->acknowledged($step);} function journal_begin(GuideJournal $job,string $step,string $method,string $path,string $requestFingerprint):array{return $job->beginAction($step,$method,$path,$requestFingerprint);} function journal_fingerprint(mixed $value):string{return JournalProtocol::fingerprint(journal_values($value));} function journal_saved(GuideJournal $job,string $step):array{return $job->saved($step);} function not_value(bool $value):bool{return !$value;} function open_journal(string $path,string $base,string $workspace,string $slug,string $job,string $inputFingerprint,array $writes,string $mode):GuideJournal{return new GuideJournal($path,$base,$workspace,$slug,$job,$inputFingerprint,$writes,$mode);} function positive_id(string $value):string{if(!preg_match("/^[1-9][0-9]*$/D",$value)||strlen($value)>19||(strlen($value)===19&&strcmp($value,"9223372036854775807")>0))throw new RuntimeException("Use a positive record ID");return $value;} function print_value(mixed $value):void{echo (is_string($value)?$value:json_encode($value,JSON_THROW_ON_ERROR))."\n";} function require_condition(bool $value,string $message):void{if(!$value)throw new RuntimeException($message);} function response_status(array $value):string{return(string)$value["status"];} function text(mixed $value):string{if($value===null)return "";if(is_string($value))return $value;if(is_bool($value))return $value?"true":"false";if(is_int($value))return (string)$value;throw new RuntimeException("Expected a scalar response value");} function main():void { $inventory_asset_id = positive_id(required('EXHIBITDAY_ASSET_ID')); $inventory_location_id = positive_id(required('EXHIBITDAY_STORAGE_LOCATION_ID')); $inventory_journal_path = required('EXHIBITDAY_JOURNAL'); $inventory_job_id = required('EXHIBITDAY_JOB_ID'); $inventory_job_mode = optional('EXHIBITDAY_JOB_MODE', 'resume'); require_condition(either(equal($inventory_job_mode, 'new'), equal($inventory_job_mode, 'resume')), 'Use exact new or resume for EXHIBITDAY_JOB_MODE.'); $inventory_received = bounded_whole_number(required('EXHIBITDAY_RECEIVED_QUANTITY'), 'EXHIBITDAY_RECEIVED_QUANTITY', '2147483647'); require_condition(not_value(equal($inventory_received, '0')), 'EXHIBITDAY_RECEIVED_QUANTITY must be greater than zero.'); $inventory_recount = optional('EXHIBITDAY_RECOUNT_QUANTITY', ''); $inventory_expected = $inventory_received; if (not_value(equal($inventory_recount, ''))) { $inventory_recount = bounded_whole_number($inventory_recount, 'EXHIBITDAY_RECOUNT_QUANTITY', '2147483647'); require_condition(not_value(equal($inventory_recount, '0')), 'EXHIBITDAY_RECOUNT_QUANTITY must be greater than zero.'); $inventory_expected = $inventory_recount; } $inventory_workspace_response = call('workspace_binding', [], null, null); require_condition(equal(response_status($inventory_workspace_response), '200'), 'Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.'); $inventory_workspace = $inventory_workspace_response["body"]; $inventory_workspace_id = positive_id(text(field($inventory_workspace, 'id'))); $inventory_input_fingerprint = journal_fingerprint((object)['workflow_contract_sha256' => 'F9CCD36E69D6E5A76E22B460D9FB853A89937E942238AAD7DF5A63BE8EA9F49D', 'asset_id' => $inventory_asset_id, 'storage_location_id' => $inventory_location_id, 'create_quantity' => $inventory_received, 'correct_quantity' => $inventory_recount]); $inventory_job = open_journal($inventory_journal_path, 'https://api.exhibitday.com/v1', $inventory_workspace_id, 'collateral-inventory-storage', $inventory_job_id, $inventory_input_fingerprint, [['create_adjustment', 'POST', '/v1/assets/inventory_adjustments'], ['correct_count', 'PATCH', '/v1/assets/inventory_adjustments']], $inventory_job_mode); try { require_condition(either(not_value(journal_acknowledged($inventory_job, 'correct_count')), journal_acknowledged($inventory_job, 'create_adjustment')), 'A correction is acknowledged before its create. Stop and reconcile the journal.'); require_condition(either(not_value(journal_acknowledged($inventory_job, 'correct_count')), not_value(equal($inventory_recount, ''))), 'This journal records a correction without a recount quantity. Stop and reconcile.'); $inventory_adjustment_id = ''; if (journal_acknowledged($inventory_job, 'create_adjustment')) { $inventory_created_saved = journal_saved($inventory_job, 'create_adjustment'); $inventory_adjustment_id = positive_id(text(field($inventory_created_saved, 'id'))); require_condition(both(equal(text(field($inventory_created_saved, 'asset_id')), $inventory_asset_id), equal(text(field($inventory_created_saved, 'storage_location_id')), $inventory_location_id)), 'The saved adjustment belongs to different inventory or storage; do not create a replacement.'); } else { $inventory_create_fingerprint = journal_fingerprint((object)['asset_id' => $inventory_asset_id, 'storage_location_id' => $inventory_location_id, 'quantity' => $inventory_received, 'is_increase' => 'true', 'description' => 'Brochures received for Annual Expo']); $inventory_create_intent = journal_begin($inventory_job, 'create_adjustment', 'POST', '/v1/assets/inventory_adjustments', $inventory_create_fingerprint); $inventory_create_response = call('create_adjustment', [], (object)['asset_id' => $inventory_asset_id, 'storage_location_id' => $inventory_location_id, 'quantity' => $inventory_received, 'is_increase' => true, 'description' => 'Brochures received for Annual Expo'], text(field($inventory_create_intent, 'idempotency_key'))); require_condition(equal(response_status($inventory_create_response), '200'), 'Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.'); $inventory_created = $inventory_create_response["body"]; $inventory_adjustment_id = positive_id(text(field($inventory_created, 'id'))); require_condition(both(both(equal(text(field($inventory_created, 'id')), $inventory_adjustment_id), equal(text(field($inventory_created, 'asset_id')), $inventory_asset_id)), both(equal(text(field($inventory_created, 'storage_location_id')), $inventory_location_id), both(both(equal(text(field($inventory_created, 'quantity_adjustment')), $inventory_received), equal(text(field($inventory_created, 'quantity')), $inventory_received)), equal(field($inventory_created, 'is_increase'), true)))), 'The create acknowledgement differs from this item, location or stock increase. Keep pending state and reconcile.'); journal_acknowledge($inventory_job, 'create_adjustment', (object)['id' => $inventory_adjustment_id, 'asset_id' => $inventory_asset_id, 'storage_location_id' => $inventory_location_id]); } if (not_value(equal($inventory_recount, ''))) { $inventory_read_response = call('read_adjustment', ['id' => $inventory_adjustment_id, '$include_record_revision' => 'true'], null, null); require_condition(equal(response_status($inventory_read_response), '200'), 'Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.'); $inventory_current = $inventory_read_response["body"]; if (journal_acknowledged($inventory_job, 'correct_count')) { $inventory_corrected_saved = journal_saved($inventory_job, 'correct_count'); require_condition(both(equal(text(field($inventory_corrected_saved, 'id')), $inventory_adjustment_id), both(equal(text(field($inventory_corrected_saved, 'asset_id')), $inventory_asset_id), both(equal(text(field($inventory_corrected_saved, 'storage_location_id')), $inventory_location_id), equal(text(field($inventory_corrected_saved, 'quantity')), $inventory_recount)))), 'The acknowledged correction differs from this record or quantity; stop and reconcile.'); require_condition(both(both(equal(text(field($inventory_current, 'id')), $inventory_adjustment_id), equal(text(field($inventory_current, 'asset_id')), $inventory_asset_id)), both(equal(text(field($inventory_current, 'storage_location_id')), $inventory_location_id), both(both(equal(text(field($inventory_current, 'quantity_adjustment')), $inventory_recount), equal(text(field($inventory_current, 'quantity')), $inventory_recount)), equal(field($inventory_current, 'is_increase'), true)))), 'The acknowledged adjustment is now missing, rebound or changed; do not silently restore it.'); } else { require_condition(both(both(equal(text(field($inventory_current, 'id')), $inventory_adjustment_id), equal(text(field($inventory_current, 'asset_id')), $inventory_asset_id)), both(equal(text(field($inventory_current, 'storage_location_id')), $inventory_location_id), both(both(equal(text(field($inventory_current, 'quantity_adjustment')), $inventory_received), equal(text(field($inventory_current, 'quantity')), $inventory_received)), equal(field($inventory_current, 'is_increase'), true)))), 'The saved adjustment is no longer the expected stock increase. Review it before any correction.'); $inventory_revision = text(field($inventory_current, 'record_revision')); require_condition(is_present($inventory_revision), 'The inventory read must return its actual record_revision before correction.'); $inventory_patch = (object)['id' => $inventory_adjustment_id, 'quantity' => $inventory_recount, 'expected_revision' => $inventory_revision]; $inventory_patch_fingerprint = journal_fingerprint((object)['id' => $inventory_adjustment_id, 'quantity' => $inventory_recount, 'expected_revision' => $inventory_revision]); journal_begin($inventory_job, 'correct_count', 'PATCH', '/v1/assets/inventory_adjustments', $inventory_patch_fingerprint); $inventory_patch_response = call('correct_count', [], $inventory_patch, null); require_condition(equal(response_status($inventory_patch_response), '200'), 'Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.'); $inventory_patch_receipt = $inventory_patch_response["body"]; $inventory_after_revision = text(field($inventory_patch_receipt, 'record_revision')); require_condition(is_present($inventory_after_revision), 'A checked correction acknowledgement requires its returned record_revision.'); journal_acknowledge($inventory_job, 'correct_count', (object)['id' => $inventory_adjustment_id, 'asset_id' => $inventory_asset_id, 'storage_location_id' => $inventory_location_id, 'quantity' => $inventory_recount, 'record_revision' => $inventory_after_revision]); } } $inventory_verify_response = call('verify_adjustment', ['id' => $inventory_adjustment_id], null, null); require_condition(equal(response_status($inventory_verify_response), '200'), 'Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.'); $inventory_verified = $inventory_verify_response["body"]; require_condition(both(both(equal(text(field($inventory_verified, 'id')), $inventory_adjustment_id), equal(text(field($inventory_verified, 'asset_id')), $inventory_asset_id)), both(equal(text(field($inventory_verified, 'storage_location_id')), $inventory_location_id), both(both(equal(text(field($inventory_verified, 'quantity_adjustment')), $inventory_expected), equal(text(field($inventory_verified, 'quantity')), $inventory_expected)), equal(field($inventory_verified, 'is_increase'), true)))), 'The final adjustment does not match the acknowledged record, location and stock increase. Reconcile; do not add another adjustment or undo it automatically.'); print_value((object)['id' => $inventory_adjustment_id, 'asset_id' => $inventory_asset_id, 'storage_location_id' => $inventory_location_id, 'quantity' => $inventory_expected]); } finally { $inventory_job->close(); } } if (realpath($_SERVER['SCRIPT_FILENAME'] ?? '') === __FILE__) main(); ``` ```ruby # 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":true,"requests":{"workspace_binding":{"method":"GET","path":"/references/workspace_info"},"create_adjustment":{"method":"POST","path":"/assets/inventory_adjustments"},"read_adjustment":{"method":"GET","path":"/assets/inventory_adjustments/info"},"correct_count":{"method":"PATCH","path":"/assets/inventory_adjustments"},"verify_adjustment":{"method":"GET","path":"/assets/inventory_adjustments/info"}}}') API_KEY = ENV.fetch('EXHIBITDAY_API_KEY') raise 'Use the API key as one ASCII header value without control characters' if API_KEY.each_codepoint.any?{|point|point<32||point>126} 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, 'DELETE' => Net::HTTP::Delete }.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, key = nil) route = SPEC.fetch('requests').fetch(name) headers = { 'Authorization' => 'Bearer ' + API_KEY, 'Accept' => 'application/json' } if route.fetch('method') == 'POST' headers['Idempotency-Key'] = key || raise('Persist a logical create key before sending POST') # 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) # 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.fetch('method') == 'GET' 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 = resend && (status == 429 || (500..599).cover?(status)) 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, raw: raw } end raise 'Retry limit reached' end def both(left,right);left&&right;end def bounded_whole_number(value,name,maximum) unless /\A(?:0|[1-9][0-9]*)\z/.match?(value) && (value.lengthraw.bytesize-offset value=raw.byteslice(offset,size).dup.force_encoding(Encoding::UTF_8);raise Refusal,'Invalid UTF8 string' unless value.valid_encoding? values<=raw.bytesize-offset payload=raw.byteslice(offset,size);offset+=size raise Refusal,'Journal integrity failed; reconcile before retry' unless raw.getbyte(offset)==10&&digest(payload)==match[2] records<0 offset+=written end file.flush;file.fsync end end class GuideJournal P=GuideJournalProtocol def initialize(path,base,workspace,slug,job,input_fingerprint,writes,mode='resume') @path=path.dup;@lock_path=path+'.lock';@file=nil;@owned=false;@tainted=false;@intents={};@saved={};@allowed={} address=URI(base) raise P::Refusal,'Use actual API base and closed guide slug' unless ['https','http'].include?(address.scheme)&&address.host&&address.userinfo.nil?&&address.query.nil?&&address.fragment.nil?&&slug.match?(/\A[a-z][a-z0-9-]*\z/) raise P::Refusal,'Use actual workspace, stable explicit job ID and exact fingerprint' unless !job.strip.empty?&&workspace.match?(/\A[1-9][0-9]*\z/)&&input_fingerprint.match?(/\A[0-9A-F]{64}\z/) raise P::Refusal,'Choose new or resume for this local job' unless ['new','resume'].include?(mode) manifest=[] writes.each do|step,method,route| raise P::Refusal,'Use closed unique write manifest' unless step.match?(/\A[a-z][a-z0-9_-]*\z/)&&!@allowed.key?(step)&&['POST','PATCH','DELETE'].include?(method)&&route.match?(/\A\/v1\/[A-Za-z0-9_\/-]+\z/)&&!route.include?('//') @allowed[step.dup.freeze]=[method.dup.freeze,route.dup.freeze].freeze;manifest.concat([step,method,route]) end raise P::Refusal,'Only write workflows need a restart journal' if @allowed.empty? @header=['H','1',base,workspace,slug,job,input_fingerprint,P.digest(P.strings(manifest))].map{|value|value.dup.freeze}.freeze;P.strings(@header) begin @file=File.open(@lock_path,File::RDWR|File::CREAT|File::EXCL,0o600);@file.binmode;@owned=true rescue Errno::EEXIST raise P::Refusal,'This journal is locked; do not overlap jobs or steal a stale lock' end begin @owner=SecureRandom.hex(16).freeze;P.write_all(@file,@owner.b);@identity=@file.stat # Ruby's Windows fstat reports dev=0 while lstat reports the drive number. # Both expose the same exact inode. Retain it plus the initial path device; # compare like-for-like instead of treating the differing dev APIs as equal. named_identity=File.lstat(@lock_path);raise P::Refusal,'Lock identity did not bind' unless named_identity.ino==@identity.ino @path_device=named_identity.dev raise P::Refusal,'Choose a private regular journal file' if File.symlink?(@path) raise P::Refusal,'Journal missing: stop and reconcile lost state before starting a new logical job' if mode=='resume'&&!File.exist?(@path) raise P::Refusal,'Journal exists; use resume for the same logical job' if mode=='new'&&File.exist?(@path) if mode=='new' File.open(@path,File::WRONLY|File::CREAT|File::EXCL,0o600){|target|target.binmode;P.write_all(target,P::PREAMBLE+P.frame(@header))} end records=P.decode(File.binread(@path));raise P::Refusal,'Journal workspace/base/guide/job/input binding differs' if records.empty?||records[0]!=@header records.drop(1).each{|record|apply(record)} raise P::Refusal,'Saved intent lacks ACK; stop and reconcile before retry' if @intents.keys.any?{|step|!@saved.key?(step)} rescue Exception close;raise end end def apply(record) case record[0] when 'I' raise P::Refusal,'Invalid intent shape' unless record.length==6 _,step,method,route,fingerprint,key=record raise P::Refusal,'Invalid, future or repeated intent' unless step.match?(/\A[a-z][a-z0-9_-]*\z/)&&!@intents.key?(step)&&@allowed[step]==[method,route]&&fingerprint.match?(/\A[0-9A-F]{64}\z/)&&!@intents.keys.any?{|name|!@saved.key?(name)} raise P::Refusal,'Invalid persisted action key' unless (method=='POST'&&key.match?(/\A[0-9a-f]{32}\z/))||(method!='POST'&&key=='') @intents[step.dup.freeze]={'method'=>method.dup.freeze,'path'=>route.dup.freeze,'request_fingerprint'=>fingerprint.dup.freeze,'idempotency_key'=>key.dup.freeze}.freeze when 'A' raise P::Refusal,'Invalid ACK shape' unless record.length>=3 _,step,count,*pairs=record raise P::Refusal,'ACK without exactly one prior intent' unless count.match?(/\A(?:0|[1-9][0-9]*)\z/)&&pairs.length==2*count.to_i&&@intents.key?(step)&&!@saved.key?(step) names=pairs.each_slice(2).map(&:first) raise P::Refusal,'ACK fields must be unique sorted secret-free identifiers' unless names==names.uniq.sort&&names.all?{|name|name.match?(/\A[a-z][a-z0-9_]*\z/)&&!['api_key','exhibitday_api_key'].include?(name)} @saved[step.dup.freeze]=pairs.each_slice(2).to_h.transform_values{|value|value.dup.freeze}.freeze else raise P::Refusal,'Unknown journal transition' end end def require_active raise P::Refusal,'Journal is closed or IO outcome needs reconciliation' unless @owned&&@file&&!@tainted current=File.lstat(@lock_path) raise P::Refusal,'Journal lock replaced; stop without deleting it' unless current.dev==@path_device&¤t.ino==@identity.ino&&File.binread(@lock_path)==@owner.b end def append(record) require_active;raw=P.frame(record) begin File.open(@path,'ab'){|target|P.write_all(target,raw)} rescue Exception @tainted=true;raise end end def acknowledged(step);require_active;@saved.key?(step);end def saved(step) require_active;raise P::Refusal,'No acknowledged state exists' unless @saved.key?(step) @saved.fetch(step).transform_values(&:dup) end def begin_action(step,method,route,request_fingerprint) require_active;raise P::Refusal,'Never blindly repeat an action' if @intents.key?(step) record=['I',step,method,route,request_fingerprint,method=='POST'?SecureRandom.hex(16):''] previous=@intents.dup;begin;apply(record);ensure;@intents=previous;end append(record);apply(record);@intents.fetch(step).transform_values(&:dup) end def acknowledge(step,saved) require_active;record=['A',step,saved.length.to_s];saved.keys.sort.each{|name|record.concat([name,saved.fetch(name)])} previous=@saved.dup;begin;apply(record);P.strings(record);ensure;@saved=previous;end append(record);apply(record) end def close return unless @owned if @tainted;@file.close;@file=nil;@owned=false;return;end begin;require_active;rescue Exception;@file.close;@file=nil;@owned=false;raise;end @file.close;@file=nil;@owned=false;File.unlink(@lock_path) end end def journal_values(value) raise GuideJournalProtocol::Refusal,'Saved/fingerprint values must be exact strings' unless value.is_a?(Hash)&&value.all?{|name,item|name.is_a?(String)&&item.is_a?(String)} value.transform_values(&:dup) end def journal_acknowledge(job,step,saved);job.acknowledge(step,journal_values(saved));end def journal_acknowledged(job,step);job.acknowledged(step);end def journal_begin(job,step,method,path,request_fingerprint);job.begin_action(step,method,path,request_fingerprint);end def journal_fingerprint(value);GuideJournalProtocol.fingerprint(journal_values(value));end def journal_saved(job,step);job.saved(step);end def not_value(value) raise "Expected a Boolean" unless value==true || value==false !value end def open_journal(path,base,workspace,slug,job,input_fingerprint,writes,mode);GuideJournal.new(path,base,workspace,slug,job,input_fingerprint,writes,mode);end def optional(name,fallback) value=ENV[name] value.nil? || value.empty? ? fallback : value end def positive_id(value) raise "Use a positive record ID" unless /\A[1-9][0-9]*\z/.match?(value) && Integer(value)<=9223372036854775807 value end def print_value(value) STDOUT.binmode.write((value.is_a?(String)?value:JSON.generate(value))+"\n") end def require_condition(value,message) raise message unless value==true end def required(name) value=ENV[name] raise "Set #{name}" if value.nil? || value.strip.empty? value end def response_status(value);value.fetch(:status).to_s;end def text(value) return "" if value.nil? return value.to_s if value.is_a?(String)||value.is_a?(Integer)||value==true||value==false raise "Expected a scalar response value" end def main inventory_asset_id = positive_id(required('EXHIBITDAY_ASSET_ID')) inventory_location_id = positive_id(required('EXHIBITDAY_STORAGE_LOCATION_ID')) inventory_journal_path = required('EXHIBITDAY_JOURNAL') inventory_job_id = required('EXHIBITDAY_JOB_ID') inventory_job_mode = optional('EXHIBITDAY_JOB_MODE', 'resume') require_condition(either(equal(inventory_job_mode, 'new'), equal(inventory_job_mode, 'resume')), 'Use exact new or resume for EXHIBITDAY_JOB_MODE.') inventory_received = bounded_whole_number(required('EXHIBITDAY_RECEIVED_QUANTITY'), 'EXHIBITDAY_RECEIVED_QUANTITY', '2147483647') require_condition(not_value(equal(inventory_received, '0')), 'EXHIBITDAY_RECEIVED_QUANTITY must be greater than zero.') inventory_recount = optional('EXHIBITDAY_RECOUNT_QUANTITY', '') inventory_expected = inventory_received if not_value(equal(inventory_recount, '')) inventory_recount = bounded_whole_number(inventory_recount, 'EXHIBITDAY_RECOUNT_QUANTITY', '2147483647') require_condition(not_value(equal(inventory_recount, '0')), 'EXHIBITDAY_RECOUNT_QUANTITY must be greater than zero.') inventory_expected = inventory_recount end inventory_workspace_response = call('workspace_binding', {}, nil, nil) require_condition(equal(response_status(inventory_workspace_response), '200'), 'Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.') inventory_workspace = inventory_workspace_response.fetch(:body) inventory_workspace_id = positive_id(text(field(inventory_workspace, 'id'))) inventory_input_fingerprint = journal_fingerprint({'workflow_contract_sha256' => 'F9CCD36E69D6E5A76E22B460D9FB853A89937E942238AAD7DF5A63BE8EA9F49D', 'asset_id' => inventory_asset_id, 'storage_location_id' => inventory_location_id, 'create_quantity' => inventory_received, 'correct_quantity' => inventory_recount}) inventory_job = open_journal(inventory_journal_path, 'https://api.exhibitday.com/v1', inventory_workspace_id, 'collateral-inventory-storage', inventory_job_id, inventory_input_fingerprint, [['create_adjustment', 'POST', '/v1/assets/inventory_adjustments'], ['correct_count', 'PATCH', '/v1/assets/inventory_adjustments']], inventory_job_mode) begin require_condition(either(not_value(journal_acknowledged(inventory_job, 'correct_count')), journal_acknowledged(inventory_job, 'create_adjustment')), 'A correction is acknowledged before its create. Stop and reconcile the journal.') require_condition(either(not_value(journal_acknowledged(inventory_job, 'correct_count')), not_value(equal(inventory_recount, ''))), 'This journal records a correction without a recount quantity. Stop and reconcile.') inventory_adjustment_id = '' if journal_acknowledged(inventory_job, 'create_adjustment') inventory_created_saved = journal_saved(inventory_job, 'create_adjustment') inventory_adjustment_id = positive_id(text(field(inventory_created_saved, 'id'))) require_condition(both(equal(text(field(inventory_created_saved, 'asset_id')), inventory_asset_id), equal(text(field(inventory_created_saved, 'storage_location_id')), inventory_location_id)), 'The saved adjustment belongs to different inventory or storage; do not create a replacement.') else inventory_create_fingerprint = journal_fingerprint({'asset_id' => inventory_asset_id, 'storage_location_id' => inventory_location_id, 'quantity' => inventory_received, 'is_increase' => 'true', 'description' => 'Brochures received for Annual Expo'}) inventory_create_intent = journal_begin(inventory_job, 'create_adjustment', 'POST', '/v1/assets/inventory_adjustments', inventory_create_fingerprint) inventory_create_response = call('create_adjustment', {}, {'asset_id' => inventory_asset_id, 'storage_location_id' => inventory_location_id, 'quantity' => inventory_received, 'is_increase' => true, 'description' => 'Brochures received for Annual Expo'}, text(field(inventory_create_intent, 'idempotency_key'))) require_condition(equal(response_status(inventory_create_response), '200'), 'Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.') inventory_created = inventory_create_response.fetch(:body) inventory_adjustment_id = positive_id(text(field(inventory_created, 'id'))) require_condition(both(both(equal(text(field(inventory_created, 'id')), inventory_adjustment_id), equal(text(field(inventory_created, 'asset_id')), inventory_asset_id)), both(equal(text(field(inventory_created, 'storage_location_id')), inventory_location_id), both(both(equal(text(field(inventory_created, 'quantity_adjustment')), inventory_received), equal(text(field(inventory_created, 'quantity')), inventory_received)), equal(field(inventory_created, 'is_increase'), true)))), 'The create acknowledgement differs from this item, location or stock increase. Keep pending state and reconcile.') journal_acknowledge(inventory_job, 'create_adjustment', {'id' => inventory_adjustment_id, 'asset_id' => inventory_asset_id, 'storage_location_id' => inventory_location_id}) end if not_value(equal(inventory_recount, '')) inventory_read_response = call('read_adjustment', {'id' => inventory_adjustment_id, '$include_record_revision' => 'true'}, nil, nil) require_condition(equal(response_status(inventory_read_response), '200'), 'Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.') inventory_current = inventory_read_response.fetch(:body) if journal_acknowledged(inventory_job, 'correct_count') inventory_corrected_saved = journal_saved(inventory_job, 'correct_count') require_condition(both(equal(text(field(inventory_corrected_saved, 'id')), inventory_adjustment_id), both(equal(text(field(inventory_corrected_saved, 'asset_id')), inventory_asset_id), both(equal(text(field(inventory_corrected_saved, 'storage_location_id')), inventory_location_id), equal(text(field(inventory_corrected_saved, 'quantity')), inventory_recount)))), 'The acknowledged correction differs from this record or quantity; stop and reconcile.') require_condition(both(both(equal(text(field(inventory_current, 'id')), inventory_adjustment_id), equal(text(field(inventory_current, 'asset_id')), inventory_asset_id)), both(equal(text(field(inventory_current, 'storage_location_id')), inventory_location_id), both(both(equal(text(field(inventory_current, 'quantity_adjustment')), inventory_recount), equal(text(field(inventory_current, 'quantity')), inventory_recount)), equal(field(inventory_current, 'is_increase'), true)))), 'The acknowledged adjustment is now missing, rebound or changed; do not silently restore it.') else require_condition(both(both(equal(text(field(inventory_current, 'id')), inventory_adjustment_id), equal(text(field(inventory_current, 'asset_id')), inventory_asset_id)), both(equal(text(field(inventory_current, 'storage_location_id')), inventory_location_id), both(both(equal(text(field(inventory_current, 'quantity_adjustment')), inventory_received), equal(text(field(inventory_current, 'quantity')), inventory_received)), equal(field(inventory_current, 'is_increase'), true)))), 'The saved adjustment is no longer the expected stock increase. Review it before any correction.') inventory_revision = text(field(inventory_current, 'record_revision')) require_condition(is_present(inventory_revision), 'The inventory read must return its actual record_revision before correction.') inventory_patch = {'id' => inventory_adjustment_id, 'quantity' => inventory_recount, 'expected_revision' => inventory_revision} inventory_patch_fingerprint = journal_fingerprint({'id' => inventory_adjustment_id, 'quantity' => inventory_recount, 'expected_revision' => inventory_revision}) journal_begin(inventory_job, 'correct_count', 'PATCH', '/v1/assets/inventory_adjustments', inventory_patch_fingerprint) inventory_patch_response = call('correct_count', {}, inventory_patch, nil) require_condition(equal(response_status(inventory_patch_response), '200'), 'Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.') inventory_patch_receipt = inventory_patch_response.fetch(:body) inventory_after_revision = text(field(inventory_patch_receipt, 'record_revision')) require_condition(is_present(inventory_after_revision), 'A checked correction acknowledgement requires its returned record_revision.') journal_acknowledge(inventory_job, 'correct_count', {'id' => inventory_adjustment_id, 'asset_id' => inventory_asset_id, 'storage_location_id' => inventory_location_id, 'quantity' => inventory_recount, 'record_revision' => inventory_after_revision}) end end inventory_verify_response = call('verify_adjustment', {'id' => inventory_adjustment_id}, nil, nil) require_condition(equal(response_status(inventory_verify_response), '200'), 'Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.') inventory_verified = inventory_verify_response.fetch(:body) require_condition(both(both(equal(text(field(inventory_verified, 'id')), inventory_adjustment_id), equal(text(field(inventory_verified, 'asset_id')), inventory_asset_id)), both(equal(text(field(inventory_verified, 'storage_location_id')), inventory_location_id), both(both(equal(text(field(inventory_verified, 'quantity_adjustment')), inventory_expected), equal(text(field(inventory_verified, 'quantity')), inventory_expected)), equal(field(inventory_verified, 'is_increase'), true)))), 'The final adjustment does not match the acknowledged record, location and stock increase. Reconcile; do not add another adjustment or undo it automatically.') print_value({'id' => inventory_adjustment_id, 'asset_id' => inventory_asset_id, 'storage_location_id' => inventory_location_id, 'quantity' => inventory_expected}) ensure inventory_job.close() end end main if $PROGRAM_NAME == __FILE__ ``` ```go // Go 1.18+; standard library only. Set EXHIBITDAY_API_KEY. package main import ( "bytes" "crypto/rand" "crypto/sha256" "encoding/hex" "regexp" "sort" "unicode/utf8" "encoding/json" "fmt" "io" "net/http" "net/url" "os" "strconv" "strings" "time" ) const base = "https://api.exhibitday.com/v1" const specification = "{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"create_adjustment\":{\"method\":\"POST\",\"path\":\"/assets/inventory_adjustments\"},\"read_adjustment\":{\"method\":\"GET\",\"path\":\"/assets/inventory_adjustments/info\"},\"correct_count\":{\"method\":\"PATCH\",\"path\":\"/assets/inventory_adjustments\"},\"verify_adjustment\":{\"method\":\"GET\",\"path\":\"/assets/inventory_adjustments/info\"}}}" 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 }} var send = client.Do type result struct { status int; body any; headers http.Header; raw []byte } // 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 call(name string, query map[string]string, body any, key string) result { route := object(object(spec["requests"])[name]); method := text(route["method"]) headers := map[string]string{"Authorization": "Bearer " + apiKey, "Accept": "application/json"} if method == "POST" { if key == "" { panic("Persist a logical create key before sending POST") }; 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() } // 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 := method == "GET" 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 := send(request) if err != nil { if !resend { panic(apiError{0, "", "No response", true}) }; if attempt == 4 { panic(err) }; time.Sleep(time.Second*time.Duration(1<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 := resend && (response.StatusCode == 429 || response.StatusCode >= 500) if retry { if attempt == 4 { panic("Retry limit reached; check the outcome before starting a new create") } seconds := float64(int64(1)<= 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, raw} } panic("Retry limit reached") } func both(left,right bool)bool{return left&&right} func bounded_whole_number(value,name,maximum string)string{valid:=len(value)>0&&(len(value)==1||value[0]!='0');for _,ch:=range value{valid=valid&&ch>='0'&&ch<='9'};if !valid||len(value)>len(maximum)||(len(value)==len(maximum)&&value>maximum){panic(name+" must be a whole number from 0 through "+maximum)};return value} func either(left,right bool)bool{return left||right} func equal(left,right any)bool{switch a:=left.(type){case string:b,ok:=right.(string);return ok&&a==b;case bool:b,ok:=right.(bool);return ok&&a==b;case int64:b,ok:=right.(int64);return ok&&a==b};return left==nil&&right==nil} func field(value any,name string)any{obj,ok:=value.(map[string]any);if !ok{panic("Missing response object")};item,found:=obj[name];if !found{panic("Missing response field: "+name)};return item} func is_present(value string)bool{return value!=""} // Private client restart state only; no API transport or workflow interpreter. const journalPreamble = "EXHIBITDAY-GUIDE-JOURNAL 1\n" type journalRefusal struct{ message string } func (e journalRefusal) Error() string { return e.message } func journalNeed(ok bool, message string) { if !ok { panic(journalRefusal{message}) } } func journalMatch(value, pattern string) bool { return regexp.MustCompile("\\A(?:"+pattern+")\\z").MatchString(value) } func journalStrings(values []string) []byte { var output bytes.Buffer for _,value:=range values { journalNeed(utf8.ValidString(value),"Journal fields must be valid UTF8 strings"); output.WriteString(strconv.Itoa(len(value))+":");output.WriteString(value) } return output.Bytes() } func journalReadStrings(raw []byte) []string { values:=[]string{};offset:=0 for offset=0,"Incomplete journal string length");end:=offset+relative;text:=string(raw[offset:end]);journalNeed(journalMatch(text,"0|[1-9][0-9]*"),"Noncanonical journal string length");size,err:=strconv.ParseUint(text,10,64);offset=end+1;journalNeed(err==nil&&size<=uint64(len(raw)-offset),"Incomplete journal string");count:=int(size);value:=string(raw[offset:offset+count]);journalNeed(utf8.ValidString(value),"Invalid UTF8 journal field");values=append(values,value);offset+=count } return values } func journalDigest(raw []byte) string { hash:=sha256.Sum256(raw);return strings.ToUpper(hex.EncodeToString(hash[:])) } func journalFingerprint(pairs map[string]string) string { names:=make([]string,0,len(pairs));for name:=range pairs { names=append(names,name) };sort.Strings(names);values:=[]string{} for _,name:=range names { lower:=strings.ToLower(name);journalNeed(journalMatch(name,"[A-Za-z0-9_.-]+")&&lower!="api_key"&&lower!="exhibitday_api_key","Use explicit secret-free fingerprint names");values=append(values,name,pairs[name]) } return journalDigest(journalStrings(values)) } func journalFrame(values []string) []byte { raw:=journalStrings(values);header:=[]byte(strconv.Itoa(len(raw))+" "+journalDigest(raw)+"\n");result:=append(header,raw...);return append(result,'\n') } func journalDecode(raw []byte) [][]string { journalNeed(bytes.HasPrefix(raw,[]byte(journalPreamble)),"Unknown or incomplete journal version");offset:=len(journalPreamble);records:=[][]string{} for offset=0,"Incomplete frame header; reconcile before retry");end:=offset+relative;header:=string(raw[offset:end]);journalNeed(journalMatch(header,"(0|[1-9][0-9]*) [0-9A-F]{64}"),"Invalid frame header");fields:=strings.Split(header," ");size,err:=strconv.ParseUint(fields[0],10,64);offset=end+1;journalNeed(err==nil&&size0 { count,err:=file.Write(raw);if err!=nil{return err};if count<=0{return io.ErrShortWrite};raw=raw[count:] } return file.Sync() } func journalWriteFile(path string,flags int,raw []byte) (err error) { file,err:=os.OpenFile(path,flags,0600);if err!=nil{return err};defer func(){closed:=file.Close();if err==nil{err=closed}}();return journalWriteAll(file,raw) } func journalCopy(source map[string]string) map[string]string { copy:=map[string]string{};for name,value:=range source{copy[name]=value};return copy } func journalCopyStates(source map[string]map[string]string) map[string]map[string]string { copy:=map[string]map[string]string{};for name,value:=range source{copy[name]=journalCopy(value)};return copy } type guideJournal struct { path,lockPath,owner string header []string allowed map[string][2]string intents,savedValues map[string]map[string]string file *os.File identity os.FileInfo owned,tainted bool } func openGuideJournal(path,base,workspace,slug,job,inputFingerprint string,writes [][3]string,modes ...string) (result *guideJournal) { mode:="resume";journalNeed(len(modes)<=1,"Choose one local job mode");if len(modes)==1{mode=modes[0]};journalNeed(mode=="new"||mode=="resume","Choose new or resume for this local job") address,err:=url.Parse(base);journalNeed(err==nil&&address.Hostname()!=""&&(address.Scheme=="https"||address.Scheme=="http")&&address.User==nil&&address.RawQuery==""&&address.Fragment==""&&journalMatch(slug,"[a-z][a-z0-9-]*"),"Use actual API base and closed guide slug") journalNeed(strings.TrimSpace(job)!=""&&journalMatch(workspace,"[1-9][0-9]*")&&journalMatch(inputFingerprint,"[0-9A-F]{64}"),"Use actual workspace, stable explicit job ID and exact fingerprint") j:=&guideJournal{path:path,lockPath:path+".lock",allowed:map[string][2]string{},intents:map[string]map[string]string{},savedValues:map[string]map[string]string{}} manifest:=[]string{};for _,write:=range writes { step,method,route:=write[0],write[1],write[2];_,exists:=j.allowed[step];journalNeed(journalMatch(step,"[a-z][a-z0-9_-]*")&&!exists&&(method=="POST"||method=="PATCH"||method=="DELETE")&&journalMatch(route,"/v1/[A-Za-z0-9_/-]+")&&!strings.Contains(route,"//"),"Use a closed unique write manifest");j.allowed[step]=[2]string{method,route};manifest=append(manifest,step,method,route) } journalNeed(len(j.allowed)>0,"Only write workflows need a restart journal");j.header=[]string{"H","1",base,workspace,slug,job,inputFingerprint,journalDigest(journalStrings(manifest))};journalStrings(j.header) j.file,err=os.OpenFile(j.lockPath,os.O_RDWR|os.O_CREATE|os.O_EXCL,0600);if err!=nil { if os.IsExist(err){panic(journalRefusal{"This journal is locked; do not overlap jobs or steal a stale lock"})};panic(err) };j.owned=true defer func(){ if observed:=recover();observed!=nil { j.Close();panic(observed) } }() random:=make([]byte,16);if _,err=io.ReadFull(rand.Reader,random);err!=nil{panic(err)};j.owner=hex.EncodeToString(random);if err=journalWriteAll(j.file,[]byte(j.owner));err!=nil{panic(err)};j.identity,err=j.file.Stat();if err!=nil{panic(err)} info,err:=os.Lstat(path);if err!=nil&&!os.IsNotExist(err){panic(err)};exists:=err==nil;if exists{journalNeed(info.Mode()&os.ModeSymlink==0,"Choose a private regular journal file")};journalNeed(mode!="resume"||exists,"Journal missing: stop and reconcile lost state before starting a new logical job");journalNeed(mode!="new"||!exists,"Journal exists; use resume for the same logical job");if mode=="new"{raw:=append([]byte(journalPreamble),journalFrame(j.header)...);if err=journalWriteFile(path,os.O_WRONLY|os.O_CREATE|os.O_EXCL,raw);err!=nil{panic(err)}} raw,err:=os.ReadFile(path);if err!=nil{panic(err)};records:=journalDecode(raw);journalNeed(len(records)>0&&stringsEqual(records[0],j.header),"Journal workspace/base/guide/job/input binding differs");for _,record:=range records[1:]{j.apply(record)};for step:=range j.intents{_,ok:=j.savedValues[step];journalNeed(ok,"Saved intent lacks ACK; stop and reconcile before retry")};return j } func stringsEqual(left,right []string) bool { if len(left)!=len(right){return false};for i,value:=range left{if value!=right[i]{return false}};return true } func (j *guideJournal) apply(record []string) { journalNeed(len(record)>0,"Empty journal record") if record[0]=="I" { journalNeed(len(record)==6,"Invalid intent shape");step,method,route,fingerprint,key:=record[1],record[2],record[3],record[4],record[5];_,exists:=j.intents[step];expected,allowed:=j.allowed[step];pending:=false;for name:=range j.intents{if _,ok:=j.savedValues[name];!ok{pending=true}} journalNeed(journalMatch(step,"[a-z][a-z0-9_-]*")&&!exists&&allowed&&expected==[2]string{method,route}&&journalMatch(fingerprint,"[0-9A-F]{64}")&&!pending,"Invalid, future or repeated intent");journalNeed(method=="POST"&&journalMatch(key,"[0-9a-f]{32}")||method!="POST"&&key=="","Invalid persisted action key");j.intents[step]=map[string]string{"method":method,"path":route,"request_fingerprint":fingerprint,"idempotency_key":key} }else if record[0]=="A" { journalNeed(len(record)>=3,"Invalid ACK shape");step,text:=record[1],record[2];count,err:=strconv.ParseUint(text,10,64);_,prior:=j.intents[step];_,done:=j.savedValues[step];journalNeed(journalMatch(text,"0|[1-9][0-9]*")&&err==nil&&len(record)%2==1&&count==uint64((len(record)-3)/2)&&prior&&!done,"ACK without exactly one prior intent");names:=[]string{};for i:=3;i0&&value[0]!='0';for _,ch:=range value{valid=valid&&ch>='0'&&ch<='9'};id,err:=strconv.ParseInt(value,10,64);if !valid||err!=nil||id<=0{panic("Use a positive record ID")};return value} func print_value(value any){if result,ok:=value.(string);ok{fmt.Println(result);return};raw,err:=json.Marshal(value);if err!=nil{panic(err)};fmt.Println(string(raw))} func require_condition(value bool,message string){if !value{panic(message)}} func response_status(value result)string{return strconv.Itoa(value.status)} func workflow() { inventory_asset_id := positive_id(required("EXHIBITDAY_ASSET_ID")) inventory_location_id := positive_id(required("EXHIBITDAY_STORAGE_LOCATION_ID")) inventory_journal_path := required("EXHIBITDAY_JOURNAL") inventory_job_id := required("EXHIBITDAY_JOB_ID") inventory_job_mode := optional("EXHIBITDAY_JOB_MODE", "resume") require_condition(either(equal(inventory_job_mode, "new"), equal(inventory_job_mode, "resume")), "Use exact new or resume for EXHIBITDAY_JOB_MODE.") inventory_received := bounded_whole_number(required("EXHIBITDAY_RECEIVED_QUANTITY"), "EXHIBITDAY_RECEIVED_QUANTITY", "2147483647") require_condition(not_value(equal(inventory_received, "0")), "EXHIBITDAY_RECEIVED_QUANTITY must be greater than zero.") inventory_recount := optional("EXHIBITDAY_RECOUNT_QUANTITY", "") inventory_expected := inventory_received if not_value(equal(inventory_recount, "")) { inventory_recount = bounded_whole_number(inventory_recount, "EXHIBITDAY_RECOUNT_QUANTITY", "2147483647") require_condition(not_value(equal(inventory_recount, "0")), "EXHIBITDAY_RECOUNT_QUANTITY must be greater than zero.") inventory_expected = inventory_recount } inventory_workspace_response := call("workspace_binding", map[string]string{}, nil, "") require_condition(equal(response_status(inventory_workspace_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") inventory_workspace := inventory_workspace_response.body inventory_workspace_id := positive_id(text(field(inventory_workspace, "id"))) inventory_input_fingerprint := journal_fingerprint(map[string]any{"workflow_contract_sha256": "F9CCD36E69D6E5A76E22B460D9FB853A89937E942238AAD7DF5A63BE8EA9F49D", "asset_id": inventory_asset_id, "storage_location_id": inventory_location_id, "create_quantity": inventory_received, "correct_quantity": inventory_recount}) func() { inventory_job := open_journal(inventory_journal_path, "https://api.exhibitday.com/v1", inventory_workspace_id, "collateral-inventory-storage", inventory_job_id, inventory_input_fingerprint, []any{[]any{"create_adjustment", "POST", "/v1/assets/inventory_adjustments"}, []any{"correct_count", "PATCH", "/v1/assets/inventory_adjustments"}}, inventory_job_mode) defer inventory_job.Close() require_condition(either(not_value(journal_acknowledged(inventory_job, "correct_count")), journal_acknowledged(inventory_job, "create_adjustment")), "A correction is acknowledged before its create. Stop and reconcile the journal.") require_condition(either(not_value(journal_acknowledged(inventory_job, "correct_count")), not_value(equal(inventory_recount, ""))), "This journal records a correction without a recount quantity. Stop and reconcile.") inventory_adjustment_id := "" if journal_acknowledged(inventory_job, "create_adjustment") { inventory_created_saved := journal_saved(inventory_job, "create_adjustment") inventory_adjustment_id = positive_id(text(field(inventory_created_saved, "id"))) require_condition(both(equal(text(field(inventory_created_saved, "asset_id")), inventory_asset_id), equal(text(field(inventory_created_saved, "storage_location_id")), inventory_location_id)), "The saved adjustment belongs to different inventory or storage; do not create a replacement.") } else { inventory_create_fingerprint := journal_fingerprint(map[string]any{"asset_id": inventory_asset_id, "storage_location_id": inventory_location_id, "quantity": inventory_received, "is_increase": "true", "description": "Brochures received for Annual Expo"}) inventory_create_intent := journal_begin(inventory_job, "create_adjustment", "POST", "/v1/assets/inventory_adjustments", inventory_create_fingerprint) inventory_create_response := call("create_adjustment", map[string]string{}, map[string]any{"asset_id": inventory_asset_id, "storage_location_id": inventory_location_id, "quantity": inventory_received, "is_increase": true, "description": "Brochures received for Annual Expo"}, text(field(inventory_create_intent, "idempotency_key"))) require_condition(equal(response_status(inventory_create_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") inventory_created := inventory_create_response.body inventory_adjustment_id = positive_id(text(field(inventory_created, "id"))) require_condition(both(both(equal(text(field(inventory_created, "id")), inventory_adjustment_id), equal(text(field(inventory_created, "asset_id")), inventory_asset_id)), both(equal(text(field(inventory_created, "storage_location_id")), inventory_location_id), both(both(equal(text(field(inventory_created, "quantity_adjustment")), inventory_received), equal(text(field(inventory_created, "quantity")), inventory_received)), equal(field(inventory_created, "is_increase"), true)))), "The create acknowledgement differs from this item, location or stock increase. Keep pending state and reconcile.") journal_acknowledge(inventory_job, "create_adjustment", map[string]any{"id": inventory_adjustment_id, "asset_id": inventory_asset_id, "storage_location_id": inventory_location_id}) } if not_value(equal(inventory_recount, "")) { inventory_read_response := call("read_adjustment", map[string]string{"id": inventory_adjustment_id, "$include_record_revision": "true"}, nil, "") require_condition(equal(response_status(inventory_read_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") inventory_current := inventory_read_response.body if journal_acknowledged(inventory_job, "correct_count") { inventory_corrected_saved := journal_saved(inventory_job, "correct_count") require_condition(both(equal(text(field(inventory_corrected_saved, "id")), inventory_adjustment_id), both(equal(text(field(inventory_corrected_saved, "asset_id")), inventory_asset_id), both(equal(text(field(inventory_corrected_saved, "storage_location_id")), inventory_location_id), equal(text(field(inventory_corrected_saved, "quantity")), inventory_recount)))), "The acknowledged correction differs from this record or quantity; stop and reconcile.") require_condition(both(both(equal(text(field(inventory_current, "id")), inventory_adjustment_id), equal(text(field(inventory_current, "asset_id")), inventory_asset_id)), both(equal(text(field(inventory_current, "storage_location_id")), inventory_location_id), both(both(equal(text(field(inventory_current, "quantity_adjustment")), inventory_recount), equal(text(field(inventory_current, "quantity")), inventory_recount)), equal(field(inventory_current, "is_increase"), true)))), "The acknowledged adjustment is now missing, rebound or changed; do not silently restore it.") } else { require_condition(both(both(equal(text(field(inventory_current, "id")), inventory_adjustment_id), equal(text(field(inventory_current, "asset_id")), inventory_asset_id)), both(equal(text(field(inventory_current, "storage_location_id")), inventory_location_id), both(both(equal(text(field(inventory_current, "quantity_adjustment")), inventory_received), equal(text(field(inventory_current, "quantity")), inventory_received)), equal(field(inventory_current, "is_increase"), true)))), "The saved adjustment is no longer the expected stock increase. Review it before any correction.") inventory_revision := text(field(inventory_current, "record_revision")) require_condition(is_present(inventory_revision), "The inventory read must return its actual record_revision before correction.") inventory_patch := map[string]any{"id": inventory_adjustment_id, "quantity": inventory_recount, "expected_revision": inventory_revision} inventory_patch_fingerprint := journal_fingerprint(map[string]any{"id": inventory_adjustment_id, "quantity": inventory_recount, "expected_revision": inventory_revision}) journal_begin(inventory_job, "correct_count", "PATCH", "/v1/assets/inventory_adjustments", inventory_patch_fingerprint) inventory_patch_response := call("correct_count", map[string]string{}, inventory_patch, "") require_condition(equal(response_status(inventory_patch_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") inventory_patch_receipt := inventory_patch_response.body inventory_after_revision := text(field(inventory_patch_receipt, "record_revision")) require_condition(is_present(inventory_after_revision), "A checked correction acknowledgement requires its returned record_revision.") journal_acknowledge(inventory_job, "correct_count", map[string]any{"id": inventory_adjustment_id, "asset_id": inventory_asset_id, "storage_location_id": inventory_location_id, "quantity": inventory_recount, "record_revision": inventory_after_revision}) } } inventory_verify_response := call("verify_adjustment", map[string]string{"id": inventory_adjustment_id}, nil, "") require_condition(equal(response_status(inventory_verify_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.") inventory_verified := inventory_verify_response.body require_condition(both(both(equal(text(field(inventory_verified, "id")), inventory_adjustment_id), equal(text(field(inventory_verified, "asset_id")), inventory_asset_id)), both(equal(text(field(inventory_verified, "storage_location_id")), inventory_location_id), both(both(equal(text(field(inventory_verified, "quantity_adjustment")), inventory_expected), equal(text(field(inventory_verified, "quantity")), inventory_expected)), equal(field(inventory_verified, "is_increase"), true)))), "The final adjustment does not match the acknowledged record, location and stock increase. Reconcile; do not add another adjustment or undo it automatically.") print_value(map[string]any{"id": inventory_adjustment_id, "asset_id": inventory_asset_id, "storage_location_id": inventory_location_id, "quantity": inventory_expected}) }() } func header_key(value string)string{for _,ch:=range value{if ch<32||ch>126{panic("Use the API key as one ASCII header value without control characters")}};return value} func main(){apiKey=header_key(required("EXHIBITDAY_API_KEY"));if err:=json.Unmarshal([]byte(specification),&spec);err!=nil{panic(err)};workflow()} ``` #### Example response Response 200 — OK 304 — Not Modified 400 — Bad Request 401 — Unauthorized 404 — Not Found 409 — Conflict 429 — Too Many Requests 500 — Internal Server Error Example Successful request ```json { "id": 3456, "asset_id": 1234, "asset_name": "Annual Expo brochures", "storage_location_id": 2345, "storage_location_name": "Main Storage", "effective_date": "2030-01-02", "return_date": null, "quantity_adjustment": 118, "quantity": 118, "is_increase": true, "is_quantity_editable": true, "description": "Brochures received for Annual Expo", "shipping_logistics_id": 1, "is_flagged": false, "is_starred": false, "is_checked": false, "inventory_adjustment_created_timestamp": "2030-01-02T12:00:00Z" } ``` Note: The adjustment as read after the correction. It increases stock by 118 instead of 120. Use availability to check the stock balance. Note: There is no response body. Keep using your cached response. ```json { "status_code": 400, "status": "Bad Request", "message": "HTTP method override is not supported.", "error_code": "invalid_request", "errors": [ "Send the documented HTTP method directly. X-HTTP-Method-Override cannot change a request's HTTP method." ], "error_params": [ "X-HTTP-Method-Override" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "No API key was provided. Send your key in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "missing_api_key", "errors": [ "Copy the key from Workspace Settings > API & Integrations > API Access in ExhibitDay." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "The API key is not valid. Check that you copied the whole key from Workspace Settings > API & Integrations > API Access, then send it in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "invalid_api_key", "errors": [ "Check that you sent the whole key. If it was regenerated, use the current key from Workspace Settings > API & Integrations > API Access." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "Access to the ExhibitDay API is not enabled for your workspace. Please contact support@exhibitday.com to enable API Access. Once access is enabled, send your key in the Authorization header as 'Bearer YOUR_API_KEY'.", "error_code": "api_access_disabled", "errors": [ "Nothing was read or changed." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 404, "status": "Not Found", "message": "Inventory Adjustment not found. Invalid Inventory Adjustment ID: 12345.", "error_code": "not_found", "errors": [ "Inventory Adjustment not found. Invalid Inventory Adjustment ID: 12345." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "Inventory could not be read while it changed; read again.", "error_code": "record_changed", "errors": [ "No data was changed by this read." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 429, "status": "Too Many Requests", "message": "Error 429 - Too Many Requests", "error_code": "rate_limited", "errors": [ "Error 429 - Too Many Requests" ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "An unexpected error occurred. Please try again later." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` Note: Use the request_id from your own response when contacting support. ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "Check whether your change was saved before trying again." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` #### Things to keep in mind - The create uses today's date in the workspace time zone. To use a different date, review the POST date options and supply `effective_date`. The correction leaves the saved date in place. - New manual adjustments have no scheduled reversal. A PATCH that changes an older adjustment clears its scheduled reversal. An unchanged adjustment keeps it. Check the saved return date before correcting an older adjustment. - Use [Asset availability](https://api.exhibitday.com/Help/V1?epf=5&topic=availability#get-v1-assets-availability) for a dated stock balance and [Collateral transactions](https://api.exhibitday.com/Help/V1?epf=5&topic=storage-locations#get-v1-assets-storage_locations-collateral_transactions) for the supporting movements. Read every page you need. Inventory can be negative. - To delete an adjustment only if no one has changed it since your read, send its `record_revision` as `expected_revision` with [the DELETE request](https://api.exhibitday.com/Help/V1?epf=5&topic=inventory-adjustments#delete-v1-assets-inventory_adjustments). A changed adjustment returns HTTP 409 `record_changed` and nothing is deleted. - Creating or deleting a Storage Location is separate. When a location still holds Assets or inventory, review [the transfer options](https://api.exhibitday.com/Help/V1?epf=5&topic=storage-locations#delete-v1-assets-storage_locations) before deleting it. #### If a run stops - Keep the journal private. It records what the program tried to save and which save it confirmed. - To continue a run with no unresolved save, use `EXHIBITDAY_JOB_MODE=resume` with the same job ID, journal path and inputs. - Use the same quantities when resuming. A resumed run skips acknowledged writes and checks the same adjustment. - If a save stops with a lost response, check the saved adjustment and inventory in ExhibitDay before running the program again. - If you still need a change after checking the old run, use `EXHIBITDAY_JOB_MODE=new` with a new job ID and journal path. - Run only one copy per journal. - If a crash leaves a `.lock` file, make sure no copy using that journal is running or can start. Then remove the lock file and keep the journal. #### Related guides - [Avoid Overwriting Someone Else's Changes](https://api.exhibitday.com/Help/V1?guide=update-records-safely) - [Handle Errors and Retry Failed Requests](https://api.exhibitday.com/Help/V1?guide=errors-and-retries) ### Add Attendees and Their Travel Reservations to an Event Guide page: https://api.exhibitday.com/Help/V1?guide=staff-travel-tags Register a person for an Event and record their hotel, then list everything for that person. Example use case Your team books travel elsewhere and wants to track who is attending an Event and where they will stay. What you'll end up with A Staff registration and a Hotel reservation tagged to the same person. The program prints the two record IDs after verifying them. Before you start Have a workspace API key, an Event in that workspace and a current active member or Resource ID. The Staff and Travel tabs must be visible and editable to save these records. Good to know This records travel in ExhibitDay. You make the hotel booking separately. #### At a glance Time to try About 15 minutes Effect on your data Creates records Endpoints 8 The program creates a Staff registration and a Hotel reservation and writes a private local journal. - [`GET /v1/references/workspace_info`](https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-workspace_info) - [`GET /v1/events/info`](https://api.exhibitday.com/Help/V1?epf=1#get-v1-events-info) - [`GET /v1/references/users_and_resources`](https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-users_and_resources) - [`GET /v1/references/travel_reservation_types`](https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-travel_reservation_types) - [`GET /v1/events/staff`](https://api.exhibitday.com/Help/V1?epf=1&topic=staff#get-v1-events-staff) - [`POST /v1/events/staff`](https://api.exhibitday.com/Help/V1?epf=1&topic=staff#post-v1-events-staff) - [`POST /v1/events/travel_reservations`](https://api.exhibitday.com/Help/V1?epf=1&topic=travel-reservations#post-v1-events-travel_reservations) - [`GET /v1/events/travel_reservations`](https://api.exhibitday.com/Help/V1?epf=1&topic=travel-reservations#get-v1-events-travel_reservations) #### How it works 1. Choose the Event, person, hotel and local dates. The program checks the person and Hotel type. 2. It adds and verifies the Staff registration before recording the Hotel reservation. 3. It verifies the Hotel reservation and prints the two record IDs. #### Register the person and record the Hotel The examples below follow a person with no Staff registration for this Event. A resumed run skips creates it has already checked and saved in the journal. #### Step 1: Confirm the workspace Read the workspace summary so you know where the key can make changes. ```bash curl -X GET "https://api.exhibitday.com/v1/references/workspace_info" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "id": 98765 } ``` **Check:** Confirm id is the workspace you intend to use. #### Step 2: Confirm the Event Read the Event so you can confirm the destination for both records. ```bash curl -X GET "https://api.exhibitday.com/v1/events/info?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "id": 12345, "name": "Spring Expo 2030" } ``` **Check:** Confirm id and name identify the Event you want. #### Step 3: Find the person Read the workspace's people and Resources to find the person to register. ```bash curl -X GET "https://api.exhibitday.com/v1/references/users_and_resources" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "list_data": [ { "id": "f45d4ec2-6d33-4c86-a516-459d21060001" } ] } ``` **Check:** Use the selected id from list_data and keep the text exactly as returned. #### Step 4: Confirm the Hotel type Read the Travel types before using the Hotel choice. ```bash curl -X GET "https://api.exhibitday.com/v1/references/travel_reservation_types" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "list_data": [ { "id": 6, "name": "Hotel" } ] } ``` **Check:** Confirm the Hotel item in list_data has id 6. #### Step 5: Look for an existing registration Read all Staff pages for the Event and person to avoid a duplicate registration. ```bash curl -X GET "https://api.exhibitday.com/v1/events/staff?filter_by_event_id=12345&filter_by_attendee_user_ids=f45d4ec2-6d33-4c86-a516-459d21060001&%24limit=100&%24offset=0" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "records_found": 0, "total_records": 0, "has_more": false, "list_data": [] } ``` **Check:** This example has no matching Staff records. If you find one, review it before creating a registration. #### Step 6: Add the registration Create the Staff record when the person has no existing registration and the job has no saved acknowledgement. ```bash curl -X POST "https://api.exhibitday.com/v1/events/staff" -H "Authorization: Bearer YOUR_API_KEY" -H "Idempotency-Key: YOUR_PERSISTED_STAFF_KEY" -H "Content-Type: application/json" --data-binary "{\"event_id\":12345,\"attendee_user_id\":\"f45d4ec2-6d33-4c86-a516-459d21060001\",\"registration_type\":\"Conference pass\",\"notify_attendee\":false}" ``` Example response (shortened) ```json { "id": 2001, "event_id": 12345, "attendee": { "id": "f45d4ec2-6d33-4c86-a516-459d21060001", "first_name": "Alex", "last_name": "Morgan", "display_name": "Alex Morgan", "email": "alex.morgan@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true } } ``` **Check:** Keep the returned id and verify event_id and attendee.id. The record id is different from the person ID. #### Step 7: Verify the registration Read the filtered Staff list again before recording Travel. ```bash curl -X GET "https://api.exhibitday.com/v1/events/staff?filter_by_event_id=12345&filter_by_attendee_user_ids=f45d4ec2-6d33-4c86-a516-459d21060001&%24limit=100&%24offset=0" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_data": [ { "id": 2001, "event_id": 12345, "attendee": { "id": "f45d4ec2-6d33-4c86-a516-459d21060001", "first_name": "Alex", "last_name": "Morgan", "display_name": "Alex Morgan", "email": "alex.morgan@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true } } ] } ``` **Check:** Find the registration id just returned or already acknowledged by this job. #### Step 8: Record the Hotel and tag the traveler Save a separate Hotel reservation with the selected person tagged. ```bash curl -X POST "https://api.exhibitday.com/v1/events/travel_reservations" -H "Authorization: Bearer YOUR_API_KEY" -H "Idempotency-Key: YOUR_PERSISTED_TRAVEL_KEY" -H "Content-Type: application/json" --data-binary "{\"event_id\":12345,\"reservation_type_id\":6,\"origin_vendor_name\":\"Spring Expo Conference Hotel\",\"origin_checkin_date\":\"2030-01-14\",\"return_checkin_date\":\"2030-01-17\",\"tagged_user_ids\":[\"f45d4ec2-6d33-4c86-a516-459d21060001\"],\"notify_tagged_users\":false}" ``` Example response (shortened) ```json { "id": 3001, "event_id": 12345, "reservation_type_id": 6, "origin_vendor_name": "Spring Expo Conference Hotel", "origin_checkin_date": "2030-01-14", "return_checkin_date": "2030-01-17", "tagged_users": [ { "id": "f45d4ec2-6d33-4c86-a516-459d21060001", "first_name": "Alex", "last_name": "Morgan", "display_name": "Alex Morgan", "email": "alex@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true } ] } ``` **Check:** Keep the Travel id and check the Event, Hotel type, hotel name, dates and selected tag. #### Step 9: Verify the Hotel reservation Read all Travel pages for the Event and selected tag to confirm the reservation. ```bash curl -X GET "https://api.exhibitday.com/v1/events/travel_reservations?filter_by_event_id=12345&filter_by_tagged_user_ids=f45d4ec2-6d33-4c86-a516-459d21060001&filter_by_tagged_user_ids_match_type=all&%24limit=100&%24offset=0" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_data": [ { "id": 3001, "event_id": 12345, "reservation_type_id": 6, "origin_vendor_name": "Spring Expo Conference Hotel", "origin_checkin_date": "2030-01-14", "return_checkin_date": "2030-01-17", "tagged_users": [ { "id": "f45d4ec2-6d33-4c86-a516-459d21060001", "first_name": "Alex", "last_name": "Morgan", "display_name": "Alex Morgan", "email": "alex@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true } ] } ] } ``` **Check:** Find the Travel ID returned in Step 8 and verify the Hotel and its tag still match. **Careful.** A person or Resource can appear only once in an Event's Staff list. The program stops on an existing registration unless this same job already acknowledged it. After an uncertain response, review the Event and journal before sending another request. #### Defaults and tags | Option | What happens | | --- | --- | | Attendee role and attendance format | The program omits `attendee_role_id` and `attendance_format_id` to use the person's configured role and the workspace's attendance default. | | Hotel dates and booking status | Use local calendar dates. Omit `booking_status_id` for Not Specified. | | Notifications | The program sends `notify_attendee` and `notify_tagged_users` as false unless you opt in. The API defaults to true. New notifications depend on recipient eligibility and preferences. | | Changing tags later | Sending `tagged_user_ids` replaces the saved tags. Include everyone whose tag you want to keep. | | Other records with tags | Playbook activities and Misc. expenses & credits (`/v1/events/misc_expenses_credits`) take the same `tagged_user_ids` and `notify_tagged_users` fields, with the same rules. | #### Try it **Careful.** This example changes data in your workspace. Use a test Event. #### Before running the example | Variable | What to put in it | Required? | | --- | --- | --- | | `EXHIBITDAY_API_KEY` | Your workspace API key. | Yes | | `EXHIBITDAY_EVENT_ID` | The destination Event ID. | Yes | | `EXHIBITDAY_PERSON_ID` | The exact text ID from Users and Resources. | Yes | | `EXHIBITDAY_HOTEL_NAME` | A plain-text hotel name up to 125 UTF-16 code units, with no leading or trailing spaces. | Yes | | `EXHIBITDAY_CHECKIN_DATE` | The check-in date in YYYY-MM-DD format. | Yes | | `EXHIBITDAY_CHECKOUT_DATE` | The check-out date in YYYY-MM-DD format, on or after check-in. | Yes | | `EXHIBITDAY_JOB_ID` | A stable ID for this logical job. | Yes | | `EXHIBITDAY_JOURNAL` | A private local path for this job's journal. | Yes | | `EXHIBITDAY_JOB_MODE` | Use new for a new job. Use resume or omit it to continue the same job. | No | | `EXHIBITDAY_PAGE_SIZE` | Defaults to 100. | No | | `EXHIBITDAY_SEND_NOTIFICATIONS` | Defaults to false. Use true to allow eligible new notifications. | No | #### Bash ``` export EXHIBITDAY_API_KEY='YOUR_API_KEY' export EXHIBITDAY_EVENT_ID='12345' export EXHIBITDAY_PERSON_ID='YOUR_PERSON_ID' export EXHIBITDAY_HOTEL_NAME='Spring Expo Conference Hotel' export EXHIBITDAY_CHECKIN_DATE='2030-01-14' export EXHIBITDAY_CHECKOUT_DATE='2030-01-17' ``` #### PowerShell ``` $env:EXHIBITDAY_API_KEY = 'YOUR_API_KEY' $env:EXHIBITDAY_EVENT_ID = '12345' $env:EXHIBITDAY_PERSON_ID = 'YOUR_PERSON_ID' $env:EXHIBITDAY_HOTEL_NAME = 'Spring Expo Conference Hotel' $env:EXHIBITDAY_CHECKIN_DATE = '2030-01-14' $env:EXHIBITDAY_CHECKOUT_DATE = '2030-01-17' ``` Use your own Event and person IDs, hotel and dates. Set a private journal path and job ID. Set `EXHIBITDAY_JOB_MODE=new` for a new job. Then copy the complete example program below in your language and run it. #### Complete example program Code Samples ```bash #!/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\"},\"people_choices\":{\"method\":\"GET\",\"path\":\"/references/users_and_resources\"},\"travel_choices\":{\"method\":\"GET\",\"path\":\"/references/travel_reservation_types\"},\"event_before\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"find_staff\":{\"method\":\"GET\",\"path\":\"/events/staff\"},\"create_staff\":{\"method\":\"POST\",\"path\":\"/events/staff\"},\"create_travel\":{\"method\":\"POST\",\"path\":\"/events/travel_reservations\"},\"staff_readback\":{\"method\":\"GET\",\"path\":\"/events/staff\"},\"travel_readback\":{\"method\":\"GET\",\"path\":\"/events/travel_reservations\"}}}") API_KEY = os.environ["EXHIBITDAY_API_KEY"] if any(ord(char) < 32 or ord(char) > 126 for char in API_KEY): raise RuntimeError("Use the API key as one ASCII header value without control characters") if not API_KEY.strip(): raise RuntimeError("Set EXHIBITDAY_API_KEY") def decode_json(text): if SPEC["preserveNumbers"]: # Quote JSON NUMBER tokens, never text inside a JSON string, to keep CSV decimals exact. text = re.sub(r'"(?:\\.|[^"\\])*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?', lambda m: m[0] if m[0].startswith('"') else json.dumps(m[0]), text) return json.loads(text) from pathlib import Path # This terminal version uses curl for HTTP and Python's standard library for JSON/CSV. import subprocess import tempfile def transport(method, url, headers, data): with tempfile.TemporaryDirectory(prefix="exhibitday-guide-") as directory: folder = Path(directory) # curl may leave no output file for a valid bodyless304 response. (folder / "body").write_bytes(b"") command = ["curl", "--disable", "--silent", "--show-error", "--request", method, "--url", url, "--max-time", "30", "--dump-header", str(folder / "headers"), "--output", str(folder / "body"), "--write-out", "%{http_code}"] for name, value in headers.items(): command += ["--header", name + ": " + value] if data is not None: (folder / "request").write_bytes(data) command += ["--data-binary", "@" + str(folder / "request")] result = subprocess.run(command, capture_output=True, text=True) if result.returncode: raise urllib.error.URLError(result.stderr.strip()) response_headers = {} blocks = (folder / "headers").read_text(encoding="iso-8859-1").replace("\r\n", "\n").strip().split("\n\n") for line in blocks[-1].splitlines()[1:]: name, separator, value = line.partition(":") if separator: response_headers[name] = value.strip() return int(result.stdout), (folder / "body").read_bytes(), response_headers class ApiError(RuntimeError): """An API error response. Branch on error_code (and status), never on the message text. uncertain is True when a PATCH or DELETE got no response or a server error: it may or may not have been applied.""" def __init__(self, status, body, uncertain=False): self.status = status self.uncertain = uncertain self.error_code = body.get("error_code") if isinstance(body, dict) else None super().__init__(f"{body.get('error_code')} {body.get('error_params')}: {body.get('errors')} (request {body.get('request_id')})" if isinstance(body, dict) else "HTTP " + str(status) if status else "No response") def call(name, params=None, body=None, key=None): route = SPEC["requests"][name] headers = {"Authorization": "Bearer " + API_KEY, "Accept": "application/json"} if route["method"] == "POST": if not key: raise RuntimeError("Persist a logical create key before sending POST") headers["Idempotency-Key"] = key data = None if body is None else json.dumps(body).encode("utf-8") if data is not None: headers["Content-Type"] = "application/json" query = urllib.parse.urlencode(params or {}) url = BASE + route["path"] + ("?" + query if query else "") # Only GET has automatic retries in this workflow. A PATCH or DELETE that got no response or a # server error is never resent blindly: it may already have been applied, so the caller reads the record first. resend = route["method"] == "GET" for attempt in range(5): try: status, raw, response_headers = transport(route["method"], url, headers, data) except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException): if not resend: raise ApiError(0, None, uncertain=True) if attempt == 4: raise time.sleep(2 ** attempt) continue response_headers = {k.lower(): v for k, v in response_headers.items()} result = None if status != 304 and raw: try: result = decode_json(raw.decode("utf-8")) except (ValueError, UnicodeError): if status < 400: raise RuntimeError("Expected a JSON success response") if status >= 500 and not resend: raise ApiError(status, result, uncertain=True) retry = resend and (status == 429 or status >= 500) if retry: if attempt == 4: raise RuntimeError("Retry limit reached; check the request outcome before starting a new create") delay = response_headers.get("retry-after", str(2 ** attempt)) time.sleep(max(0, float(delay))) continue if status >= 400: raise ApiError(status, result) return {"status": status, "body": result, "headers": response_headers, "raw": raw} raise RuntimeError("Retry limit reached") def 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 items(value): if not isinstance(value, list): raise RuntimeError("Expected a JSON array") return value def count(value): return len(items(value)) 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] 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 offsetlen(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)-offset:raise JournalRefusal('Incomplete journal frame; reconcile before retry') payload=raw[offset:offset+size];offset+=size if raw[offset:offset+1]!=b'\n' or digest(payload).encode('ascii')!=match[2]:raise JournalRefusal('Journal integrity check failed; reconcile before retry') records.append(read_strings(payload));offset+=1 return records class Journal: def __init__(self,path,base,workspace,slug,job,input_fingerprint,writes,mode="resume"): self.path=Path(path);self.lock=Path(str(self.path)+'.lock');self.fd=None;self.owned=False;self.identity=None;self.tainted=False;self.intents={};self.saved_values={} address=urlsplit(base) if address.scheme not in ('https','http')or not address.netloc or address.username is not None or address.query or address.fragment or not re.fullmatch('[a-z][a-z0-9-]*',slug):raise JournalRefusal('Use the actual API base and closed guide slug') if not job.strip() or not re.fullmatch('[1-9][0-9]*',workspace) or not re.fullmatch('[0-9A-F]{64}',input_fingerprint):raise JournalRefusal('Use an actual workspace, explicit stable job ID and exact input fingerprint') if mode not in ("new","resume"):raise JournalRefusal("Choose new or resume for this local job") self.allowed={};manifest=[] for step,method,route in writes: if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.allowed or method not in ('POST','PATCH','DELETE')or not re.fullmatch('/v1/[A-Za-z0-9_/-]+',route)or'//'in route:raise JournalRefusal('Use a closed unique write manifest') self.allowed[step]=(method,route);manifest.extend((step,method,route)) if not self.allowed:raise JournalRefusal('Only write workflows need a restart journal') self.header=['H','1',base,workspace,slug,job,input_fingerprint,digest(strings(manifest))] strings(self.header) try: self.fd=os.open(self.lock,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600);self.owned=True except FileExistsError:raise JournalRefusal('This journal is locked; do not run overlapping jobs or steal a stale lock') try: self.owner=secrets.token_hex(16);self.identity=os.fstat(self.fd) if os.write(self.fd,self.owner.encode('ascii'))!=len(self.owner):raise OSError('Incomplete lock identity write') os.fsync(self.fd) if self.path.is_symlink():raise JournalRefusal('Choose a private regular journal file') if mode=="resume" and not self.path.exists():raise JournalRefusal("Journal missing: stop and reconcile lost state before starting a new logical job") if mode=="new" and self.path.exists():raise JournalRefusal("A journal already exists; use resume for the same logical job") if mode=="new": with open(self.path,'xb',buffering=0)as target: target.write(PREAMBLE+frame(self.header));os.fsync(target.fileno()) records=decode(self.path.read_bytes()) if not records or records[0]!=self.header:raise JournalRefusal('Journal workspace/base/guide/job/input binding differs') for record in records[1:]:self.apply(record) if any(step not in self.saved_values for step in self.intents):raise JournalRefusal('A saved before-send intent lacks an ACK; stop and reconcile its outcome before retry') except BaseException: self.close();raise def apply(self,record): if not record:raise JournalRefusal('Empty journal record') if record[0]=='I': if len(record)!=6:raise JournalRefusal('Invalid intent shape') _,step,method,path,request_fingerprint,key=record if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.intents or self.allowed.get(step)!=(method,path)or not re.fullmatch('[0-9A-F]{64}',request_fingerprint)or any(name not in self.saved_values for name in self.intents):raise JournalRefusal('Invalid, future or repeated journal intent') if method=='POST'and not re.fullmatch('[0-9a-f]{32}',key)or method!='POST'and key!='':raise JournalRefusal('Invalid persisted action key') self.intents[step]={'method':method,'path':path,'request_fingerprint':request_fingerprint,'idempotency_key':key} elif record[0]=='A': if len(record)<3:raise JournalRefusal('Invalid ACK shape') _,step,count,*pairs=record if not re.fullmatch('0|[1-9][0-9]*',count)or len(pairs)!=2*int(count)or step not in self.intents or step in self.saved_values:raise JournalRefusal('ACK without exactly one prior intent') names=pairs[::2] if names!=sorted(set(names))or any(not re.fullmatch('[a-z][a-z0-9_]*',name)or name in ('api_key','exhibitday_api_key')for name in names):raise JournalRefusal('ACK saved fields must be unique sorted secret-free identifiers') self.saved_values[step]=dict(zip(names,pairs[1::2])) else:raise JournalRefusal('Unknown journal transition') def append(self,record): # The reader commits state only after complete length/digest recognition. # A torn append is retained and refused, never silently truncated. self.require_active();raw=frame(record) try: with open(self.path,'ab',buffering=0)as target: view=memoryview(raw) while view: written=target.write(view) if not written:raise OSError('Journal write did not advance') view=view[written:] os.fsync(target.fileno()) except BaseException: self.tainted=True;raise def require_active(self): if not self.owned or self.fd is None or self.identity is None or self.tainted:raise JournalRefusal('The journal scope is closed or its IO outcome needs reconciliation') current=self.lock.stat(follow_symlinks=False) if current.st_dev!=self.identity.st_dev or current.st_ino!=self.identity.st_ino or self.lock.read_text(encoding='ascii')!=self.owner:raise JournalRefusal('The journal lock was replaced; stop without deleting it') def acknowledged(self,step): self.require_active();return step in self.saved_values def saved(self,step): self.require_active() if step not in self.saved_values:raise JournalRefusal('No acknowledged state exists for this step') return dict(self.saved_values[step]) def begin(self,step,method,path,request_fingerprint): self.require_active() if step in self.intents:raise JournalRefusal('Never blindly repeat an existing action intent') key=secrets.token_hex(16)if method=='POST'else'' record=['I',step,method,path,request_fingerprint,key] # Validate on an isolated state before touching the file. old=dict(self.intents) try:self.apply(record) finally:self.intents=old self.append(record);self.apply(record) return dict(self.intents[step]) def acknowledge(self,step,saved): self.require_active() record=['A',step,str(len(saved))] for name,value in sorted(saved.items()):record.extend((name,value)) old={name:dict(value)for name,value in self.saved_values.items()} try:self.apply(record);strings(record) finally:self.saved_values=old self.append(record);self.apply(record) def close(self): if self.owned: if self.tainted: os.close(self.fd);self.fd=None;self.owned=False return # Retain this lock after failed journal IO; manual reconciliation is required. try:self.require_active() except BaseException: os.close(self.fd);self.fd=None;self.owned=False;raise os.close(self.fd);self.fd=None;self.owned=False self.lock.unlink() def __enter__(self):return self def __exit__(self,*args):self.close() def journal_values(value): if not isinstance(value, dict) or any(not isinstance(k, str) or not isinstance(v, str) for k,v in value.items()): raise JournalRefusal('Saved/fingerprint values must be exact string fields') return dict(value) def journal_acknowledge(job, step, saved): job.acknowledge(step,journal_values(saved)) def journal_acknowledged(job, step): return job.acknowledged(step) def journal_begin(job, step, method, path, request_fingerprint): return job.begin(step,method,path,request_fingerprint) def journal_fingerprint(value): return fingerprint(journal_values(value)) def journal_saved(job, step): return job.saved(step) def 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 page_size(value): if not re.fullmatch(r"[1-9][0-9]*", value) or int(value) > 2147483647: raise RuntimeError("Page size must be a positive int32") return 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 remember_id(seen, value): if value in seen: return False seen.add(value) return True 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 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 validate_staff_travel_inputs(name, start, end): from datetime import date spaces = '\u0009\u000A\u000B\u000C\u000D\u0020\u0085\u00A0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u2028\u2029\u202F\u205F\u3000' for value, label, limit in ((name, 'EXHIBITDAY_HOTEL_NAME', 125),): utf8(value) if not value or value != value.strip(spaces): raise JournalRefusal('Remove whitespace at the start or end of ' + label) if len(value.encode('utf-16-le')) // 2 > limit: raise JournalRefusal(label + ' exceeds ' + str(limit) + ' UTF-16 code units') if any(ch in name for ch in '<>\r\n') or name.lower() == 'null': raise JournalRefusal('Use plain, single-line EXHIBITDAY_HOTEL_NAME text other than null') for value, label in ((start, 'EXHIBITDAY_CHECKIN_DATE'), (end, 'EXHIBITDAY_CHECKOUT_DATE')): try: valid = re.fullmatch(r'[0-9]{4}-[0-9]{2}-[0-9]{2}', value) and date.fromisoformat(value).year >= 1753 except ValueError: valid = False if not valid: raise JournalRefusal(label + ' must be a calendar date in YYYY-MM-DD on or after 1753-01-01') if end < start: raise JournalRefusal('EXHIBITDAY_CHECKOUT_DATE must be on or after EXHIBITDAY_CHECKIN_DATE') def main(): travel_event_id = positive_id(required("EXHIBITDAY_EVENT_ID")) travel_person_id = required("EXHIBITDAY_PERSON_ID") travel_hotel = required("EXHIBITDAY_HOTEL_NAME") travel_checkin = required("EXHIBITDAY_CHECKIN_DATE") travel_checkout = required("EXHIBITDAY_CHECKOUT_DATE") travel_page_size = page_size(optional("EXHIBITDAY_PAGE_SIZE", "100")) travel_notify = optional("EXHIBITDAY_SEND_NOTIFICATIONS", "false") require_condition(either(equal(travel_notify, "true"), equal(travel_notify, "false")), "Use exact true or false for EXHIBITDAY_SEND_NOTIFICATIONS.") travel_journal_path = required("EXHIBITDAY_JOURNAL") travel_job_id = required("EXHIBITDAY_JOB_ID") travel_job_mode = optional("EXHIBITDAY_JOB_MODE", "resume") validate_staff_travel_inputs(travel_hotel, travel_checkin, travel_checkout) travel_workspace_response = call("workspace_binding", {}, None, None) require_condition(equal(response_status(travel_workspace_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write.") travel_workspace = travel_workspace_response["body"] travel_workspace_id = positive_id(text(field(travel_workspace, "id"))) travel_event_response = call("event_before", {"id": travel_event_id}, None, None) require_condition(equal(response_status(travel_event_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write.") travel_event = travel_event_response["body"] require_condition(equal(text(field(travel_event, "id")), travel_event_id), "The Event read differs from the explicit selected Event.") travel_people_response = call("people_choices", {}, None, None) require_condition(equal(response_status(travel_people_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write.") travel_people = travel_people_response["body"] travel_person_found = "" for travel_person_choice in items(items(field(travel_people, "list_data"))): if equal(text(field(travel_person_choice, "id")), travel_person_id): require_condition(not_value(is_present(travel_person_found)), "The people reference returned the same selected person more than once.") travel_person_found = travel_person_id require_condition(equal(travel_person_found, travel_person_id), "Choose a current person or resource ID from References users_and_resources before creating Staff or Travel.") travel_types_response = call("travel_choices", {}, None, None) require_condition(equal(response_status(travel_types_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write.") travel_types = travel_types_response["body"] travel_hotel_type_found = "" for travel_type_choice in items(items(field(travel_types, "list_data"))): if equal(text(field(travel_type_choice, "id")), "6"): require_condition(both(equal(text(field(travel_type_choice, "name")), "Hotel"), not_value(is_present(travel_hotel_type_found))), "The current type6 reference is not one unambiguous Hotel choice.") travel_hotel_type_found = "6" require_condition(equal(travel_hotel_type_found, "6"), "This Hotel example requires the currently declared Hotel choice6; do not substitute a different type.") travel_staff_before_id = "" travel_staff_before_offset = "0" travel_staff_before_query = {"filter_by_event_id": travel_event_id, "filter_by_attendee_user_ids": travel_person_id, "$limit": travel_page_size} travel_staff_before_seen = new_id_set() while True: travel_staff_before_query["$offset"] = travel_staff_before_offset travel_staff_before_response = call("find_staff", travel_staff_before_query, None, None) require_condition(equal(response_status(travel_staff_before_response), "200"), "Expected HTTP200 for the current collection; stop and reconcile another response.") travel_staff_before_page = travel_staff_before_response["body"] travel_staff_before_rows = items(field(travel_staff_before_page, "list_data")) require_condition(equal(text(field(travel_staff_before_page, "records_found")), text(count(travel_staff_before_rows))), "records_found differs from this page's rows.") require_condition(is_present(text(field(travel_staff_before_page, "total_records"))), "The collection wrapper needs total_records.") require_condition(either(equal(field(travel_staff_before_page, "has_more"), True), equal(field(travel_staff_before_page, "has_more"), False)), "Expected a Boolean has_more value.") for travel_staff_before_record in items(travel_staff_before_rows): travel_staff_before_record_id = positive_id(text(field(travel_staff_before_record, "id"))) require_condition(equal(text(field(travel_staff_before_record, "event_id")), travel_event_id), "A selected collection returned a row from another Event.") require_condition(equal(text(field(field(travel_staff_before_record, "attendee"), "id")), travel_person_id), "The Staff filter returned a registration for a different person.") if remember_id(travel_staff_before_seen, travel_staff_before_record_id): require_condition(not_value(is_present(travel_staff_before_id)), "More than one Staff record matches this person and Event. Stop for review; never choose the first.") travel_staff_before_id = travel_staff_before_record_id if equal(field(travel_staff_before_page, "has_more"), False): break require_condition(not_value(is_empty(travel_staff_before_rows)), "An empty page says has_more=true. Stop and reconcile the selected query.") travel_staff_before_offset = add_offset(travel_staff_before_offset, count(travel_staff_before_rows)) travel_input_fingerprint = journal_fingerprint({"workflow_contract_sha256": "A4CE8A49EF9814D6F6F256BE0525D5A77FF09C69232E21624504C3C3DDA294AB", "event_id": travel_event_id, "user_id": travel_person_id, "hotel": travel_hotel, "checkin": travel_checkin, "checkout": travel_checkout, "notify": travel_notify, "page_size": travel_page_size}) travel_job = open_journal(travel_journal_path, "https://api.exhibitday.com/v1", travel_workspace_id, "staff-travel-tags", travel_job_id, travel_input_fingerprint, [["create_staff", "POST", "/v1/events/staff"], ["create_travel", "POST", "/v1/events/travel_reservations"]], travel_job_mode) try: require_condition(either(not_value(journal_acknowledged(travel_job, "create_travel")), journal_acknowledged(travel_job, "create_staff")), "A Travel create is acknowledged before Staff. Stop and reconcile the saved state.") travel_staff_id = "" travel_reservation_id = "" if journal_acknowledged(travel_job, "create_staff"): travel_saved_staff = journal_saved(travel_job, "create_staff") travel_staff_id = positive_id(text(field(travel_saved_staff, "id"))) require_condition(both(equal(text(field(travel_saved_staff, "event_id")), travel_event_id), both(equal(text(field(field(travel_saved_staff, "attendee"), "id")), travel_person_id), equal(text(field(travel_saved_staff, "id")), travel_staff_id))), "The Staff record differs from the captured ID, selected Event or person. Reconcile it; do not create a replacement.") require_condition(equal(travel_staff_before_id, travel_staff_id), "The acknowledged Staff entry is missing or changed. Review the current Staff list before continuing.") else: require_condition(not_value(is_present(travel_staff_before_id)), "This person already has a Staff entry without a saved acknowledgement for this job. Review that entry; do not add another registration.") travel_staff_fingerprint = journal_fingerprint({"event_id": travel_event_id, "user_id": travel_person_id, "registration_type": "Conference pass", "notify_attendee": travel_notify}) travel_staff_intent = journal_begin(travel_job, "create_staff", "POST", "/v1/events/staff", travel_staff_fingerprint) travel_staff_create_response = call("create_staff", {}, {"event_id": travel_event_id, "attendee_user_id": travel_person_id, "registration_type": "Conference pass", "notify_attendee": equal(travel_notify, "true")}, text(field(travel_staff_intent, "idempotency_key"))) require_condition(equal(response_status(travel_staff_create_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write.") travel_created_staff = travel_staff_create_response["body"] travel_staff_id = positive_id(text(field(travel_created_staff, "id"))) require_condition(both(equal(text(field(travel_created_staff, "event_id")), travel_event_id), both(equal(text(field(field(travel_created_staff, "attendee"), "id")), travel_person_id), equal(text(field(travel_created_staff, "id")), travel_staff_id))), "The Staff record differs from the captured ID, selected Event or person. Reconcile it; do not create a replacement.") require_condition(equal(text(field(travel_created_staff, "registration_type")), "Conference pass"), "The Staff acknowledgement has a different registration type; preserve pending state and reconcile.") journal_acknowledge(travel_job, "create_staff", {"id": travel_staff_id, "event_id": travel_event_id, "user_id": travel_person_id}) travel_staff_verify_id = "" travel_staff_verify_offset = "0" travel_staff_verify_query = {"filter_by_event_id": travel_event_id, "filter_by_attendee_user_ids": travel_person_id, "$limit": travel_page_size} travel_staff_verify_seen = new_id_set() while True: travel_staff_verify_query["$offset"] = travel_staff_verify_offset travel_staff_verify_response = call("staff_readback", travel_staff_verify_query, None, None) require_condition(equal(response_status(travel_staff_verify_response), "200"), "Expected HTTP200 for the current collection; stop and reconcile another response.") travel_staff_verify_page = travel_staff_verify_response["body"] travel_staff_verify_rows = items(field(travel_staff_verify_page, "list_data")) require_condition(equal(text(field(travel_staff_verify_page, "records_found")), text(count(travel_staff_verify_rows))), "records_found differs from this page's rows.") require_condition(is_present(text(field(travel_staff_verify_page, "total_records"))), "The collection wrapper needs total_records.") require_condition(either(equal(field(travel_staff_verify_page, "has_more"), True), equal(field(travel_staff_verify_page, "has_more"), False)), "Expected a Boolean has_more value.") for travel_staff_verify_record in items(travel_staff_verify_rows): travel_staff_verify_record_id = positive_id(text(field(travel_staff_verify_record, "id"))) require_condition(equal(text(field(travel_staff_verify_record, "event_id")), travel_event_id), "A selected collection returned a row from another Event.") require_condition(equal(text(field(field(travel_staff_verify_record, "attendee"), "id")), travel_person_id), "The Staff filter returned a registration for a different person.") if remember_id(travel_staff_verify_seen, travel_staff_verify_record_id): require_condition(not_value(is_present(travel_staff_verify_id)), "More than one Staff record matches this person and Event. Stop for review; never choose the first.") travel_staff_verify_id = travel_staff_verify_record_id if equal(field(travel_staff_verify_page, "has_more"), False): break require_condition(not_value(is_empty(travel_staff_verify_rows)), "An empty page says has_more=true. Stop and reconcile the selected query.") travel_staff_verify_offset = add_offset(travel_staff_verify_offset, count(travel_staff_verify_rows)) require_condition(equal(travel_staff_verify_id, travel_staff_id), "The captured Staff entry is not present in the complete current selected Event/person list. Stop before Travel creation.") if journal_acknowledged(travel_job, "create_travel"): travel_saved_reservation = journal_saved(travel_job, "create_travel") travel_reservation_id = positive_id(text(field(travel_saved_reservation, "id"))) require_condition(both(equal(text(field(travel_saved_reservation, "event_id")), travel_event_id), equal(text(field(travel_saved_reservation, "user_id")), travel_person_id)), "Saved Travel state belongs to a different Event or person. Stop and reconcile.") else: travel_create_fingerprint = journal_fingerprint({"event_id": travel_event_id, "reservation_type_id": "6", "origin_vendor_name": travel_hotel, "origin_checkin_date": travel_checkin, "return_checkin_date": travel_checkout, "tagged_user_ids": travel_person_id, "notify_tagged_users": travel_notify}) travel_create_intent = journal_begin(travel_job, "create_travel", "POST", "/v1/events/travel_reservations", travel_create_fingerprint) travel_create_response = call("create_travel", {}, {"event_id": travel_event_id, "reservation_type_id": "6", "origin_vendor_name": travel_hotel, "origin_checkin_date": travel_checkin, "return_checkin_date": travel_checkout, "tagged_user_ids": [travel_person_id], "notify_tagged_users": equal(travel_notify, "true")}, text(field(travel_create_intent, "idempotency_key"))) require_condition(equal(response_status(travel_create_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write.") travel_created_reservation = travel_create_response["body"] travel_reservation_id = positive_id(text(field(travel_created_reservation, "id"))) require_condition(both(both(both(both(both(equal(text(field(travel_created_reservation, "id")), travel_reservation_id), equal(text(field(travel_created_reservation, "event_id")), travel_event_id)), equal(text(field(travel_created_reservation, "reservation_type_id")), "6")), equal(text(field(travel_created_reservation, "origin_vendor_name")), travel_hotel)), equal(text(field(travel_created_reservation, "origin_checkin_date")), travel_checkin)), equal(text(field(travel_created_reservation, "return_checkin_date")), travel_checkout)), "The Hotel response differs from the captured ID, Event, type, vendor or dates. Keep pending state and reconcile; do not create another reservation.") travel_created_tags = items(field(travel_created_reservation, "tagged_users")) require_condition(equal(text(count(travel_created_tags)), "1"), "The Hotel acknowledgement must contain exactly the one selected tag before it can be saved as acknowledged.") for travel_created_tag in items(travel_created_tags): require_condition(equal(text(field(travel_created_tag, "id")), travel_person_id), "The acknowledged Hotel is tagged to a different person; keep pending state and reconcile.") journal_acknowledge(travel_job, "create_travel", {"id": travel_reservation_id, "event_id": travel_event_id, "user_id": travel_person_id}) travel_final_id = "" travel_final_offset = "0" travel_final_query = {"filter_by_event_id": travel_event_id, "filter_by_tagged_user_ids": travel_person_id, "$limit": travel_page_size} travel_final_query["filter_by_tagged_user_ids_match_type"] = "all" while True: travel_final_query["$offset"] = travel_final_offset travel_final_response = call("travel_readback", travel_final_query, None, None) require_condition(equal(response_status(travel_final_response), "200"), "Expected HTTP200 for the current collection; stop and reconcile another response.") travel_final_page = travel_final_response["body"] travel_final_rows = items(field(travel_final_page, "list_data")) require_condition(equal(text(field(travel_final_page, "records_found")), text(count(travel_final_rows))), "records_found differs from this page's rows.") require_condition(is_present(text(field(travel_final_page, "total_records"))), "The collection wrapper needs total_records.") require_condition(either(equal(field(travel_final_page, "has_more"), True), equal(field(travel_final_page, "has_more"), False)), "Expected a Boolean has_more value.") for travel_final_record in items(travel_final_rows): travel_final_record_id = positive_id(text(field(travel_final_record, "id"))) require_condition(equal(text(field(travel_final_record, "event_id")), travel_event_id), "A selected collection returned a row from another Event.") travel_final_person_found = "" travel_final_tags = items(field(travel_final_record, "tagged_users")) for travel_final_tag in items(travel_final_tags): if equal(text(field(travel_final_tag, "id")), travel_person_id): travel_final_person_found = "true" require_condition(equal(travel_final_person_found, "true"), "The all-tags filter returned a record without the selected person.") if equal(travel_final_record_id, travel_reservation_id): require_condition(both(both(both(both(both(equal(text(field(travel_final_record, "id")), travel_reservation_id), equal(text(field(travel_final_record, "event_id")), travel_event_id)), equal(text(field(travel_final_record, "reservation_type_id")), "6")), equal(text(field(travel_final_record, "origin_vendor_name")), travel_hotel)), equal(text(field(travel_final_record, "origin_checkin_date")), travel_checkin)), equal(text(field(travel_final_record, "return_checkin_date")), travel_checkout)), "The Hotel response differs from the captured ID, Event, type, vendor or dates. Keep pending state and reconcile; do not create another reservation.") require_condition(equal(text(count(travel_final_tags)), "1"), "The captured Hotel's tags changed; review them instead of silently restoring the original selection.") travel_final_id = travel_final_record_id if equal(field(travel_final_page, "has_more"), False): break require_condition(not_value(is_empty(travel_final_rows)), "An empty page says has_more=true. Stop and reconcile the selected query.") travel_final_offset = add_offset(travel_final_offset, count(travel_final_rows)) require_condition(equal(travel_final_id, travel_reservation_id), "The captured Hotel is missing from the complete current Event/person Travel list. Reconcile it; do not repeat the create or delete records automatically.") print_value({"event_id": travel_event_id, "user_id": travel_person_id, "staff_id": travel_staff_id, "travel_reservation_id": travel_reservation_id}) finally: travel_job.close() if __name__ == "__main__": main() EXHIBITDAY_PY ``` ```javascript // Server-side Node.js with fetch; built-in modules only. Set EXHIBITDAY_API_KEY. const BASE = "https://api.exhibitday.com/v1"; const SPEC = JSON.parse("{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"people_choices\":{\"method\":\"GET\",\"path\":\"/references/users_and_resources\"},\"travel_choices\":{\"method\":\"GET\",\"path\":\"/references/travel_reservation_types\"},\"event_before\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"find_staff\":{\"method\":\"GET\",\"path\":\"/events/staff\"},\"create_staff\":{\"method\":\"POST\",\"path\":\"/events/staff\"},\"create_travel\":{\"method\":\"POST\",\"path\":\"/events/travel_reservations\"},\"staff_readback\":{\"method\":\"GET\",\"path\":\"/events/staff\"},\"travel_readback\":{\"method\":\"GET\",\"path\":\"/events/travel_reservations\"}}}"); const API_KEY = process.env.EXHIBITDAY_API_KEY; if (!API_KEY || !API_KEY.trim()) throw new Error("Set EXHIBITDAY_API_KEY"); if (/[^\x20-\x7e]/.test(API_KEY)) throw new Error("Use the API key as one ASCII header value without control characters"); 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, errors: result.errors, error_params: result.error_params, 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, key = null) { const route = SPEC.requests[name]; const headers = { Authorization: "Bearer " + API_KEY, Accept: "application/json" }; if (route.method === "POST") { if (!key) throw new Error("Persist a logical create key before sending POST"); headers["Idempotency-Key"] = key; } 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 : ""); // 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. const resend = route.method === "GET"; 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 = resend && (response.status === 429 || response.status >= 500); 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, raw }; } throw new Error("Retry limit reached"); } function add_offset(offset, received) { const result = BigInt(offset) + received; if (received <= 0n || result > 2147483647n) throw new Error("Cannot advance this int32 offset; reconcile the query"); return result.toString(); } function both(left,right) { return left && right; } function items(value) { if (!Array.isArray(value)) throw new Error("Expected a JSON array"); return value; } function count(value) { return BigInt(items(value).length); } function either(left, right) { if (typeof left !== "boolean" || typeof right !== "boolean") throw new Error("Expected Boolean criteria"); return left || right; } function equal(left, right) { return typeof left === typeof right && left === right; } function field(value, name) { if (!value || Array.isArray(value) || typeof value !== "object" || !Object.hasOwn(value, name)) throw new Error("Missing response field: " + name); return value[name]; } function is_empty(value) { return count(value) === 0n; } function is_present(value) { return value !== null && value !== undefined && value !== ""; } 'use strict'; // Private client restart state. No HTTP or application dependency. const fs = require('node:fs'); const crypto = require('node:crypto'); const PREAMBLE = Buffer.from('EXHIBITDAY-GUIDE-JOURNAL 1\n', 'ascii'); class JournalRefusal extends Error {} function ascii(raw) { if (raw.some(value => value > 127)) throw new JournalRefusal('Journal framing must be canonical ASCII'); return raw.toString('ascii'); } function utf8(value) { if (typeof value !== 'string') throw new JournalRefusal('Journal fields are exact strings'); for (const unit of value) if (unit.length === 1 && unit.charCodeAt(0) >= 0xd800 && unit.charCodeAt(0) <= 0xdfff) throw new JournalRefusal('Invalid Unicode journal field'); return Buffer.from(value, 'utf8'); } function strings(values) { const parts = []; for (const value of values) { const raw = utf8(value); parts.push(Buffer.from(String(raw.length) + ':', 'ascii'), raw); } return Buffer.concat(parts); } function readStrings(raw) { const values = []; let offset = 0; while (offset < raw.length) { const end = raw.indexOf(58, offset); if (end < 0) throw new JournalRefusal('Incomplete journal string length'); const length = ascii(raw.subarray(offset, end)); if (!/^(0|[1-9][0-9]*)$/.test(length)) throw new JournalRefusal('Noncanonical journal string length'); const size = BigInt(length); offset = end + 1; if (size > BigInt(raw.length - offset)) throw new JournalRefusal('Incomplete journal string'); const count = Number(size); values.push(new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(raw.subarray(offset, offset + count))); offset += count; } return values; } function digest(raw) { return crypto.createHash('sha256').update(raw).digest('hex').toUpperCase(); } function fingerprint(pairs) { const values = []; for (const name of Object.keys(pairs).sort()) { if (!/^[A-Za-z0-9_.-]+$/.test(name) || ['api_key', 'exhibitday_api_key'].includes(name.toLowerCase())) throw new JournalRefusal('Use explicit secret-free fingerprint field names'); values.push(name, pairs[name]); } return digest(strings(values)); } function frame(values) { const raw = strings(values); return Buffer.concat([Buffer.from(String(raw.length) + ' ' + digest(raw) + '\n', 'ascii'), raw, Buffer.from('\n')]); } function decode(raw) { if (!raw.subarray(0, PREAMBLE.length).equals(PREAMBLE)) throw new JournalRefusal('Unknown or incomplete journal version'); let offset = PREAMBLE.length; const records = []; while (offset < raw.length) { const end = raw.indexOf(10, offset); if (end < 0) throw new JournalRefusal('Incomplete journal frame header; reconcile before retry'); const match = /^(0|[1-9][0-9]*) ([0-9A-F]{64})$/.exec(ascii(raw.subarray(offset, end))); if (!match) throw new JournalRefusal('Invalid journal frame header'); const size = BigInt(match[1]); offset = end + 1; if (size >= BigInt(raw.length - offset)) throw new JournalRefusal('Incomplete journal frame; reconcile before retry'); const count = Number(size), payload = raw.subarray(offset, offset + count); offset += count; if (raw[offset] !== 10 || digest(payload) !== match[2]) throw new JournalRefusal('Journal integrity check failed; reconcile before retry'); records.push(readStrings(payload)); offset++; } return records; } function writeAll(fd, raw) { let offset = 0; while (offset < raw.length) { const count = fs.writeSync(fd, raw, offset, raw.length - offset); if (!count) throw new Error('Journal write did not advance'); offset += count; } } function same(left, right) { return left.length === right.length && left.every((value, index) => value === right[index]); } class Journal { constructor(path, base, workspace, slug, job, inputFingerprint, writes, mode = 'resume') { this.path = path; this.lock = path + '.lock'; this.fd = null; this.owned = false; this.identity = null; this.tainted = false; this.intents = new Map(); this.savedValues = new Map(); this.allowed = new Map(); if (!['new', 'resume'].includes(mode)) throw new JournalRefusal('Choose new or resume for this local job'); const address = new URL(base); if (!['https:', 'http:'].includes(address.protocol) || !address.hostname || address.username || address.password || address.search || address.hash || !/^[a-z][a-z0-9-]*$/.test(slug)) throw new JournalRefusal('Use the actual API base and closed guide slug'); if (!job.trim() || !/^[1-9][0-9]*$/.test(workspace) || !/^[0-9A-F]{64}$/.test(inputFingerprint)) throw new JournalRefusal('Use an actual workspace, stable explicit job ID and exact input fingerprint'); const manifest = []; for (const [step, method, route] of writes) { if (!/^[a-z][a-z0-9_-]*$/.test(step) || this.allowed.has(step) || !['POST', 'PATCH', 'DELETE'].includes(method) || !/^\/v1\/[A-Za-z0-9_/-]+$/.test(route) || route.includes('//')) throw new JournalRefusal('Use a closed unique write manifest'); this.allowed.set(step, [method, route]); manifest.push(step, method, route); } if (!this.allowed.size) throw new JournalRefusal('Only write workflows need a restart journal'); this.header = ['H', '1', base, workspace, slug, job, inputFingerprint, digest(strings(manifest))]; strings(this.header); try { this.fd = fs.openSync(this.lock, 'wx', 0o600); this.owned = true; } catch (error) { if (error.code === 'EEXIST') throw new JournalRefusal('This journal is locked; do not overlap jobs or steal a stale lock'); throw error; } try { this.owner = crypto.randomBytes(16).toString('hex'); this.identity = fs.fstatSync(this.fd, { bigint: true }); writeAll(this.fd, Buffer.from(this.owner, 'ascii')); fs.fsyncSync(this.fd); let exists = true; try { if (fs.lstatSync(path).isSymbolicLink()) throw new JournalRefusal('Choose a private regular journal file'); } catch (error) { if (error.code === 'ENOENT') exists = false; else throw error; } if (mode === 'resume' && !exists) throw new JournalRefusal('Journal missing: stop and reconcile lost state before starting a new logical job'); if (mode === 'new' && exists) throw new JournalRefusal('Journal already exists; use resume for the same logical job'); if (mode === 'new') { const target = fs.openSync(path, 'wx', 0o600); try { writeAll(target, Buffer.concat([PREAMBLE, frame(this.header)])); fs.fsyncSync(target); } finally { fs.closeSync(target); } } const records = decode(fs.readFileSync(path)); if (!records.length || !same(records[0], this.header)) throw new JournalRefusal('Journal workspace/base/guide/job/input binding differs'); for (const record of records.slice(1)) this.apply(record); if ([...this.intents.keys()].some(step => !this.savedValues.has(step))) throw new JournalRefusal('Saved before-send intent lacks ACK; stop and reconcile before retry'); } catch (error) { this.close(); throw error; } } apply(record) { if (record[0] === 'I') { if (record.length !== 6) throw new JournalRefusal('Invalid intent shape'); const [, step, method, path, requestFingerprint, key] = record; if (!/^[a-z][a-z0-9_-]*$/.test(step) || this.intents.has(step) || !this.allowed.has(step) || !same(this.allowed.get(step), [method, path]) || !/^[0-9A-F]{64}$/.test(requestFingerprint) || [...this.intents.keys()].some(name => !this.savedValues.has(name))) throw new JournalRefusal('Invalid, future or repeated intent'); if ((method === 'POST' && !/^[0-9a-f]{32}$/.test(key)) || (method !== 'POST' && key !== '')) throw new JournalRefusal('Invalid persisted action key'); this.intents.set(step, { method, path, request_fingerprint: requestFingerprint, idempotency_key: key }); } else if (record[0] === 'A') { const [, step, count, ...pairs] = record; if (record.length < 3 || !/^(0|[1-9][0-9]*)$/.test(count) || BigInt(pairs.length) !== 2n * BigInt(count) || !this.intents.has(step) || this.savedValues.has(step)) throw new JournalRefusal('ACK without exactly one prior intent'); const names = pairs.filter((_, index) => index % 2 === 0); if (!same(names, [...new Set(names)].sort()) || names.some(name => !/^[a-z][a-z0-9_]*$/.test(name) || ['api_key', 'exhibitday_api_key'].includes(name))) throw new JournalRefusal('ACK fields must be unique sorted secret-free identifiers'); this.savedValues.set(step, Object.fromEntries(names.map((name, index) => [name, pairs[index * 2 + 1]]))); } else throw new JournalRefusal('Unknown journal transition'); } requireActive() { if (!this.owned || this.fd === null || this.identity === null || this.tainted) throw new JournalRefusal('Journal is closed or its IO outcome needs reconciliation'); const current = fs.lstatSync(this.lock, { bigint: true }); if (current.dev !== this.identity.dev || current.ino !== this.identity.ino || ascii(fs.readFileSync(this.lock)) !== this.owner) throw new JournalRefusal('Journal lock was replaced; stop without deleting it'); } append(record) { this.requireActive(); const raw = frame(record); let target; try { target = fs.openSync(this.path, 'a'); writeAll(target, raw); fs.fsyncSync(target); } catch (error) { this.tainted = true; throw error; } finally { if (target !== undefined) fs.closeSync(target); } } acknowledged(step) { this.requireActive(); return this.savedValues.has(step); } saved(step) { this.requireActive(); if (!this.savedValues.has(step)) throw new JournalRefusal('No acknowledged state exists'); return { ...this.savedValues.get(step) }; } begin(step, method, path, requestFingerprint) { this.requireActive(); if (this.intents.has(step)) throw new JournalRefusal('Never blindly repeat an existing action'); const key = method === 'POST' ? crypto.randomBytes(16).toString('hex') : '', record = ['I', step, method, path, requestFingerprint, key]; const old = new Map(this.intents); try { this.apply(record); } finally { this.intents = old; } this.append(record); this.apply(record); return { ...this.intents.get(step) }; } acknowledge(step, saved) { this.requireActive(); const names = Object.keys(saved).sort(), record = ['A', step, String(names.length)]; for (const name of names) record.push(name, saved[name]); const old = new Map(this.savedValues); try { this.apply(record); strings(record); } finally { this.savedValues = old; } this.append(record); this.apply(record); } close() { if (!this.owned) return; if (this.tainted) { fs.closeSync(this.fd); this.fd = null; this.owned = false; return; } try { this.requireActive(); } catch (error) { fs.closeSync(this.fd); this.fd = null; this.owned = false; throw error; } fs.closeSync(this.fd); this.fd = null; this.owned = false; fs.unlinkSync(this.lock); } } function journal_values(value) { if (!value || typeof value !== 'object' || Array.isArray(value) || Object.values(value).some(item=>typeof item!=='string')) throw new JournalRefusal('Saved/fingerprint values must be exact strings'); return {...value}; } function journal_acknowledge(job,step,saved) { job.acknowledge(step,journal_values(saved)); } function journal_acknowledged(job,step) { return job.acknowledged(step); } function journal_begin(job,step,method,path,requestFingerprint) { return job.begin(step,method,path,requestFingerprint); } function journal_fingerprint(value) { return fingerprint(journal_values(value)); } function journal_saved(job,step) { return job.saved(step); } function new_id_set() { return new Set(); } function not_value(value) { if (typeof value !== "boolean") throw new Error("Expected a Boolean"); return !value; } function open_journal(path,base,workspace,slug,job,inputFingerprint,writes,mode) { return new Journal(path,base,workspace,slug,job,inputFingerprint,writes,mode); } function optional(name, fallback) { const value = process.env[name]; return value === undefined || value === "" ? fallback : value; } function page_size(value) { if (!/^[1-9][0-9]*$/.test(value) || BigInt(value) > 2147483647n) throw new Error("Page size must be a positive int32"); return value; } function positive_id(value) { if (!/^[1-9][0-9]*$/.test(value) || BigInt(value) > 9223372036854775807n) throw new Error("Use a positive record ID"); return value; } function print_value(value) { console.log(typeof value === "string" ? value : JSON.stringify(value)); } function remember_id(seen, value) { if (seen.has(value)) return false; seen.add(value); return true; } function require_condition(value, message) { if (value !== true) throw new Error(message); } function required(name) { const value = process.env[name]; if (value === undefined || !value.trim()) throw new Error("Set " + name); return value; } function response_status(value) { return String(value.status); } function text(value) { if (value === null || value === undefined) return ""; if (["string", "boolean", "bigint"].includes(typeof value)) return String(value); throw new Error("Expected a scalar response value"); } function validate_staff_travel_inputs(name, start, end) { const boundary = /^[\u0009-\u000D\u0020\u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]|[\u0009-\u000D\u0020\u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]$/; for (const [value,label,limit] of [[name,'EXHIBITDAY_HOTEL_NAME',125]]) { utf8(value); if (!value || boundary.test(value)) throw new JournalRefusal('Remove whitespace at the start or end of ' + label); if (value.length > limit) throw new JournalRefusal(label + ' exceeds ' + limit + ' UTF-16 code units'); } if (/[<>\r\n]/.test(name) || name.toLowerCase() === 'null') throw new JournalRefusal('Use plain, single-line EXHIBITDAY_HOTEL_NAME text other than null'); for (const [value,label] of [[start,'EXHIBITDAY_CHECKIN_DATE'],[end,'EXHIBITDAY_CHECKOUT_DATE']]) { const time = new Date(value + 'T00:00:00Z'); if (value.length !== 10 || !/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test(value) || value < '1753-01-01' || Number.isNaN(time.getTime()) || time.toISOString().slice(0,10) !== value) throw new JournalRefusal(label + ' must be a calendar date in YYYY-MM-DD on or after 1753-01-01'); } if (end < start) throw new JournalRefusal('EXHIBITDAY_CHECKOUT_DATE must be on or after EXHIBITDAY_CHECKIN_DATE'); } async function main() { let travel_event_id = positive_id(required("EXHIBITDAY_EVENT_ID")); let travel_person_id = required("EXHIBITDAY_PERSON_ID"); let travel_hotel = required("EXHIBITDAY_HOTEL_NAME"); let travel_checkin = required("EXHIBITDAY_CHECKIN_DATE"); let travel_checkout = required("EXHIBITDAY_CHECKOUT_DATE"); let travel_page_size = page_size(optional("EXHIBITDAY_PAGE_SIZE", "100")); let travel_notify = optional("EXHIBITDAY_SEND_NOTIFICATIONS", "false"); require_condition(either(equal(travel_notify, "true"), equal(travel_notify, "false")), "Use exact true or false for EXHIBITDAY_SEND_NOTIFICATIONS."); let travel_journal_path = required("EXHIBITDAY_JOURNAL"); let travel_job_id = required("EXHIBITDAY_JOB_ID"); let travel_job_mode = optional("EXHIBITDAY_JOB_MODE", "resume"); validate_staff_travel_inputs(travel_hotel, travel_checkin, travel_checkout); let travel_workspace_response = await call("workspace_binding", {}, null, null); require_condition(equal(response_status(travel_workspace_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write."); let travel_workspace = travel_workspace_response.body; let travel_workspace_id = positive_id(text(field(travel_workspace, "id"))); let travel_event_response = await call("event_before", {"id": travel_event_id}, null, null); require_condition(equal(response_status(travel_event_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write."); let travel_event = travel_event_response.body; require_condition(equal(text(field(travel_event, "id")), travel_event_id), "The Event read differs from the explicit selected Event."); let travel_people_response = await call("people_choices", {}, null, null); require_condition(equal(response_status(travel_people_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write."); let travel_people = travel_people_response.body; let travel_person_found = ""; for (const travel_person_choice of items(items(field(travel_people, "list_data")))) { if (equal(text(field(travel_person_choice, "id")), travel_person_id)) { require_condition(not_value(is_present(travel_person_found)), "The people reference returned the same selected person more than once."); travel_person_found = travel_person_id; } } require_condition(equal(travel_person_found, travel_person_id), "Choose a current person or resource ID from References users_and_resources before creating Staff or Travel."); let travel_types_response = await call("travel_choices", {}, null, null); require_condition(equal(response_status(travel_types_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write."); let travel_types = travel_types_response.body; let travel_hotel_type_found = ""; for (const travel_type_choice of items(items(field(travel_types, "list_data")))) { if (equal(text(field(travel_type_choice, "id")), "6")) { require_condition(both(equal(text(field(travel_type_choice, "name")), "Hotel"), not_value(is_present(travel_hotel_type_found))), "The current type6 reference is not one unambiguous Hotel choice."); travel_hotel_type_found = "6"; } } require_condition(equal(travel_hotel_type_found, "6"), "This Hotel example requires the currently declared Hotel choice6; do not substitute a different type."); let travel_staff_before_id = ""; let travel_staff_before_offset = "0"; let travel_staff_before_query = {"filter_by_event_id": travel_event_id, "filter_by_attendee_user_ids": travel_person_id, "$limit": travel_page_size}; let travel_staff_before_seen = new_id_set(); while (true) { travel_staff_before_query["$offset"] = travel_staff_before_offset; let travel_staff_before_response = await call("find_staff", travel_staff_before_query, null, null); require_condition(equal(response_status(travel_staff_before_response), "200"), "Expected HTTP200 for the current collection; stop and reconcile another response."); let travel_staff_before_page = travel_staff_before_response.body; let travel_staff_before_rows = items(field(travel_staff_before_page, "list_data")); require_condition(equal(text(field(travel_staff_before_page, "records_found")), text(count(travel_staff_before_rows))), "records_found differs from this page's rows."); require_condition(is_present(text(field(travel_staff_before_page, "total_records"))), "The collection wrapper needs total_records."); require_condition(either(equal(field(travel_staff_before_page, "has_more"), true), equal(field(travel_staff_before_page, "has_more"), false)), "Expected a Boolean has_more value."); for (const travel_staff_before_record of items(travel_staff_before_rows)) { let travel_staff_before_record_id = positive_id(text(field(travel_staff_before_record, "id"))); require_condition(equal(text(field(travel_staff_before_record, "event_id")), travel_event_id), "A selected collection returned a row from another Event."); require_condition(equal(text(field(field(travel_staff_before_record, "attendee"), "id")), travel_person_id), "The Staff filter returned a registration for a different person."); if (remember_id(travel_staff_before_seen, travel_staff_before_record_id)) { require_condition(not_value(is_present(travel_staff_before_id)), "More than one Staff record matches this person and Event. Stop for review; never choose the first."); travel_staff_before_id = travel_staff_before_record_id; } } if (equal(field(travel_staff_before_page, "has_more"), false)) { break; } require_condition(not_value(is_empty(travel_staff_before_rows)), "An empty page says has_more=true. Stop and reconcile the selected query."); travel_staff_before_offset = add_offset(travel_staff_before_offset, count(travel_staff_before_rows)); } let travel_input_fingerprint = journal_fingerprint({"workflow_contract_sha256": "A4CE8A49EF9814D6F6F256BE0525D5A77FF09C69232E21624504C3C3DDA294AB", "event_id": travel_event_id, "user_id": travel_person_id, "hotel": travel_hotel, "checkin": travel_checkin, "checkout": travel_checkout, "notify": travel_notify, "page_size": travel_page_size}); let travel_job = open_journal(travel_journal_path, "https://api.exhibitday.com/v1", travel_workspace_id, "staff-travel-tags", travel_job_id, travel_input_fingerprint, [["create_staff", "POST", "/v1/events/staff"], ["create_travel", "POST", "/v1/events/travel_reservations"]], travel_job_mode); try { require_condition(either(not_value(journal_acknowledged(travel_job, "create_travel")), journal_acknowledged(travel_job, "create_staff")), "A Travel create is acknowledged before Staff. Stop and reconcile the saved state."); let travel_staff_id = ""; let travel_reservation_id = ""; if (journal_acknowledged(travel_job, "create_staff")) { let travel_saved_staff = journal_saved(travel_job, "create_staff"); travel_staff_id = positive_id(text(field(travel_saved_staff, "id"))); require_condition(both(equal(text(field(travel_saved_staff, "event_id")), travel_event_id), both(equal(text(field(field(travel_saved_staff, "attendee"), "id")), travel_person_id), equal(text(field(travel_saved_staff, "id")), travel_staff_id))), "The Staff record differs from the captured ID, selected Event or person. Reconcile it; do not create a replacement."); require_condition(equal(travel_staff_before_id, travel_staff_id), "The acknowledged Staff entry is missing or changed. Review the current Staff list before continuing."); } else { require_condition(not_value(is_present(travel_staff_before_id)), "This person already has a Staff entry without a saved acknowledgement for this job. Review that entry; do not add another registration."); let travel_staff_fingerprint = journal_fingerprint({"event_id": travel_event_id, "user_id": travel_person_id, "registration_type": "Conference pass", "notify_attendee": travel_notify}); let travel_staff_intent = journal_begin(travel_job, "create_staff", "POST", "/v1/events/staff", travel_staff_fingerprint); let travel_staff_create_response = await call("create_staff", {}, {"event_id": travel_event_id, "attendee_user_id": travel_person_id, "registration_type": "Conference pass", "notify_attendee": equal(travel_notify, "true")}, text(field(travel_staff_intent, "idempotency_key"))); require_condition(equal(response_status(travel_staff_create_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write."); let travel_created_staff = travel_staff_create_response.body; travel_staff_id = positive_id(text(field(travel_created_staff, "id"))); require_condition(both(equal(text(field(travel_created_staff, "event_id")), travel_event_id), both(equal(text(field(field(travel_created_staff, "attendee"), "id")), travel_person_id), equal(text(field(travel_created_staff, "id")), travel_staff_id))), "The Staff record differs from the captured ID, selected Event or person. Reconcile it; do not create a replacement."); require_condition(equal(text(field(travel_created_staff, "registration_type")), "Conference pass"), "The Staff acknowledgement has a different registration type; preserve pending state and reconcile."); journal_acknowledge(travel_job, "create_staff", {"id": travel_staff_id, "event_id": travel_event_id, "user_id": travel_person_id}); } let travel_staff_verify_id = ""; let travel_staff_verify_offset = "0"; let travel_staff_verify_query = {"filter_by_event_id": travel_event_id, "filter_by_attendee_user_ids": travel_person_id, "$limit": travel_page_size}; let travel_staff_verify_seen = new_id_set(); while (true) { travel_staff_verify_query["$offset"] = travel_staff_verify_offset; let travel_staff_verify_response = await call("staff_readback", travel_staff_verify_query, null, null); require_condition(equal(response_status(travel_staff_verify_response), "200"), "Expected HTTP200 for the current collection; stop and reconcile another response."); let travel_staff_verify_page = travel_staff_verify_response.body; let travel_staff_verify_rows = items(field(travel_staff_verify_page, "list_data")); require_condition(equal(text(field(travel_staff_verify_page, "records_found")), text(count(travel_staff_verify_rows))), "records_found differs from this page's rows."); require_condition(is_present(text(field(travel_staff_verify_page, "total_records"))), "The collection wrapper needs total_records."); require_condition(either(equal(field(travel_staff_verify_page, "has_more"), true), equal(field(travel_staff_verify_page, "has_more"), false)), "Expected a Boolean has_more value."); for (const travel_staff_verify_record of items(travel_staff_verify_rows)) { let travel_staff_verify_record_id = positive_id(text(field(travel_staff_verify_record, "id"))); require_condition(equal(text(field(travel_staff_verify_record, "event_id")), travel_event_id), "A selected collection returned a row from another Event."); require_condition(equal(text(field(field(travel_staff_verify_record, "attendee"), "id")), travel_person_id), "The Staff filter returned a registration for a different person."); if (remember_id(travel_staff_verify_seen, travel_staff_verify_record_id)) { require_condition(not_value(is_present(travel_staff_verify_id)), "More than one Staff record matches this person and Event. Stop for review; never choose the first."); travel_staff_verify_id = travel_staff_verify_record_id; } } if (equal(field(travel_staff_verify_page, "has_more"), false)) { break; } require_condition(not_value(is_empty(travel_staff_verify_rows)), "An empty page says has_more=true. Stop and reconcile the selected query."); travel_staff_verify_offset = add_offset(travel_staff_verify_offset, count(travel_staff_verify_rows)); } require_condition(equal(travel_staff_verify_id, travel_staff_id), "The captured Staff entry is not present in the complete current selected Event/person list. Stop before Travel creation."); if (journal_acknowledged(travel_job, "create_travel")) { let travel_saved_reservation = journal_saved(travel_job, "create_travel"); travel_reservation_id = positive_id(text(field(travel_saved_reservation, "id"))); require_condition(both(equal(text(field(travel_saved_reservation, "event_id")), travel_event_id), equal(text(field(travel_saved_reservation, "user_id")), travel_person_id)), "Saved Travel state belongs to a different Event or person. Stop and reconcile."); } else { let travel_create_fingerprint = journal_fingerprint({"event_id": travel_event_id, "reservation_type_id": "6", "origin_vendor_name": travel_hotel, "origin_checkin_date": travel_checkin, "return_checkin_date": travel_checkout, "tagged_user_ids": travel_person_id, "notify_tagged_users": travel_notify}); let travel_create_intent = journal_begin(travel_job, "create_travel", "POST", "/v1/events/travel_reservations", travel_create_fingerprint); let travel_create_response = await call("create_travel", {}, {"event_id": travel_event_id, "reservation_type_id": "6", "origin_vendor_name": travel_hotel, "origin_checkin_date": travel_checkin, "return_checkin_date": travel_checkout, "tagged_user_ids": [travel_person_id], "notify_tagged_users": equal(travel_notify, "true")}, text(field(travel_create_intent, "idempotency_key"))); require_condition(equal(response_status(travel_create_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write."); let travel_created_reservation = travel_create_response.body; travel_reservation_id = positive_id(text(field(travel_created_reservation, "id"))); require_condition(both(both(both(both(both(equal(text(field(travel_created_reservation, "id")), travel_reservation_id), equal(text(field(travel_created_reservation, "event_id")), travel_event_id)), equal(text(field(travel_created_reservation, "reservation_type_id")), "6")), equal(text(field(travel_created_reservation, "origin_vendor_name")), travel_hotel)), equal(text(field(travel_created_reservation, "origin_checkin_date")), travel_checkin)), equal(text(field(travel_created_reservation, "return_checkin_date")), travel_checkout)), "The Hotel response differs from the captured ID, Event, type, vendor or dates. Keep pending state and reconcile; do not create another reservation."); let travel_created_tags = items(field(travel_created_reservation, "tagged_users")); require_condition(equal(text(count(travel_created_tags)), "1"), "The Hotel acknowledgement must contain exactly the one selected tag before it can be saved as acknowledged."); for (const travel_created_tag of items(travel_created_tags)) { require_condition(equal(text(field(travel_created_tag, "id")), travel_person_id), "The acknowledged Hotel is tagged to a different person; keep pending state and reconcile."); } journal_acknowledge(travel_job, "create_travel", {"id": travel_reservation_id, "event_id": travel_event_id, "user_id": travel_person_id}); } let travel_final_id = ""; let travel_final_offset = "0"; let travel_final_query = {"filter_by_event_id": travel_event_id, "filter_by_tagged_user_ids": travel_person_id, "$limit": travel_page_size}; travel_final_query["filter_by_tagged_user_ids_match_type"] = "all"; while (true) { travel_final_query["$offset"] = travel_final_offset; let travel_final_response = await call("travel_readback", travel_final_query, null, null); require_condition(equal(response_status(travel_final_response), "200"), "Expected HTTP200 for the current collection; stop and reconcile another response."); let travel_final_page = travel_final_response.body; let travel_final_rows = items(field(travel_final_page, "list_data")); require_condition(equal(text(field(travel_final_page, "records_found")), text(count(travel_final_rows))), "records_found differs from this page's rows."); require_condition(is_present(text(field(travel_final_page, "total_records"))), "The collection wrapper needs total_records."); require_condition(either(equal(field(travel_final_page, "has_more"), true), equal(field(travel_final_page, "has_more"), false)), "Expected a Boolean has_more value."); for (const travel_final_record of items(travel_final_rows)) { let travel_final_record_id = positive_id(text(field(travel_final_record, "id"))); require_condition(equal(text(field(travel_final_record, "event_id")), travel_event_id), "A selected collection returned a row from another Event."); let travel_final_person_found = ""; let travel_final_tags = items(field(travel_final_record, "tagged_users")); for (const travel_final_tag of items(travel_final_tags)) { if (equal(text(field(travel_final_tag, "id")), travel_person_id)) { travel_final_person_found = "true"; } } require_condition(equal(travel_final_person_found, "true"), "The all-tags filter returned a record without the selected person."); if (equal(travel_final_record_id, travel_reservation_id)) { require_condition(both(both(both(both(both(equal(text(field(travel_final_record, "id")), travel_reservation_id), equal(text(field(travel_final_record, "event_id")), travel_event_id)), equal(text(field(travel_final_record, "reservation_type_id")), "6")), equal(text(field(travel_final_record, "origin_vendor_name")), travel_hotel)), equal(text(field(travel_final_record, "origin_checkin_date")), travel_checkin)), equal(text(field(travel_final_record, "return_checkin_date")), travel_checkout)), "The Hotel response differs from the captured ID, Event, type, vendor or dates. Keep pending state and reconcile; do not create another reservation."); require_condition(equal(text(count(travel_final_tags)), "1"), "The captured Hotel's tags changed; review them instead of silently restoring the original selection."); travel_final_id = travel_final_record_id; } } if (equal(field(travel_final_page, "has_more"), false)) { break; } require_condition(not_value(is_empty(travel_final_rows)), "An empty page says has_more=true. Stop and reconcile the selected query."); travel_final_offset = add_offset(travel_final_offset, count(travel_final_rows)); } require_condition(equal(travel_final_id, travel_reservation_id), "The captured Hotel is missing from the complete current Event/person Travel list. Reconcile it; do not repeat the create or delete records automatically."); print_value({"event_id": travel_event_id, "user_id": travel_person_id, "staff_id": travel_staff_id, "travel_reservation_id": travel_reservation_id}); } finally { travel_job.close(); } } if (require.main === module) main().catch(error => { console.error(error.message); process.exitCode = 1; }); module.exports = { main }; ``` ```python # 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\"},\"people_choices\":{\"method\":\"GET\",\"path\":\"/references/users_and_resources\"},\"travel_choices\":{\"method\":\"GET\",\"path\":\"/references/travel_reservation_types\"},\"event_before\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"find_staff\":{\"method\":\"GET\",\"path\":\"/events/staff\"},\"create_staff\":{\"method\":\"POST\",\"path\":\"/events/staff\"},\"create_travel\":{\"method\":\"POST\",\"path\":\"/events/travel_reservations\"},\"staff_readback\":{\"method\":\"GET\",\"path\":\"/events/staff\"},\"travel_readback\":{\"method\":\"GET\",\"path\":\"/events/travel_reservations\"}}}") 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) 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, key=None): route = SPEC["requests"][name] headers = {"Authorization": "Bearer " + API_KEY, "Accept": "application/json"} if route["method"] == "POST": if not key: raise RuntimeError("Persist a logical create key before sending POST") headers["Idempotency-Key"] = key data = None if body is None else json.dumps(body).encode("utf-8") if data is not None: headers["Content-Type"] = "application/json" query = urllib.parse.urlencode(params or {}) url = BASE + route["path"] + ("?" + query if query else "") # Only GET has automatic retries in this workflow. A PATCH or DELETE that got no response or a # server error is never resent blindly: it may already have been applied, so the caller reads the record first. resend = route["method"] == "GET" for attempt in range(5): try: status, raw, response_headers = transport(route["method"], url, headers, data) except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException): if not resend: raise ApiError(0, None, uncertain=True) if attempt == 4: raise time.sleep(2 ** attempt) continue response_headers = {k.lower(): v for k, v in response_headers.items()} result = None if status != 304 and raw: try: result = decode_json(raw.decode("utf-8")) except (ValueError, UnicodeError): if status < 400: raise RuntimeError("Expected a JSON success response") if status >= 500 and not resend: raise ApiError(status, result, uncertain=True) retry = resend and (status == 429 or status >= 500) if retry: if attempt == 4: raise RuntimeError("Retry limit reached; check the request outcome before starting a new create") delay = response_headers.get("retry-after", str(2 ** attempt)) time.sleep(max(0, float(delay))) continue if status >= 400: raise ApiError(status, result) return {"status": status, "body": result, "headers": response_headers, "raw": raw} raise RuntimeError("Retry limit reached") def 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 items(value): if not isinstance(value, list): raise RuntimeError("Expected a JSON array") return value def count(value): return len(items(value)) 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] 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 offsetlen(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)-offset:raise JournalRefusal('Incomplete journal frame; reconcile before retry') payload=raw[offset:offset+size];offset+=size if raw[offset:offset+1]!=b'\n' or digest(payload).encode('ascii')!=match[2]:raise JournalRefusal('Journal integrity check failed; reconcile before retry') records.append(read_strings(payload));offset+=1 return records class Journal: def __init__(self,path,base,workspace,slug,job,input_fingerprint,writes,mode="resume"): self.path=Path(path);self.lock=Path(str(self.path)+'.lock');self.fd=None;self.owned=False;self.identity=None;self.tainted=False;self.intents={};self.saved_values={} address=urlsplit(base) if address.scheme not in ('https','http')or not address.netloc or address.username is not None or address.query or address.fragment or not re.fullmatch('[a-z][a-z0-9-]*',slug):raise JournalRefusal('Use the actual API base and closed guide slug') if not job.strip() or not re.fullmatch('[1-9][0-9]*',workspace) or not re.fullmatch('[0-9A-F]{64}',input_fingerprint):raise JournalRefusal('Use an actual workspace, explicit stable job ID and exact input fingerprint') if mode not in ("new","resume"):raise JournalRefusal("Choose new or resume for this local job") self.allowed={};manifest=[] for step,method,route in writes: if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.allowed or method not in ('POST','PATCH','DELETE')or not re.fullmatch('/v1/[A-Za-z0-9_/-]+',route)or'//'in route:raise JournalRefusal('Use a closed unique write manifest') self.allowed[step]=(method,route);manifest.extend((step,method,route)) if not self.allowed:raise JournalRefusal('Only write workflows need a restart journal') self.header=['H','1',base,workspace,slug,job,input_fingerprint,digest(strings(manifest))] strings(self.header) try: self.fd=os.open(self.lock,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600);self.owned=True except FileExistsError:raise JournalRefusal('This journal is locked; do not run overlapping jobs or steal a stale lock') try: self.owner=secrets.token_hex(16);self.identity=os.fstat(self.fd) if os.write(self.fd,self.owner.encode('ascii'))!=len(self.owner):raise OSError('Incomplete lock identity write') os.fsync(self.fd) if self.path.is_symlink():raise JournalRefusal('Choose a private regular journal file') if mode=="resume" and not self.path.exists():raise JournalRefusal("Journal missing: stop and reconcile lost state before starting a new logical job") if mode=="new" and self.path.exists():raise JournalRefusal("A journal already exists; use resume for the same logical job") if mode=="new": with open(self.path,'xb',buffering=0)as target: target.write(PREAMBLE+frame(self.header));os.fsync(target.fileno()) records=decode(self.path.read_bytes()) if not records or records[0]!=self.header:raise JournalRefusal('Journal workspace/base/guide/job/input binding differs') for record in records[1:]:self.apply(record) if any(step not in self.saved_values for step in self.intents):raise JournalRefusal('A saved before-send intent lacks an ACK; stop and reconcile its outcome before retry') except BaseException: self.close();raise def apply(self,record): if not record:raise JournalRefusal('Empty journal record') if record[0]=='I': if len(record)!=6:raise JournalRefusal('Invalid intent shape') _,step,method,path,request_fingerprint,key=record if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.intents or self.allowed.get(step)!=(method,path)or not re.fullmatch('[0-9A-F]{64}',request_fingerprint)or any(name not in self.saved_values for name in self.intents):raise JournalRefusal('Invalid, future or repeated journal intent') if method=='POST'and not re.fullmatch('[0-9a-f]{32}',key)or method!='POST'and key!='':raise JournalRefusal('Invalid persisted action key') self.intents[step]={'method':method,'path':path,'request_fingerprint':request_fingerprint,'idempotency_key':key} elif record[0]=='A': if len(record)<3:raise JournalRefusal('Invalid ACK shape') _,step,count,*pairs=record if not re.fullmatch('0|[1-9][0-9]*',count)or len(pairs)!=2*int(count)or step not in self.intents or step in self.saved_values:raise JournalRefusal('ACK without exactly one prior intent') names=pairs[::2] if names!=sorted(set(names))or any(not re.fullmatch('[a-z][a-z0-9_]*',name)or name in ('api_key','exhibitday_api_key')for name in names):raise JournalRefusal('ACK saved fields must be unique sorted secret-free identifiers') self.saved_values[step]=dict(zip(names,pairs[1::2])) else:raise JournalRefusal('Unknown journal transition') def append(self,record): # The reader commits state only after complete length/digest recognition. # A torn append is retained and refused, never silently truncated. self.require_active();raw=frame(record) try: with open(self.path,'ab',buffering=0)as target: view=memoryview(raw) while view: written=target.write(view) if not written:raise OSError('Journal write did not advance') view=view[written:] os.fsync(target.fileno()) except BaseException: self.tainted=True;raise def require_active(self): if not self.owned or self.fd is None or self.identity is None or self.tainted:raise JournalRefusal('The journal scope is closed or its IO outcome needs reconciliation') current=self.lock.stat(follow_symlinks=False) if current.st_dev!=self.identity.st_dev or current.st_ino!=self.identity.st_ino or self.lock.read_text(encoding='ascii')!=self.owner:raise JournalRefusal('The journal lock was replaced; stop without deleting it') def acknowledged(self,step): self.require_active();return step in self.saved_values def saved(self,step): self.require_active() if step not in self.saved_values:raise JournalRefusal('No acknowledged state exists for this step') return dict(self.saved_values[step]) def begin(self,step,method,path,request_fingerprint): self.require_active() if step in self.intents:raise JournalRefusal('Never blindly repeat an existing action intent') key=secrets.token_hex(16)if method=='POST'else'' record=['I',step,method,path,request_fingerprint,key] # Validate on an isolated state before touching the file. old=dict(self.intents) try:self.apply(record) finally:self.intents=old self.append(record);self.apply(record) return dict(self.intents[step]) def acknowledge(self,step,saved): self.require_active() record=['A',step,str(len(saved))] for name,value in sorted(saved.items()):record.extend((name,value)) old={name:dict(value)for name,value in self.saved_values.items()} try:self.apply(record);strings(record) finally:self.saved_values=old self.append(record);self.apply(record) def close(self): if self.owned: if self.tainted: os.close(self.fd);self.fd=None;self.owned=False return # Retain this lock after failed journal IO; manual reconciliation is required. try:self.require_active() except BaseException: os.close(self.fd);self.fd=None;self.owned=False;raise os.close(self.fd);self.fd=None;self.owned=False self.lock.unlink() def __enter__(self):return self def __exit__(self,*args):self.close() def journal_values(value): if not isinstance(value, dict) or any(not isinstance(k, str) or not isinstance(v, str) for k,v in value.items()): raise JournalRefusal('Saved/fingerprint values must be exact string fields') return dict(value) def journal_acknowledge(job, step, saved): job.acknowledge(step,journal_values(saved)) def journal_acknowledged(job, step): return job.acknowledged(step) def journal_begin(job, step, method, path, request_fingerprint): return job.begin(step,method,path,request_fingerprint) def journal_fingerprint(value): return fingerprint(journal_values(value)) def journal_saved(job, step): return job.saved(step) def 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 page_size(value): if not re.fullmatch(r"[1-9][0-9]*", value) or int(value) > 2147483647: raise RuntimeError("Page size must be a positive int32") return 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 remember_id(seen, value): if value in seen: return False seen.add(value) return True 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 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 validate_staff_travel_inputs(name, start, end): from datetime import date spaces = '\u0009\u000A\u000B\u000C\u000D\u0020\u0085\u00A0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u2028\u2029\u202F\u205F\u3000' for value, label, limit in ((name, 'EXHIBITDAY_HOTEL_NAME', 125),): utf8(value) if not value or value != value.strip(spaces): raise JournalRefusal('Remove whitespace at the start or end of ' + label) if len(value.encode('utf-16-le')) // 2 > limit: raise JournalRefusal(label + ' exceeds ' + str(limit) + ' UTF-16 code units') if any(ch in name for ch in '<>\r\n') or name.lower() == 'null': raise JournalRefusal('Use plain, single-line EXHIBITDAY_HOTEL_NAME text other than null') for value, label in ((start, 'EXHIBITDAY_CHECKIN_DATE'), (end, 'EXHIBITDAY_CHECKOUT_DATE')): try: valid = re.fullmatch(r'[0-9]{4}-[0-9]{2}-[0-9]{2}', value) and date.fromisoformat(value).year >= 1753 except ValueError: valid = False if not valid: raise JournalRefusal(label + ' must be a calendar date in YYYY-MM-DD on or after 1753-01-01') if end < start: raise JournalRefusal('EXHIBITDAY_CHECKOUT_DATE must be on or after EXHIBITDAY_CHECKIN_DATE') def main(): travel_event_id = positive_id(required("EXHIBITDAY_EVENT_ID")) travel_person_id = required("EXHIBITDAY_PERSON_ID") travel_hotel = required("EXHIBITDAY_HOTEL_NAME") travel_checkin = required("EXHIBITDAY_CHECKIN_DATE") travel_checkout = required("EXHIBITDAY_CHECKOUT_DATE") travel_page_size = page_size(optional("EXHIBITDAY_PAGE_SIZE", "100")) travel_notify = optional("EXHIBITDAY_SEND_NOTIFICATIONS", "false") require_condition(either(equal(travel_notify, "true"), equal(travel_notify, "false")), "Use exact true or false for EXHIBITDAY_SEND_NOTIFICATIONS.") travel_journal_path = required("EXHIBITDAY_JOURNAL") travel_job_id = required("EXHIBITDAY_JOB_ID") travel_job_mode = optional("EXHIBITDAY_JOB_MODE", "resume") validate_staff_travel_inputs(travel_hotel, travel_checkin, travel_checkout) travel_workspace_response = call("workspace_binding", {}, None, None) require_condition(equal(response_status(travel_workspace_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write.") travel_workspace = travel_workspace_response["body"] travel_workspace_id = positive_id(text(field(travel_workspace, "id"))) travel_event_response = call("event_before", {"id": travel_event_id}, None, None) require_condition(equal(response_status(travel_event_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write.") travel_event = travel_event_response["body"] require_condition(equal(text(field(travel_event, "id")), travel_event_id), "The Event read differs from the explicit selected Event.") travel_people_response = call("people_choices", {}, None, None) require_condition(equal(response_status(travel_people_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write.") travel_people = travel_people_response["body"] travel_person_found = "" for travel_person_choice in items(items(field(travel_people, "list_data"))): if equal(text(field(travel_person_choice, "id")), travel_person_id): require_condition(not_value(is_present(travel_person_found)), "The people reference returned the same selected person more than once.") travel_person_found = travel_person_id require_condition(equal(travel_person_found, travel_person_id), "Choose a current person or resource ID from References users_and_resources before creating Staff or Travel.") travel_types_response = call("travel_choices", {}, None, None) require_condition(equal(response_status(travel_types_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write.") travel_types = travel_types_response["body"] travel_hotel_type_found = "" for travel_type_choice in items(items(field(travel_types, "list_data"))): if equal(text(field(travel_type_choice, "id")), "6"): require_condition(both(equal(text(field(travel_type_choice, "name")), "Hotel"), not_value(is_present(travel_hotel_type_found))), "The current type6 reference is not one unambiguous Hotel choice.") travel_hotel_type_found = "6" require_condition(equal(travel_hotel_type_found, "6"), "This Hotel example requires the currently declared Hotel choice6; do not substitute a different type.") travel_staff_before_id = "" travel_staff_before_offset = "0" travel_staff_before_query = {"filter_by_event_id": travel_event_id, "filter_by_attendee_user_ids": travel_person_id, "$limit": travel_page_size} travel_staff_before_seen = new_id_set() while True: travel_staff_before_query["$offset"] = travel_staff_before_offset travel_staff_before_response = call("find_staff", travel_staff_before_query, None, None) require_condition(equal(response_status(travel_staff_before_response), "200"), "Expected HTTP200 for the current collection; stop and reconcile another response.") travel_staff_before_page = travel_staff_before_response["body"] travel_staff_before_rows = items(field(travel_staff_before_page, "list_data")) require_condition(equal(text(field(travel_staff_before_page, "records_found")), text(count(travel_staff_before_rows))), "records_found differs from this page's rows.") require_condition(is_present(text(field(travel_staff_before_page, "total_records"))), "The collection wrapper needs total_records.") require_condition(either(equal(field(travel_staff_before_page, "has_more"), True), equal(field(travel_staff_before_page, "has_more"), False)), "Expected a Boolean has_more value.") for travel_staff_before_record in items(travel_staff_before_rows): travel_staff_before_record_id = positive_id(text(field(travel_staff_before_record, "id"))) require_condition(equal(text(field(travel_staff_before_record, "event_id")), travel_event_id), "A selected collection returned a row from another Event.") require_condition(equal(text(field(field(travel_staff_before_record, "attendee"), "id")), travel_person_id), "The Staff filter returned a registration for a different person.") if remember_id(travel_staff_before_seen, travel_staff_before_record_id): require_condition(not_value(is_present(travel_staff_before_id)), "More than one Staff record matches this person and Event. Stop for review; never choose the first.") travel_staff_before_id = travel_staff_before_record_id if equal(field(travel_staff_before_page, "has_more"), False): break require_condition(not_value(is_empty(travel_staff_before_rows)), "An empty page says has_more=true. Stop and reconcile the selected query.") travel_staff_before_offset = add_offset(travel_staff_before_offset, count(travel_staff_before_rows)) travel_input_fingerprint = journal_fingerprint({"workflow_contract_sha256": "A4CE8A49EF9814D6F6F256BE0525D5A77FF09C69232E21624504C3C3DDA294AB", "event_id": travel_event_id, "user_id": travel_person_id, "hotel": travel_hotel, "checkin": travel_checkin, "checkout": travel_checkout, "notify": travel_notify, "page_size": travel_page_size}) travel_job = open_journal(travel_journal_path, "https://api.exhibitday.com/v1", travel_workspace_id, "staff-travel-tags", travel_job_id, travel_input_fingerprint, [["create_staff", "POST", "/v1/events/staff"], ["create_travel", "POST", "/v1/events/travel_reservations"]], travel_job_mode) try: require_condition(either(not_value(journal_acknowledged(travel_job, "create_travel")), journal_acknowledged(travel_job, "create_staff")), "A Travel create is acknowledged before Staff. Stop and reconcile the saved state.") travel_staff_id = "" travel_reservation_id = "" if journal_acknowledged(travel_job, "create_staff"): travel_saved_staff = journal_saved(travel_job, "create_staff") travel_staff_id = positive_id(text(field(travel_saved_staff, "id"))) require_condition(both(equal(text(field(travel_saved_staff, "event_id")), travel_event_id), both(equal(text(field(field(travel_saved_staff, "attendee"), "id")), travel_person_id), equal(text(field(travel_saved_staff, "id")), travel_staff_id))), "The Staff record differs from the captured ID, selected Event or person. Reconcile it; do not create a replacement.") require_condition(equal(travel_staff_before_id, travel_staff_id), "The acknowledged Staff entry is missing or changed. Review the current Staff list before continuing.") else: require_condition(not_value(is_present(travel_staff_before_id)), "This person already has a Staff entry without a saved acknowledgement for this job. Review that entry; do not add another registration.") travel_staff_fingerprint = journal_fingerprint({"event_id": travel_event_id, "user_id": travel_person_id, "registration_type": "Conference pass", "notify_attendee": travel_notify}) travel_staff_intent = journal_begin(travel_job, "create_staff", "POST", "/v1/events/staff", travel_staff_fingerprint) travel_staff_create_response = call("create_staff", {}, {"event_id": travel_event_id, "attendee_user_id": travel_person_id, "registration_type": "Conference pass", "notify_attendee": equal(travel_notify, "true")}, text(field(travel_staff_intent, "idempotency_key"))) require_condition(equal(response_status(travel_staff_create_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write.") travel_created_staff = travel_staff_create_response["body"] travel_staff_id = positive_id(text(field(travel_created_staff, "id"))) require_condition(both(equal(text(field(travel_created_staff, "event_id")), travel_event_id), both(equal(text(field(field(travel_created_staff, "attendee"), "id")), travel_person_id), equal(text(field(travel_created_staff, "id")), travel_staff_id))), "The Staff record differs from the captured ID, selected Event or person. Reconcile it; do not create a replacement.") require_condition(equal(text(field(travel_created_staff, "registration_type")), "Conference pass"), "The Staff acknowledgement has a different registration type; preserve pending state and reconcile.") journal_acknowledge(travel_job, "create_staff", {"id": travel_staff_id, "event_id": travel_event_id, "user_id": travel_person_id}) travel_staff_verify_id = "" travel_staff_verify_offset = "0" travel_staff_verify_query = {"filter_by_event_id": travel_event_id, "filter_by_attendee_user_ids": travel_person_id, "$limit": travel_page_size} travel_staff_verify_seen = new_id_set() while True: travel_staff_verify_query["$offset"] = travel_staff_verify_offset travel_staff_verify_response = call("staff_readback", travel_staff_verify_query, None, None) require_condition(equal(response_status(travel_staff_verify_response), "200"), "Expected HTTP200 for the current collection; stop and reconcile another response.") travel_staff_verify_page = travel_staff_verify_response["body"] travel_staff_verify_rows = items(field(travel_staff_verify_page, "list_data")) require_condition(equal(text(field(travel_staff_verify_page, "records_found")), text(count(travel_staff_verify_rows))), "records_found differs from this page's rows.") require_condition(is_present(text(field(travel_staff_verify_page, "total_records"))), "The collection wrapper needs total_records.") require_condition(either(equal(field(travel_staff_verify_page, "has_more"), True), equal(field(travel_staff_verify_page, "has_more"), False)), "Expected a Boolean has_more value.") for travel_staff_verify_record in items(travel_staff_verify_rows): travel_staff_verify_record_id = positive_id(text(field(travel_staff_verify_record, "id"))) require_condition(equal(text(field(travel_staff_verify_record, "event_id")), travel_event_id), "A selected collection returned a row from another Event.") require_condition(equal(text(field(field(travel_staff_verify_record, "attendee"), "id")), travel_person_id), "The Staff filter returned a registration for a different person.") if remember_id(travel_staff_verify_seen, travel_staff_verify_record_id): require_condition(not_value(is_present(travel_staff_verify_id)), "More than one Staff record matches this person and Event. Stop for review; never choose the first.") travel_staff_verify_id = travel_staff_verify_record_id if equal(field(travel_staff_verify_page, "has_more"), False): break require_condition(not_value(is_empty(travel_staff_verify_rows)), "An empty page says has_more=true. Stop and reconcile the selected query.") travel_staff_verify_offset = add_offset(travel_staff_verify_offset, count(travel_staff_verify_rows)) require_condition(equal(travel_staff_verify_id, travel_staff_id), "The captured Staff entry is not present in the complete current selected Event/person list. Stop before Travel creation.") if journal_acknowledged(travel_job, "create_travel"): travel_saved_reservation = journal_saved(travel_job, "create_travel") travel_reservation_id = positive_id(text(field(travel_saved_reservation, "id"))) require_condition(both(equal(text(field(travel_saved_reservation, "event_id")), travel_event_id), equal(text(field(travel_saved_reservation, "user_id")), travel_person_id)), "Saved Travel state belongs to a different Event or person. Stop and reconcile.") else: travel_create_fingerprint = journal_fingerprint({"event_id": travel_event_id, "reservation_type_id": "6", "origin_vendor_name": travel_hotel, "origin_checkin_date": travel_checkin, "return_checkin_date": travel_checkout, "tagged_user_ids": travel_person_id, "notify_tagged_users": travel_notify}) travel_create_intent = journal_begin(travel_job, "create_travel", "POST", "/v1/events/travel_reservations", travel_create_fingerprint) travel_create_response = call("create_travel", {}, {"event_id": travel_event_id, "reservation_type_id": "6", "origin_vendor_name": travel_hotel, "origin_checkin_date": travel_checkin, "return_checkin_date": travel_checkout, "tagged_user_ids": [travel_person_id], "notify_tagged_users": equal(travel_notify, "true")}, text(field(travel_create_intent, "idempotency_key"))) require_condition(equal(response_status(travel_create_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write.") travel_created_reservation = travel_create_response["body"] travel_reservation_id = positive_id(text(field(travel_created_reservation, "id"))) require_condition(both(both(both(both(both(equal(text(field(travel_created_reservation, "id")), travel_reservation_id), equal(text(field(travel_created_reservation, "event_id")), travel_event_id)), equal(text(field(travel_created_reservation, "reservation_type_id")), "6")), equal(text(field(travel_created_reservation, "origin_vendor_name")), travel_hotel)), equal(text(field(travel_created_reservation, "origin_checkin_date")), travel_checkin)), equal(text(field(travel_created_reservation, "return_checkin_date")), travel_checkout)), "The Hotel response differs from the captured ID, Event, type, vendor or dates. Keep pending state and reconcile; do not create another reservation.") travel_created_tags = items(field(travel_created_reservation, "tagged_users")) require_condition(equal(text(count(travel_created_tags)), "1"), "The Hotel acknowledgement must contain exactly the one selected tag before it can be saved as acknowledged.") for travel_created_tag in items(travel_created_tags): require_condition(equal(text(field(travel_created_tag, "id")), travel_person_id), "The acknowledged Hotel is tagged to a different person; keep pending state and reconcile.") journal_acknowledge(travel_job, "create_travel", {"id": travel_reservation_id, "event_id": travel_event_id, "user_id": travel_person_id}) travel_final_id = "" travel_final_offset = "0" travel_final_query = {"filter_by_event_id": travel_event_id, "filter_by_tagged_user_ids": travel_person_id, "$limit": travel_page_size} travel_final_query["filter_by_tagged_user_ids_match_type"] = "all" while True: travel_final_query["$offset"] = travel_final_offset travel_final_response = call("travel_readback", travel_final_query, None, None) require_condition(equal(response_status(travel_final_response), "200"), "Expected HTTP200 for the current collection; stop and reconcile another response.") travel_final_page = travel_final_response["body"] travel_final_rows = items(field(travel_final_page, "list_data")) require_condition(equal(text(field(travel_final_page, "records_found")), text(count(travel_final_rows))), "records_found differs from this page's rows.") require_condition(is_present(text(field(travel_final_page, "total_records"))), "The collection wrapper needs total_records.") require_condition(either(equal(field(travel_final_page, "has_more"), True), equal(field(travel_final_page, "has_more"), False)), "Expected a Boolean has_more value.") for travel_final_record in items(travel_final_rows): travel_final_record_id = positive_id(text(field(travel_final_record, "id"))) require_condition(equal(text(field(travel_final_record, "event_id")), travel_event_id), "A selected collection returned a row from another Event.") travel_final_person_found = "" travel_final_tags = items(field(travel_final_record, "tagged_users")) for travel_final_tag in items(travel_final_tags): if equal(text(field(travel_final_tag, "id")), travel_person_id): travel_final_person_found = "true" require_condition(equal(travel_final_person_found, "true"), "The all-tags filter returned a record without the selected person.") if equal(travel_final_record_id, travel_reservation_id): require_condition(both(both(both(both(both(equal(text(field(travel_final_record, "id")), travel_reservation_id), equal(text(field(travel_final_record, "event_id")), travel_event_id)), equal(text(field(travel_final_record, "reservation_type_id")), "6")), equal(text(field(travel_final_record, "origin_vendor_name")), travel_hotel)), equal(text(field(travel_final_record, "origin_checkin_date")), travel_checkin)), equal(text(field(travel_final_record, "return_checkin_date")), travel_checkout)), "The Hotel response differs from the captured ID, Event, type, vendor or dates. Keep pending state and reconcile; do not create another reservation.") require_condition(equal(text(count(travel_final_tags)), "1"), "The captured Hotel's tags changed; review them instead of silently restoring the original selection.") travel_final_id = travel_final_record_id if equal(field(travel_final_page, "has_more"), False): break require_condition(not_value(is_empty(travel_final_rows)), "An empty page says has_more=true. Stop and reconcile the selected query.") travel_final_offset = add_offset(travel_final_offset, count(travel_final_rows)) require_condition(equal(travel_final_id, travel_reservation_id), "The captured Hotel is missing from the complete current Event/person Travel list. Reconcile it; do not repeat the create or delete records automatically.") print_value({"event_id": travel_event_id, "user_id": travel_person_id, "staff_id": travel_staff_id, "travel_reservation_id": travel_reservation_id}) finally: travel_job.close() if __name__ == "__main__": main() ``` ```csharp // .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\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"people_choices\":{\"method\":\"GET\",\"path\":\"/references/users_and_resources\"},\"travel_choices\":{\"method\":\"GET\",\"path\":\"/references/travel_reservation_types\"},\"event_before\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"find_staff\":{\"method\":\"GET\",\"path\":\"/events/staff\"},\"create_staff\":{\"method\":\"POST\",\"path\":\"/events/staff\"},\"create_travel\":{\"method\":\"POST\",\"path\":\"/events/travel_reservations\"},\"staff_readback\":{\"method\":\"GET\",\"path\":\"/events/staff\"},\"travel_readback\":{\"method\":\"GET\",\"path\":\"/events/travel_reservations\"}}}"); static readonly string ApiKey = HeaderKey(Required("EXHIBITDAY_API_KEY")); static string HeaderKey(string value) { if(value.Any(c=>c<32||c>126))throw new Exception("Use the API key as one ASCII header value without control characters");return value; } static readonly HttpClient Client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false }) { Timeout = TimeSpan.FromSeconds(30) }; internal static Func> Send = request => Client.SendAsync(request); sealed class Result { public int Status; public JsonNode Body; public Dictionary Headers; public string Raw; } // 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(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 Call(string name, JsonObject query = null, JsonNode body = null, string key = null) { var route = Spec["requests"][name]; var method = Text(route["method"]); var headers = new Dictionary(StringComparer.OrdinalIgnoreCase) { ["Authorization"] = "Bearer " + ApiKey, ["Accept"] = "application/json" }; if (method == "POST") { if (string.IsNullOrEmpty(key)) throw new Exception("Persist a logical create key before sending POST"); headers["Idempotency-Key"] = key; } 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); // 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. var resend = method == "GET"; 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 Send(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 = resend && (status == 429 || status >= 500); 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, Raw = raw }; } } throw new Exception("Retry limit reached"); } static string AddOffset(string offset,long received) { var result=checked(long.Parse(offset,CultureInfo.InvariantCulture)+received);if(received<=0||result>int.MaxValue)throw new Exception("Cannot advance this int32 offset; reconcile the query");return result.ToString(CultureInfo.InvariantCulture); } static bool Both(bool left,bool right)=>left&&right; static JsonNode CopyNode(JsonNode value) => value?.DeepClone(); static JsonArray Items(JsonNode value) => value as JsonArray ?? throw new Exception("Expected a JSON array"); static long Count(JsonNode value) => Items(value).Count; static bool Either(bool left,bool right) => left || right; static object Scalar(object value) { if(value is JsonValue json){if(json.TryGetValue(out var boolean))return boolean;if(json.TryGetValue(out var text))return text;return json.ToJsonString();}return value; } static bool Equal(object left,object right) => object.Equals(Scalar(left),Scalar(right)); static JsonNode Field(JsonNode value,string name) { if(value is not JsonObject obj || !obj.TryGetPropertyValue(name,out var item))throw new Exception("Missing response field: "+name);return item; } static bool IsEmpty(JsonNode value) => Count(value)==0; static bool IsPresent(string value) => value!=null && value!=""; public sealed class JournalRefusal : Exception { public JournalRefusal(string message) : base(message) {} } public static class JournalProtocol { public static readonly byte[] Preamble = Encoding.ASCII.GetBytes("EXHIBITDAY-GUIDE-JOURNAL 1\n"); static readonly UTF8Encoding Utf8 = new UTF8Encoding(false, true); static bool Match(string value,string pattern) => value != null && System.Text.RegularExpressions.Regex.IsMatch(value,"\\A(?:"+pattern+")\\z",System.Text.RegularExpressions.RegexOptions.CultureInvariant); public static bool Valid(string value,string pattern) => Match(value,pattern); static string Ascii(byte[] raw,int start,int count) { for(var i=start;i127)throw new JournalRefusal("Journal framing must be canonical ASCII");return Encoding.ASCII.GetString(raw,start,count); } public static byte[] Strings(IEnumerable values) { using var data=new MemoryStream(); foreach(var value in values){if(value==null)throw new JournalRefusal("Journal fields are exact strings");var item=Utf8.GetBytes(value);var prefix=Encoding.ASCII.GetBytes(item.Length.ToString(CultureInfo.InvariantCulture)+":");data.Write(prefix);data.Write(item);} return data.ToArray(); } public static List ReadStrings(byte[] raw) { var values=new List();var offset=0; while(offsetraw.Length-offset)throw new JournalRefusal("Incomplete journal string");values.Add(Utf8.GetString(raw,offset,(int)size));offset+=(int)size;} return values; } public static string Digest(byte[] raw)=>Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(raw)); public static string Fingerprint(IReadOnlyDictionary pairs) { var values=new List();foreach(var name in pairs.Keys.OrderBy(n=>n,StringComparer.Ordinal)){ if(!Match(name,"[A-Za-z0-9_.-]+")||new[]{"api_key","exhibitday_api_key"}.Contains(name.ToLowerInvariant()))throw new JournalRefusal("Use explicit secret-free fingerprint names");values.Add(name);values.Add(pairs[name]);} return Digest(Strings(values)); } public static byte[] Frame(IEnumerable values) { var payload=Strings(values);var header=Encoding.ASCII.GetBytes(payload.Length.ToString(CultureInfo.InvariantCulture)+" "+Digest(payload)+"\n"); using var data=new MemoryStream();data.Write(header);data.Write(payload);data.WriteByte(10);return data.ToArray(); } public static List> Decode(byte[] raw) { if(raw.Length>(); while(offset=raw.Length-offset)throw new JournalRefusal("Incomplete frame; reconcile before retry");var payload=raw.AsSpan(offset,(int)size).ToArray();offset+=(int)size; if(raw[offset]!=10||Digest(payload)!=split[1])throw new JournalRefusal("Journal integrity failed; reconcile before retry");records.Add(ReadStrings(payload));offset++;} return records; } } public sealed class Journal : IDisposable { readonly string path,lockPath,owner;readonly List header; readonly Dictionary allowed=new Dictionary(StringComparer.Ordinal); Dictionary> intents=new Dictionary>(StringComparer.Ordinal),savedValues=new Dictionary>(StringComparer.Ordinal); FileStream lockStream;bool owned,tainted;DateTime creation; static FileStream CreatePrivate(string target,FileAccess access,FileShare share) { var options=new FileStreamOptions{Mode=FileMode.CreateNew,Access=access,Share=share}; if(!OperatingSystem.IsWindows())options.UnixCreateMode=UnixFileMode.UserRead|UnixFileMode.UserWrite; return new FileStream(target,options); } public Journal(string path,string apiBase,string workspace,string slug,string job,string inputFingerprint,IEnumerable<(string Step,string Method,string Path)> writes,string mode="resume") { this.path=path;lockPath=path+".lock";owner=Convert.ToHexString(System.Security.Cryptography.RandomNumberGenerator.GetBytes(16)).ToLowerInvariant(); if(!Uri.TryCreate(apiBase,UriKind.Absolute,out var address)||address.Scheme!="https"&&address.Scheme!="http"||address.UserInfo.Length!=0||address.Query.Length!=0||address.Fragment.Length!=0||!JournalProtocol.Valid(slug,"[a-z][a-z0-9-]*"))throw new JournalRefusal("Use the actual API base and closed guide slug"); if(string.IsNullOrWhiteSpace(job)||!JournalProtocol.Valid(workspace,"[1-9][0-9]*")||!JournalProtocol.Valid(inputFingerprint,"[0-9A-F]{64}"))throw new JournalRefusal("Use actual workspace, stable explicit job ID and exact fingerprint"); if(mode!="new"&&mode!="resume")throw new JournalRefusal("Choose new or resume for this local job"); var manifest=new List();foreach(var write in writes){ if(!JournalProtocol.Valid(write.Step,"[a-z][a-z0-9_-]*")||allowed.ContainsKey(write.Step)||!new[]{"POST","PATCH","DELETE"}.Contains(write.Method)||!JournalProtocol.Valid(write.Path,"/v1/[A-Za-z0-9_/-]+")||write.Path.Contains("//"))throw new JournalRefusal("Use a closed unique write manifest"); allowed.Add(write.Step,(write.Method,write.Path));manifest.AddRange(new[]{write.Step,write.Method,write.Path});} if(allowed.Count==0)throw new JournalRefusal("Only write workflows need a restart journal"); header=new List{"H","1",apiBase,workspace,slug,job,inputFingerprint,JournalProtocol.Digest(JournalProtocol.Strings(manifest))};JournalProtocol.Strings(header); try{lockStream=CreatePrivate(lockPath,FileAccess.ReadWrite,FileShare.Read);owned=true;} catch(IOException)when(File.Exists(lockPath)){throw new JournalRefusal("This journal is locked; do not overlap jobs or steal a stale lock");} try{ var token=Encoding.ASCII.GetBytes(owner);lockStream.Write(token);lockStream.Flush(true);creation=File.GetCreationTimeUtc(lockPath); if(File.Exists(path)&&(File.GetAttributes(path)&FileAttributes.ReparsePoint)!=0)throw new JournalRefusal("Choose a private regular journal file"); if(mode=="resume"&&!File.Exists(path))throw new JournalRefusal("Journal missing: stop and reconcile lost state before starting a new logical job"); if(mode=="new"&&File.Exists(path))throw new JournalRefusal("Journal exists; use resume for the same logical job"); if(mode=="new"){using var output=CreatePrivate(path,FileAccess.Write,FileShare.None);output.Write(JournalProtocol.Preamble);output.Write(JournalProtocol.Frame(header));output.Flush(true);} var records=JournalProtocol.Decode(File.ReadAllBytes(path));if(records.Count==0||!records[0].SequenceEqual(header))throw new JournalRefusal("Journal workspace/base/guide/job/input binding differs"); foreach(var record in records.Skip(1))Apply(record);if(intents.Keys.Any(step=>!savedValues.ContainsKey(step)))throw new JournalRefusal("Saved intent lacks ACK; stop and reconcile before retry"); }catch{Dispose();throw;} } void Apply(IReadOnlyList record) { if(record.Count==0)throw new JournalRefusal("Empty journal record"); if(record[0]=="I"){ if(record.Count!=6)throw new JournalRefusal("Invalid intent shape");var step=record[1];var method=record[2];var route=record[3];var fingerprint=record[4];var key=record[5]; if(!JournalProtocol.Valid(step,"[a-z][a-z0-9_-]*")||intents.ContainsKey(step)||!allowed.TryGetValue(step,out var expected)||expected!=(method,route)||!JournalProtocol.Valid(fingerprint,"[0-9A-F]{64}")||intents.Keys.Any(name=>!savedValues.ContainsKey(name)))throw new JournalRefusal("Invalid, future or repeated intent"); if(method=="POST"&&!JournalProtocol.Valid(key,"[0-9a-f]{32}")||method!="POST"&&key!="")throw new JournalRefusal("Invalid persisted action key"); intents.Add(step,new Dictionary{{"method",method},{"path",route},{"request_fingerprint",fingerprint},{"idempotency_key",key}}); }else if(record[0]=="A"){ if(record.Count<3||!JournalProtocol.Valid(record[2],"0|[1-9][0-9]*")||!long.TryParse(record[2],NumberStyles.None,CultureInfo.InvariantCulture,out var count)||count!=(record.Count-3L)/2||record.Count%2!=1||!intents.ContainsKey(record[1])||savedValues.ContainsKey(record[1]))throw new JournalRefusal("ACK without exactly one prior intent"); var names=record.Skip(3).Where((_,index)=>index%2==0).ToArray(); if(!names.SequenceEqual(names.Distinct(StringComparer.Ordinal).OrderBy(name=>name,StringComparer.Ordinal))||names.Any(name=>!JournalProtocol.Valid(name,"[a-z][a-z0-9_]*")||name=="api_key"||name=="exhibitday_api_key"))throw new JournalRefusal("ACK fields must be unique sorted secret-free identifiers"); var saved=new Dictionary(StringComparer.Ordinal);for(var i=0;i record) { RequireActive();var raw=JournalProtocol.Frame(record); try{using var output=new FileStream(path,FileMode.Append,FileAccess.Write,FileShare.None);output.Write(raw);output.Flush(true);} catch{tainted=true;throw;} } public bool Acknowledged(string step){RequireActive();return savedValues.ContainsKey(step);} public Dictionary Saved(string step){RequireActive();if(!savedValues.ContainsKey(step))throw new JournalRefusal("No acknowledged state exists");return new Dictionary(savedValues[step],StringComparer.Ordinal);} public Dictionary Begin(string step,string method,string route,string requestFingerprint) { RequireActive();if(intents.ContainsKey(step))throw new JournalRefusal("Never blindly repeat an existing action"); var key=method=="POST"?Convert.ToHexString(System.Security.Cryptography.RandomNumberGenerator.GetBytes(16)).ToLowerInvariant():""; var record=new[]{"I",step,method,route,requestFingerprint,key};var previous=new Dictionary>(intents,StringComparer.Ordinal);try{Apply(record);}finally{intents=previous;} Append(record);Apply(record);return new Dictionary(intents[step],StringComparer.Ordinal); } public void Acknowledge(string step,IReadOnlyDictionary saved) { RequireActive();var record=new List{"A",step,saved.Count.ToString(CultureInfo.InvariantCulture)};foreach(var name in saved.Keys.OrderBy(name=>name,StringComparer.Ordinal))record.AddRange(new[]{name,saved[name]}); var previous=new Dictionary>(savedValues,StringComparer.Ordinal);try{Apply(record);JournalProtocol.Strings(record);}finally{savedValues=previous;} Append(record);Apply(record); } public void Dispose() { if(!owned)return;if(tainted){lockStream.Dispose();lockStream=null;owned=false;return;} try{RequireActive();}catch{lockStream.Dispose();lockStream=null;owned=false;throw;} lockStream.Dispose();lockStream=null;owned=false;File.Delete(lockPath); } } static Dictionary JournalValues(JsonNode value) { if(value is not JsonObject fields)throw new JournalRefusal("Saved/fingerprint values need an explicit object"); var result=new Dictionary(StringComparer.Ordinal); foreach(var field in fields){if(field.Value is not JsonValue item || !item.TryGetValue(out var text) || text==null)throw new JournalRefusal("Saved/fingerprint values must be exact strings");result.Add(field.Key,text);}return result; } static JsonObject JournalObject(IReadOnlyDictionary fields){var result=new JsonObject();foreach(var field in fields)result.Add(field.Key,JsonValue.Create(field.Value));return result;} static void JournalAcknowledge(Journal job,string step,JsonNode saved)=>job.Acknowledge(step,JournalValues(saved)); static bool JournalAcknowledged(Journal job,string step)=>job.Acknowledged(step); static JsonNode JournalBegin(Journal job,string step,string method,string path,string requestFingerprint)=>JournalObject(job.Begin(step,method,path,requestFingerprint)); static string JournalFingerprint(JsonNode value)=>JournalProtocol.Fingerprint(JournalValues(value)); static JsonNode JournalSaved(Journal job,string step)=>JournalObject(job.Saved(step)); static HashSet NewIdSet() => new HashSet(StringComparer.Ordinal); static bool NotValue(bool value) => !value; static Journal OpenJournal(string path,string apiBase,string workspace,string slug,string job,string inputFingerprint,JsonNode manifest,string mode) { if(manifest is not JsonArray rows)throw new JournalRefusal("A closed write manifest is required");var writes=new List<(string,string,string)>(); foreach(var row in rows){if(row is not JsonArray fields || fields.Count!=3)throw new JournalRefusal("Each write must bind its step/method/path");var values=fields.Select(value=>value is JsonValue item&&item.TryGetValue(out var text)&&text!=null?text:throw new JournalRefusal("Manifest values are exact strings")).ToArray();writes.Add((values[0],values[1],values[2]));} return new Journal(path,apiBase,workspace,slug,job,inputFingerprint,writes,mode); } static string Optional(string name,string fallback) { var value=Environment.GetEnvironmentVariable(name);return value==null||value==""?fallback:value; } static string PageSize(string value) { if(string.IsNullOrEmpty(value)||value[0]=='0'||!value.All(c=>c>='0'&&c<='9')||!int.TryParse(value,NumberStyles.None,CultureInfo.InvariantCulture,out var limit)||limit<=0)throw new Exception("Page size must be a positive int32");return value; } static string PositiveId(string value) { if(string.IsNullOrEmpty(value)||value[0]=='0'||!value.All(c=>c>='0'&&c<='9')||!long.TryParse(value,NumberStyles.None,CultureInfo.InvariantCulture,out var id)||id<=0)throw new Exception("Use a positive record ID");return value; } static void PrintValue(object value) => Console.WriteLine(value is string text ? text : JsonSerializer.Serialize(value)); static bool RememberId(HashSet seen,string value) => seen.Add(value); static void RequireCondition(bool value,string message) { if(!value)throw new Exception(message); } static string ResponseStatus(Result value)=>value.Status.ToString(CultureInfo.InvariantCulture); static string Text(object value) => value==null?"":value is JsonNode node?Text(node):Convert.ToString(value,CultureInfo.InvariantCulture); static void ValidateStaffTravelInputs(string name, string start, string end) { void TextInput(string value, string label, int limit) { JournalProtocol.Strings(new[] { value }); if (value.Length == 0 || value != value.Trim()) throw new JournalRefusal("Remove whitespace at the start or end of " + label); if (value.Length > limit) throw new JournalRefusal(label + " exceeds " + limit + " UTF-16 code units"); } void DateInput(string value, string label) { if (!DateTime.TryParseExact(value, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date) || value != date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) || date.Year < 1753) throw new JournalRefusal(label + " must be a calendar date in YYYY-MM-DD on or after 1753-01-01"); } TextInput(name, "EXHIBITDAY_HOTEL_NAME", 125); if (name.IndexOfAny(new[] { '<', '>', '\r', '\n' }) >= 0 || name.Equals("null", StringComparison.OrdinalIgnoreCase)) throw new JournalRefusal("Use plain, single-line EXHIBITDAY_HOTEL_NAME text other than null"); DateInput(start, "EXHIBITDAY_CHECKIN_DATE"); DateInput(end, "EXHIBITDAY_CHECKOUT_DATE"); if (string.CompareOrdinal(end, start) < 0) throw new JournalRefusal("EXHIBITDAY_CHECKOUT_DATE must be on or after EXHIBITDAY_CHECKIN_DATE"); } internal static async Task Run() { var travel_event_id = PositiveId(Required("EXHIBITDAY_EVENT_ID")); var travel_person_id = Required("EXHIBITDAY_PERSON_ID"); var travel_hotel = Required("EXHIBITDAY_HOTEL_NAME"); var travel_checkin = Required("EXHIBITDAY_CHECKIN_DATE"); var travel_checkout = Required("EXHIBITDAY_CHECKOUT_DATE"); var travel_page_size = PageSize(Optional("EXHIBITDAY_PAGE_SIZE", "100")); var travel_notify = Optional("EXHIBITDAY_SEND_NOTIFICATIONS", "false"); RequireCondition(Either(Equal(travel_notify, "true"), Equal(travel_notify, "false")), "Use exact true or false for EXHIBITDAY_SEND_NOTIFICATIONS."); var travel_journal_path = Required("EXHIBITDAY_JOURNAL"); var travel_job_id = Required("EXHIBITDAY_JOB_ID"); var travel_job_mode = Optional("EXHIBITDAY_JOB_MODE", "resume"); ValidateStaffTravelInputs(travel_hotel, travel_checkin, travel_checkout); var travel_workspace_response = await Call("workspace_binding", new JsonObject { }, null, null); RequireCondition(Equal(ResponseStatus(travel_workspace_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write."); var travel_workspace = travel_workspace_response.Body; var travel_workspace_id = PositiveId(Text(Field(travel_workspace, "id"))); var travel_event_response = await Call("event_before", new JsonObject { ["id"] = travel_event_id }, null, null); RequireCondition(Equal(ResponseStatus(travel_event_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write."); var travel_event = travel_event_response.Body; RequireCondition(Equal(Text(Field(travel_event, "id")), travel_event_id), "The Event read differs from the explicit selected Event."); var travel_people_response = await Call("people_choices", new JsonObject { }, null, null); RequireCondition(Equal(ResponseStatus(travel_people_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write."); var travel_people = travel_people_response.Body; var travel_person_found = ""; foreach (var travel_person_choice in Items(Items(Field(travel_people, "list_data")))) { if (Equal(Text(Field(travel_person_choice, "id")), travel_person_id)) { RequireCondition(NotValue(IsPresent(travel_person_found)), "The people reference returned the same selected person more than once."); travel_person_found = travel_person_id; } } RequireCondition(Equal(travel_person_found, travel_person_id), "Choose a current person or resource ID from References users_and_resources before creating Staff or Travel."); var travel_types_response = await Call("travel_choices", new JsonObject { }, null, null); RequireCondition(Equal(ResponseStatus(travel_types_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write."); var travel_types = travel_types_response.Body; var travel_hotel_type_found = ""; foreach (var travel_type_choice in Items(Items(Field(travel_types, "list_data")))) { if (Equal(Text(Field(travel_type_choice, "id")), "6")) { RequireCondition(Both(Equal(Text(Field(travel_type_choice, "name")), "Hotel"), NotValue(IsPresent(travel_hotel_type_found))), "The current type6 reference is not one unambiguous Hotel choice."); travel_hotel_type_found = "6"; } } RequireCondition(Equal(travel_hotel_type_found, "6"), "This Hotel example requires the currently declared Hotel choice6; do not substitute a different type."); var travel_staff_before_id = ""; var travel_staff_before_offset = "0"; var travel_staff_before_query = new JsonObject { ["filter_by_event_id"] = travel_event_id, ["filter_by_attendee_user_ids"] = travel_person_id, ["$limit"] = travel_page_size }; var travel_staff_before_seen = NewIdSet(); while (true) { travel_staff_before_query["$offset"] = travel_staff_before_offset; var travel_staff_before_response = await Call("find_staff", travel_staff_before_query, null, null); RequireCondition(Equal(ResponseStatus(travel_staff_before_response), "200"), "Expected HTTP200 for the current collection; stop and reconcile another response."); var travel_staff_before_page = travel_staff_before_response.Body; var travel_staff_before_rows = Items(Field(travel_staff_before_page, "list_data")); RequireCondition(Equal(Text(Field(travel_staff_before_page, "records_found")), Text(Count(travel_staff_before_rows))), "records_found differs from this page's rows."); RequireCondition(IsPresent(Text(Field(travel_staff_before_page, "total_records"))), "The collection wrapper needs total_records."); RequireCondition(Either(Equal(Field(travel_staff_before_page, "has_more"), true), Equal(Field(travel_staff_before_page, "has_more"), false)), "Expected a Boolean has_more value."); foreach (var travel_staff_before_record in Items(travel_staff_before_rows)) { var travel_staff_before_record_id = PositiveId(Text(Field(travel_staff_before_record, "id"))); RequireCondition(Equal(Text(Field(travel_staff_before_record, "event_id")), travel_event_id), "A selected collection returned a row from another Event."); RequireCondition(Equal(Text(Field(Field(travel_staff_before_record, "attendee"), "id")), travel_person_id), "The Staff filter returned a registration for a different person."); if (RememberId(travel_staff_before_seen, travel_staff_before_record_id)) { RequireCondition(NotValue(IsPresent(travel_staff_before_id)), "More than one Staff record matches this person and Event. Stop for review; never choose the first."); travel_staff_before_id = travel_staff_before_record_id; } } if (Equal(Field(travel_staff_before_page, "has_more"), false)) { break; } RequireCondition(NotValue(IsEmpty(travel_staff_before_rows)), "An empty page says has_more=true. Stop and reconcile the selected query."); travel_staff_before_offset = AddOffset(travel_staff_before_offset, Count(travel_staff_before_rows)); } var travel_input_fingerprint = JournalFingerprint(new JsonObject { ["workflow_contract_sha256"] = "A4CE8A49EF9814D6F6F256BE0525D5A77FF09C69232E21624504C3C3DDA294AB", ["event_id"] = travel_event_id, ["user_id"] = travel_person_id, ["hotel"] = travel_hotel, ["checkin"] = travel_checkin, ["checkout"] = travel_checkout, ["notify"] = travel_notify, ["page_size"] = travel_page_size }); using (var travel_job = OpenJournal(travel_journal_path, "https://api.exhibitday.com/v1", travel_workspace_id, "staff-travel-tags", travel_job_id, travel_input_fingerprint, new JsonArray(new JsonArray("create_staff", "POST", "/v1/events/staff"), new JsonArray("create_travel", "POST", "/v1/events/travel_reservations")), travel_job_mode)) { RequireCondition(Either(NotValue(JournalAcknowledged(travel_job, "create_travel")), JournalAcknowledged(travel_job, "create_staff")), "A Travel create is acknowledged before Staff. Stop and reconcile the saved state."); var travel_staff_id = ""; var travel_reservation_id = ""; if (JournalAcknowledged(travel_job, "create_staff")) { var travel_saved_staff = JournalSaved(travel_job, "create_staff"); travel_staff_id = PositiveId(Text(Field(travel_saved_staff, "id"))); RequireCondition(Both(Equal(Text(Field(travel_saved_staff, "event_id")), travel_event_id), Both(Equal(Text(Field(Field(travel_saved_staff, "attendee"), "id")), travel_person_id), Equal(Text(Field(travel_saved_staff, "id")), travel_staff_id))), "The Staff record differs from the captured ID, selected Event or person. Reconcile it; do not create a replacement."); RequireCondition(Equal(travel_staff_before_id, travel_staff_id), "The acknowledged Staff entry is missing or changed. Review the current Staff list before continuing."); } else { RequireCondition(NotValue(IsPresent(travel_staff_before_id)), "This person already has a Staff entry without a saved acknowledgement for this job. Review that entry; do not add another registration."); var travel_staff_fingerprint = JournalFingerprint(new JsonObject { ["event_id"] = travel_event_id, ["user_id"] = travel_person_id, ["registration_type"] = "Conference pass", ["notify_attendee"] = travel_notify }); var travel_staff_intent = JournalBegin(travel_job, "create_staff", "POST", "/v1/events/staff", travel_staff_fingerprint); var travel_staff_create_response = await Call("create_staff", new JsonObject { }, new JsonObject { ["event_id"] = travel_event_id, ["attendee_user_id"] = travel_person_id, ["registration_type"] = "Conference pass", ["notify_attendee"] = Equal(travel_notify, "true") }, Text(Field(travel_staff_intent, "idempotency_key"))); RequireCondition(Equal(ResponseStatus(travel_staff_create_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write."); var travel_created_staff = travel_staff_create_response.Body; travel_staff_id = PositiveId(Text(Field(travel_created_staff, "id"))); RequireCondition(Both(Equal(Text(Field(travel_created_staff, "event_id")), travel_event_id), Both(Equal(Text(Field(Field(travel_created_staff, "attendee"), "id")), travel_person_id), Equal(Text(Field(travel_created_staff, "id")), travel_staff_id))), "The Staff record differs from the captured ID, selected Event or person. Reconcile it; do not create a replacement."); RequireCondition(Equal(Text(Field(travel_created_staff, "registration_type")), "Conference pass"), "The Staff acknowledgement has a different registration type; preserve pending state and reconcile."); JournalAcknowledge(travel_job, "create_staff", new JsonObject { ["id"] = travel_staff_id, ["event_id"] = travel_event_id, ["user_id"] = travel_person_id }); } var travel_staff_verify_id = ""; var travel_staff_verify_offset = "0"; var travel_staff_verify_query = new JsonObject { ["filter_by_event_id"] = travel_event_id, ["filter_by_attendee_user_ids"] = travel_person_id, ["$limit"] = travel_page_size }; var travel_staff_verify_seen = NewIdSet(); while (true) { travel_staff_verify_query["$offset"] = travel_staff_verify_offset; var travel_staff_verify_response = await Call("staff_readback", travel_staff_verify_query, null, null); RequireCondition(Equal(ResponseStatus(travel_staff_verify_response), "200"), "Expected HTTP200 for the current collection; stop and reconcile another response."); var travel_staff_verify_page = travel_staff_verify_response.Body; var travel_staff_verify_rows = Items(Field(travel_staff_verify_page, "list_data")); RequireCondition(Equal(Text(Field(travel_staff_verify_page, "records_found")), Text(Count(travel_staff_verify_rows))), "records_found differs from this page's rows."); RequireCondition(IsPresent(Text(Field(travel_staff_verify_page, "total_records"))), "The collection wrapper needs total_records."); RequireCondition(Either(Equal(Field(travel_staff_verify_page, "has_more"), true), Equal(Field(travel_staff_verify_page, "has_more"), false)), "Expected a Boolean has_more value."); foreach (var travel_staff_verify_record in Items(travel_staff_verify_rows)) { var travel_staff_verify_record_id = PositiveId(Text(Field(travel_staff_verify_record, "id"))); RequireCondition(Equal(Text(Field(travel_staff_verify_record, "event_id")), travel_event_id), "A selected collection returned a row from another Event."); RequireCondition(Equal(Text(Field(Field(travel_staff_verify_record, "attendee"), "id")), travel_person_id), "The Staff filter returned a registration for a different person."); if (RememberId(travel_staff_verify_seen, travel_staff_verify_record_id)) { RequireCondition(NotValue(IsPresent(travel_staff_verify_id)), "More than one Staff record matches this person and Event. Stop for review; never choose the first."); travel_staff_verify_id = travel_staff_verify_record_id; } } if (Equal(Field(travel_staff_verify_page, "has_more"), false)) { break; } RequireCondition(NotValue(IsEmpty(travel_staff_verify_rows)), "An empty page says has_more=true. Stop and reconcile the selected query."); travel_staff_verify_offset = AddOffset(travel_staff_verify_offset, Count(travel_staff_verify_rows)); } RequireCondition(Equal(travel_staff_verify_id, travel_staff_id), "The captured Staff entry is not present in the complete current selected Event/person list. Stop before Travel creation."); if (JournalAcknowledged(travel_job, "create_travel")) { var travel_saved_reservation = JournalSaved(travel_job, "create_travel"); travel_reservation_id = PositiveId(Text(Field(travel_saved_reservation, "id"))); RequireCondition(Both(Equal(Text(Field(travel_saved_reservation, "event_id")), travel_event_id), Equal(Text(Field(travel_saved_reservation, "user_id")), travel_person_id)), "Saved Travel state belongs to a different Event or person. Stop and reconcile."); } else { var travel_create_fingerprint = JournalFingerprint(new JsonObject { ["event_id"] = travel_event_id, ["reservation_type_id"] = "6", ["origin_vendor_name"] = travel_hotel, ["origin_checkin_date"] = travel_checkin, ["return_checkin_date"] = travel_checkout, ["tagged_user_ids"] = travel_person_id, ["notify_tagged_users"] = travel_notify }); var travel_create_intent = JournalBegin(travel_job, "create_travel", "POST", "/v1/events/travel_reservations", travel_create_fingerprint); var travel_create_response = await Call("create_travel", new JsonObject { }, new JsonObject { ["event_id"] = travel_event_id, ["reservation_type_id"] = "6", ["origin_vendor_name"] = travel_hotel, ["origin_checkin_date"] = travel_checkin, ["return_checkin_date"] = travel_checkout, ["tagged_user_ids"] = CopyNode(new JsonArray(travel_person_id)), ["notify_tagged_users"] = Equal(travel_notify, "true") }, Text(Field(travel_create_intent, "idempotency_key"))); RequireCondition(Equal(ResponseStatus(travel_create_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write."); var travel_created_reservation = travel_create_response.Body; travel_reservation_id = PositiveId(Text(Field(travel_created_reservation, "id"))); RequireCondition(Both(Both(Both(Both(Both(Equal(Text(Field(travel_created_reservation, "id")), travel_reservation_id), Equal(Text(Field(travel_created_reservation, "event_id")), travel_event_id)), Equal(Text(Field(travel_created_reservation, "reservation_type_id")), "6")), Equal(Text(Field(travel_created_reservation, "origin_vendor_name")), travel_hotel)), Equal(Text(Field(travel_created_reservation, "origin_checkin_date")), travel_checkin)), Equal(Text(Field(travel_created_reservation, "return_checkin_date")), travel_checkout)), "The Hotel response differs from the captured ID, Event, type, vendor or dates. Keep pending state and reconcile; do not create another reservation."); var travel_created_tags = Items(Field(travel_created_reservation, "tagged_users")); RequireCondition(Equal(Text(Count(travel_created_tags)), "1"), "The Hotel acknowledgement must contain exactly the one selected tag before it can be saved as acknowledged."); foreach (var travel_created_tag in Items(travel_created_tags)) { RequireCondition(Equal(Text(Field(travel_created_tag, "id")), travel_person_id), "The acknowledged Hotel is tagged to a different person; keep pending state and reconcile."); } JournalAcknowledge(travel_job, "create_travel", new JsonObject { ["id"] = travel_reservation_id, ["event_id"] = travel_event_id, ["user_id"] = travel_person_id }); } var travel_final_id = ""; var travel_final_offset = "0"; var travel_final_query = new JsonObject { ["filter_by_event_id"] = travel_event_id, ["filter_by_tagged_user_ids"] = travel_person_id, ["$limit"] = travel_page_size }; travel_final_query["filter_by_tagged_user_ids_match_type"] = "all"; while (true) { travel_final_query["$offset"] = travel_final_offset; var travel_final_response = await Call("travel_readback", travel_final_query, null, null); RequireCondition(Equal(ResponseStatus(travel_final_response), "200"), "Expected HTTP200 for the current collection; stop and reconcile another response."); var travel_final_page = travel_final_response.Body; var travel_final_rows = Items(Field(travel_final_page, "list_data")); RequireCondition(Equal(Text(Field(travel_final_page, "records_found")), Text(Count(travel_final_rows))), "records_found differs from this page's rows."); RequireCondition(IsPresent(Text(Field(travel_final_page, "total_records"))), "The collection wrapper needs total_records."); RequireCondition(Either(Equal(Field(travel_final_page, "has_more"), true), Equal(Field(travel_final_page, "has_more"), false)), "Expected a Boolean has_more value."); foreach (var travel_final_record in Items(travel_final_rows)) { var travel_final_record_id = PositiveId(Text(Field(travel_final_record, "id"))); RequireCondition(Equal(Text(Field(travel_final_record, "event_id")), travel_event_id), "A selected collection returned a row from another Event."); var travel_final_person_found = ""; var travel_final_tags = Items(Field(travel_final_record, "tagged_users")); foreach (var travel_final_tag in Items(travel_final_tags)) { if (Equal(Text(Field(travel_final_tag, "id")), travel_person_id)) { travel_final_person_found = "true"; } } RequireCondition(Equal(travel_final_person_found, "true"), "The all-tags filter returned a record without the selected person."); if (Equal(travel_final_record_id, travel_reservation_id)) { RequireCondition(Both(Both(Both(Both(Both(Equal(Text(Field(travel_final_record, "id")), travel_reservation_id), Equal(Text(Field(travel_final_record, "event_id")), travel_event_id)), Equal(Text(Field(travel_final_record, "reservation_type_id")), "6")), Equal(Text(Field(travel_final_record, "origin_vendor_name")), travel_hotel)), Equal(Text(Field(travel_final_record, "origin_checkin_date")), travel_checkin)), Equal(Text(Field(travel_final_record, "return_checkin_date")), travel_checkout)), "The Hotel response differs from the captured ID, Event, type, vendor or dates. Keep pending state and reconcile; do not create another reservation."); RequireCondition(Equal(Text(Count(travel_final_tags)), "1"), "The captured Hotel's tags changed; review them instead of silently restoring the original selection."); travel_final_id = travel_final_record_id; } } if (Equal(Field(travel_final_page, "has_more"), false)) { break; } RequireCondition(NotValue(IsEmpty(travel_final_rows)), "An empty page says has_more=true. Stop and reconcile the selected query."); travel_final_offset = AddOffset(travel_final_offset, Count(travel_final_rows)); } RequireCondition(Equal(travel_final_id, travel_reservation_id), "The captured Hotel is missing from the complete current Event/person Travel list. Reconcile it; do not repeat the create or delete records automatically."); PrintValue(new JsonObject { ["event_id"] = travel_event_id, ["user_id"] = travel_person_id, ["staff_id"] = travel_staff_id, ["travel_reservation_id"] = travel_reservation_id }); } } static Task Main() => Run(); } ``` ```java // 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 SPEC = JSON.fromJson("{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"people_choices\":{\"method\":\"GET\",\"path\":\"/references/users_and_resources\"},\"travel_choices\":{\"method\":\"GET\",\"path\":\"/references/travel_reservation_types\"},\"event_before\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"find_staff\":{\"method\":\"GET\",\"path\":\"/events/staff\"},\"create_staff\":{\"method\":\"POST\",\"path\":\"/events/staff\"},\"create_travel\":{\"method\":\"POST\",\"path\":\"/events/travel_reservations\"},\"staff_readback\":{\"method\":\"GET\",\"path\":\"/events/staff\"},\"travel_readback\":{\"method\":\"GET\",\"path\":\"/events/travel_reservations\"}}}", Map.class); static final String API_KEY = headerKey(required("EXHIBITDAY_API_KEY")); static String headerKey(String value){if(value.chars().anyMatch(c->c<32||c>126))throw new IllegalArgumentException("Use the API key as one ASCII header value without control characters");return value;} static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).followRedirects(HttpClient.Redirect.NEVER).build(); interface RequestSender { HttpResponse send(HttpRequest request)throws IOException,InterruptedException; } static RequestSender SEND=request->CLIENT.send(request,HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); static class Result { int status; Object body; Map headers; String raw; Result(int s, Object b, Map h,String r) {status=s;body=b;headers=h;raw=r;} } // 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 obj(Object value) {return value==null?new LinkedHashMap<>(): (Map)value;} @SuppressWarnings("unchecked") static List list(Object value) {return value==null?Collections.emptyList():(List)value;} static Map map(Object... pairs) {Map result=new LinkedHashMap<>();for(int i=0;i query,Object body,String key) { Map route=obj(obj(SPEC.get("requests")).get(name));String method=text(route.get("method")); Map headers=map("Authorization","Bearer " + API_KEY,"Accept","application/json"); if(method.equals("POST")){if(key==null||key.isEmpty())throw new IllegalArgumentException("Persist a logical create key before sending POST");headers.put("Idempotency-Key",key);} 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); // 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. boolean resend=method.equals("GET"); 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 response; try {response=SEND.send(request.build());} 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();Object parsed=null; if(status!=304&&!response.body().isEmpty()) { try {parsed=JSON.fromJson(response.body(),Object.class);} catch(RuntimeException error){if(status<400)throw new IllegalStateException("Expected a JSON success response",error);} } Map 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=resend&&(status==429||status>=500); 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,response.body()); } throw new IllegalStateException("Retry limit reached"); } static String add_offset(String offset,long received){long result=Math.addExact(Long.parseLong(offset),received);if(received<=0||result>Integer.MAX_VALUE)throw new IllegalStateException("Cannot advance this int32 offset; reconcile the query");return Long.toString(result);} static boolean both(boolean left,boolean right){return left&&right;} static List items(Object value){if(!(value instanceof List))throw new IllegalStateException("Expected a JSON array");return list(value);} static long count(Object value){return items(value).size();} static boolean either(boolean left,boolean right){return left||right;} static boolean equal(Object left,Object right){return Objects.equals(left,right);} static Object field(Object value,String name){if(!(value instanceof Map)||!obj(value).containsKey(name))throw new IllegalStateException("Missing response field: "+name);return obj(value).get(name);} static boolean is_empty(Object value){return count(value)==0;} static boolean is_present(String value){return value!=null&&!value.isEmpty();} // Private client restart state only. No transport, application or JSON interpreter. static final class Journal implements AutoCloseable { public static final class Refusal extends IllegalStateException { Refusal(String message){super(message);} } public static final byte[] PREAMBLE="EXHIBITDAY-GUIDE-JOURNAL 1\n".getBytes(StandardCharsets.US_ASCII); static boolean valid(String value,String pattern){return value!=null&&value.matches(pattern);} static byte[] utf8(String value)throws java.nio.charset.CharacterCodingException { if(value==null)throw new Refusal("Journal fields are exact strings"); java.nio.ByteBuffer encoded=StandardCharsets.UTF_8.newEncoder().onMalformedInput(java.nio.charset.CodingErrorAction.REPORT).onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT).encode(java.nio.CharBuffer.wrap(value));byte[] raw=new byte[encoded.remaining()];encoded.get(raw);return raw; } static String ascii(byte[] raw,int start,int count){for(int i=start;i127)throw new Refusal("Journal framing must be canonical ASCII");return new String(raw,start,count,StandardCharsets.US_ASCII);} public static byte[] strings(Collection values)throws IOException { ByteArrayOutputStream output=new ByteArrayOutputStream();for(String value:values){byte[] raw=utf8(value);output.write((raw.length+":").getBytes(StandardCharsets.US_ASCII));output.write(raw);}return output.toByteArray(); } static int find(byte[] raw,int offset,int value){for(int i=offset;i readStrings(byte[] raw)throws IOException { List values=new ArrayList<>();int offset=0; while(offset0)throw new Refusal("Incomplete journal string");int count=size.intValueExact(); values.add(StandardCharsets.UTF_8.newDecoder().onMalformedInput(java.nio.charset.CodingErrorAction.REPORT).onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT).decode(java.nio.ByteBuffer.wrap(raw,offset,count)).toString());offset+=count;} return values; } public static String digest(byte[] raw){try{byte[] hash=java.security.MessageDigest.getInstance("SHA-256").digest(raw);StringBuilder text=new StringBuilder();for(byte item:hash)text.append(String.format(Locale.ROOT,"%02X",item&255));return text.toString();}catch(java.security.NoSuchAlgorithmException error){throw new IllegalStateException(error);}} public static String fingerprint(Map pairs)throws IOException { List values=new ArrayList<>();for(String name:new TreeSet<>(pairs.keySet())){if(!valid(name,"[A-Za-z0-9_.-]+")||Arrays.asList("api_key","exhibitday_api_key").contains(name.toLowerCase(Locale.ROOT)))throw new Refusal("Use explicit secret-free fingerprint names");values.add(name);values.add(pairs.get(name));}return digest(strings(values)); } public static byte[] frame(Collection values)throws IOException {byte[] payload=strings(values);ByteArrayOutputStream output=new ByteArrayOutputStream();output.write((payload.length+" "+digest(payload)+"\n").getBytes(StandardCharsets.US_ASCII));output.write(payload);output.write(10);return output.toByteArray();} public static List> decode(byte[] raw)throws IOException { if(raw.length> records=new ArrayList<>(); while(offset=0)throw new Refusal("Incomplete frame; reconcile before retry");int count=size.intValueExact();byte[] payload=Arrays.copyOfRange(raw,offset,offset+count);offset+=count; if(raw[offset]!=10||!digest(payload).equals(fields[1]))throw new Refusal("Journal integrity failed; reconcile before retry");records.add(readStrings(payload));offset++;}return records; } static void writeAll(java.nio.channels.FileChannel target,byte[] raw)throws IOException {java.nio.ByteBuffer data=java.nio.ByteBuffer.wrap(raw);while(data.hasRemaining())if(target.write(data)<=0)throw new IOException("Journal write did not advance");} static java.nio.channels.FileChannel createPrivate(Path path,OpenOption... options)throws IOException { java.nio.file.attribute.FileAttribute[] attributes=FileSystems.getDefault().supportedFileAttributeViews().contains("posix")?new java.nio.file.attribute.FileAttribute[]{java.nio.file.attribute.PosixFilePermissions.asFileAttribute(java.nio.file.attribute.PosixFilePermissions.fromString("rw-------"))}:new java.nio.file.attribute.FileAttribute[0]; return java.nio.channels.FileChannel.open(path,new HashSet<>(Arrays.asList(options)),attributes); } final Path path,lockPath;final String owner;final List header; final Map> allowed=new LinkedHashMap<>();Map> intents=new LinkedHashMap<>(),savedValues=new LinkedHashMap<>(); java.nio.channels.FileChannel lock;boolean owned,tainted;Object fileKey;java.nio.file.attribute.FileTime creation; public Journal(Path path,String apiBase,String workspace,String slug,String job,String inputFingerprint,List> writes)throws IOException {this(path,apiBase,workspace,slug,job,inputFingerprint,writes,"resume");} public Journal(Path path,String apiBase,String workspace,String slug,String job,String inputFingerprint,List> writes,String mode)throws IOException { this.path=path;lockPath=Path.of(path.toString()+".lock");byte[] random=new byte[16];new java.security.SecureRandom().nextBytes(random);StringBuilder token=new StringBuilder();for(byte item:random)token.append(String.format(Locale.ROOT,"%02x",item&255));owner=token.toString(); URI address=URI.create(apiBase);if(!Arrays.asList("https","http").contains(address.getScheme())||address.getHost()==null||address.getUserInfo()!=null||address.getRawQuery()!=null||address.getRawFragment()!=null||!valid(slug,"[a-z][a-z0-9-]*"))throw new Refusal("Use actual API base and closed guide slug"); if(job==null||job.trim().isEmpty()||!valid(workspace,"[1-9][0-9]*")||!valid(inputFingerprint,"[0-9A-F]{64}"))throw new Refusal("Use actual workspace, stable explicit job ID and exact fingerprint"); if(!Arrays.asList("new","resume").contains(mode))throw new Refusal("Choose new or resume for this local job"); List manifest=new ArrayList<>();for(List item:writes){if(item.size()!=3)throw new Refusal("Invalid write manifest shape");String step=item.get(0),method=item.get(1),route=item.get(2); if(!valid(step,"[a-z][a-z0-9_-]*")||allowed.containsKey(step)||!Arrays.asList("POST","PATCH","DELETE").contains(method)||!valid(route,"/v1/[A-Za-z0-9_/-]+")||route.contains("//"))throw new Refusal("Use a closed unique write manifest");allowed.put(step,List.of(method,route));manifest.addAll(item);} if(allowed.isEmpty())throw new Refusal("Only write workflows need a restart journal");header=List.of("H","1",apiBase,workspace,slug,job,inputFingerprint,digest(strings(manifest)));strings(header); try{lock=createPrivate(lockPath,StandardOpenOption.CREATE_NEW,StandardOpenOption.READ,StandardOpenOption.WRITE);owned=true;}catch(FileAlreadyExistsException error){throw new Refusal("This journal is locked; do not overlap jobs or steal a stale lock");} try{writeAll(lock,owner.getBytes(StandardCharsets.US_ASCII));lock.force(true);java.nio.file.attribute.BasicFileAttributes identity=Files.readAttributes(lockPath,java.nio.file.attribute.BasicFileAttributes.class,LinkOption.NOFOLLOW_LINKS);fileKey=identity.fileKey();creation=identity.creationTime(); if(Files.isSymbolicLink(path))throw new Refusal("Choose a private regular journal file"); if(mode.equals("resume")&&!Files.exists(path))throw new Refusal("Journal missing: stop and reconcile lost state before starting a new logical job"); if(mode.equals("new")&&Files.exists(path))throw new Refusal("Journal exists; use resume for the same logical job"); if(mode.equals("new")){try(java.nio.channels.FileChannel target=createPrivate(path,StandardOpenOption.CREATE_NEW,StandardOpenOption.WRITE)){writeAll(target,PREAMBLE);writeAll(target,frame(header));target.force(true);}} List> records=decode(Files.readAllBytes(path));if(records.isEmpty()||!records.get(0).equals(header))throw new Refusal("Journal workspace/base/guide/job/input binding differs");for(List record:records.subList(1,records.size()))apply(record); if(intents.keySet().stream().anyMatch(step->!savedValues.containsKey(step)))throw new Refusal("Saved intent lacks ACK; stop and reconcile before retry"); }catch(IOException|RuntimeException error){close();throw error;} } void apply(List record){ if(record.isEmpty())throw new Refusal("Empty journal record"); if(record.get(0).equals("I")){ if(record.size()!=6)throw new Refusal("Invalid intent shape");String step=record.get(1),method=record.get(2),route=record.get(3),fingerprint=record.get(4),key=record.get(5); if(!valid(step,"[a-z][a-z0-9_-]*")||intents.containsKey(step)||!List.of(method,route).equals(allowed.get(step))||!valid(fingerprint,"[0-9A-F]{64}")||intents.keySet().stream().anyMatch(name->!savedValues.containsKey(name)))throw new Refusal("Invalid, future or repeated intent"); if(method.equals("POST")&&!valid(key,"[0-9a-f]{32}")||!method.equals("POST")&&!key.isEmpty())throw new Refusal("Invalid persisted action key");intents.put(step,new LinkedHashMap<>(Map.of("method",method,"path",route,"request_fingerprint",fingerprint,"idempotency_key",key))); }else if(record.get(0).equals("A")){ if(record.size()<3||!valid(record.get(2),"0|[1-9][0-9]*")||!new java.math.BigInteger(record.get(2)).multiply(java.math.BigInteger.TWO).equals(java.math.BigInteger.valueOf(record.size()-3))||!intents.containsKey(record.get(1))||savedValues.containsKey(record.get(1)))throw new Refusal("ACK without exactly one prior intent"); List names=new ArrayList<>();for(int i=3;i(new TreeSet<>(names)))||names.stream().anyMatch(name->!valid(name,"[a-z][a-z0-9_]*")||name.equals("api_key")||name.equals("exhibitday_api_key")))throw new Refusal("ACK fields must be unique sorted secret-free identifiers"); Map saved=new LinkedHashMap<>();for(int i=0;i record)throws IOException {requireActive();byte[] raw=frame(record);try(java.nio.channels.FileChannel target=java.nio.channels.FileChannel.open(path,StandardOpenOption.WRITE,StandardOpenOption.APPEND)){writeAll(target,raw);target.force(true);}catch(IOException|RuntimeException error){tainted=true;throw error;}} public boolean acknowledged(String step)throws IOException{requireActive();return savedValues.containsKey(step);} public Map saved(String step)throws IOException{requireActive();if(!savedValues.containsKey(step))throw new Refusal("No acknowledged state exists");return new LinkedHashMap<>(savedValues.get(step));} public Map begin(String step,String method,String route,String requestFingerprint)throws IOException { requireActive();if(intents.containsKey(step))throw new Refusal("Never blindly repeat an existing action");String key="";if(method.equals("POST")){byte[] bytes=new byte[16];new java.security.SecureRandom().nextBytes(bytes);StringBuilder text=new StringBuilder();for(byte item:bytes)text.append(String.format(Locale.ROOT,"%02x",item&255));key=text.toString();} List record=List.of("I",step,method,route,requestFingerprint,key);Map> previous=new LinkedHashMap<>(intents);try{apply(record);}finally{intents=previous;}append(record);apply(record);return new LinkedHashMap<>(intents.get(step)); } public void acknowledge(String step,Map saved)throws IOException { requireActive();List record=new ArrayList<>(List.of("A",step,Integer.toString(saved.size())));for(String name:new TreeSet<>(saved.keySet())){record.add(name);record.add(saved.get(name));} Map> previous=new LinkedHashMap<>(savedValues);try{apply(record);strings(record);}finally{savedValues=previous;}append(record);apply(record); } public void close()throws IOException { if(!owned)return;if(tainted){lock.close();lock=null;owned=false;return;} try{requireActive();}catch(IOException|RuntimeException error){lock.close();lock=null;owned=false;throw error;}lock.close();lock=null;owned=false;Files.delete(lockPath); } } static Map journal_values(Object value){if(!(value instanceof Map))throw new Journal.Refusal("Saved/fingerprint values need an explicit object");Map result=new LinkedHashMap<>();for(Map.Entry field:((Map)value).entrySet()){if(!(field.getKey() instanceof String)||!(field.getValue() instanceof String))throw new Journal.Refusal("Saved/fingerprint values must be exact strings");result.put((String)field.getKey(),(String)field.getValue());}return result;} static void journal_acknowledge(Journal job,String step,Object saved)throws IOException{job.acknowledge(step,journal_values(saved));} static boolean journal_acknowledged(Journal job,String step)throws IOException{return job.acknowledged(step);} static Object journal_begin(Journal job,String step,String method,String path,String requestFingerprint)throws IOException{return new LinkedHashMap(job.begin(step,method,path,requestFingerprint));} static String journal_fingerprint(Object value)throws IOException{return Journal.fingerprint(journal_values(value));} static Object journal_saved(Journal job,String step)throws IOException{return new LinkedHashMap(job.saved(step));} static Set new_id_set(){return new HashSet<>();} static boolean not_value(boolean value){return !value;} static Journal open_journal(String path,String base,String workspace,String slug,String job,String inputFingerprint,Object manifest,String mode)throws IOException { if(!(manifest instanceof List))throw new Journal.Refusal("A closed write manifest is required");List> writes=new ArrayList<>();for(Object row:(List)manifest){if(!(row instanceof List)||((List)row).size()!=3)throw new Journal.Refusal("Each write must bind step/method/path");List fields=new ArrayList<>();for(Object value:(List)row){if(!(value instanceof String))throw new Journal.Refusal("Manifest values are exact strings");fields.add((String)value);}writes.add(fields);}return new Journal(Path.of(path),base,workspace,slug,job,inputFingerprint,writes,mode); } static String optional(String name,String fallback){String value=System.getenv(name);return value==null||value.isEmpty()?fallback:value;} static String page_size(String value){try{if(value==null||!value.matches("[1-9][0-9]*")||Integer.parseInt(value)<=0)throw new IllegalArgumentException();return value;}catch(RuntimeException error){throw new IllegalArgumentException("Page size must be a positive int32");}} static String positive_id(String value){try{if(value==null||!value.matches("[1-9][0-9]*")||Long.parseLong(value)<=0)throw new IllegalArgumentException();return value;}catch(RuntimeException error){throw new IllegalArgumentException("Use a positive record ID");}} static void print_value(Object value){try{String text=value instanceof String?(String)value:JSON.toJson(value);System.out.write((text+"\n").getBytes(StandardCharsets.UTF_8));}catch(IOException error){throw new UncheckedIOException(error);}} static boolean remember_id(Set seen,String value){return seen.add(value);} static void require_condition(boolean value,String message){if(!value)throw new IllegalStateException(message);} static String response_status(Result value){return Integer.toString(value.status);} static void validate_staff_travel_inputs(String name, String start, String end) throws IOException { staff_travel_text(name, "EXHIBITDAY_HOTEL_NAME", 125); if (name.indexOf('<') >= 0 || name.indexOf('>') >= 0 || name.indexOf('\r') >= 0 || name.indexOf('\n') >= 0 || name.equalsIgnoreCase("null")) throw new Journal.Refusal("Use plain, single-line EXHIBITDAY_HOTEL_NAME text other than null"); staff_travel_date(start, "EXHIBITDAY_CHECKIN_DATE"); staff_travel_date(end, "EXHIBITDAY_CHECKOUT_DATE"); if (end.compareTo(start) < 0) throw new Journal.Refusal("EXHIBITDAY_CHECKOUT_DATE must be on or after EXHIBITDAY_CHECKIN_DATE"); } static void staff_travel_text(String value, String label, int limit) throws IOException { Journal.strings(List.of(value)); if (value.isEmpty() || staff_travel_space(value.charAt(0)) || staff_travel_space(value.charAt(value.length()-1))) throw new Journal.Refusal("Remove whitespace at the start or end of " + label); if (value.length() > limit) throw new Journal.Refusal(label + " exceeds " + limit + " UTF-16 code units"); } static boolean staff_travel_space(char c) { return Character.isWhitespace(c) && !(c >= 0x1C && c <= 0x1F) || Character.isSpaceChar(c) || c == 0x85; } static void staff_travel_date(String value, String label) { boolean valid; try { valid = value.matches("[0-9]{4}-[0-9]{2}-[0-9]{2}") && LocalDate.parse(value).getYear() >= 1753; } catch (java.time.format.DateTimeParseException error) { valid = false; } if (!valid) throw new Journal.Refusal(label + " must be a calendar date in YYYY-MM-DD on or after 1753-01-01"); } static void run()throws Exception { String travel_event_id = positive_id(required("EXHIBITDAY_EVENT_ID")); String travel_person_id = required("EXHIBITDAY_PERSON_ID"); String travel_hotel = required("EXHIBITDAY_HOTEL_NAME"); String travel_checkin = required("EXHIBITDAY_CHECKIN_DATE"); String travel_checkout = required("EXHIBITDAY_CHECKOUT_DATE"); String travel_page_size = page_size(optional("EXHIBITDAY_PAGE_SIZE", "100")); String travel_notify = optional("EXHIBITDAY_SEND_NOTIFICATIONS", "false"); require_condition(either(equal(travel_notify, "true"), equal(travel_notify, "false")), "Use exact true or false for EXHIBITDAY_SEND_NOTIFICATIONS."); String travel_journal_path = required("EXHIBITDAY_JOURNAL"); String travel_job_id = required("EXHIBITDAY_JOB_ID"); String travel_job_mode = optional("EXHIBITDAY_JOB_MODE", "resume"); validate_staff_travel_inputs(travel_hotel, travel_checkin, travel_checkout); Result travel_workspace_response = call("workspace_binding", map(), null, null); require_condition(equal(response_status(travel_workspace_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write."); Object travel_workspace = travel_workspace_response.body; String travel_workspace_id = positive_id(text(field(travel_workspace, "id"))); Result travel_event_response = call("event_before", map("id", travel_event_id), null, null); require_condition(equal(response_status(travel_event_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write."); Object travel_event = travel_event_response.body; require_condition(equal(text(field(travel_event, "id")), travel_event_id), "The Event read differs from the explicit selected Event."); Result travel_people_response = call("people_choices", map(), null, null); require_condition(equal(response_status(travel_people_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write."); Object travel_people = travel_people_response.body; String travel_person_found = ""; for (Object travel_person_choice : items(items(field(travel_people, "list_data")))) { if (equal(text(field(travel_person_choice, "id")), travel_person_id)) { require_condition(not_value(is_present(travel_person_found)), "The people reference returned the same selected person more than once."); travel_person_found = travel_person_id; } } require_condition(equal(travel_person_found, travel_person_id), "Choose a current person or resource ID from References users_and_resources before creating Staff or Travel."); Result travel_types_response = call("travel_choices", map(), null, null); require_condition(equal(response_status(travel_types_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write."); Object travel_types = travel_types_response.body; String travel_hotel_type_found = ""; for (Object travel_type_choice : items(items(field(travel_types, "list_data")))) { if (equal(text(field(travel_type_choice, "id")), "6")) { require_condition(both(equal(text(field(travel_type_choice, "name")), "Hotel"), not_value(is_present(travel_hotel_type_found))), "The current type6 reference is not one unambiguous Hotel choice."); travel_hotel_type_found = "6"; } } require_condition(equal(travel_hotel_type_found, "6"), "This Hotel example requires the currently declared Hotel choice6; do not substitute a different type."); String travel_staff_before_id = ""; String travel_staff_before_offset = "0"; Map travel_staff_before_query = map("filter_by_event_id", travel_event_id, "filter_by_attendee_user_ids", travel_person_id, "$limit", travel_page_size); Set travel_staff_before_seen = new_id_set(); while (true) { travel_staff_before_query.put("$offset", travel_staff_before_offset); Result travel_staff_before_response = call("find_staff", travel_staff_before_query, null, null); require_condition(equal(response_status(travel_staff_before_response), "200"), "Expected HTTP200 for the current collection; stop and reconcile another response."); Object travel_staff_before_page = travel_staff_before_response.body; List travel_staff_before_rows = items(field(travel_staff_before_page, "list_data")); require_condition(equal(text(field(travel_staff_before_page, "records_found")), text(count(travel_staff_before_rows))), "records_found differs from this page's rows."); require_condition(is_present(text(field(travel_staff_before_page, "total_records"))), "The collection wrapper needs total_records."); require_condition(either(equal(field(travel_staff_before_page, "has_more"), true), equal(field(travel_staff_before_page, "has_more"), false)), "Expected a Boolean has_more value."); for (Object travel_staff_before_record : items(travel_staff_before_rows)) { String travel_staff_before_record_id = positive_id(text(field(travel_staff_before_record, "id"))); require_condition(equal(text(field(travel_staff_before_record, "event_id")), travel_event_id), "A selected collection returned a row from another Event."); require_condition(equal(text(field(field(travel_staff_before_record, "attendee"), "id")), travel_person_id), "The Staff filter returned a registration for a different person."); if (remember_id(travel_staff_before_seen, travel_staff_before_record_id)) { require_condition(not_value(is_present(travel_staff_before_id)), "More than one Staff record matches this person and Event. Stop for review; never choose the first."); travel_staff_before_id = travel_staff_before_record_id; } } if (equal(field(travel_staff_before_page, "has_more"), false)) { break; } require_condition(not_value(is_empty(travel_staff_before_rows)), "An empty page says has_more=true. Stop and reconcile the selected query."); travel_staff_before_offset = add_offset(travel_staff_before_offset, count(travel_staff_before_rows)); } String travel_input_fingerprint = journal_fingerprint(map("workflow_contract_sha256", "A4CE8A49EF9814D6F6F256BE0525D5A77FF09C69232E21624504C3C3DDA294AB", "event_id", travel_event_id, "user_id", travel_person_id, "hotel", travel_hotel, "checkin", travel_checkin, "checkout", travel_checkout, "notify", travel_notify, "page_size", travel_page_size)); try (Journal travel_job = open_journal(travel_journal_path, "https://api.exhibitday.com/v1", travel_workspace_id, "staff-travel-tags", travel_job_id, travel_input_fingerprint, Arrays.asList(Arrays.asList("create_staff", "POST", "/v1/events/staff"), Arrays.asList("create_travel", "POST", "/v1/events/travel_reservations")), travel_job_mode)) { require_condition(either(not_value(journal_acknowledged(travel_job, "create_travel")), journal_acknowledged(travel_job, "create_staff")), "A Travel create is acknowledged before Staff. Stop and reconcile the saved state."); String travel_staff_id = ""; String travel_reservation_id = ""; if (journal_acknowledged(travel_job, "create_staff")) { Object travel_saved_staff = journal_saved(travel_job, "create_staff"); travel_staff_id = positive_id(text(field(travel_saved_staff, "id"))); require_condition(both(equal(text(field(travel_saved_staff, "event_id")), travel_event_id), both(equal(text(field(field(travel_saved_staff, "attendee"), "id")), travel_person_id), equal(text(field(travel_saved_staff, "id")), travel_staff_id))), "The Staff record differs from the captured ID, selected Event or person. Reconcile it; do not create a replacement."); require_condition(equal(travel_staff_before_id, travel_staff_id), "The acknowledged Staff entry is missing or changed. Review the current Staff list before continuing."); } else { require_condition(not_value(is_present(travel_staff_before_id)), "This person already has a Staff entry without a saved acknowledgement for this job. Review that entry; do not add another registration."); String travel_staff_fingerprint = journal_fingerprint(map("event_id", travel_event_id, "user_id", travel_person_id, "registration_type", "Conference pass", "notify_attendee", travel_notify)); Object travel_staff_intent = journal_begin(travel_job, "create_staff", "POST", "/v1/events/staff", travel_staff_fingerprint); Result travel_staff_create_response = call("create_staff", map(), map("event_id", travel_event_id, "attendee_user_id", travel_person_id, "registration_type", "Conference pass", "notify_attendee", equal(travel_notify, "true")), text(field(travel_staff_intent, "idempotency_key"))); require_condition(equal(response_status(travel_staff_create_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write."); Object travel_created_staff = travel_staff_create_response.body; travel_staff_id = positive_id(text(field(travel_created_staff, "id"))); require_condition(both(equal(text(field(travel_created_staff, "event_id")), travel_event_id), both(equal(text(field(field(travel_created_staff, "attendee"), "id")), travel_person_id), equal(text(field(travel_created_staff, "id")), travel_staff_id))), "The Staff record differs from the captured ID, selected Event or person. Reconcile it; do not create a replacement."); require_condition(equal(text(field(travel_created_staff, "registration_type")), "Conference pass"), "The Staff acknowledgement has a different registration type; preserve pending state and reconcile."); journal_acknowledge(travel_job, "create_staff", map("id", travel_staff_id, "event_id", travel_event_id, "user_id", travel_person_id)); } String travel_staff_verify_id = ""; String travel_staff_verify_offset = "0"; Map travel_staff_verify_query = map("filter_by_event_id", travel_event_id, "filter_by_attendee_user_ids", travel_person_id, "$limit", travel_page_size); Set travel_staff_verify_seen = new_id_set(); while (true) { travel_staff_verify_query.put("$offset", travel_staff_verify_offset); Result travel_staff_verify_response = call("staff_readback", travel_staff_verify_query, null, null); require_condition(equal(response_status(travel_staff_verify_response), "200"), "Expected HTTP200 for the current collection; stop and reconcile another response."); Object travel_staff_verify_page = travel_staff_verify_response.body; List travel_staff_verify_rows = items(field(travel_staff_verify_page, "list_data")); require_condition(equal(text(field(travel_staff_verify_page, "records_found")), text(count(travel_staff_verify_rows))), "records_found differs from this page's rows."); require_condition(is_present(text(field(travel_staff_verify_page, "total_records"))), "The collection wrapper needs total_records."); require_condition(either(equal(field(travel_staff_verify_page, "has_more"), true), equal(field(travel_staff_verify_page, "has_more"), false)), "Expected a Boolean has_more value."); for (Object travel_staff_verify_record : items(travel_staff_verify_rows)) { String travel_staff_verify_record_id = positive_id(text(field(travel_staff_verify_record, "id"))); require_condition(equal(text(field(travel_staff_verify_record, "event_id")), travel_event_id), "A selected collection returned a row from another Event."); require_condition(equal(text(field(field(travel_staff_verify_record, "attendee"), "id")), travel_person_id), "The Staff filter returned a registration for a different person."); if (remember_id(travel_staff_verify_seen, travel_staff_verify_record_id)) { require_condition(not_value(is_present(travel_staff_verify_id)), "More than one Staff record matches this person and Event. Stop for review; never choose the first."); travel_staff_verify_id = travel_staff_verify_record_id; } } if (equal(field(travel_staff_verify_page, "has_more"), false)) { break; } require_condition(not_value(is_empty(travel_staff_verify_rows)), "An empty page says has_more=true. Stop and reconcile the selected query."); travel_staff_verify_offset = add_offset(travel_staff_verify_offset, count(travel_staff_verify_rows)); } require_condition(equal(travel_staff_verify_id, travel_staff_id), "The captured Staff entry is not present in the complete current selected Event/person list. Stop before Travel creation."); if (journal_acknowledged(travel_job, "create_travel")) { Object travel_saved_reservation = journal_saved(travel_job, "create_travel"); travel_reservation_id = positive_id(text(field(travel_saved_reservation, "id"))); require_condition(both(equal(text(field(travel_saved_reservation, "event_id")), travel_event_id), equal(text(field(travel_saved_reservation, "user_id")), travel_person_id)), "Saved Travel state belongs to a different Event or person. Stop and reconcile."); } else { String travel_create_fingerprint = journal_fingerprint(map("event_id", travel_event_id, "reservation_type_id", "6", "origin_vendor_name", travel_hotel, "origin_checkin_date", travel_checkin, "return_checkin_date", travel_checkout, "tagged_user_ids", travel_person_id, "notify_tagged_users", travel_notify)); Object travel_create_intent = journal_begin(travel_job, "create_travel", "POST", "/v1/events/travel_reservations", travel_create_fingerprint); Result travel_create_response = call("create_travel", map(), map("event_id", travel_event_id, "reservation_type_id", "6", "origin_vendor_name", travel_hotel, "origin_checkin_date", travel_checkin, "return_checkin_date", travel_checkout, "tagged_user_ids", Arrays.asList(travel_person_id), "notify_tagged_users", equal(travel_notify, "true")), text(field(travel_create_intent, "idempotency_key"))); require_condition(equal(response_status(travel_create_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write."); Object travel_created_reservation = travel_create_response.body; travel_reservation_id = positive_id(text(field(travel_created_reservation, "id"))); require_condition(both(both(both(both(both(equal(text(field(travel_created_reservation, "id")), travel_reservation_id), equal(text(field(travel_created_reservation, "event_id")), travel_event_id)), equal(text(field(travel_created_reservation, "reservation_type_id")), "6")), equal(text(field(travel_created_reservation, "origin_vendor_name")), travel_hotel)), equal(text(field(travel_created_reservation, "origin_checkin_date")), travel_checkin)), equal(text(field(travel_created_reservation, "return_checkin_date")), travel_checkout)), "The Hotel response differs from the captured ID, Event, type, vendor or dates. Keep pending state and reconcile; do not create another reservation."); List travel_created_tags = items(field(travel_created_reservation, "tagged_users")); require_condition(equal(text(count(travel_created_tags)), "1"), "The Hotel acknowledgement must contain exactly the one selected tag before it can be saved as acknowledged."); for (Object travel_created_tag : items(travel_created_tags)) { require_condition(equal(text(field(travel_created_tag, "id")), travel_person_id), "The acknowledged Hotel is tagged to a different person; keep pending state and reconcile."); } journal_acknowledge(travel_job, "create_travel", map("id", travel_reservation_id, "event_id", travel_event_id, "user_id", travel_person_id)); } String travel_final_id = ""; String travel_final_offset = "0"; Map travel_final_query = map("filter_by_event_id", travel_event_id, "filter_by_tagged_user_ids", travel_person_id, "$limit", travel_page_size); travel_final_query.put("filter_by_tagged_user_ids_match_type", "all"); while (true) { travel_final_query.put("$offset", travel_final_offset); Result travel_final_response = call("travel_readback", travel_final_query, null, null); require_condition(equal(response_status(travel_final_response), "200"), "Expected HTTP200 for the current collection; stop and reconcile another response."); Object travel_final_page = travel_final_response.body; List travel_final_rows = items(field(travel_final_page, "list_data")); require_condition(equal(text(field(travel_final_page, "records_found")), text(count(travel_final_rows))), "records_found differs from this page's rows."); require_condition(is_present(text(field(travel_final_page, "total_records"))), "The collection wrapper needs total_records."); require_condition(either(equal(field(travel_final_page, "has_more"), true), equal(field(travel_final_page, "has_more"), false)), "Expected a Boolean has_more value."); for (Object travel_final_record : items(travel_final_rows)) { String travel_final_record_id = positive_id(text(field(travel_final_record, "id"))); require_condition(equal(text(field(travel_final_record, "event_id")), travel_event_id), "A selected collection returned a row from another Event."); String travel_final_person_found = ""; List travel_final_tags = items(field(travel_final_record, "tagged_users")); for (Object travel_final_tag : items(travel_final_tags)) { if (equal(text(field(travel_final_tag, "id")), travel_person_id)) { travel_final_person_found = "true"; } } require_condition(equal(travel_final_person_found, "true"), "The all-tags filter returned a record without the selected person."); if (equal(travel_final_record_id, travel_reservation_id)) { require_condition(both(both(both(both(both(equal(text(field(travel_final_record, "id")), travel_reservation_id), equal(text(field(travel_final_record, "event_id")), travel_event_id)), equal(text(field(travel_final_record, "reservation_type_id")), "6")), equal(text(field(travel_final_record, "origin_vendor_name")), travel_hotel)), equal(text(field(travel_final_record, "origin_checkin_date")), travel_checkin)), equal(text(field(travel_final_record, "return_checkin_date")), travel_checkout)), "The Hotel response differs from the captured ID, Event, type, vendor or dates. Keep pending state and reconcile; do not create another reservation."); require_condition(equal(text(count(travel_final_tags)), "1"), "The captured Hotel's tags changed; review them instead of silently restoring the original selection."); travel_final_id = travel_final_record_id; } } if (equal(field(travel_final_page, "has_more"), false)) { break; } require_condition(not_value(is_empty(travel_final_rows)), "An empty page says has_more=true. Stop and reconcile the selected query."); travel_final_offset = add_offset(travel_final_offset, count(travel_final_rows)); } require_condition(equal(travel_final_id, travel_reservation_id), "The captured Hotel is missing from the complete current Event/person Travel list. Reconcile it; do not repeat the create or delete records automatically."); print_value(map("event_id", travel_event_id, "user_id", travel_person_id, "staff_id", travel_staff_id, "travel_reservation_id", travel_reservation_id)); } } public static void main(String[] args)throws Exception {run();} } ``` ```php $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, ?string $key = null): array { global $spec, $apiKey, $transport; $route = $spec['requests'][$name]; $headers = ['Authorization' => 'Bearer ' . $apiKey, 'Accept' => 'application/json']; if ($route['method'] === 'POST') { if ($key === null || $key === '') throw new RuntimeException('Persist a logical create key before sending POST'); $headers['Idempotency-Key'] = $key; // 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); // 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 = 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 = $resend && ($status === 429 || $status >= 500); 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, 'raw' => $raw]; } throw new RuntimeException('Retry limit reached'); } $transport = Closure::fromCallable('nativeTransport'); function add_offset(string $offset,int $received):string{$result=(int)$offset+$received;if($received<=0||$result>2147483647)throw new RuntimeException("Cannot advance this int32 offset; reconcile the query");return (string)$result;} function both(bool $left,bool $right):bool{return $left&&$right;} function either(bool $left,bool $right):bool{return $left||$right;} function equal(mixed $left,mixed $right):bool{return $left===$right;} function field(mixed $value,string $name):mixed{if(!is_array($value)||!array_key_exists($name,$value))throw new RuntimeException("Missing response field: ".$name);return $value[$name];} function items(mixed $value):array{if(!is_array($value)||!array_is_list($value))throw new RuntimeException("Expected a JSON array");return $value;} function is_empty(mixed $value):bool{return count(items($value))===0;} function is_present(?string $value):bool{return $value!==null&&$value!=="";} final class JournalRefusal extends RuntimeException {} final class JournalProtocol { public const PREAMBLE="EXHIBITDAY-GUIDE-JOURNAL 1\n"; public static function utf8(mixed $value):string {if(!is_string($value)||preg_match('//u',$value)!==1)throw new JournalRefusal('Journal fields must be exact valid UTF8 strings');return$value;} public static function strings(array $values):string {$raw='';foreach($values as$value){$item=self::utf8($value);$raw.=strlen($item).':'.$item;}return$raw;} private static function length(string $text,int $remaining):int {if(!preg_match('/\A(?:0|[1-9][0-9]*)\z/',$text))throw new JournalRefusal('Noncanonical string length');$maximum=(string)$remaining;if(strlen($text)>strlen($maximum)||(strlen($text)===strlen($maximum)&&strcmp($text,$maximum)>0))throw new JournalRefusal('Incomplete journal string/frame');return(int)$text;} public static function readStrings(string $raw):array {$values=[];$offset=0;while($offset=strlen($raw)-$offset)throw new JournalRefusal('Incomplete frame; reconcile before retry');$payload=substr($raw,$offset,$size);$offset+=$size;if($raw[$offset]!=="\n"||self::digest($payload)!==$match[2])throw new JournalRefusal('Journal integrity failed; reconcile before retry');$records[]=self::readStrings($payload);$offset++;}return$records;} public static function writeAll($file,string $raw):void {$offset=0;while($offsetpath=$path;$this->lockPath=$path.'.lock';$this->owner=bin2hex(random_bytes(16));$address=parse_url($base); if($address===false||!in_array($address['scheme']??null,['https','http'],true)||!isset($address['host'])||isset($address['user'])||isset($address['pass'])||isset($address['query'])||isset($address['fragment'])||!preg_match('/\A[a-z][a-z0-9-]*\z/',$slug))throw new JournalRefusal('Use actual API base and closed guide slug'); if(trim($job)===''||!preg_match('/\A[1-9][0-9]*\z/',$workspace)||!preg_match('/\A[0-9A-F]{64}\z/',$inputFingerprint))throw new JournalRefusal('Use actual workspace, stable explicit job ID and exact fingerprint'); if(!in_array($mode,['new','resume'],true))throw new JournalRefusal('Choose new or resume for this local job'); $manifest=[];foreach($writes as$write){if(!is_array($write)||!array_is_list($write)||count($write)!==3)throw new JournalRefusal('Invalid write manifest');[$step,$method,$route]=$write; if(!is_string($step)||!preg_match('/\A[a-z][a-z0-9_-]*\z/',$step)||isset($this->allowed[$step])||!in_array($method,['POST','PATCH','DELETE'],true)||!is_string($route)||!preg_match('~\A/v1/[A-Za-z0-9_/-]+\z~',$route)||str_contains($route,'//'))throw new JournalRefusal('Use a closed unique write manifest');$this->allowed[$step]=[$method,$route];array_push($manifest,$step,$method,$route);} if($this->allowed===[])throw new JournalRefusal('Only write workflows need restart journal');$this->header=['H','1',$base,$workspace,$slug,$job,$inputFingerprint,JournalProtocol::digest(JournalProtocol::strings($manifest))];JournalProtocol::strings($this->header); $this->file=JournalProtocol::createPrivate($this->lockPath);$this->owned=true; try{ JournalProtocol::writeAll($this->file,$this->owner);$identity=fstat($this->file);if($identity===false)throw new JournalRefusal('Cannot bind acquired lock identity');$this->identity=$identity; clearstatcache(true,$path);if(is_link($path))throw new JournalRefusal('Choose private regular journal file'); $exists=file_exists($path);if($mode==='resume'&&!$exists)throw new JournalRefusal('Journal missing: stop and reconcile lost state before starting a new logical job');if($mode==='new'&&$exists)throw new JournalRefusal('Journal exists; use resume for the same logical job'); if($mode==='new'){$target=JournalProtocol::createPrivate($path);try{JournalProtocol::writeAll($target,JournalProtocol::PREAMBLE.JournalProtocol::frame($this->header));}finally{fclose($target);}} $raw=file_get_contents($path);if($raw===false)throw new JournalRefusal('Cannot read journal');$records=JournalProtocol::decode($raw);if($records===[]||$records[0]!==$this->header)throw new JournalRefusal('Journal workspace/base/guide/job/input binding differs');foreach(array_slice($records,1)as$record)$this->apply($record); if(array_diff(array_keys($this->intents),array_keys($this->savedValues))!==[])throw new JournalRefusal('Saved intent lacks ACK; stop and reconcile before retry'); }catch(Throwable $error){$this->close();throw$error;} } private function apply(array $record):void { if(($record[0]??null)==='I'){ if(count($record)!==6)throw new JournalRefusal('Invalid intent shape');[,$step,$method,$route,$fingerprint,$key]=$record; if(!preg_match('/\A[a-z][a-z0-9_-]*\z/',$step)||isset($this->intents[$step])||($this->allowed[$step]??null)!==[$method,$route]||!preg_match('/\A[0-9A-F]{64}\z/',$fingerprint)||array_diff(array_keys($this->intents),array_keys($this->savedValues))!==[])throw new JournalRefusal('Invalid, future or repeated intent'); if(($method==='POST'&&!preg_match('/\A[0-9a-f]{32}\z/',$key))||($method!=='POST'&&$key!==''))throw new JournalRefusal('Invalid persisted action key');$this->intents[$step]=['method'=>$method,'path'=>$route,'request_fingerprint'=>$fingerprint,'idempotency_key'=>$key]; }elseif(($record[0]??null)==='A'){ if(count($record)<3)throw new JournalRefusal('Invalid ACK shape');[,$step,$count]=$record;$pairs=array_slice($record,3); if(!preg_match('/\A(?:0|[1-9][0-9]*)\z/',$count)||(string)intdiv(count($pairs),2)!==$count||count($pairs)%2!==0||!isset($this->intents[$step])||isset($this->savedValues[$step]))throw new JournalRefusal('ACK without exactly one prior intent'); $names=[];for($i=0;$i$name){if(!preg_match('/\A[a-z][a-z0-9_]*\z/',$name)||in_array($name,['api_key','exhibitday_api_key'],true))throw new JournalRefusal('Use secret-free ACK field names');$saved[$name]=$pairs[$i*2+1];}$this->savedValues[$step]=$saved; }else throw new JournalRefusal('Unknown journal transition'); } private function requireActive():void { if(!$this->owned||$this->file===null||$this->tainted)throw new JournalRefusal('Journal closed or IO outcome needs reconciliation');clearstatcache(true,$this->lockPath);$current=@lstat($this->lockPath);$token=@file_get_contents($this->lockPath); if($current===false||($current['dev']??null)!==($this->identity['dev']??null)||($current['ino']??null)!==($this->identity['ino']??null)||$token!==$this->owner)throw new JournalRefusal('Journal lock replaced; stop without deleting it'); } private function append(array $record):void { $this->requireActive();$raw=JournalProtocol::frame($record);$target=null; try{$target=@fopen($this->path,'ab');if($target===false)throw new JournalRefusal('Cannot append journal; stop and reconcile');JournalProtocol::writeAll($target,$raw);}catch(Throwable $error){$this->tainted=true;throw$error;}finally{if(is_resource($target))fclose($target);} } public function acknowledged(string $step):bool{$this->requireActive();return isset($this->savedValues[$step]);} public function saved(string $step):array{$this->requireActive();if(!isset($this->savedValues[$step]))throw new JournalRefusal('No acknowledged state exists');return$this->savedValues[$step];} public function beginAction(string $step,string $method,string $route,string $requestFingerprint):array { $this->requireActive();if(isset($this->intents[$step]))throw new JournalRefusal('Never blindly repeat an existing action');$key=$method==='POST'?bin2hex(random_bytes(16)):'';$record=['I',$step,$method,$route,$requestFingerprint,$key];$previous=$this->intents;try{$this->apply($record);}finally{$this->intents=$previous;}$this->append($record);$this->apply($record);return$this->intents[$step]; } public function acknowledge(string $step,array $saved):void { $this->requireActive();$record=['A',$step,(string)count($saved)];$names=array_keys($saved);sort($names,SORT_STRING);foreach($names as$name){$record[]=$name;$record[]=$saved[$name];}$previous=$this->savedValues;try{$this->apply($record);JournalProtocol::strings($record);}finally{$this->savedValues=$previous;}$this->append($record);$this->apply($record); } public function close():void { if(!$this->owned)return;if($this->tainted){fclose($this->file);$this->file=null;$this->owned=false;return;} try{$this->requireActive();}catch(Throwable $error){fclose($this->file);$this->file=null;$this->owned=false;throw$error;}fclose($this->file);$this->file=null;$this->owned=false;if(!unlink($this->lockPath))throw new JournalRefusal('Could not release owned journal lock'); } } function journal_values(mixed $value):array{if(!is_object($value))throw new JournalRefusal('Saved/fingerprint values need an explicit object');$result=get_object_vars($value);foreach($result as$name=>$item)if(!is_string($name)||!is_string($item))throw new JournalRefusal('Saved/fingerprint values must be exact strings');return$result;} function journal_acknowledge(GuideJournal $job,string $step,mixed $saved):void{$job->acknowledge($step,journal_values($saved));} function journal_acknowledged(GuideJournal $job,string $step):bool{return $job->acknowledged($step);} function journal_begin(GuideJournal $job,string $step,string $method,string $path,string $requestFingerprint):array{return $job->beginAction($step,$method,$path,$requestFingerprint);} function journal_fingerprint(mixed $value):string{return JournalProtocol::fingerprint(journal_values($value));} function journal_saved(GuideJournal $job,string $step):array{return $job->saved($step);} function new_id_set():array{return [];} function not_value(bool $value):bool{return !$value;} function open_journal(string $path,string $base,string $workspace,string $slug,string $job,string $inputFingerprint,array $writes,string $mode):GuideJournal{return new GuideJournal($path,$base,$workspace,$slug,$job,$inputFingerprint,$writes,$mode);} function page_size(string $value):string{if(!preg_match("/^[1-9][0-9]*$/D",$value)||strlen($value)>10||(strlen($value)===10&&strcmp($value,"2147483647")>0))throw new RuntimeException("Page size must be a positive int32");return $value;} function positive_id(string $value):string{if(!preg_match("/^[1-9][0-9]*$/D",$value)||strlen($value)>19||(strlen($value)===19&&strcmp($value,"9223372036854775807")>0))throw new RuntimeException("Use a positive record ID");return $value;} function print_value(mixed $value):void{echo (is_string($value)?$value:json_encode($value,JSON_THROW_ON_ERROR))."\n";} function remember_id(array &$seen,string $value):bool{if(array_key_exists($value,$seen))return false;$seen[$value]=true;return true;} function require_condition(bool $value,string $message):void{if(!$value)throw new RuntimeException($message);} function response_status(array $value):string{return(string)$value["status"];} function text(mixed $value):string{if($value===null)return "";if(is_string($value))return $value;if(is_bool($value))return $value?"true":"false";if(is_int($value))return (string)$value;throw new RuntimeException("Expected a scalar response value");} function validate_staff_travel_inputs(string $name, string $start, string $end): void { $spaces = '[\x{0009}-\x{000D}\x{0020}\x{0085}\x{00A0}\x{1680}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]'; foreach ([[$name,'EXHIBITDAY_HOTEL_NAME',125]] as [$value,$label,$limit]) { JournalProtocol::utf8($value); if ($value === '' || preg_match('~\A'.$spaces.'|'.$spaces.'\z~u', $value)) throw new JournalRefusal('Remove whitespace at the start or end of '.$label); if (preg_match_all('/./us',$value) + preg_match_all('/[\x{10000}-\x{10FFFF}]/u',$value) > $limit) throw new JournalRefusal($label.' exceeds '.$limit.' UTF-16 code units'); } if (strpbrk($name, "<>\r\n") !== false || strtolower($name) === 'null') throw new JournalRefusal('Use plain, single-line EXHIBITDAY_HOTEL_NAME text other than null'); foreach ([[$start,'EXHIBITDAY_CHECKIN_DATE'],[$end,'EXHIBITDAY_CHECKOUT_DATE']] as [$value,$label]) { if (!preg_match('/\A([0-9]{4})-([0-9]{2})-([0-9]{2})\z/', $value, $match) || (int)$match[1] < 1753 || !checkdate((int)$match[2],(int)$match[3],(int)$match[1])) throw new JournalRefusal($label.' must be a calendar date in YYYY-MM-DD on or after 1753-01-01'); } if (strcmp($end,$start) < 0) throw new JournalRefusal('EXHIBITDAY_CHECKOUT_DATE must be on or after EXHIBITDAY_CHECKIN_DATE'); } function main():void { $travel_event_id = positive_id(required('EXHIBITDAY_EVENT_ID')); $travel_person_id = required('EXHIBITDAY_PERSON_ID'); $travel_hotel = required('EXHIBITDAY_HOTEL_NAME'); $travel_checkin = required('EXHIBITDAY_CHECKIN_DATE'); $travel_checkout = required('EXHIBITDAY_CHECKOUT_DATE'); $travel_page_size = page_size(optional('EXHIBITDAY_PAGE_SIZE', '100')); $travel_notify = optional('EXHIBITDAY_SEND_NOTIFICATIONS', 'false'); require_condition(either(equal($travel_notify, 'true'), equal($travel_notify, 'false')), 'Use exact true or false for EXHIBITDAY_SEND_NOTIFICATIONS.'); $travel_journal_path = required('EXHIBITDAY_JOURNAL'); $travel_job_id = required('EXHIBITDAY_JOB_ID'); $travel_job_mode = optional('EXHIBITDAY_JOB_MODE', 'resume'); validate_staff_travel_inputs($travel_hotel, $travel_checkin, $travel_checkout); $travel_workspace_response = call('workspace_binding', [], null, null); require_condition(equal(response_status($travel_workspace_response), '200'), 'Expected HTTP200. Keep any durable pending intent and reconcile this response before another write.'); $travel_workspace = $travel_workspace_response["body"]; $travel_workspace_id = positive_id(text(field($travel_workspace, 'id'))); $travel_event_response = call('event_before', ['id' => $travel_event_id], null, null); require_condition(equal(response_status($travel_event_response), '200'), 'Expected HTTP200. Keep any durable pending intent and reconcile this response before another write.'); $travel_event = $travel_event_response["body"]; require_condition(equal(text(field($travel_event, 'id')), $travel_event_id), 'The Event read differs from the explicit selected Event.'); $travel_people_response = call('people_choices', [], null, null); require_condition(equal(response_status($travel_people_response), '200'), 'Expected HTTP200. Keep any durable pending intent and reconcile this response before another write.'); $travel_people = $travel_people_response["body"]; $travel_person_found = ''; foreach (items(items(field($travel_people, 'list_data'))) as $travel_person_choice) { if (equal(text(field($travel_person_choice, 'id')), $travel_person_id)) { require_condition(not_value(is_present($travel_person_found)), 'The people reference returned the same selected person more than once.'); $travel_person_found = $travel_person_id; } } require_condition(equal($travel_person_found, $travel_person_id), 'Choose a current person or resource ID from References users_and_resources before creating Staff or Travel.'); $travel_types_response = call('travel_choices', [], null, null); require_condition(equal(response_status($travel_types_response), '200'), 'Expected HTTP200. Keep any durable pending intent and reconcile this response before another write.'); $travel_types = $travel_types_response["body"]; $travel_hotel_type_found = ''; foreach (items(items(field($travel_types, 'list_data'))) as $travel_type_choice) { if (equal(text(field($travel_type_choice, 'id')), '6')) { require_condition(both(equal(text(field($travel_type_choice, 'name')), 'Hotel'), not_value(is_present($travel_hotel_type_found))), 'The current type6 reference is not one unambiguous Hotel choice.'); $travel_hotel_type_found = '6'; } } require_condition(equal($travel_hotel_type_found, '6'), 'This Hotel example requires the currently declared Hotel choice6; do not substitute a different type.'); $travel_staff_before_id = ''; $travel_staff_before_offset = '0'; $travel_staff_before_query = ['filter_by_event_id' => $travel_event_id, 'filter_by_attendee_user_ids' => $travel_person_id, '$limit' => $travel_page_size]; $travel_staff_before_seen = new_id_set(); while (true) { $travel_staff_before_query['$offset'] = $travel_staff_before_offset; $travel_staff_before_response = call('find_staff', $travel_staff_before_query, null, null); require_condition(equal(response_status($travel_staff_before_response), '200'), 'Expected HTTP200 for the current collection; stop and reconcile another response.'); $travel_staff_before_page = $travel_staff_before_response["body"]; $travel_staff_before_rows = items(field($travel_staff_before_page, 'list_data')); require_condition(equal(text(field($travel_staff_before_page, 'records_found')), text(count($travel_staff_before_rows))), 'records_found differs from this page\'s rows.'); require_condition(is_present(text(field($travel_staff_before_page, 'total_records'))), 'The collection wrapper needs total_records.'); require_condition(either(equal(field($travel_staff_before_page, 'has_more'), true), equal(field($travel_staff_before_page, 'has_more'), false)), 'Expected a Boolean has_more value.'); foreach (items($travel_staff_before_rows) as $travel_staff_before_record) { $travel_staff_before_record_id = positive_id(text(field($travel_staff_before_record, 'id'))); require_condition(equal(text(field($travel_staff_before_record, 'event_id')), $travel_event_id), 'A selected collection returned a row from another Event.'); require_condition(equal(text(field(field($travel_staff_before_record, 'attendee'), 'id')), $travel_person_id), 'The Staff filter returned a registration for a different person.'); if (remember_id($travel_staff_before_seen, $travel_staff_before_record_id)) { require_condition(not_value(is_present($travel_staff_before_id)), 'More than one Staff record matches this person and Event. Stop for review; never choose the first.'); $travel_staff_before_id = $travel_staff_before_record_id; } } if (equal(field($travel_staff_before_page, 'has_more'), false)) { break; } require_condition(not_value(is_empty($travel_staff_before_rows)), 'An empty page says has_more=true. Stop and reconcile the selected query.'); $travel_staff_before_offset = add_offset($travel_staff_before_offset, count($travel_staff_before_rows)); } $travel_input_fingerprint = journal_fingerprint((object)['workflow_contract_sha256' => 'A4CE8A49EF9814D6F6F256BE0525D5A77FF09C69232E21624504C3C3DDA294AB', 'event_id' => $travel_event_id, 'user_id' => $travel_person_id, 'hotel' => $travel_hotel, 'checkin' => $travel_checkin, 'checkout' => $travel_checkout, 'notify' => $travel_notify, 'page_size' => $travel_page_size]); $travel_job = open_journal($travel_journal_path, 'https://api.exhibitday.com/v1', $travel_workspace_id, 'staff-travel-tags', $travel_job_id, $travel_input_fingerprint, [['create_staff', 'POST', '/v1/events/staff'], ['create_travel', 'POST', '/v1/events/travel_reservations']], $travel_job_mode); try { require_condition(either(not_value(journal_acknowledged($travel_job, 'create_travel')), journal_acknowledged($travel_job, 'create_staff')), 'A Travel create is acknowledged before Staff. Stop and reconcile the saved state.'); $travel_staff_id = ''; $travel_reservation_id = ''; if (journal_acknowledged($travel_job, 'create_staff')) { $travel_saved_staff = journal_saved($travel_job, 'create_staff'); $travel_staff_id = positive_id(text(field($travel_saved_staff, 'id'))); require_condition(both(equal(text(field($travel_saved_staff, 'event_id')), $travel_event_id), both(equal(text(field(field($travel_saved_staff, 'attendee'), 'id')), $travel_person_id), equal(text(field($travel_saved_staff, 'id')), $travel_staff_id))), 'The Staff record differs from the captured ID, selected Event or person. Reconcile it; do not create a replacement.'); require_condition(equal($travel_staff_before_id, $travel_staff_id), 'The acknowledged Staff entry is missing or changed. Review the current Staff list before continuing.'); } else { require_condition(not_value(is_present($travel_staff_before_id)), 'This person already has a Staff entry without a saved acknowledgement for this job. Review that entry; do not add another registration.'); $travel_staff_fingerprint = journal_fingerprint((object)['event_id' => $travel_event_id, 'user_id' => $travel_person_id, 'registration_type' => 'Conference pass', 'notify_attendee' => $travel_notify]); $travel_staff_intent = journal_begin($travel_job, 'create_staff', 'POST', '/v1/events/staff', $travel_staff_fingerprint); $travel_staff_create_response = call('create_staff', [], (object)['event_id' => $travel_event_id, 'attendee_user_id' => $travel_person_id, 'registration_type' => 'Conference pass', 'notify_attendee' => equal($travel_notify, 'true')], text(field($travel_staff_intent, 'idempotency_key'))); require_condition(equal(response_status($travel_staff_create_response), '200'), 'Expected HTTP200. Keep any durable pending intent and reconcile this response before another write.'); $travel_created_staff = $travel_staff_create_response["body"]; $travel_staff_id = positive_id(text(field($travel_created_staff, 'id'))); require_condition(both(equal(text(field($travel_created_staff, 'event_id')), $travel_event_id), both(equal(text(field(field($travel_created_staff, 'attendee'), 'id')), $travel_person_id), equal(text(field($travel_created_staff, 'id')), $travel_staff_id))), 'The Staff record differs from the captured ID, selected Event or person. Reconcile it; do not create a replacement.'); require_condition(equal(text(field($travel_created_staff, 'registration_type')), 'Conference pass'), 'The Staff acknowledgement has a different registration type; preserve pending state and reconcile.'); journal_acknowledge($travel_job, 'create_staff', (object)['id' => $travel_staff_id, 'event_id' => $travel_event_id, 'user_id' => $travel_person_id]); } $travel_staff_verify_id = ''; $travel_staff_verify_offset = '0'; $travel_staff_verify_query = ['filter_by_event_id' => $travel_event_id, 'filter_by_attendee_user_ids' => $travel_person_id, '$limit' => $travel_page_size]; $travel_staff_verify_seen = new_id_set(); while (true) { $travel_staff_verify_query['$offset'] = $travel_staff_verify_offset; $travel_staff_verify_response = call('staff_readback', $travel_staff_verify_query, null, null); require_condition(equal(response_status($travel_staff_verify_response), '200'), 'Expected HTTP200 for the current collection; stop and reconcile another response.'); $travel_staff_verify_page = $travel_staff_verify_response["body"]; $travel_staff_verify_rows = items(field($travel_staff_verify_page, 'list_data')); require_condition(equal(text(field($travel_staff_verify_page, 'records_found')), text(count($travel_staff_verify_rows))), 'records_found differs from this page\'s rows.'); require_condition(is_present(text(field($travel_staff_verify_page, 'total_records'))), 'The collection wrapper needs total_records.'); require_condition(either(equal(field($travel_staff_verify_page, 'has_more'), true), equal(field($travel_staff_verify_page, 'has_more'), false)), 'Expected a Boolean has_more value.'); foreach (items($travel_staff_verify_rows) as $travel_staff_verify_record) { $travel_staff_verify_record_id = positive_id(text(field($travel_staff_verify_record, 'id'))); require_condition(equal(text(field($travel_staff_verify_record, 'event_id')), $travel_event_id), 'A selected collection returned a row from another Event.'); require_condition(equal(text(field(field($travel_staff_verify_record, 'attendee'), 'id')), $travel_person_id), 'The Staff filter returned a registration for a different person.'); if (remember_id($travel_staff_verify_seen, $travel_staff_verify_record_id)) { require_condition(not_value(is_present($travel_staff_verify_id)), 'More than one Staff record matches this person and Event. Stop for review; never choose the first.'); $travel_staff_verify_id = $travel_staff_verify_record_id; } } if (equal(field($travel_staff_verify_page, 'has_more'), false)) { break; } require_condition(not_value(is_empty($travel_staff_verify_rows)), 'An empty page says has_more=true. Stop and reconcile the selected query.'); $travel_staff_verify_offset = add_offset($travel_staff_verify_offset, count($travel_staff_verify_rows)); } require_condition(equal($travel_staff_verify_id, $travel_staff_id), 'The captured Staff entry is not present in the complete current selected Event/person list. Stop before Travel creation.'); if (journal_acknowledged($travel_job, 'create_travel')) { $travel_saved_reservation = journal_saved($travel_job, 'create_travel'); $travel_reservation_id = positive_id(text(field($travel_saved_reservation, 'id'))); require_condition(both(equal(text(field($travel_saved_reservation, 'event_id')), $travel_event_id), equal(text(field($travel_saved_reservation, 'user_id')), $travel_person_id)), 'Saved Travel state belongs to a different Event or person. Stop and reconcile.'); } else { $travel_create_fingerprint = journal_fingerprint((object)['event_id' => $travel_event_id, 'reservation_type_id' => '6', 'origin_vendor_name' => $travel_hotel, 'origin_checkin_date' => $travel_checkin, 'return_checkin_date' => $travel_checkout, 'tagged_user_ids' => $travel_person_id, 'notify_tagged_users' => $travel_notify]); $travel_create_intent = journal_begin($travel_job, 'create_travel', 'POST', '/v1/events/travel_reservations', $travel_create_fingerprint); $travel_create_response = call('create_travel', [], (object)['event_id' => $travel_event_id, 'reservation_type_id' => '6', 'origin_vendor_name' => $travel_hotel, 'origin_checkin_date' => $travel_checkin, 'return_checkin_date' => $travel_checkout, 'tagged_user_ids' => [$travel_person_id], 'notify_tagged_users' => equal($travel_notify, 'true')], text(field($travel_create_intent, 'idempotency_key'))); require_condition(equal(response_status($travel_create_response), '200'), 'Expected HTTP200. Keep any durable pending intent and reconcile this response before another write.'); $travel_created_reservation = $travel_create_response["body"]; $travel_reservation_id = positive_id(text(field($travel_created_reservation, 'id'))); require_condition(both(both(both(both(both(equal(text(field($travel_created_reservation, 'id')), $travel_reservation_id), equal(text(field($travel_created_reservation, 'event_id')), $travel_event_id)), equal(text(field($travel_created_reservation, 'reservation_type_id')), '6')), equal(text(field($travel_created_reservation, 'origin_vendor_name')), $travel_hotel)), equal(text(field($travel_created_reservation, 'origin_checkin_date')), $travel_checkin)), equal(text(field($travel_created_reservation, 'return_checkin_date')), $travel_checkout)), 'The Hotel response differs from the captured ID, Event, type, vendor or dates. Keep pending state and reconcile; do not create another reservation.'); $travel_created_tags = items(field($travel_created_reservation, 'tagged_users')); require_condition(equal(text(count($travel_created_tags)), '1'), 'The Hotel acknowledgement must contain exactly the one selected tag before it can be saved as acknowledged.'); foreach (items($travel_created_tags) as $travel_created_tag) { require_condition(equal(text(field($travel_created_tag, 'id')), $travel_person_id), 'The acknowledged Hotel is tagged to a different person; keep pending state and reconcile.'); } journal_acknowledge($travel_job, 'create_travel', (object)['id' => $travel_reservation_id, 'event_id' => $travel_event_id, 'user_id' => $travel_person_id]); } $travel_final_id = ''; $travel_final_offset = '0'; $travel_final_query = ['filter_by_event_id' => $travel_event_id, 'filter_by_tagged_user_ids' => $travel_person_id, '$limit' => $travel_page_size]; $travel_final_query['filter_by_tagged_user_ids_match_type'] = 'all'; while (true) { $travel_final_query['$offset'] = $travel_final_offset; $travel_final_response = call('travel_readback', $travel_final_query, null, null); require_condition(equal(response_status($travel_final_response), '200'), 'Expected HTTP200 for the current collection; stop and reconcile another response.'); $travel_final_page = $travel_final_response["body"]; $travel_final_rows = items(field($travel_final_page, 'list_data')); require_condition(equal(text(field($travel_final_page, 'records_found')), text(count($travel_final_rows))), 'records_found differs from this page\'s rows.'); require_condition(is_present(text(field($travel_final_page, 'total_records'))), 'The collection wrapper needs total_records.'); require_condition(either(equal(field($travel_final_page, 'has_more'), true), equal(field($travel_final_page, 'has_more'), false)), 'Expected a Boolean has_more value.'); foreach (items($travel_final_rows) as $travel_final_record) { $travel_final_record_id = positive_id(text(field($travel_final_record, 'id'))); require_condition(equal(text(field($travel_final_record, 'event_id')), $travel_event_id), 'A selected collection returned a row from another Event.'); $travel_final_person_found = ''; $travel_final_tags = items(field($travel_final_record, 'tagged_users')); foreach (items($travel_final_tags) as $travel_final_tag) { if (equal(text(field($travel_final_tag, 'id')), $travel_person_id)) { $travel_final_person_found = 'true'; } } require_condition(equal($travel_final_person_found, 'true'), 'The all-tags filter returned a record without the selected person.'); if (equal($travel_final_record_id, $travel_reservation_id)) { require_condition(both(both(both(both(both(equal(text(field($travel_final_record, 'id')), $travel_reservation_id), equal(text(field($travel_final_record, 'event_id')), $travel_event_id)), equal(text(field($travel_final_record, 'reservation_type_id')), '6')), equal(text(field($travel_final_record, 'origin_vendor_name')), $travel_hotel)), equal(text(field($travel_final_record, 'origin_checkin_date')), $travel_checkin)), equal(text(field($travel_final_record, 'return_checkin_date')), $travel_checkout)), 'The Hotel response differs from the captured ID, Event, type, vendor or dates. Keep pending state and reconcile; do not create another reservation.'); require_condition(equal(text(count($travel_final_tags)), '1'), 'The captured Hotel\'s tags changed; review them instead of silently restoring the original selection.'); $travel_final_id = $travel_final_record_id; } } if (equal(field($travel_final_page, 'has_more'), false)) { break; } require_condition(not_value(is_empty($travel_final_rows)), 'An empty page says has_more=true. Stop and reconcile the selected query.'); $travel_final_offset = add_offset($travel_final_offset, count($travel_final_rows)); } require_condition(equal($travel_final_id, $travel_reservation_id), 'The captured Hotel is missing from the complete current Event/person Travel list. Reconcile it; do not repeat the create or delete records automatically.'); print_value((object)['event_id' => $travel_event_id, 'user_id' => $travel_person_id, 'staff_id' => $travel_staff_id, 'travel_reservation_id' => $travel_reservation_id]); } finally { $travel_job->close(); } } if (realpath($_SERVER['SCRIPT_FILENAME'] ?? '') === __FILE__) main(); ``` ```ruby # 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":true,"requests":{"workspace_binding":{"method":"GET","path":"/references/workspace_info"},"people_choices":{"method":"GET","path":"/references/users_and_resources"},"travel_choices":{"method":"GET","path":"/references/travel_reservation_types"},"event_before":{"method":"GET","path":"/events/info"},"find_staff":{"method":"GET","path":"/events/staff"},"create_staff":{"method":"POST","path":"/events/staff"},"create_travel":{"method":"POST","path":"/events/travel_reservations"},"staff_readback":{"method":"GET","path":"/events/staff"},"travel_readback":{"method":"GET","path":"/events/travel_reservations"}}}') API_KEY = ENV.fetch('EXHIBITDAY_API_KEY') raise 'Use the API key as one ASCII header value without control characters' if API_KEY.each_codepoint.any?{|point|point<32||point>126} 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, 'DELETE' => Net::HTTP::Delete }.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, key = nil) route = SPEC.fetch('requests').fetch(name) headers = { 'Authorization' => 'Bearer ' + API_KEY, 'Accept' => 'application/json' } if route.fetch('method') == 'POST' headers['Idempotency-Key'] = key || raise('Persist a logical create key before sending POST') # 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) # 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.fetch('method') == 'GET' 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 = resend && (status == 429 || (500..599).cover?(status)) 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, raw: raw } end raise 'Retry limit reached' end def add_offset(offset,received) result=Integer(offset)+received raise "Cannot advance this int32 offset; reconcile the query" if received<=0 || result>2147483647 result.to_s end def both(left,right);left&&right;end def items(value) raise "Expected a JSON array" unless value.is_a?(Array) value end def count(value) items(value).length end def either(left,right) raise "Expected Boolean criteria" unless [true,false].include?(left) && [true,false].include?(right) left || right end def equal(left,right) left.class==right.class && left==right end def field(value,name) raise "Missing response field: #{name}" unless value.is_a?(Hash) && value.key?(name) value.fetch(name) end def is_empty(value) count(value)==0 end def is_present(value) !value.nil? && value!="" end require 'digest' require 'securerandom' require 'uri' # Private client restart state, with no transport or application dependency. module GuideJournalProtocol PREAMBLE="EXHIBITDAY-GUIDE-JOURNAL 1\n".b.freeze class Refusal < StandardError; end def self.utf8(value) raise Refusal,'Journal fields are exact strings' unless value.is_a?(String)&&value.valid_encoding? raw=value.encode(Encoding::UTF_8) raise Refusal,'Invalid UTF8 journal field' unless raw.valid_encoding? raw.b end def self.strings(values) values.map{|value|raw=utf8(value);raw.bytesize.to_s.b+':'.b+raw}.join.b end def self.read_strings(raw) values=[];offset=0 while offsetraw.bytesize-offset value=raw.byteslice(offset,size).dup.force_encoding(Encoding::UTF_8);raise Refusal,'Invalid UTF8 string' unless value.valid_encoding? values<=raw.bytesize-offset payload=raw.byteslice(offset,size);offset+=size raise Refusal,'Journal integrity failed; reconcile before retry' unless raw.getbyte(offset)==10&&digest(payload)==match[2] records<0 offset+=written end file.flush;file.fsync end end class GuideJournal P=GuideJournalProtocol def initialize(path,base,workspace,slug,job,input_fingerprint,writes,mode='resume') @path=path.dup;@lock_path=path+'.lock';@file=nil;@owned=false;@tainted=false;@intents={};@saved={};@allowed={} address=URI(base) raise P::Refusal,'Use actual API base and closed guide slug' unless ['https','http'].include?(address.scheme)&&address.host&&address.userinfo.nil?&&address.query.nil?&&address.fragment.nil?&&slug.match?(/\A[a-z][a-z0-9-]*\z/) raise P::Refusal,'Use actual workspace, stable explicit job ID and exact fingerprint' unless !job.strip.empty?&&workspace.match?(/\A[1-9][0-9]*\z/)&&input_fingerprint.match?(/\A[0-9A-F]{64}\z/) raise P::Refusal,'Choose new or resume for this local job' unless ['new','resume'].include?(mode) manifest=[] writes.each do|step,method,route| raise P::Refusal,'Use closed unique write manifest' unless step.match?(/\A[a-z][a-z0-9_-]*\z/)&&!@allowed.key?(step)&&['POST','PATCH','DELETE'].include?(method)&&route.match?(/\A\/v1\/[A-Za-z0-9_\/-]+\z/)&&!route.include?('//') @allowed[step.dup.freeze]=[method.dup.freeze,route.dup.freeze].freeze;manifest.concat([step,method,route]) end raise P::Refusal,'Only write workflows need a restart journal' if @allowed.empty? @header=['H','1',base,workspace,slug,job,input_fingerprint,P.digest(P.strings(manifest))].map{|value|value.dup.freeze}.freeze;P.strings(@header) begin @file=File.open(@lock_path,File::RDWR|File::CREAT|File::EXCL,0o600);@file.binmode;@owned=true rescue Errno::EEXIST raise P::Refusal,'This journal is locked; do not overlap jobs or steal a stale lock' end begin @owner=SecureRandom.hex(16).freeze;P.write_all(@file,@owner.b);@identity=@file.stat # Ruby's Windows fstat reports dev=0 while lstat reports the drive number. # Both expose the same exact inode. Retain it plus the initial path device; # compare like-for-like instead of treating the differing dev APIs as equal. named_identity=File.lstat(@lock_path);raise P::Refusal,'Lock identity did not bind' unless named_identity.ino==@identity.ino @path_device=named_identity.dev raise P::Refusal,'Choose a private regular journal file' if File.symlink?(@path) raise P::Refusal,'Journal missing: stop and reconcile lost state before starting a new logical job' if mode=='resume'&&!File.exist?(@path) raise P::Refusal,'Journal exists; use resume for the same logical job' if mode=='new'&&File.exist?(@path) if mode=='new' File.open(@path,File::WRONLY|File::CREAT|File::EXCL,0o600){|target|target.binmode;P.write_all(target,P::PREAMBLE+P.frame(@header))} end records=P.decode(File.binread(@path));raise P::Refusal,'Journal workspace/base/guide/job/input binding differs' if records.empty?||records[0]!=@header records.drop(1).each{|record|apply(record)} raise P::Refusal,'Saved intent lacks ACK; stop and reconcile before retry' if @intents.keys.any?{|step|!@saved.key?(step)} rescue Exception close;raise end end def apply(record) case record[0] when 'I' raise P::Refusal,'Invalid intent shape' unless record.length==6 _,step,method,route,fingerprint,key=record raise P::Refusal,'Invalid, future or repeated intent' unless step.match?(/\A[a-z][a-z0-9_-]*\z/)&&!@intents.key?(step)&&@allowed[step]==[method,route]&&fingerprint.match?(/\A[0-9A-F]{64}\z/)&&!@intents.keys.any?{|name|!@saved.key?(name)} raise P::Refusal,'Invalid persisted action key' unless (method=='POST'&&key.match?(/\A[0-9a-f]{32}\z/))||(method!='POST'&&key=='') @intents[step.dup.freeze]={'method'=>method.dup.freeze,'path'=>route.dup.freeze,'request_fingerprint'=>fingerprint.dup.freeze,'idempotency_key'=>key.dup.freeze}.freeze when 'A' raise P::Refusal,'Invalid ACK shape' unless record.length>=3 _,step,count,*pairs=record raise P::Refusal,'ACK without exactly one prior intent' unless count.match?(/\A(?:0|[1-9][0-9]*)\z/)&&pairs.length==2*count.to_i&&@intents.key?(step)&&!@saved.key?(step) names=pairs.each_slice(2).map(&:first) raise P::Refusal,'ACK fields must be unique sorted secret-free identifiers' unless names==names.uniq.sort&&names.all?{|name|name.match?(/\A[a-z][a-z0-9_]*\z/)&&!['api_key','exhibitday_api_key'].include?(name)} @saved[step.dup.freeze]=pairs.each_slice(2).to_h.transform_values{|value|value.dup.freeze}.freeze else raise P::Refusal,'Unknown journal transition' end end def require_active raise P::Refusal,'Journal is closed or IO outcome needs reconciliation' unless @owned&&@file&&!@tainted current=File.lstat(@lock_path) raise P::Refusal,'Journal lock replaced; stop without deleting it' unless current.dev==@path_device&¤t.ino==@identity.ino&&File.binread(@lock_path)==@owner.b end def append(record) require_active;raw=P.frame(record) begin File.open(@path,'ab'){|target|P.write_all(target,raw)} rescue Exception @tainted=true;raise end end def acknowledged(step);require_active;@saved.key?(step);end def saved(step) require_active;raise P::Refusal,'No acknowledged state exists' unless @saved.key?(step) @saved.fetch(step).transform_values(&:dup) end def begin_action(step,method,route,request_fingerprint) require_active;raise P::Refusal,'Never blindly repeat an action' if @intents.key?(step) record=['I',step,method,route,request_fingerprint,method=='POST'?SecureRandom.hex(16):''] previous=@intents.dup;begin;apply(record);ensure;@intents=previous;end append(record);apply(record);@intents.fetch(step).transform_values(&:dup) end def acknowledge(step,saved) require_active;record=['A',step,saved.length.to_s];saved.keys.sort.each{|name|record.concat([name,saved.fetch(name)])} previous=@saved.dup;begin;apply(record);P.strings(record);ensure;@saved=previous;end append(record);apply(record) end def close return unless @owned if @tainted;@file.close;@file=nil;@owned=false;return;end begin;require_active;rescue Exception;@file.close;@file=nil;@owned=false;raise;end @file.close;@file=nil;@owned=false;File.unlink(@lock_path) end end def journal_values(value) raise GuideJournalProtocol::Refusal,'Saved/fingerprint values must be exact strings' unless value.is_a?(Hash)&&value.all?{|name,item|name.is_a?(String)&&item.is_a?(String)} value.transform_values(&:dup) end def journal_acknowledge(job,step,saved);job.acknowledge(step,journal_values(saved));end def journal_acknowledged(job,step);job.acknowledged(step);end def journal_begin(job,step,method,path,request_fingerprint);job.begin_action(step,method,path,request_fingerprint);end def journal_fingerprint(value);GuideJournalProtocol.fingerprint(journal_values(value));end def journal_saved(job,step);job.saved(step);end def new_id_set {} end def not_value(value) raise "Expected a Boolean" unless value==true || value==false !value end def open_journal(path,base,workspace,slug,job,input_fingerprint,writes,mode);GuideJournal.new(path,base,workspace,slug,job,input_fingerprint,writes,mode);end def optional(name,fallback) value=ENV[name] value.nil? || value.empty? ? fallback : value end def page_size(value) raise "Page size must be a positive int32" unless /\A[1-9][0-9]*\z/.match?(value) && Integer(value)<=2147483647 value end def positive_id(value) raise "Use a positive record ID" unless /\A[1-9][0-9]*\z/.match?(value) && Integer(value)<=9223372036854775807 value end def print_value(value) STDOUT.binmode.write((value.is_a?(String)?value:JSON.generate(value))+"\n") end def remember_id(seen,value) return false if seen.key?(value) seen[value]=true true end def require_condition(value,message) raise message unless value==true end def required(name) value=ENV[name] raise "Set #{name}" if value.nil? || value.strip.empty? value end def response_status(value);value.fetch(:status).to_s;end def text(value) return "" if value.nil? return value.to_s if value.is_a?(String)||value.is_a?(Integer)||value==true||value==false raise "Expected a scalar response value" end def validate_staff_travel_inputs(name, start_date, end_date) boundary = /\A[\u0009-\u000D\u0020\u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]|[\u0009-\u000D\u0020\u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]\z/ [[name,'EXHIBITDAY_HOTEL_NAME',125]].each do |value,label,limit| GuideJournalProtocol.utf8(value) raise GuideJournalProtocol::Refusal,'Remove whitespace at the start or end of '+label if value.empty? || boundary.match?(value) raise GuideJournalProtocol::Refusal,label+" exceeds #{limit} UTF-16 code units" if value.encode('UTF-16LE').bytesize / 2 > limit end if name.match?(/[<>\r\n]/) || name.downcase == 'null' raise GuideJournalProtocol::Refusal,'Use plain, single-line EXHIBITDAY_HOTEL_NAME text other than null' end [[start_date,'EXHIBITDAY_CHECKIN_DATE'],[end_date,'EXHIBITDAY_CHECKOUT_DATE']].each do |value,label| match = /\A([0-9]{4})-([0-9]{2})-([0-9]{2})\z/.match(value) unless match && match[1].to_i >= 1753 && Date.valid_date?(*match.captures.map(&:to_i)) raise GuideJournalProtocol::Refusal,label+' must be a calendar date in YYYY-MM-DD on or after 1753-01-01' end end raise GuideJournalProtocol::Refusal,'EXHIBITDAY_CHECKOUT_DATE must be on or after EXHIBITDAY_CHECKIN_DATE' if end_date < start_date end def main travel_event_id = positive_id(required('EXHIBITDAY_EVENT_ID')) travel_person_id = required('EXHIBITDAY_PERSON_ID') travel_hotel = required('EXHIBITDAY_HOTEL_NAME') travel_checkin = required('EXHIBITDAY_CHECKIN_DATE') travel_checkout = required('EXHIBITDAY_CHECKOUT_DATE') travel_page_size = page_size(optional('EXHIBITDAY_PAGE_SIZE', '100')) travel_notify = optional('EXHIBITDAY_SEND_NOTIFICATIONS', 'false') require_condition(either(equal(travel_notify, 'true'), equal(travel_notify, 'false')), 'Use exact true or false for EXHIBITDAY_SEND_NOTIFICATIONS.') travel_journal_path = required('EXHIBITDAY_JOURNAL') travel_job_id = required('EXHIBITDAY_JOB_ID') travel_job_mode = optional('EXHIBITDAY_JOB_MODE', 'resume') validate_staff_travel_inputs(travel_hotel, travel_checkin, travel_checkout) travel_workspace_response = call('workspace_binding', {}, nil, nil) require_condition(equal(response_status(travel_workspace_response), '200'), 'Expected HTTP200. Keep any durable pending intent and reconcile this response before another write.') travel_workspace = travel_workspace_response.fetch(:body) travel_workspace_id = positive_id(text(field(travel_workspace, 'id'))) travel_event_response = call('event_before', {'id' => travel_event_id}, nil, nil) require_condition(equal(response_status(travel_event_response), '200'), 'Expected HTTP200. Keep any durable pending intent and reconcile this response before another write.') travel_event = travel_event_response.fetch(:body) require_condition(equal(text(field(travel_event, 'id')), travel_event_id), 'The Event read differs from the explicit selected Event.') travel_people_response = call('people_choices', {}, nil, nil) require_condition(equal(response_status(travel_people_response), '200'), 'Expected HTTP200. Keep any durable pending intent and reconcile this response before another write.') travel_people = travel_people_response.fetch(:body) travel_person_found = '' items(items(field(travel_people, 'list_data'))).each do |travel_person_choice| if equal(text(field(travel_person_choice, 'id')), travel_person_id) require_condition(not_value(is_present(travel_person_found)), 'The people reference returned the same selected person more than once.') travel_person_found = travel_person_id end end require_condition(equal(travel_person_found, travel_person_id), 'Choose a current person or resource ID from References users_and_resources before creating Staff or Travel.') travel_types_response = call('travel_choices', {}, nil, nil) require_condition(equal(response_status(travel_types_response), '200'), 'Expected HTTP200. Keep any durable pending intent and reconcile this response before another write.') travel_types = travel_types_response.fetch(:body) travel_hotel_type_found = '' items(items(field(travel_types, 'list_data'))).each do |travel_type_choice| if equal(text(field(travel_type_choice, 'id')), '6') require_condition(both(equal(text(field(travel_type_choice, 'name')), 'Hotel'), not_value(is_present(travel_hotel_type_found))), 'The current type6 reference is not one unambiguous Hotel choice.') travel_hotel_type_found = '6' end end require_condition(equal(travel_hotel_type_found, '6'), 'This Hotel example requires the currently declared Hotel choice6; do not substitute a different type.') travel_staff_before_id = '' travel_staff_before_offset = '0' travel_staff_before_query = {'filter_by_event_id' => travel_event_id, 'filter_by_attendee_user_ids' => travel_person_id, '$limit' => travel_page_size} travel_staff_before_seen = new_id_set() while true travel_staff_before_query['$offset'] = travel_staff_before_offset travel_staff_before_response = call('find_staff', travel_staff_before_query, nil, nil) require_condition(equal(response_status(travel_staff_before_response), '200'), 'Expected HTTP200 for the current collection; stop and reconcile another response.') travel_staff_before_page = travel_staff_before_response.fetch(:body) travel_staff_before_rows = items(field(travel_staff_before_page, 'list_data')) require_condition(equal(text(field(travel_staff_before_page, 'records_found')), text(count(travel_staff_before_rows))), 'records_found differs from this page\'s rows.') require_condition(is_present(text(field(travel_staff_before_page, 'total_records'))), 'The collection wrapper needs total_records.') require_condition(either(equal(field(travel_staff_before_page, 'has_more'), true), equal(field(travel_staff_before_page, 'has_more'), false)), 'Expected a Boolean has_more value.') items(travel_staff_before_rows).each do |travel_staff_before_record| travel_staff_before_record_id = positive_id(text(field(travel_staff_before_record, 'id'))) require_condition(equal(text(field(travel_staff_before_record, 'event_id')), travel_event_id), 'A selected collection returned a row from another Event.') require_condition(equal(text(field(field(travel_staff_before_record, 'attendee'), 'id')), travel_person_id), 'The Staff filter returned a registration for a different person.') if remember_id(travel_staff_before_seen, travel_staff_before_record_id) require_condition(not_value(is_present(travel_staff_before_id)), 'More than one Staff record matches this person and Event. Stop for review; never choose the first.') travel_staff_before_id = travel_staff_before_record_id end end if equal(field(travel_staff_before_page, 'has_more'), false) break end require_condition(not_value(is_empty(travel_staff_before_rows)), 'An empty page says has_more=true. Stop and reconcile the selected query.') travel_staff_before_offset = add_offset(travel_staff_before_offset, count(travel_staff_before_rows)) end travel_input_fingerprint = journal_fingerprint({'workflow_contract_sha256' => 'A4CE8A49EF9814D6F6F256BE0525D5A77FF09C69232E21624504C3C3DDA294AB', 'event_id' => travel_event_id, 'user_id' => travel_person_id, 'hotel' => travel_hotel, 'checkin' => travel_checkin, 'checkout' => travel_checkout, 'notify' => travel_notify, 'page_size' => travel_page_size}) travel_job = open_journal(travel_journal_path, 'https://api.exhibitday.com/v1', travel_workspace_id, 'staff-travel-tags', travel_job_id, travel_input_fingerprint, [['create_staff', 'POST', '/v1/events/staff'], ['create_travel', 'POST', '/v1/events/travel_reservations']], travel_job_mode) begin require_condition(either(not_value(journal_acknowledged(travel_job, 'create_travel')), journal_acknowledged(travel_job, 'create_staff')), 'A Travel create is acknowledged before Staff. Stop and reconcile the saved state.') travel_staff_id = '' travel_reservation_id = '' if journal_acknowledged(travel_job, 'create_staff') travel_saved_staff = journal_saved(travel_job, 'create_staff') travel_staff_id = positive_id(text(field(travel_saved_staff, 'id'))) require_condition(both(equal(text(field(travel_saved_staff, 'event_id')), travel_event_id), both(equal(text(field(field(travel_saved_staff, 'attendee'), 'id')), travel_person_id), equal(text(field(travel_saved_staff, 'id')), travel_staff_id))), 'The Staff record differs from the captured ID, selected Event or person. Reconcile it; do not create a replacement.') require_condition(equal(travel_staff_before_id, travel_staff_id), 'The acknowledged Staff entry is missing or changed. Review the current Staff list before continuing.') else require_condition(not_value(is_present(travel_staff_before_id)), 'This person already has a Staff entry without a saved acknowledgement for this job. Review that entry; do not add another registration.') travel_staff_fingerprint = journal_fingerprint({'event_id' => travel_event_id, 'user_id' => travel_person_id, 'registration_type' => 'Conference pass', 'notify_attendee' => travel_notify}) travel_staff_intent = journal_begin(travel_job, 'create_staff', 'POST', '/v1/events/staff', travel_staff_fingerprint) travel_staff_create_response = call('create_staff', {}, {'event_id' => travel_event_id, 'attendee_user_id' => travel_person_id, 'registration_type' => 'Conference pass', 'notify_attendee' => equal(travel_notify, 'true')}, text(field(travel_staff_intent, 'idempotency_key'))) require_condition(equal(response_status(travel_staff_create_response), '200'), 'Expected HTTP200. Keep any durable pending intent and reconcile this response before another write.') travel_created_staff = travel_staff_create_response.fetch(:body) travel_staff_id = positive_id(text(field(travel_created_staff, 'id'))) require_condition(both(equal(text(field(travel_created_staff, 'event_id')), travel_event_id), both(equal(text(field(field(travel_created_staff, 'attendee'), 'id')), travel_person_id), equal(text(field(travel_created_staff, 'id')), travel_staff_id))), 'The Staff record differs from the captured ID, selected Event or person. Reconcile it; do not create a replacement.') require_condition(equal(text(field(travel_created_staff, 'registration_type')), 'Conference pass'), 'The Staff acknowledgement has a different registration type; preserve pending state and reconcile.') journal_acknowledge(travel_job, 'create_staff', {'id' => travel_staff_id, 'event_id' => travel_event_id, 'user_id' => travel_person_id}) end travel_staff_verify_id = '' travel_staff_verify_offset = '0' travel_staff_verify_query = {'filter_by_event_id' => travel_event_id, 'filter_by_attendee_user_ids' => travel_person_id, '$limit' => travel_page_size} travel_staff_verify_seen = new_id_set() while true travel_staff_verify_query['$offset'] = travel_staff_verify_offset travel_staff_verify_response = call('staff_readback', travel_staff_verify_query, nil, nil) require_condition(equal(response_status(travel_staff_verify_response), '200'), 'Expected HTTP200 for the current collection; stop and reconcile another response.') travel_staff_verify_page = travel_staff_verify_response.fetch(:body) travel_staff_verify_rows = items(field(travel_staff_verify_page, 'list_data')) require_condition(equal(text(field(travel_staff_verify_page, 'records_found')), text(count(travel_staff_verify_rows))), 'records_found differs from this page\'s rows.') require_condition(is_present(text(field(travel_staff_verify_page, 'total_records'))), 'The collection wrapper needs total_records.') require_condition(either(equal(field(travel_staff_verify_page, 'has_more'), true), equal(field(travel_staff_verify_page, 'has_more'), false)), 'Expected a Boolean has_more value.') items(travel_staff_verify_rows).each do |travel_staff_verify_record| travel_staff_verify_record_id = positive_id(text(field(travel_staff_verify_record, 'id'))) require_condition(equal(text(field(travel_staff_verify_record, 'event_id')), travel_event_id), 'A selected collection returned a row from another Event.') require_condition(equal(text(field(field(travel_staff_verify_record, 'attendee'), 'id')), travel_person_id), 'The Staff filter returned a registration for a different person.') if remember_id(travel_staff_verify_seen, travel_staff_verify_record_id) require_condition(not_value(is_present(travel_staff_verify_id)), 'More than one Staff record matches this person and Event. Stop for review; never choose the first.') travel_staff_verify_id = travel_staff_verify_record_id end end if equal(field(travel_staff_verify_page, 'has_more'), false) break end require_condition(not_value(is_empty(travel_staff_verify_rows)), 'An empty page says has_more=true. Stop and reconcile the selected query.') travel_staff_verify_offset = add_offset(travel_staff_verify_offset, count(travel_staff_verify_rows)) end require_condition(equal(travel_staff_verify_id, travel_staff_id), 'The captured Staff entry is not present in the complete current selected Event/person list. Stop before Travel creation.') if journal_acknowledged(travel_job, 'create_travel') travel_saved_reservation = journal_saved(travel_job, 'create_travel') travel_reservation_id = positive_id(text(field(travel_saved_reservation, 'id'))) require_condition(both(equal(text(field(travel_saved_reservation, 'event_id')), travel_event_id), equal(text(field(travel_saved_reservation, 'user_id')), travel_person_id)), 'Saved Travel state belongs to a different Event or person. Stop and reconcile.') else travel_create_fingerprint = journal_fingerprint({'event_id' => travel_event_id, 'reservation_type_id' => '6', 'origin_vendor_name' => travel_hotel, 'origin_checkin_date' => travel_checkin, 'return_checkin_date' => travel_checkout, 'tagged_user_ids' => travel_person_id, 'notify_tagged_users' => travel_notify}) travel_create_intent = journal_begin(travel_job, 'create_travel', 'POST', '/v1/events/travel_reservations', travel_create_fingerprint) travel_create_response = call('create_travel', {}, {'event_id' => travel_event_id, 'reservation_type_id' => '6', 'origin_vendor_name' => travel_hotel, 'origin_checkin_date' => travel_checkin, 'return_checkin_date' => travel_checkout, 'tagged_user_ids' => [travel_person_id], 'notify_tagged_users' => equal(travel_notify, 'true')}, text(field(travel_create_intent, 'idempotency_key'))) require_condition(equal(response_status(travel_create_response), '200'), 'Expected HTTP200. Keep any durable pending intent and reconcile this response before another write.') travel_created_reservation = travel_create_response.fetch(:body) travel_reservation_id = positive_id(text(field(travel_created_reservation, 'id'))) require_condition(both(both(both(both(both(equal(text(field(travel_created_reservation, 'id')), travel_reservation_id), equal(text(field(travel_created_reservation, 'event_id')), travel_event_id)), equal(text(field(travel_created_reservation, 'reservation_type_id')), '6')), equal(text(field(travel_created_reservation, 'origin_vendor_name')), travel_hotel)), equal(text(field(travel_created_reservation, 'origin_checkin_date')), travel_checkin)), equal(text(field(travel_created_reservation, 'return_checkin_date')), travel_checkout)), 'The Hotel response differs from the captured ID, Event, type, vendor or dates. Keep pending state and reconcile; do not create another reservation.') travel_created_tags = items(field(travel_created_reservation, 'tagged_users')) require_condition(equal(text(count(travel_created_tags)), '1'), 'The Hotel acknowledgement must contain exactly the one selected tag before it can be saved as acknowledged.') items(travel_created_tags).each do |travel_created_tag| require_condition(equal(text(field(travel_created_tag, 'id')), travel_person_id), 'The acknowledged Hotel is tagged to a different person; keep pending state and reconcile.') end journal_acknowledge(travel_job, 'create_travel', {'id' => travel_reservation_id, 'event_id' => travel_event_id, 'user_id' => travel_person_id}) end travel_final_id = '' travel_final_offset = '0' travel_final_query = {'filter_by_event_id' => travel_event_id, 'filter_by_tagged_user_ids' => travel_person_id, '$limit' => travel_page_size} travel_final_query['filter_by_tagged_user_ids_match_type'] = 'all' while true travel_final_query['$offset'] = travel_final_offset travel_final_response = call('travel_readback', travel_final_query, nil, nil) require_condition(equal(response_status(travel_final_response), '200'), 'Expected HTTP200 for the current collection; stop and reconcile another response.') travel_final_page = travel_final_response.fetch(:body) travel_final_rows = items(field(travel_final_page, 'list_data')) require_condition(equal(text(field(travel_final_page, 'records_found')), text(count(travel_final_rows))), 'records_found differs from this page\'s rows.') require_condition(is_present(text(field(travel_final_page, 'total_records'))), 'The collection wrapper needs total_records.') require_condition(either(equal(field(travel_final_page, 'has_more'), true), equal(field(travel_final_page, 'has_more'), false)), 'Expected a Boolean has_more value.') items(travel_final_rows).each do |travel_final_record| travel_final_record_id = positive_id(text(field(travel_final_record, 'id'))) require_condition(equal(text(field(travel_final_record, 'event_id')), travel_event_id), 'A selected collection returned a row from another Event.') travel_final_person_found = '' travel_final_tags = items(field(travel_final_record, 'tagged_users')) items(travel_final_tags).each do |travel_final_tag| if equal(text(field(travel_final_tag, 'id')), travel_person_id) travel_final_person_found = 'true' end end require_condition(equal(travel_final_person_found, 'true'), 'The all-tags filter returned a record without the selected person.') if equal(travel_final_record_id, travel_reservation_id) require_condition(both(both(both(both(both(equal(text(field(travel_final_record, 'id')), travel_reservation_id), equal(text(field(travel_final_record, 'event_id')), travel_event_id)), equal(text(field(travel_final_record, 'reservation_type_id')), '6')), equal(text(field(travel_final_record, 'origin_vendor_name')), travel_hotel)), equal(text(field(travel_final_record, 'origin_checkin_date')), travel_checkin)), equal(text(field(travel_final_record, 'return_checkin_date')), travel_checkout)), 'The Hotel response differs from the captured ID, Event, type, vendor or dates. Keep pending state and reconcile; do not create another reservation.') require_condition(equal(text(count(travel_final_tags)), '1'), 'The captured Hotel\'s tags changed; review them instead of silently restoring the original selection.') travel_final_id = travel_final_record_id end end if equal(field(travel_final_page, 'has_more'), false) break end require_condition(not_value(is_empty(travel_final_rows)), 'An empty page says has_more=true. Stop and reconcile the selected query.') travel_final_offset = add_offset(travel_final_offset, count(travel_final_rows)) end require_condition(equal(travel_final_id, travel_reservation_id), 'The captured Hotel is missing from the complete current Event/person Travel list. Reconcile it; do not repeat the create or delete records automatically.') print_value({'event_id' => travel_event_id, 'user_id' => travel_person_id, 'staff_id' => travel_staff_id, 'travel_reservation_id' => travel_reservation_id}) ensure travel_job.close() end end main if $PROGRAM_NAME == __FILE__ ``` ```go // Go 1.18+; standard library only. Set EXHIBITDAY_API_KEY. package main import ( "bytes" "crypto/rand" "crypto/sha256" "encoding/hex" "regexp" "sort" "unicode/utf8" "encoding/json" "fmt" "io" "net/http" "net/url" "os" "strconv" "strings" "time" ) const base = "https://api.exhibitday.com/v1" const specification = "{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"people_choices\":{\"method\":\"GET\",\"path\":\"/references/users_and_resources\"},\"travel_choices\":{\"method\":\"GET\",\"path\":\"/references/travel_reservation_types\"},\"event_before\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"find_staff\":{\"method\":\"GET\",\"path\":\"/events/staff\"},\"create_staff\":{\"method\":\"POST\",\"path\":\"/events/staff\"},\"create_travel\":{\"method\":\"POST\",\"path\":\"/events/travel_reservations\"},\"staff_readback\":{\"method\":\"GET\",\"path\":\"/events/staff\"},\"travel_readback\":{\"method\":\"GET\",\"path\":\"/events/travel_reservations\"}}}" 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 }} var send = client.Do type result struct { status int; body any; headers http.Header; raw []byte } // 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 call(name string, query map[string]string, body any, key string) result { route := object(object(spec["requests"])[name]); method := text(route["method"]) headers := map[string]string{"Authorization": "Bearer " + apiKey, "Accept": "application/json"} if method == "POST" { if key == "" { panic("Persist a logical create key before sending POST") }; 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() } // 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 := method == "GET" 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 := send(request) if err != nil { if !resend { panic(apiError{0, "", "No response", true}) }; if attempt == 4 { panic(err) }; time.Sleep(time.Second*time.Duration(1<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 := resend && (response.StatusCode == 429 || response.StatusCode >= 500) if retry { if attempt == 4 { panic("Retry limit reached; check the outcome before starting a new create") } seconds := float64(int64(1)<= 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, raw} } panic("Retry limit reached") } func add_offset(offset string,received int64)string{previous,err:=strconv.ParseInt(offset,10,32);if err!=nil||received<=0||received>2147483647-previous{panic("Cannot advance this int32 offset; reconcile the query")};return strconv.FormatInt(previous+received,10)} func both(left,right bool)bool{return left&&right} func items(value any)[]any{result,ok:=value.([]any);if !ok{panic("Expected a JSON array")};return result} func count(value any)int64{return int64(len(items(value)))} func either(left,right bool)bool{return left||right} func equal(left,right any)bool{switch a:=left.(type){case string:b,ok:=right.(string);return ok&&a==b;case bool:b,ok:=right.(bool);return ok&&a==b;case int64:b,ok:=right.(int64);return ok&&a==b};return left==nil&&right==nil} func field(value any,name string)any{obj,ok:=value.(map[string]any);if !ok{panic("Missing response object")};item,found:=obj[name];if !found{panic("Missing response field: "+name)};return item} func is_empty(value any)bool{return count(value)==0} func is_present(value string)bool{return value!=""} // Private client restart state only; no API transport or workflow interpreter. const journalPreamble = "EXHIBITDAY-GUIDE-JOURNAL 1\n" type journalRefusal struct{ message string } func (e journalRefusal) Error() string { return e.message } func journalNeed(ok bool, message string) { if !ok { panic(journalRefusal{message}) } } func journalMatch(value, pattern string) bool { return regexp.MustCompile("\\A(?:"+pattern+")\\z").MatchString(value) } func journalStrings(values []string) []byte { var output bytes.Buffer for _,value:=range values { journalNeed(utf8.ValidString(value),"Journal fields must be valid UTF8 strings"); output.WriteString(strconv.Itoa(len(value))+":");output.WriteString(value) } return output.Bytes() } func journalReadStrings(raw []byte) []string { values:=[]string{};offset:=0 for offset=0,"Incomplete journal string length");end:=offset+relative;text:=string(raw[offset:end]);journalNeed(journalMatch(text,"0|[1-9][0-9]*"),"Noncanonical journal string length");size,err:=strconv.ParseUint(text,10,64);offset=end+1;journalNeed(err==nil&&size<=uint64(len(raw)-offset),"Incomplete journal string");count:=int(size);value:=string(raw[offset:offset+count]);journalNeed(utf8.ValidString(value),"Invalid UTF8 journal field");values=append(values,value);offset+=count } return values } func journalDigest(raw []byte) string { hash:=sha256.Sum256(raw);return strings.ToUpper(hex.EncodeToString(hash[:])) } func journalFingerprint(pairs map[string]string) string { names:=make([]string,0,len(pairs));for name:=range pairs { names=append(names,name) };sort.Strings(names);values:=[]string{} for _,name:=range names { lower:=strings.ToLower(name);journalNeed(journalMatch(name,"[A-Za-z0-9_.-]+")&&lower!="api_key"&&lower!="exhibitday_api_key","Use explicit secret-free fingerprint names");values=append(values,name,pairs[name]) } return journalDigest(journalStrings(values)) } func journalFrame(values []string) []byte { raw:=journalStrings(values);header:=[]byte(strconv.Itoa(len(raw))+" "+journalDigest(raw)+"\n");result:=append(header,raw...);return append(result,'\n') } func journalDecode(raw []byte) [][]string { journalNeed(bytes.HasPrefix(raw,[]byte(journalPreamble)),"Unknown or incomplete journal version");offset:=len(journalPreamble);records:=[][]string{} for offset=0,"Incomplete frame header; reconcile before retry");end:=offset+relative;header:=string(raw[offset:end]);journalNeed(journalMatch(header,"(0|[1-9][0-9]*) [0-9A-F]{64}"),"Invalid frame header");fields:=strings.Split(header," ");size,err:=strconv.ParseUint(fields[0],10,64);offset=end+1;journalNeed(err==nil&&size0 { count,err:=file.Write(raw);if err!=nil{return err};if count<=0{return io.ErrShortWrite};raw=raw[count:] } return file.Sync() } func journalWriteFile(path string,flags int,raw []byte) (err error) { file,err:=os.OpenFile(path,flags,0600);if err!=nil{return err};defer func(){closed:=file.Close();if err==nil{err=closed}}();return journalWriteAll(file,raw) } func journalCopy(source map[string]string) map[string]string { copy:=map[string]string{};for name,value:=range source{copy[name]=value};return copy } func journalCopyStates(source map[string]map[string]string) map[string]map[string]string { copy:=map[string]map[string]string{};for name,value:=range source{copy[name]=journalCopy(value)};return copy } type guideJournal struct { path,lockPath,owner string header []string allowed map[string][2]string intents,savedValues map[string]map[string]string file *os.File identity os.FileInfo owned,tainted bool } func openGuideJournal(path,base,workspace,slug,job,inputFingerprint string,writes [][3]string,modes ...string) (result *guideJournal) { mode:="resume";journalNeed(len(modes)<=1,"Choose one local job mode");if len(modes)==1{mode=modes[0]};journalNeed(mode=="new"||mode=="resume","Choose new or resume for this local job") address,err:=url.Parse(base);journalNeed(err==nil&&address.Hostname()!=""&&(address.Scheme=="https"||address.Scheme=="http")&&address.User==nil&&address.RawQuery==""&&address.Fragment==""&&journalMatch(slug,"[a-z][a-z0-9-]*"),"Use actual API base and closed guide slug") journalNeed(strings.TrimSpace(job)!=""&&journalMatch(workspace,"[1-9][0-9]*")&&journalMatch(inputFingerprint,"[0-9A-F]{64}"),"Use actual workspace, stable explicit job ID and exact fingerprint") j:=&guideJournal{path:path,lockPath:path+".lock",allowed:map[string][2]string{},intents:map[string]map[string]string{},savedValues:map[string]map[string]string{}} manifest:=[]string{};for _,write:=range writes { step,method,route:=write[0],write[1],write[2];_,exists:=j.allowed[step];journalNeed(journalMatch(step,"[a-z][a-z0-9_-]*")&&!exists&&(method=="POST"||method=="PATCH"||method=="DELETE")&&journalMatch(route,"/v1/[A-Za-z0-9_/-]+")&&!strings.Contains(route,"//"),"Use a closed unique write manifest");j.allowed[step]=[2]string{method,route};manifest=append(manifest,step,method,route) } journalNeed(len(j.allowed)>0,"Only write workflows need a restart journal");j.header=[]string{"H","1",base,workspace,slug,job,inputFingerprint,journalDigest(journalStrings(manifest))};journalStrings(j.header) j.file,err=os.OpenFile(j.lockPath,os.O_RDWR|os.O_CREATE|os.O_EXCL,0600);if err!=nil { if os.IsExist(err){panic(journalRefusal{"This journal is locked; do not overlap jobs or steal a stale lock"})};panic(err) };j.owned=true defer func(){ if observed:=recover();observed!=nil { j.Close();panic(observed) } }() random:=make([]byte,16);if _,err=io.ReadFull(rand.Reader,random);err!=nil{panic(err)};j.owner=hex.EncodeToString(random);if err=journalWriteAll(j.file,[]byte(j.owner));err!=nil{panic(err)};j.identity,err=j.file.Stat();if err!=nil{panic(err)} info,err:=os.Lstat(path);if err!=nil&&!os.IsNotExist(err){panic(err)};exists:=err==nil;if exists{journalNeed(info.Mode()&os.ModeSymlink==0,"Choose a private regular journal file")};journalNeed(mode!="resume"||exists,"Journal missing: stop and reconcile lost state before starting a new logical job");journalNeed(mode!="new"||!exists,"Journal exists; use resume for the same logical job");if mode=="new"{raw:=append([]byte(journalPreamble),journalFrame(j.header)...);if err=journalWriteFile(path,os.O_WRONLY|os.O_CREATE|os.O_EXCL,raw);err!=nil{panic(err)}} raw,err:=os.ReadFile(path);if err!=nil{panic(err)};records:=journalDecode(raw);journalNeed(len(records)>0&&stringsEqual(records[0],j.header),"Journal workspace/base/guide/job/input binding differs");for _,record:=range records[1:]{j.apply(record)};for step:=range j.intents{_,ok:=j.savedValues[step];journalNeed(ok,"Saved intent lacks ACK; stop and reconcile before retry")};return j } func stringsEqual(left,right []string) bool { if len(left)!=len(right){return false};for i,value:=range left{if value!=right[i]{return false}};return true } func (j *guideJournal) apply(record []string) { journalNeed(len(record)>0,"Empty journal record") if record[0]=="I" { journalNeed(len(record)==6,"Invalid intent shape");step,method,route,fingerprint,key:=record[1],record[2],record[3],record[4],record[5];_,exists:=j.intents[step];expected,allowed:=j.allowed[step];pending:=false;for name:=range j.intents{if _,ok:=j.savedValues[name];!ok{pending=true}} journalNeed(journalMatch(step,"[a-z][a-z0-9_-]*")&&!exists&&allowed&&expected==[2]string{method,route}&&journalMatch(fingerprint,"[0-9A-F]{64}")&&!pending,"Invalid, future or repeated intent");journalNeed(method=="POST"&&journalMatch(key,"[0-9a-f]{32}")||method!="POST"&&key=="","Invalid persisted action key");j.intents[step]=map[string]string{"method":method,"path":route,"request_fingerprint":fingerprint,"idempotency_key":key} }else if record[0]=="A" { journalNeed(len(record)>=3,"Invalid ACK shape");step,text:=record[1],record[2];count,err:=strconv.ParseUint(text,10,64);_,prior:=j.intents[step];_,done:=j.savedValues[step];journalNeed(journalMatch(text,"0|[1-9][0-9]*")&&err==nil&&len(record)%2==1&&count==uint64((len(record)-3)/2)&&prior&&!done,"ACK without exactly one prior intent");names:=[]string{};for i:=3;i0&&value[0]!='0';for _,ch:=range value{valid=valid&&ch>='0'&&ch<='9'};size,err:=strconv.ParseInt(value,10,32);if !valid||err!=nil||size<=0{panic("Page size must be a positive int32")};return value} func positive_id(value string)string{valid:=len(value)>0&&value[0]!='0';for _,ch:=range value{valid=valid&&ch>='0'&&ch<='9'};id,err:=strconv.ParseInt(value,10,64);if !valid||err!=nil||id<=0{panic("Use a positive record ID")};return value} func print_value(value any){if result,ok:=value.(string);ok{fmt.Println(result);return};raw,err:=json.Marshal(value);if err!=nil{panic(err)};fmt.Println(string(raw))} func remember_id(seen map[string]bool,value string)bool{if seen[value]{return false};seen[value]=true;return true} func require_condition(value bool,message string){if !value{panic(message)}} func response_status(value result)string{return strconv.Itoa(value.status)} func validate_staff_travel_inputs(name, start, end string) { space := func(c rune) bool { return c >= 9 && c <= 13 || c == 32 || c == 0x85 || c == 0xA0 || c == 0x1680 || c >= 0x2000 && c <= 0x200A || c == 0x2028 || c == 0x2029 || c == 0x202F || c == 0x205F || c == 0x3000 } checkText := func(value, label string, limit int) { journalNeed(utf8.ValidString(value), "Use valid UTF-8 for "+label) journalNeed(value != "" && strings.TrimFunc(value,space) == value, "Remove whitespace at the start or end of "+label) units := 0 for _, character := range value { units++; if character > 0xFFFF { units++ } } journalNeed(units <= limit, fmt.Sprintf("%s exceeds %d UTF-16 code units",label,limit)) } checkDate := func(value,label string) { const format = "2006-01-02" date,err := time.Parse(format,value) journalNeed(err == nil && date.Format(format) == value && date.Year() >= 1753, label+" must be a calendar date in YYYY-MM-DD on or after 1753-01-01") } checkText(name,"EXHIBITDAY_HOTEL_NAME",125) journalNeed(!strings.ContainsAny(name,"<>\r\n") && !strings.EqualFold(name,"null"), "Use plain, single-line EXHIBITDAY_HOTEL_NAME text other than null") checkDate(start,"EXHIBITDAY_CHECKIN_DATE") checkDate(end,"EXHIBITDAY_CHECKOUT_DATE") journalNeed(end >= start,"EXHIBITDAY_CHECKOUT_DATE must be on or after EXHIBITDAY_CHECKIN_DATE") } func workflow() { travel_event_id := positive_id(required("EXHIBITDAY_EVENT_ID")) travel_person_id := required("EXHIBITDAY_PERSON_ID") travel_hotel := required("EXHIBITDAY_HOTEL_NAME") travel_checkin := required("EXHIBITDAY_CHECKIN_DATE") travel_checkout := required("EXHIBITDAY_CHECKOUT_DATE") travel_page_size := page_size(optional("EXHIBITDAY_PAGE_SIZE", "100")) travel_notify := optional("EXHIBITDAY_SEND_NOTIFICATIONS", "false") require_condition(either(equal(travel_notify, "true"), equal(travel_notify, "false")), "Use exact true or false for EXHIBITDAY_SEND_NOTIFICATIONS.") travel_journal_path := required("EXHIBITDAY_JOURNAL") travel_job_id := required("EXHIBITDAY_JOB_ID") travel_job_mode := optional("EXHIBITDAY_JOB_MODE", "resume") validate_staff_travel_inputs(travel_hotel, travel_checkin, travel_checkout) travel_workspace_response := call("workspace_binding", map[string]string{}, nil, "") require_condition(equal(response_status(travel_workspace_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write.") travel_workspace := travel_workspace_response.body travel_workspace_id := positive_id(text(field(travel_workspace, "id"))) travel_event_response := call("event_before", map[string]string{"id": travel_event_id}, nil, "") require_condition(equal(response_status(travel_event_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write.") travel_event := travel_event_response.body require_condition(equal(text(field(travel_event, "id")), travel_event_id), "The Event read differs from the explicit selected Event.") travel_people_response := call("people_choices", map[string]string{}, nil, "") require_condition(equal(response_status(travel_people_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write.") travel_people := travel_people_response.body travel_person_found := "" for _, travel_person_choice := range items(items(field(travel_people, "list_data"))) { if equal(text(field(travel_person_choice, "id")), travel_person_id) { require_condition(not_value(is_present(travel_person_found)), "The people reference returned the same selected person more than once.") travel_person_found = travel_person_id } } require_condition(equal(travel_person_found, travel_person_id), "Choose a current person or resource ID from References users_and_resources before creating Staff or Travel.") travel_types_response := call("travel_choices", map[string]string{}, nil, "") require_condition(equal(response_status(travel_types_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write.") travel_types := travel_types_response.body travel_hotel_type_found := "" for _, travel_type_choice := range items(items(field(travel_types, "list_data"))) { if equal(text(field(travel_type_choice, "id")), "6") { require_condition(both(equal(text(field(travel_type_choice, "name")), "Hotel"), not_value(is_present(travel_hotel_type_found))), "The current type6 reference is not one unambiguous Hotel choice.") travel_hotel_type_found = "6" } } require_condition(equal(travel_hotel_type_found, "6"), "This Hotel example requires the currently declared Hotel choice6; do not substitute a different type.") travel_staff_before_id := "" travel_staff_before_offset := "0" travel_staff_before_query := map[string]string{"filter_by_event_id": travel_event_id, "filter_by_attendee_user_ids": travel_person_id, "$limit": travel_page_size} travel_staff_before_seen := new_id_set() for true { travel_staff_before_query["$offset"] = travel_staff_before_offset travel_staff_before_response := call("find_staff", travel_staff_before_query, nil, "") require_condition(equal(response_status(travel_staff_before_response), "200"), "Expected HTTP200 for the current collection; stop and reconcile another response.") travel_staff_before_page := travel_staff_before_response.body travel_staff_before_rows := items(field(travel_staff_before_page, "list_data")) require_condition(equal(text(field(travel_staff_before_page, "records_found")), text(count(travel_staff_before_rows))), "records_found differs from this page's rows.") require_condition(is_present(text(field(travel_staff_before_page, "total_records"))), "The collection wrapper needs total_records.") require_condition(either(equal(field(travel_staff_before_page, "has_more"), true), equal(field(travel_staff_before_page, "has_more"), false)), "Expected a Boolean has_more value.") for _, travel_staff_before_record := range items(travel_staff_before_rows) { travel_staff_before_record_id := positive_id(text(field(travel_staff_before_record, "id"))) require_condition(equal(text(field(travel_staff_before_record, "event_id")), travel_event_id), "A selected collection returned a row from another Event.") require_condition(equal(text(field(field(travel_staff_before_record, "attendee"), "id")), travel_person_id), "The Staff filter returned a registration for a different person.") if remember_id(travel_staff_before_seen, travel_staff_before_record_id) { require_condition(not_value(is_present(travel_staff_before_id)), "More than one Staff record matches this person and Event. Stop for review; never choose the first.") travel_staff_before_id = travel_staff_before_record_id } } if equal(field(travel_staff_before_page, "has_more"), false) { break } require_condition(not_value(is_empty(travel_staff_before_rows)), "An empty page says has_more=true. Stop and reconcile the selected query.") travel_staff_before_offset = add_offset(travel_staff_before_offset, count(travel_staff_before_rows)) } travel_input_fingerprint := journal_fingerprint(map[string]any{"workflow_contract_sha256": "A4CE8A49EF9814D6F6F256BE0525D5A77FF09C69232E21624504C3C3DDA294AB", "event_id": travel_event_id, "user_id": travel_person_id, "hotel": travel_hotel, "checkin": travel_checkin, "checkout": travel_checkout, "notify": travel_notify, "page_size": travel_page_size}) func() { travel_job := open_journal(travel_journal_path, "https://api.exhibitday.com/v1", travel_workspace_id, "staff-travel-tags", travel_job_id, travel_input_fingerprint, []any{[]any{"create_staff", "POST", "/v1/events/staff"}, []any{"create_travel", "POST", "/v1/events/travel_reservations"}}, travel_job_mode) defer travel_job.Close() require_condition(either(not_value(journal_acknowledged(travel_job, "create_travel")), journal_acknowledged(travel_job, "create_staff")), "A Travel create is acknowledged before Staff. Stop and reconcile the saved state.") travel_staff_id := "" travel_reservation_id := "" if journal_acknowledged(travel_job, "create_staff") { travel_saved_staff := journal_saved(travel_job, "create_staff") travel_staff_id = positive_id(text(field(travel_saved_staff, "id"))) require_condition(both(equal(text(field(travel_saved_staff, "event_id")), travel_event_id), both(equal(text(field(field(travel_saved_staff, "attendee"), "id")), travel_person_id), equal(text(field(travel_saved_staff, "id")), travel_staff_id))), "The Staff record differs from the captured ID, selected Event or person. Reconcile it; do not create a replacement.") require_condition(equal(travel_staff_before_id, travel_staff_id), "The acknowledged Staff entry is missing or changed. Review the current Staff list before continuing.") } else { require_condition(not_value(is_present(travel_staff_before_id)), "This person already has a Staff entry without a saved acknowledgement for this job. Review that entry; do not add another registration.") travel_staff_fingerprint := journal_fingerprint(map[string]any{"event_id": travel_event_id, "user_id": travel_person_id, "registration_type": "Conference pass", "notify_attendee": travel_notify}) travel_staff_intent := journal_begin(travel_job, "create_staff", "POST", "/v1/events/staff", travel_staff_fingerprint) travel_staff_create_response := call("create_staff", map[string]string{}, map[string]any{"event_id": travel_event_id, "attendee_user_id": travel_person_id, "registration_type": "Conference pass", "notify_attendee": equal(travel_notify, "true")}, text(field(travel_staff_intent, "idempotency_key"))) require_condition(equal(response_status(travel_staff_create_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write.") travel_created_staff := travel_staff_create_response.body travel_staff_id = positive_id(text(field(travel_created_staff, "id"))) require_condition(both(equal(text(field(travel_created_staff, "event_id")), travel_event_id), both(equal(text(field(field(travel_created_staff, "attendee"), "id")), travel_person_id), equal(text(field(travel_created_staff, "id")), travel_staff_id))), "The Staff record differs from the captured ID, selected Event or person. Reconcile it; do not create a replacement.") require_condition(equal(text(field(travel_created_staff, "registration_type")), "Conference pass"), "The Staff acknowledgement has a different registration type; preserve pending state and reconcile.") journal_acknowledge(travel_job, "create_staff", map[string]any{"id": travel_staff_id, "event_id": travel_event_id, "user_id": travel_person_id}) } travel_staff_verify_id := "" travel_staff_verify_offset := "0" travel_staff_verify_query := map[string]string{"filter_by_event_id": travel_event_id, "filter_by_attendee_user_ids": travel_person_id, "$limit": travel_page_size} travel_staff_verify_seen := new_id_set() for true { travel_staff_verify_query["$offset"] = travel_staff_verify_offset travel_staff_verify_response := call("staff_readback", travel_staff_verify_query, nil, "") require_condition(equal(response_status(travel_staff_verify_response), "200"), "Expected HTTP200 for the current collection; stop and reconcile another response.") travel_staff_verify_page := travel_staff_verify_response.body travel_staff_verify_rows := items(field(travel_staff_verify_page, "list_data")) require_condition(equal(text(field(travel_staff_verify_page, "records_found")), text(count(travel_staff_verify_rows))), "records_found differs from this page's rows.") require_condition(is_present(text(field(travel_staff_verify_page, "total_records"))), "The collection wrapper needs total_records.") require_condition(either(equal(field(travel_staff_verify_page, "has_more"), true), equal(field(travel_staff_verify_page, "has_more"), false)), "Expected a Boolean has_more value.") for _, travel_staff_verify_record := range items(travel_staff_verify_rows) { travel_staff_verify_record_id := positive_id(text(field(travel_staff_verify_record, "id"))) require_condition(equal(text(field(travel_staff_verify_record, "event_id")), travel_event_id), "A selected collection returned a row from another Event.") require_condition(equal(text(field(field(travel_staff_verify_record, "attendee"), "id")), travel_person_id), "The Staff filter returned a registration for a different person.") if remember_id(travel_staff_verify_seen, travel_staff_verify_record_id) { require_condition(not_value(is_present(travel_staff_verify_id)), "More than one Staff record matches this person and Event. Stop for review; never choose the first.") travel_staff_verify_id = travel_staff_verify_record_id } } if equal(field(travel_staff_verify_page, "has_more"), false) { break } require_condition(not_value(is_empty(travel_staff_verify_rows)), "An empty page says has_more=true. Stop and reconcile the selected query.") travel_staff_verify_offset = add_offset(travel_staff_verify_offset, count(travel_staff_verify_rows)) } require_condition(equal(travel_staff_verify_id, travel_staff_id), "The captured Staff entry is not present in the complete current selected Event/person list. Stop before Travel creation.") if journal_acknowledged(travel_job, "create_travel") { travel_saved_reservation := journal_saved(travel_job, "create_travel") travel_reservation_id = positive_id(text(field(travel_saved_reservation, "id"))) require_condition(both(equal(text(field(travel_saved_reservation, "event_id")), travel_event_id), equal(text(field(travel_saved_reservation, "user_id")), travel_person_id)), "Saved Travel state belongs to a different Event or person. Stop and reconcile.") } else { travel_create_fingerprint := journal_fingerprint(map[string]any{"event_id": travel_event_id, "reservation_type_id": "6", "origin_vendor_name": travel_hotel, "origin_checkin_date": travel_checkin, "return_checkin_date": travel_checkout, "tagged_user_ids": travel_person_id, "notify_tagged_users": travel_notify}) travel_create_intent := journal_begin(travel_job, "create_travel", "POST", "/v1/events/travel_reservations", travel_create_fingerprint) travel_create_response := call("create_travel", map[string]string{}, map[string]any{"event_id": travel_event_id, "reservation_type_id": "6", "origin_vendor_name": travel_hotel, "origin_checkin_date": travel_checkin, "return_checkin_date": travel_checkout, "tagged_user_ids": []any{travel_person_id}, "notify_tagged_users": equal(travel_notify, "true")}, text(field(travel_create_intent, "idempotency_key"))) require_condition(equal(response_status(travel_create_response), "200"), "Expected HTTP200. Keep any durable pending intent and reconcile this response before another write.") travel_created_reservation := travel_create_response.body travel_reservation_id = positive_id(text(field(travel_created_reservation, "id"))) require_condition(both(both(both(both(both(equal(text(field(travel_created_reservation, "id")), travel_reservation_id), equal(text(field(travel_created_reservation, "event_id")), travel_event_id)), equal(text(field(travel_created_reservation, "reservation_type_id")), "6")), equal(text(field(travel_created_reservation, "origin_vendor_name")), travel_hotel)), equal(text(field(travel_created_reservation, "origin_checkin_date")), travel_checkin)), equal(text(field(travel_created_reservation, "return_checkin_date")), travel_checkout)), "The Hotel response differs from the captured ID, Event, type, vendor or dates. Keep pending state and reconcile; do not create another reservation.") travel_created_tags := items(field(travel_created_reservation, "tagged_users")) require_condition(equal(text(count(travel_created_tags)), "1"), "The Hotel acknowledgement must contain exactly the one selected tag before it can be saved as acknowledged.") for _, travel_created_tag := range items(travel_created_tags) { require_condition(equal(text(field(travel_created_tag, "id")), travel_person_id), "The acknowledged Hotel is tagged to a different person; keep pending state and reconcile.") } journal_acknowledge(travel_job, "create_travel", map[string]any{"id": travel_reservation_id, "event_id": travel_event_id, "user_id": travel_person_id}) } travel_final_id := "" travel_final_offset := "0" travel_final_query := map[string]string{"filter_by_event_id": travel_event_id, "filter_by_tagged_user_ids": travel_person_id, "$limit": travel_page_size} travel_final_query["filter_by_tagged_user_ids_match_type"] = "all" for true { travel_final_query["$offset"] = travel_final_offset travel_final_response := call("travel_readback", travel_final_query, nil, "") require_condition(equal(response_status(travel_final_response), "200"), "Expected HTTP200 for the current collection; stop and reconcile another response.") travel_final_page := travel_final_response.body travel_final_rows := items(field(travel_final_page, "list_data")) require_condition(equal(text(field(travel_final_page, "records_found")), text(count(travel_final_rows))), "records_found differs from this page's rows.") require_condition(is_present(text(field(travel_final_page, "total_records"))), "The collection wrapper needs total_records.") require_condition(either(equal(field(travel_final_page, "has_more"), true), equal(field(travel_final_page, "has_more"), false)), "Expected a Boolean has_more value.") for _, travel_final_record := range items(travel_final_rows) { travel_final_record_id := positive_id(text(field(travel_final_record, "id"))) require_condition(equal(text(field(travel_final_record, "event_id")), travel_event_id), "A selected collection returned a row from another Event.") travel_final_person_found := "" travel_final_tags := items(field(travel_final_record, "tagged_users")) for _, travel_final_tag := range items(travel_final_tags) { if equal(text(field(travel_final_tag, "id")), travel_person_id) { travel_final_person_found = "true" } } require_condition(equal(travel_final_person_found, "true"), "The all-tags filter returned a record without the selected person.") if equal(travel_final_record_id, travel_reservation_id) { require_condition(both(both(both(both(both(equal(text(field(travel_final_record, "id")), travel_reservation_id), equal(text(field(travel_final_record, "event_id")), travel_event_id)), equal(text(field(travel_final_record, "reservation_type_id")), "6")), equal(text(field(travel_final_record, "origin_vendor_name")), travel_hotel)), equal(text(field(travel_final_record, "origin_checkin_date")), travel_checkin)), equal(text(field(travel_final_record, "return_checkin_date")), travel_checkout)), "The Hotel response differs from the captured ID, Event, type, vendor or dates. Keep pending state and reconcile; do not create another reservation.") require_condition(equal(text(count(travel_final_tags)), "1"), "The captured Hotel's tags changed; review them instead of silently restoring the original selection.") travel_final_id = travel_final_record_id } } if equal(field(travel_final_page, "has_more"), false) { break } require_condition(not_value(is_empty(travel_final_rows)), "An empty page says has_more=true. Stop and reconcile the selected query.") travel_final_offset = add_offset(travel_final_offset, count(travel_final_rows)) } require_condition(equal(travel_final_id, travel_reservation_id), "The captured Hotel is missing from the complete current Event/person Travel list. Reconcile it; do not repeat the create or delete records automatically.") print_value(map[string]any{"event_id": travel_event_id, "user_id": travel_person_id, "staff_id": travel_staff_id, "travel_reservation_id": travel_reservation_id}) }() } func header_key(value string)string{for _,ch:=range value{if ch<32||ch>126{panic("Use the API key as one ASCII header value without control characters")}};return value} func main(){apiKey=header_key(required("EXHIBITDAY_API_KEY"));if err:=json.Unmarshal([]byte(specification),&spec);err!=nil{panic(err)};workflow()} ``` #### Example response Response 200 — OK 304 — Not Modified 400 — Bad Request 401 — Unauthorized 404 — Not Found 409 — Conflict 429 — Too Many Requests 500 — Internal Server Error Example Successful request ```json { "list_type": "travel_reservation", "list_data": [ { "id": 3001, "event_id": 12345, "event_name": "Spring Expo 2030", "reservation_type_id": 6, "booking_status_id": null, "book_by_date": null, "date_booked": null, "booking_url": null, "cancellation_instructions": null, "vehicle_drop_off_location": null, "reservation_number": null, "origin_vendor_name": "Spring Expo Conference Hotel", "origin_flight_number": null, "origin_reservation_item_info": null, "origin_checkin_location": null, "origin_checkin_date": "2030-01-14", "origin_checkin_time": null, "origin_reservation_details": null, "origin_destination_location": null, "origin_destination_date": null, "origin_destination_time": null, "origin_reservation_final_details": null, "return_vendor_name": null, "return_flight_number": null, "return_reservation_item_info": null, "return_checkin_location": null, "return_checkin_date": "2030-01-17", "return_checkin_time": null, "return_reservation_details": null, "return_destination_location": null, "return_destination_date": null, "return_destination_time": null, "return_reservation_final_details": null, "origin_vendor_address": null, "notes": "", "payment_status_id": 0, "payment_due_date": null, "next_payment_due_date": null, "payment_notes": null, "invoice_attachment": null, "reservation_type": "Hotel", "reservation_group": "Lodging", "booking_status": "Not Specified", "payment_status": { "id": 0, "name": "N/A" }, "cost": { "amount": 0.00, "cost_center_breakdown": [] }, "tagged_users": [ { "id": "f45d4ec2-6d33-4c86-a516-459d21060001", "first_name": "Alex", "last_name": "Morgan", "display_name": "Alex Morgan", "email": "alex@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true } ], "created_by": { "id": null, "first_name": "ExhibitDay", "last_name": "API", "display_name": "ExhibitDay API", "email": null, "type": null, "workspace_role": null, "is_active": true } } ], "records_found": 1, "total_records": 1, "has_more": false } ``` Note: Verified Hotel reservation. The final Travel page contains the captured Hotel ID after separate Staff and Travel creates. The console prints only the captured IDs; this is the complete API response body. Note: There is no response body. Keep using your cached response. ```json { "status_code": 400, "status": "Bad Request", "message": "X-HTTP-Method-Override: hTTP method override is not supported.", "error_code": "invalid_request", "errors": [ "Send the documented HTTP method directly. X-HTTP-Method-Override cannot change a request's HTTP method." ], "error_params": [ "X-HTTP-Method-Override" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 400, "status": "Bad Request", "message": "filter_by_tagged_user_ids must be one user ID or an array of user IDs. Each ID is text of 1 to 128 characters; numbers, true/false, null, blank values and objects are not IDs. For example, send \"user-id\" or [\"user-id\",\"other-user-id\"].", "error_code": "invalid_request", "errors": [ "filter_by_tagged_user_ids must be one user ID or an array of user IDs. Each ID is text of 1 to 128 characters; numbers, true/false, null, blank values and objects are not IDs. For example, send \"user-id\" or [\"user-id\",\"other-user-id\"]." ], "error_params": [ "filter_by_tagged_user_ids" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "No API key was provided. Send your key in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "missing_api_key", "errors": [ "Copy the key from Workspace Settings > API & Integrations > API Access in ExhibitDay." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "The API key is not valid. Check that you copied the whole key from Workspace Settings > API & Integrations > API Access, then send it in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "invalid_api_key", "errors": [ "Check that you sent the whole key. If it was regenerated, use the current key from Workspace Settings > API & Integrations > API Access." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "Access to the ExhibitDay API is not enabled for your workspace. Please contact support@exhibitday.com to enable API Access. Once access is enabled, send your key in the Authorization header as 'Bearer YOUR_API_KEY'.", "error_code": "api_access_disabled", "errors": [ "Nothing was read or changed." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "The API key is not valid for this request. Send your current key in the Authorization header as 'Bearer YOUR_API_KEY'.", "error_code": "invalid_api_key", "errors": [ "The API key is not valid for this request. Send your current key in the Authorization header as 'Bearer YOUR_API_KEY'." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "Access to the ExhibitDay API is not enabled for your workspace. Please contact support@exhibitday.com to enable API Access. Once access is enabled, send your key in the Authorization header as 'Bearer YOUR_API_KEY'.", "error_code": "api_access_disabled", "errors": [ "Access to the ExhibitDay API is not enabled for your workspace. Please contact support@exhibitday.com to enable API Access. Once access is enabled, send your key in the Authorization header as 'Bearer YOUR_API_KEY'." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 404, "status": "Not Found", "message": "The invoice attachment is not available under this owning record.", "error_code": "not_found", "errors": [ "The invoice attachment is not available under this owning record." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "The invoice attachment or its owning record changed or has conflicting saved information. Retrieve the current record before retrying.", "error_code": "record_changed", "errors": [ "The invoice attachment or its owning record changed or has conflicting saved information. Retrieve the current record before retrying." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "The Travel entries changed while they were being read. Send the GET request again.", "error_code": "record_changed", "errors": [ "The Travel entries changed while they were being read. Send the GET request again." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 429, "status": "Too Many Requests", "message": "Error 429 - Too Many Requests", "error_code": "rate_limited", "errors": [ "Error 429 - Too Many Requests" ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "An unexpected error occurred. Please try again later." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "An unexpected error occurred. Please try again later." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` Note: Use the request_id from your own response when contacting support. ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "Check whether your change was saved before trying again." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` #### Things to keep in mind - If the Event's Staff or Travel tab is hidden or locked, adding or changing these records returns HTTP 400 (not_allowed), and the message names the tab. Show or unlock the tab in ExhibitDay first. - This example saves the registration type Conference pass. To use a different registration label, change it consistently in the request, its check and its fingerprint. - New assignments require an eligible active member or Resource. Stored assignments can still match filters after a person becomes inactive or is removed. - Staff can match one or more person IDs. Travel can match any or all selected tags. - Keep the same filters on every page. Other changes to the list can move rows between requests. #### If a run stops - Keep the journal private. It records what the program tried to save and which save it confirmed. - To continue a run with no unresolved save, use `EXHIBITDAY_JOB_MODE=resume` with the same job ID, journal path and inputs. - Each save is separate. The Staff registration can remain if the Travel save stops. - A resumed run skips creates the journal already checked and verifies the saved records. - If a save stops with a lost response or the record has changed, check the Event before running the program again. - If you still need a change after checking the old run, use `EXHIBITDAY_JOB_MODE=new` with a new job ID and journal path. - Run only one copy per journal. - If a crash leaves a `.lock` file, make sure no copy using that journal is running or can start. Then remove the lock file and keep the journal. #### Related guides - [Get a Complete List of Attendees, Travel and More](https://api.exhibitday.com/Help/V1?guide=find-filter-page) - [Handle Errors and Retry Failed Requests](https://api.exhibitday.com/Help/V1?guide=errors-and-retries) ### Update Shipment Tracking and Status Automatically Guide page: https://api.exhibitday.com/Help/V1?guide=shipment-tracking Add tracking numbers and Shipped status to Event Shipments from your shipping system or carrier (for example FedEx or UPS). Example use case Your shipping system has issued a tracking number and you want to mark the corresponding Event Shipment as Shipped. What you'll end up with An updated Shipment with the new tracking number and status and a verified, unchanged package list. Before you start Have a workspace API key, the expected Event ID and the ID of an existing Shipment you can read and edit. Good to know The Shipment and its packages have separate tracking numbers. This example updates only the Shipment's tracking number and status. #### At a glance Time to try About 10 minutes Effect on your data Updates records Endpoints 3 The example updates the Shipment's tracking number and status and writes a private local journal. - [`GET /v1/references/workspace_info`](https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-workspace_info) - [`GET /v1/events/shipments/info`](https://api.exhibitday.com/Help/V1?epf=1&topic=shipments#get-v1-events-shipments-info) - [`PATCH /v1/events/shipments`](https://api.exhibitday.com/Help/V1?epf=1&topic=shipments#patch-v1-events-shipments) #### How it works 1. The program reads the Shipment and checks that it belongs to the expected Event. 2. It saves the tracking number and Shipped status using the revision from that read. 3. It reads the Shipment again and compares its package list with the original. #### Update Shipment tracking The examples below update one Shipment and verify that its packages are unchanged. #### Step 1: Confirm the workspace Check where the key will make changes so you can confirm the workspace. ```bash curl -X GET "https://api.exhibitday.com/v1/references/workspace_info" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "id": 98765 } ``` **Check:** Confirm id is the workspace you intended to use. #### Step 2: Read the Shipment and its packages Get its revision and keep the full package list so you can check both the update and the readback. ```bash curl -X GET "https://api.exhibitday.com/v1/events/shipments/info?id=7001&%24include_record_revision=true" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "id": 7001, "event_id": 5001, "tracking_number": "OLD-TRACKING-001", "shipment_status_id": 1, "components": [ { "id": 12002, "component_type_id": null, "component_type": "Not Specified", "description": "Display stand case", "tracking_number": "PACKAGE-1001", "dimensions_length": 48.0, "dimensions_width": 24.0, "dimensions_height": 18.0, "weight": 65.0 }, { "id": 12003, "component_type_id": null, "component_type": "Not Specified", "description": "Brochure carton", "tracking_number": "PACKAGE-1002", "dimensions_length": 20.0, "dimensions_width": 16.0, "dimensions_height": 12.0, "weight": 18.5 } ], "record_revision": "COPY_SHIPMENT_REVISION_FROM_YOUR_READ" } ``` **Check:** Confirm id and event_id, save the components and copy record_revision from your own read. #### Step 3: Save the tracking number and Shipped status Send the new tracking number and status with expected_revision so the API can detect a conflicting change. ```bash curl -X PATCH "https://api.exhibitday.com/v1/events/shipments" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" --data-binary "{\"id\":7001,\"tracking_number\":\"TEST-ANNUAL-EXPO-001\",\"shipment_status_id\":2,\"expected_revision\":\"COPY_SHIPMENT_REVISION_FROM_YOUR_READ\"}" ``` Example response ```json { "status_code": 200, "status": "OK", "message": "Shipment updated.", "errors": [], "record_revision": "NEW_SHIPMENT_REVISION" } ``` **Check:** Look for record_revision in the response. Leave components out to keep the existing packages. #### Step 4: Verify the Shipment and packages Read the same Shipment again to confirm the update and compare its packages with your original list. ```bash curl -X GET "https://api.exhibitday.com/v1/events/shipments/info?id=7001" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "id": 7001, "event_id": 5001, "tracking_number": "TEST-ANNUAL-EXPO-001", "shipment_status_id": 2, "components": [ { "id": 12002, "component_type_id": null, "component_type": "Not Specified", "description": "Display stand case", "tracking_number": "PACKAGE-1001", "dimensions_length": 48.0, "dimensions_width": 24.0, "dimensions_height": 18.0, "weight": 65.0 }, { "id": 12003, "component_type_id": null, "component_type": "Not Specified", "description": "Brochure carton", "tracking_number": "PACKAGE-1002", "dimensions_length": 20.0, "dimensions_width": 16.0, "dimensions_height": 12.0, "weight": 18.5 } ] } ``` **Check:** Confirm the Shipment and Event IDs, tracking number and status. Compare every returned package field with the original list. **Careful.** Omit components to preserve the saved packages. Sending an empty list clears them. #### Try it #### Before running the example | Variable | What to put in it | Required? | | --- | --- | --- | | `EXHIBITDAY_API_KEY` | Your workspace API key. | Yes | | `EXHIBITDAY_EVENT_ID` | The expected Event ID. The program checks it against the Shipment response. | Yes | | `EXHIBITDAY_SHIPMENT_ID` | The ID of an existing Shipment on that Event. | Yes | | `EXHIBITDAY_TRACKING_NUMBER` | The tracking number from your shipping system or carrier. Use plain text on one line, up to 125 UTF-16 code units. | Yes | | `EXHIBITDAY_JOB_ID` | A stable ID for this logical change. | Yes | | `EXHIBITDAY_JOURNAL` | A private local path for this job's journal. | Yes | | `EXHIBITDAY_JOB_MODE` | Use new for a genuinely new job or resume with the existing journal. The default is resume. | No | **Careful.** This example updates an existing Shipment. Use a test Shipment. #### Bash ``` export EXHIBITDAY_API_KEY='YOUR_API_KEY' export EXHIBITDAY_EVENT_ID='5001' export EXHIBITDAY_SHIPMENT_ID='7001' export EXHIBITDAY_TRACKING_NUMBER='TEST-ANNUAL-EXPO-001' ``` #### PowerShell ``` $env:EXHIBITDAY_API_KEY = 'YOUR_API_KEY' $env:EXHIBITDAY_EVENT_ID = '5001' $env:EXHIBITDAY_SHIPMENT_ID = '7001' $env:EXHIBITDAY_TRACKING_NUMBER = 'TEST-ANNUAL-EXPO-001' ``` Use your own Event and Shipment IDs and tracking number. Set a private journal path and job ID. Set `EXHIBITDAY_JOB_MODE=new` for a new job, then run the complete example in your language. #### Complete example program Code Samples ```bash #!/usr/bin/env bash # Requires Bash, curl and Python3. No API key is written into the program. python3 - <<'EXHIBITDAY_PY' # Python 3; standard library only. Set EXHIBITDAY_API_KEY before running. import http.client import json import os import re import time import urllib.error import urllib.parse import urllib.request BASE = "https://api.exhibitday.com/v1" SPEC = json.loads("{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"read_shipment\":{\"method\":\"GET\",\"path\":\"/events/shipments/info\"},\"update_tracking\":{\"method\":\"PATCH\",\"path\":\"/events/shipments\"},\"verify_shipment\":{\"method\":\"GET\",\"path\":\"/events/shipments/info\"}}}") API_KEY = os.environ["EXHIBITDAY_API_KEY"] if any(ord(char) < 32 or ord(char) > 126 for char in API_KEY): raise RuntimeError("Use the API key as one ASCII header value without control characters") if not API_KEY.strip(): raise RuntimeError("Set EXHIBITDAY_API_KEY") def decode_json(text): if SPEC["preserveNumbers"]: # Quote JSON NUMBER tokens, never text inside a JSON string, to keep CSV decimals exact. text = re.sub(r'"(?:\\.|[^"\\])*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?', lambda m: m[0] if m[0].startswith('"') else json.dumps(m[0]), text) return json.loads(text) from pathlib import Path # This terminal version uses curl for HTTP and Python's standard library for JSON/CSV. import subprocess import tempfile def transport(method, url, headers, data): with tempfile.TemporaryDirectory(prefix="exhibitday-guide-") as directory: folder = Path(directory) # curl may leave no output file for a valid bodyless304 response. (folder / "body").write_bytes(b"") command = ["curl", "--disable", "--silent", "--show-error", "--request", method, "--url", url, "--max-time", "30", "--dump-header", str(folder / "headers"), "--output", str(folder / "body"), "--write-out", "%{http_code}"] for name, value in headers.items(): command += ["--header", name + ": " + value] if data is not None: (folder / "request").write_bytes(data) command += ["--data-binary", "@" + str(folder / "request")] result = subprocess.run(command, capture_output=True, text=True) if result.returncode: raise urllib.error.URLError(result.stderr.strip()) response_headers = {} blocks = (folder / "headers").read_text(encoding="iso-8859-1").replace("\r\n", "\n").strip().split("\n\n") for line in blocks[-1].splitlines()[1:]: name, separator, value = line.partition(":") if separator: response_headers[name] = value.strip() return int(result.stdout), (folder / "body").read_bytes(), response_headers class ApiError(RuntimeError): """An API error response. Branch on error_code (and status), never on the message text. uncertain is True when a PATCH or DELETE got no response or a server error: it may or may not have been applied.""" def __init__(self, status, body, uncertain=False): self.status = status self.uncertain = uncertain self.error_code = body.get("error_code") if isinstance(body, dict) else None super().__init__(f"{body.get('error_code')} {body.get('error_params')}: {body.get('errors')} (request {body.get('request_id')})" if isinstance(body, dict) else "HTTP " + str(status) if status else "No response") def call(name, params=None, body=None, key=None): route = SPEC["requests"][name] headers = {"Authorization": "Bearer " + API_KEY, "Accept": "application/json"} if route["method"] == "POST": if not key: raise RuntimeError("Persist a logical create key before sending POST") headers["Idempotency-Key"] = key data = None if body is None else json.dumps(body).encode("utf-8") if data is not None: headers["Content-Type"] = "application/json" query = urllib.parse.urlencode(params or {}) url = BASE + route["path"] + ("?" + query if query else "") # Only GET has automatic retries in this workflow. A PATCH or DELETE that got no response or a # server error is never resent blindly: it may already have been applied, so the caller reads the record first. resend = route["method"] == "GET" for attempt in range(5): try: status, raw, response_headers = transport(route["method"], url, headers, data) except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException): if not resend: raise ApiError(0, None, uncertain=True) if attempt == 4: raise time.sleep(2 ** attempt) continue response_headers = {k.lower(): v for k, v in response_headers.items()} result = None if status != 304 and raw: try: result = decode_json(raw.decode("utf-8")) except (ValueError, UnicodeError): if status < 400: raise RuntimeError("Expected a JSON success response") if status >= 500 and not resend: raise ApiError(status, result, uncertain=True) retry = resend and (status == 429 or status >= 500) if retry: if attempt == 4: raise RuntimeError("Retry limit reached; check the request outcome before starting a new create") delay = response_headers.get("retry-after", str(2 ** attempt)) time.sleep(max(0, float(delay))) continue if status >= 400: raise ApiError(status, result) return {"status": status, "body": result, "headers": response_headers, "raw": raw} raise RuntimeError("Retry limit reached") def both(left,right): return left and right def deep_equal(left,right): if type(left) is not type(right): return False if isinstance(left,dict): return left.keys()==right.keys() and all(deep_equal(left[k],right[k]) for k in left) if isinstance(left,list): return len(left)==len(right) and all(deep_equal(a,b) for a,b in zip(left,right)) return left==right def equal(left, right): return type(left) is type(right) and left == right def field(value, name): if not isinstance(value, dict) or name not in value: raise RuntimeError("Missing response field: " + name) return value[name] def is_present(value): return value is not None and value != "" def items(value): if not isinstance(value, list): raise RuntimeError("Expected a JSON array") return value """Strict private client journal reference; no transport or application dependency.""" from pathlib import Path import hashlib import os import re import secrets from urllib.parse import urlsplit PREAMBLE=b'EXHIBITDAY-GUIDE-JOURNAL 1\n' class JournalRefusal(RuntimeError): pass def utf8(value): if not isinstance(value,str):raise JournalRefusal('Journal fields are exact strings') return value.encode('utf-8',errors='strict') def strings(values): raw=bytearray() for value in values: item=utf8(value);raw.extend(str(len(item)).encode('ascii'));raw.extend(b':');raw.extend(item) return bytes(raw) def read_strings(raw): values=[];offset=0 while offsetlen(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)-offset:raise JournalRefusal('Incomplete journal frame; reconcile before retry') payload=raw[offset:offset+size];offset+=size if raw[offset:offset+1]!=b'\n' or digest(payload).encode('ascii')!=match[2]:raise JournalRefusal('Journal integrity check failed; reconcile before retry') records.append(read_strings(payload));offset+=1 return records class Journal: def __init__(self,path,base,workspace,slug,job,input_fingerprint,writes,mode="resume"): self.path=Path(path);self.lock=Path(str(self.path)+'.lock');self.fd=None;self.owned=False;self.identity=None;self.tainted=False;self.intents={};self.saved_values={} address=urlsplit(base) if address.scheme not in ('https','http')or not address.netloc or address.username is not None or address.query or address.fragment or not re.fullmatch('[a-z][a-z0-9-]*',slug):raise JournalRefusal('Use the actual API base and closed guide slug') if not job.strip() or not re.fullmatch('[1-9][0-9]*',workspace) or not re.fullmatch('[0-9A-F]{64}',input_fingerprint):raise JournalRefusal('Use an actual workspace, explicit stable job ID and exact input fingerprint') if mode not in ("new","resume"):raise JournalRefusal("Choose new or resume for this local job") self.allowed={};manifest=[] for step,method,route in writes: if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.allowed or method not in ('POST','PATCH','DELETE')or not re.fullmatch('/v1/[A-Za-z0-9_/-]+',route)or'//'in route:raise JournalRefusal('Use a closed unique write manifest') self.allowed[step]=(method,route);manifest.extend((step,method,route)) if not self.allowed:raise JournalRefusal('Only write workflows need a restart journal') self.header=['H','1',base,workspace,slug,job,input_fingerprint,digest(strings(manifest))] strings(self.header) try: self.fd=os.open(self.lock,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600);self.owned=True except FileExistsError:raise JournalRefusal('This journal is locked; do not run overlapping jobs or steal a stale lock') try: self.owner=secrets.token_hex(16);self.identity=os.fstat(self.fd) if os.write(self.fd,self.owner.encode('ascii'))!=len(self.owner):raise OSError('Incomplete lock identity write') os.fsync(self.fd) if self.path.is_symlink():raise JournalRefusal('Choose a private regular journal file') if mode=="resume" and not self.path.exists():raise JournalRefusal("Journal missing: stop and reconcile lost state before starting a new logical job") if mode=="new" and self.path.exists():raise JournalRefusal("A journal already exists; use resume for the same logical job") if mode=="new": with open(self.path,'xb',buffering=0)as target: target.write(PREAMBLE+frame(self.header));os.fsync(target.fileno()) records=decode(self.path.read_bytes()) if not records or records[0]!=self.header:raise JournalRefusal('Journal workspace/base/guide/job/input binding differs') for record in records[1:]:self.apply(record) if any(step not in self.saved_values for step in self.intents):raise JournalRefusal('A saved before-send intent lacks an ACK; stop and reconcile its outcome before retry') except BaseException: self.close();raise def apply(self,record): if not record:raise JournalRefusal('Empty journal record') if record[0]=='I': if len(record)!=6:raise JournalRefusal('Invalid intent shape') _,step,method,path,request_fingerprint,key=record if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.intents or self.allowed.get(step)!=(method,path)or not re.fullmatch('[0-9A-F]{64}',request_fingerprint)or any(name not in self.saved_values for name in self.intents):raise JournalRefusal('Invalid, future or repeated journal intent') if method=='POST'and not re.fullmatch('[0-9a-f]{32}',key)or method!='POST'and key!='':raise JournalRefusal('Invalid persisted action key') self.intents[step]={'method':method,'path':path,'request_fingerprint':request_fingerprint,'idempotency_key':key} elif record[0]=='A': if len(record)<3:raise JournalRefusal('Invalid ACK shape') _,step,count,*pairs=record if not re.fullmatch('0|[1-9][0-9]*',count)or len(pairs)!=2*int(count)or step not in self.intents or step in self.saved_values:raise JournalRefusal('ACK without exactly one prior intent') names=pairs[::2] if names!=sorted(set(names))or any(not re.fullmatch('[a-z][a-z0-9_]*',name)or name in ('api_key','exhibitday_api_key')for name in names):raise JournalRefusal('ACK saved fields must be unique sorted secret-free identifiers') self.saved_values[step]=dict(zip(names,pairs[1::2])) else:raise JournalRefusal('Unknown journal transition') def append(self,record): # The reader commits state only after complete length/digest recognition. # A torn append is retained and refused, never silently truncated. self.require_active();raw=frame(record) try: with open(self.path,'ab',buffering=0)as target: view=memoryview(raw) while view: written=target.write(view) if not written:raise OSError('Journal write did not advance') view=view[written:] os.fsync(target.fileno()) except BaseException: self.tainted=True;raise def require_active(self): if not self.owned or self.fd is None or self.identity is None or self.tainted:raise JournalRefusal('The journal scope is closed or its IO outcome needs reconciliation') current=self.lock.stat(follow_symlinks=False) if current.st_dev!=self.identity.st_dev or current.st_ino!=self.identity.st_ino or self.lock.read_text(encoding='ascii')!=self.owner:raise JournalRefusal('The journal lock was replaced; stop without deleting it') def acknowledged(self,step): self.require_active();return step in self.saved_values def saved(self,step): self.require_active() if step not in self.saved_values:raise JournalRefusal('No acknowledged state exists for this step') return dict(self.saved_values[step]) def begin(self,step,method,path,request_fingerprint): self.require_active() if step in self.intents:raise JournalRefusal('Never blindly repeat an existing action intent') key=secrets.token_hex(16)if method=='POST'else'' record=['I',step,method,path,request_fingerprint,key] # Validate on an isolated state before touching the file. old=dict(self.intents) try:self.apply(record) finally:self.intents=old self.append(record);self.apply(record) return dict(self.intents[step]) def acknowledge(self,step,saved): self.require_active() record=['A',step,str(len(saved))] for name,value in sorted(saved.items()):record.extend((name,value)) old={name:dict(value)for name,value in self.saved_values.items()} try:self.apply(record);strings(record) finally:self.saved_values=old self.append(record);self.apply(record) def close(self): if self.owned: if self.tainted: os.close(self.fd);self.fd=None;self.owned=False return # Retain this lock after failed journal IO; manual reconciliation is required. try:self.require_active() except BaseException: os.close(self.fd);self.fd=None;self.owned=False;raise os.close(self.fd);self.fd=None;self.owned=False self.lock.unlink() def __enter__(self):return self def __exit__(self,*args):self.close() def journal_values(value): if not isinstance(value, dict) or any(not isinstance(k, str) or not isinstance(v, str) for k,v in value.items()): raise JournalRefusal('Saved/fingerprint values must be exact string fields') return dict(value) def journal_acknowledge(job, step, saved): job.acknowledge(step,journal_values(saved)) def journal_acknowledged(job, step): return job.acknowledged(step) def journal_begin(job, step, method, path, request_fingerprint): return job.begin(step,method,path,request_fingerprint) def journal_fingerprint(value): return fingerprint(journal_values(value)) def journal_saved(job, step): return job.saved(step) def json_string(value): return json.dumps(value,ensure_ascii=False,allow_nan=False,separators=(",",":")) def open_journal(path, base, workspace, slug, job, input_fingerprint, writes, mode): return Journal(path,base,workspace,slug,job,input_fingerprint,writes,mode) def optional(name, fallback): value = os.environ.get(name) return fallback if value is None or value == "" else value def parse_json(value): return json.loads(value) def positive_id(value): if not re.fullmatch(r"[1-9][0-9]*", value) or int(value) > 9223372036854775807: raise RuntimeError("Use a positive record ID") return value def print_value(value): print(value if isinstance(value, str) else json.dumps(value, ensure_ascii=False)) def require_condition(value, message): if value is not True: raise RuntimeError(message) def required(name): value = os.environ.get(name) if value is None or not value.strip(): raise RuntimeError("Set " + name) return value def response_status(value): return str(value["status"]) def shipment_tracking_number(value): utf8(value) value = value.strip('\u0009\u000A\u000B\u000C\u000D\u0020\u0085\u00A0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u2028\u2029\u202F\u205F\u3000') if any(character in value for character in '<>\r\n'): raise JournalRefusal('Enter a single-line tracking number without angle brackets.') if not value or len(value.encode('utf-16-le')) // 2 > 125: raise JournalRefusal('Enter a nonblank tracking number of at most 125 UTF-16 code units.') return value def text(value): if value is None: return "" if isinstance(value, str): return value if isinstance(value, bool): return "true" if value else "false" if isinstance(value, int): return str(value) raise RuntimeError("Expected a scalar response value") def main(): expected_shipment_event_id = positive_id(required("EXHIBITDAY_EVENT_ID")) selected_shipment_id = positive_id(required("EXHIBITDAY_SHIPMENT_ID")) desired_tracking_number = shipment_tracking_number(required("EXHIBITDAY_TRACKING_NUMBER")) shipment_journal_path = required("EXHIBITDAY_JOURNAL") shipment_job_id = required("EXHIBITDAY_JOB_ID") shipment_job_mode = optional("EXHIBITDAY_JOB_MODE", "resume") shipment_workspace_response = call("workspace_binding", {}, None, None) require_condition(equal(response_status(shipment_workspace_response), "200"), "Expected the endpoint's documented HTTP200 response; preserve pending state and reconcile any other outcome.") shipment_workspace = shipment_workspace_response["body"] shipment_workspace_id = positive_id(text(field(shipment_workspace, "id"))) initial_shipment_response = call("read_shipment", {"id": selected_shipment_id, "$include_record_revision": "true"}, None, None) require_condition(equal(response_status(initial_shipment_response), "200"), "Expected the endpoint's documented HTTP200 response; preserve pending state and reconcile any other outcome.") initial_shipment = initial_shipment_response["body"] require_condition(both(equal(text(field(initial_shipment, "id")), selected_shipment_id), equal(text(field(initial_shipment, "event_id")), expected_shipment_event_id)), "The selected Shipment does not belong to the expected Event; no write was sent.") shipment_revision = text(field(initial_shipment, "record_revision")) require_condition(is_present(shipment_revision), "Read the actual Shipment with $include_record_revision=true before attempting the change.") original_components = items(field(initial_shipment, "components")) shipment_input_fingerprint = journal_fingerprint({"workflow_contract_sha256": "150EE3B0A50D2C1B961E315183D849281F9A38E47247AB7A5D526BB60983BA90", "event_id": expected_shipment_event_id, "shipment_id": selected_shipment_id, "tracking_number": desired_tracking_number, "shipment_status_id": "2"}) shipment_job = open_journal(shipment_journal_path, "https://api.exhibitday.com/v1", shipment_workspace_id, "shipment-tracking", shipment_job_id, shipment_input_fingerprint, [["update_tracking", "PATCH", "/v1/events/shipments"]], shipment_job_mode) try: component_snapshot = "" if journal_acknowledged(shipment_job, "update_tracking"): saved_shipment = journal_saved(shipment_job, "update_tracking") require_condition(both(equal(text(field(saved_shipment, "id")), selected_shipment_id), both(equal(text(field(saved_shipment, "event_id")), expected_shipment_event_id), both(equal(text(field(saved_shipment, "tracking_number")), desired_tracking_number), equal(text(field(saved_shipment, "shipment_status_id")), "2")))), "The acknowledged Shipment change belongs to another record, Event or desired tracking state.") component_snapshot = text(field(saved_shipment, "components_json")) else: component_snapshot = json_string(original_components) tracking_patch = {"id": selected_shipment_id, "tracking_number": desired_tracking_number, "shipment_status_id": "2", "expected_revision": shipment_revision} shipment_write_fingerprint = journal_fingerprint({"id": selected_shipment_id, "tracking_number": desired_tracking_number, "shipment_status_id": "2", "expected_revision": shipment_revision}) journal_begin(shipment_job, "update_tracking", "PATCH", "/v1/events/shipments", shipment_write_fingerprint) tracking_save_response = call("update_tracking", {}, tracking_patch, None) require_condition(equal(response_status(tracking_save_response), "200"), "Expected the endpoint's documented HTTP200 response; preserve pending state and reconcile any other outcome.") tracking_receipt = tracking_save_response["body"] saved_shipment_revision = text(field(tracking_receipt, "record_revision")) require_condition(is_present(saved_shipment_revision), "A checked save acknowledgement needs its actual returned record_revision.") journal_acknowledge(shipment_job, "update_tracking", {"id": selected_shipment_id, "event_id": expected_shipment_event_id, "tracking_number": desired_tracking_number, "shipment_status_id": "2", "record_revision": saved_shipment_revision, "components_json": component_snapshot}) shipment_readback_response = call("verify_shipment", {"id": selected_shipment_id}, None, None) require_condition(equal(response_status(shipment_readback_response), "200"), "Expected the endpoint's documented HTTP200 response; preserve pending state and reconcile any other outcome.") shipment_readback = shipment_readback_response["body"] require_condition(both(equal(text(field(shipment_readback, "id")), selected_shipment_id), equal(text(field(shipment_readback, "event_id")), expected_shipment_event_id)), "The final Shipment is missing or rebound; earlier saved state remains in the journal.") require_condition(both(equal(text(field(shipment_readback, "tracking_number")), desired_tracking_number), equal(text(field(shipment_readback, "shipment_status_id")), "2")), "The Shipment no longer matches the acknowledged tracking/status; inspect it instead of automatically restoring the change.") recorded_components = items(parse_json(component_snapshot)) require_condition(deep_equal(field(shipment_readback, "components"), recorded_components), "Shipment components differ from the original saved snapshot. Inspect the packages; do not replace or automatically restore them.") print_value({"shipment_id": selected_shipment_id, "event_id": expected_shipment_event_id, "tracking_number": desired_tracking_number, "components_unchanged": "true"}) finally: shipment_job.close() if __name__ == "__main__": main() EXHIBITDAY_PY ``` ```javascript // Server-side Node.js with fetch; built-in modules only. Set EXHIBITDAY_API_KEY. const BASE = "https://api.exhibitday.com/v1"; const SPEC = JSON.parse("{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"read_shipment\":{\"method\":\"GET\",\"path\":\"/events/shipments/info\"},\"update_tracking\":{\"method\":\"PATCH\",\"path\":\"/events/shipments\"},\"verify_shipment\":{\"method\":\"GET\",\"path\":\"/events/shipments/info\"}}}"); const API_KEY = process.env.EXHIBITDAY_API_KEY; if (!API_KEY || !API_KEY.trim()) throw new Error("Set EXHIBITDAY_API_KEY"); if (/[^\x20-\x7e]/.test(API_KEY)) throw new Error("Use the API key as one ASCII header value without control characters"); 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, errors: result.errors, error_params: result.error_params, 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, key = null) { const route = SPEC.requests[name]; const headers = { Authorization: "Bearer " + API_KEY, Accept: "application/json" }; if (route.method === "POST") { if (!key) throw new Error("Persist a logical create key before sending POST"); headers["Idempotency-Key"] = key; } 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 : ""); // 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. const resend = route.method === "GET"; 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 = resend && (response.status === 429 || response.status >= 500); 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, raw }; } throw new Error("Retry limit reached"); } function both(left,right) { return left && right; } function deep_equal(left,right) { if(left===null||right===null)return left===right; if(typeof left!==typeof right||Array.isArray(left)!==Array.isArray(right))return false; if(typeof left!=='object')return left===right; const a=Object.keys(left).sort(),b=Object.keys(right).sort();return a.length===b.length&&a.every((k,i)=>k===b[i]&&deep_equal(left[k],right[k])); } function equal(left, right) { return typeof left === typeof right && left === right; } function field(value, name) { if (!value || Array.isArray(value) || typeof value !== "object" || !Object.hasOwn(value, name)) throw new Error("Missing response field: " + name); return value[name]; } function is_present(value) { return value !== null && value !== undefined && value !== ""; } function items(value) { if (!Array.isArray(value)) throw new Error("Expected a JSON array"); return value; } 'use strict'; // Private client restart state. No HTTP or application dependency. const fs = require('node:fs'); const crypto = require('node:crypto'); const PREAMBLE = Buffer.from('EXHIBITDAY-GUIDE-JOURNAL 1\n', 'ascii'); class JournalRefusal extends Error {} function ascii(raw) { if (raw.some(value => value > 127)) throw new JournalRefusal('Journal framing must be canonical ASCII'); return raw.toString('ascii'); } function utf8(value) { if (typeof value !== 'string') throw new JournalRefusal('Journal fields are exact strings'); for (const unit of value) if (unit.length === 1 && unit.charCodeAt(0) >= 0xd800 && unit.charCodeAt(0) <= 0xdfff) throw new JournalRefusal('Invalid Unicode journal field'); return Buffer.from(value, 'utf8'); } function strings(values) { const parts = []; for (const value of values) { const raw = utf8(value); parts.push(Buffer.from(String(raw.length) + ':', 'ascii'), raw); } return Buffer.concat(parts); } function readStrings(raw) { const values = []; let offset = 0; while (offset < raw.length) { const end = raw.indexOf(58, offset); if (end < 0) throw new JournalRefusal('Incomplete journal string length'); const length = ascii(raw.subarray(offset, end)); if (!/^(0|[1-9][0-9]*)$/.test(length)) throw new JournalRefusal('Noncanonical journal string length'); const size = BigInt(length); offset = end + 1; if (size > BigInt(raw.length - offset)) throw new JournalRefusal('Incomplete journal string'); const count = Number(size); values.push(new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(raw.subarray(offset, offset + count))); offset += count; } return values; } function digest(raw) { return crypto.createHash('sha256').update(raw).digest('hex').toUpperCase(); } function fingerprint(pairs) { const values = []; for (const name of Object.keys(pairs).sort()) { if (!/^[A-Za-z0-9_.-]+$/.test(name) || ['api_key', 'exhibitday_api_key'].includes(name.toLowerCase())) throw new JournalRefusal('Use explicit secret-free fingerprint field names'); values.push(name, pairs[name]); } return digest(strings(values)); } function frame(values) { const raw = strings(values); return Buffer.concat([Buffer.from(String(raw.length) + ' ' + digest(raw) + '\n', 'ascii'), raw, Buffer.from('\n')]); } function decode(raw) { if (!raw.subarray(0, PREAMBLE.length).equals(PREAMBLE)) throw new JournalRefusal('Unknown or incomplete journal version'); let offset = PREAMBLE.length; const records = []; while (offset < raw.length) { const end = raw.indexOf(10, offset); if (end < 0) throw new JournalRefusal('Incomplete journal frame header; reconcile before retry'); const match = /^(0|[1-9][0-9]*) ([0-9A-F]{64})$/.exec(ascii(raw.subarray(offset, end))); if (!match) throw new JournalRefusal('Invalid journal frame header'); const size = BigInt(match[1]); offset = end + 1; if (size >= BigInt(raw.length - offset)) throw new JournalRefusal('Incomplete journal frame; reconcile before retry'); const count = Number(size), payload = raw.subarray(offset, offset + count); offset += count; if (raw[offset] !== 10 || digest(payload) !== match[2]) throw new JournalRefusal('Journal integrity check failed; reconcile before retry'); records.push(readStrings(payload)); offset++; } return records; } function writeAll(fd, raw) { let offset = 0; while (offset < raw.length) { const count = fs.writeSync(fd, raw, offset, raw.length - offset); if (!count) throw new Error('Journal write did not advance'); offset += count; } } function same(left, right) { return left.length === right.length && left.every((value, index) => value === right[index]); } class Journal { constructor(path, base, workspace, slug, job, inputFingerprint, writes, mode = 'resume') { this.path = path; this.lock = path + '.lock'; this.fd = null; this.owned = false; this.identity = null; this.tainted = false; this.intents = new Map(); this.savedValues = new Map(); this.allowed = new Map(); if (!['new', 'resume'].includes(mode)) throw new JournalRefusal('Choose new or resume for this local job'); const address = new URL(base); if (!['https:', 'http:'].includes(address.protocol) || !address.hostname || address.username || address.password || address.search || address.hash || !/^[a-z][a-z0-9-]*$/.test(slug)) throw new JournalRefusal('Use the actual API base and closed guide slug'); if (!job.trim() || !/^[1-9][0-9]*$/.test(workspace) || !/^[0-9A-F]{64}$/.test(inputFingerprint)) throw new JournalRefusal('Use an actual workspace, stable explicit job ID and exact input fingerprint'); const manifest = []; for (const [step, method, route] of writes) { if (!/^[a-z][a-z0-9_-]*$/.test(step) || this.allowed.has(step) || !['POST', 'PATCH', 'DELETE'].includes(method) || !/^\/v1\/[A-Za-z0-9_/-]+$/.test(route) || route.includes('//')) throw new JournalRefusal('Use a closed unique write manifest'); this.allowed.set(step, [method, route]); manifest.push(step, method, route); } if (!this.allowed.size) throw new JournalRefusal('Only write workflows need a restart journal'); this.header = ['H', '1', base, workspace, slug, job, inputFingerprint, digest(strings(manifest))]; strings(this.header); try { this.fd = fs.openSync(this.lock, 'wx', 0o600); this.owned = true; } catch (error) { if (error.code === 'EEXIST') throw new JournalRefusal('This journal is locked; do not overlap jobs or steal a stale lock'); throw error; } try { this.owner = crypto.randomBytes(16).toString('hex'); this.identity = fs.fstatSync(this.fd, { bigint: true }); writeAll(this.fd, Buffer.from(this.owner, 'ascii')); fs.fsyncSync(this.fd); let exists = true; try { if (fs.lstatSync(path).isSymbolicLink()) throw new JournalRefusal('Choose a private regular journal file'); } catch (error) { if (error.code === 'ENOENT') exists = false; else throw error; } if (mode === 'resume' && !exists) throw new JournalRefusal('Journal missing: stop and reconcile lost state before starting a new logical job'); if (mode === 'new' && exists) throw new JournalRefusal('Journal already exists; use resume for the same logical job'); if (mode === 'new') { const target = fs.openSync(path, 'wx', 0o600); try { writeAll(target, Buffer.concat([PREAMBLE, frame(this.header)])); fs.fsyncSync(target); } finally { fs.closeSync(target); } } const records = decode(fs.readFileSync(path)); if (!records.length || !same(records[0], this.header)) throw new JournalRefusal('Journal workspace/base/guide/job/input binding differs'); for (const record of records.slice(1)) this.apply(record); if ([...this.intents.keys()].some(step => !this.savedValues.has(step))) throw new JournalRefusal('Saved before-send intent lacks ACK; stop and reconcile before retry'); } catch (error) { this.close(); throw error; } } apply(record) { if (record[0] === 'I') { if (record.length !== 6) throw new JournalRefusal('Invalid intent shape'); const [, step, method, path, requestFingerprint, key] = record; if (!/^[a-z][a-z0-9_-]*$/.test(step) || this.intents.has(step) || !this.allowed.has(step) || !same(this.allowed.get(step), [method, path]) || !/^[0-9A-F]{64}$/.test(requestFingerprint) || [...this.intents.keys()].some(name => !this.savedValues.has(name))) throw new JournalRefusal('Invalid, future or repeated intent'); if ((method === 'POST' && !/^[0-9a-f]{32}$/.test(key)) || (method !== 'POST' && key !== '')) throw new JournalRefusal('Invalid persisted action key'); this.intents.set(step, { method, path, request_fingerprint: requestFingerprint, idempotency_key: key }); } else if (record[0] === 'A') { const [, step, count, ...pairs] = record; if (record.length < 3 || !/^(0|[1-9][0-9]*)$/.test(count) || BigInt(pairs.length) !== 2n * BigInt(count) || !this.intents.has(step) || this.savedValues.has(step)) throw new JournalRefusal('ACK without exactly one prior intent'); const names = pairs.filter((_, index) => index % 2 === 0); if (!same(names, [...new Set(names)].sort()) || names.some(name => !/^[a-z][a-z0-9_]*$/.test(name) || ['api_key', 'exhibitday_api_key'].includes(name))) throw new JournalRefusal('ACK fields must be unique sorted secret-free identifiers'); this.savedValues.set(step, Object.fromEntries(names.map((name, index) => [name, pairs[index * 2 + 1]]))); } else throw new JournalRefusal('Unknown journal transition'); } requireActive() { if (!this.owned || this.fd === null || this.identity === null || this.tainted) throw new JournalRefusal('Journal is closed or its IO outcome needs reconciliation'); const current = fs.lstatSync(this.lock, { bigint: true }); if (current.dev !== this.identity.dev || current.ino !== this.identity.ino || ascii(fs.readFileSync(this.lock)) !== this.owner) throw new JournalRefusal('Journal lock was replaced; stop without deleting it'); } append(record) { this.requireActive(); const raw = frame(record); let target; try { target = fs.openSync(this.path, 'a'); writeAll(target, raw); fs.fsyncSync(target); } catch (error) { this.tainted = true; throw error; } finally { if (target !== undefined) fs.closeSync(target); } } acknowledged(step) { this.requireActive(); return this.savedValues.has(step); } saved(step) { this.requireActive(); if (!this.savedValues.has(step)) throw new JournalRefusal('No acknowledged state exists'); return { ...this.savedValues.get(step) }; } begin(step, method, path, requestFingerprint) { this.requireActive(); if (this.intents.has(step)) throw new JournalRefusal('Never blindly repeat an existing action'); const key = method === 'POST' ? crypto.randomBytes(16).toString('hex') : '', record = ['I', step, method, path, requestFingerprint, key]; const old = new Map(this.intents); try { this.apply(record); } finally { this.intents = old; } this.append(record); this.apply(record); return { ...this.intents.get(step) }; } acknowledge(step, saved) { this.requireActive(); const names = Object.keys(saved).sort(), record = ['A', step, String(names.length)]; for (const name of names) record.push(name, saved[name]); const old = new Map(this.savedValues); try { this.apply(record); strings(record); } finally { this.savedValues = old; } this.append(record); this.apply(record); } close() { if (!this.owned) return; if (this.tainted) { fs.closeSync(this.fd); this.fd = null; this.owned = false; return; } try { this.requireActive(); } catch (error) { fs.closeSync(this.fd); this.fd = null; this.owned = false; throw error; } fs.closeSync(this.fd); this.fd = null; this.owned = false; fs.unlinkSync(this.lock); } } function journal_values(value) { if (!value || typeof value !== 'object' || Array.isArray(value) || Object.values(value).some(item=>typeof item!=='string')) throw new JournalRefusal('Saved/fingerprint values must be exact strings'); return {...value}; } function journal_acknowledge(job,step,saved) { job.acknowledge(step,journal_values(saved)); } function journal_acknowledged(job,step) { return job.acknowledged(step); } function journal_begin(job,step,method,path,requestFingerprint) { return job.begin(step,method,path,requestFingerprint); } function journal_fingerprint(value) { return fingerprint(journal_values(value)); } function journal_saved(job,step) { return job.saved(step); } function json_string(value) { return JSON.stringify(value); } function open_journal(path,base,workspace,slug,job,inputFingerprint,writes,mode) { return new Journal(path,base,workspace,slug,job,inputFingerprint,writes,mode); } function optional(name, fallback) { const value = process.env[name]; return value === undefined || value === "" ? fallback : value; } function parse_json(value) { return JSON.parse(value); } function positive_id(value) { if (!/^[1-9][0-9]*$/.test(value) || BigInt(value) > 9223372036854775807n) throw new Error("Use a positive record ID"); return value; } function print_value(value) { console.log(typeof value === "string" ? value : JSON.stringify(value)); } function require_condition(value, message) { if (value !== true) throw new Error(message); } function required(name) { const value = process.env[name]; if (value === undefined || !value.trim()) throw new Error("Set " + name); return value; } function response_status(value) { return String(value.status); } function shipment_tracking_number(value) { utf8(value); value = value.replace(/^[\u0009-\u000D\u0020\u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]+|[\u0009-\u000D\u0020\u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]+$/g, ''); if (/[<>\r\n]/.test(value)) throw new JournalRefusal('Enter a single-line tracking number without angle brackets.'); if (!value || value.length > 125) throw new JournalRefusal('Enter a nonblank tracking number of at most 125 UTF-16 code units.'); return value; } function text(value) { if (value === null || value === undefined) return ""; if (["string", "boolean", "bigint"].includes(typeof value)) return String(value); throw new Error("Expected a scalar response value"); } async function main() { let expected_shipment_event_id = positive_id(required("EXHIBITDAY_EVENT_ID")); let selected_shipment_id = positive_id(required("EXHIBITDAY_SHIPMENT_ID")); let desired_tracking_number = shipment_tracking_number(required("EXHIBITDAY_TRACKING_NUMBER")); let shipment_journal_path = required("EXHIBITDAY_JOURNAL"); let shipment_job_id = required("EXHIBITDAY_JOB_ID"); let shipment_job_mode = optional("EXHIBITDAY_JOB_MODE", "resume"); let shipment_workspace_response = await call("workspace_binding", {}, null, null); require_condition(equal(response_status(shipment_workspace_response), "200"), "Expected the endpoint's documented HTTP200 response; preserve pending state and reconcile any other outcome."); let shipment_workspace = shipment_workspace_response.body; let shipment_workspace_id = positive_id(text(field(shipment_workspace, "id"))); let initial_shipment_response = await call("read_shipment", {"id": selected_shipment_id, "$include_record_revision": "true"}, null, null); require_condition(equal(response_status(initial_shipment_response), "200"), "Expected the endpoint's documented HTTP200 response; preserve pending state and reconcile any other outcome."); let initial_shipment = initial_shipment_response.body; require_condition(both(equal(text(field(initial_shipment, "id")), selected_shipment_id), equal(text(field(initial_shipment, "event_id")), expected_shipment_event_id)), "The selected Shipment does not belong to the expected Event; no write was sent."); let shipment_revision = text(field(initial_shipment, "record_revision")); require_condition(is_present(shipment_revision), "Read the actual Shipment with $include_record_revision=true before attempting the change."); let original_components = items(field(initial_shipment, "components")); let shipment_input_fingerprint = journal_fingerprint({"workflow_contract_sha256": "150EE3B0A50D2C1B961E315183D849281F9A38E47247AB7A5D526BB60983BA90", "event_id": expected_shipment_event_id, "shipment_id": selected_shipment_id, "tracking_number": desired_tracking_number, "shipment_status_id": "2"}); let shipment_job = open_journal(shipment_journal_path, "https://api.exhibitday.com/v1", shipment_workspace_id, "shipment-tracking", shipment_job_id, shipment_input_fingerprint, [["update_tracking", "PATCH", "/v1/events/shipments"]], shipment_job_mode); try { let component_snapshot = ""; if (journal_acknowledged(shipment_job, "update_tracking")) { let saved_shipment = journal_saved(shipment_job, "update_tracking"); require_condition(both(equal(text(field(saved_shipment, "id")), selected_shipment_id), both(equal(text(field(saved_shipment, "event_id")), expected_shipment_event_id), both(equal(text(field(saved_shipment, "tracking_number")), desired_tracking_number), equal(text(field(saved_shipment, "shipment_status_id")), "2")))), "The acknowledged Shipment change belongs to another record, Event or desired tracking state."); component_snapshot = text(field(saved_shipment, "components_json")); } else { component_snapshot = json_string(original_components); let tracking_patch = {"id": selected_shipment_id, "tracking_number": desired_tracking_number, "shipment_status_id": "2", "expected_revision": shipment_revision}; let shipment_write_fingerprint = journal_fingerprint({"id": selected_shipment_id, "tracking_number": desired_tracking_number, "shipment_status_id": "2", "expected_revision": shipment_revision}); journal_begin(shipment_job, "update_tracking", "PATCH", "/v1/events/shipments", shipment_write_fingerprint); let tracking_save_response = await call("update_tracking", {}, tracking_patch, null); require_condition(equal(response_status(tracking_save_response), "200"), "Expected the endpoint's documented HTTP200 response; preserve pending state and reconcile any other outcome."); let tracking_receipt = tracking_save_response.body; let saved_shipment_revision = text(field(tracking_receipt, "record_revision")); require_condition(is_present(saved_shipment_revision), "A checked save acknowledgement needs its actual returned record_revision."); journal_acknowledge(shipment_job, "update_tracking", {"id": selected_shipment_id, "event_id": expected_shipment_event_id, "tracking_number": desired_tracking_number, "shipment_status_id": "2", "record_revision": saved_shipment_revision, "components_json": component_snapshot}); } let shipment_readback_response = await call("verify_shipment", {"id": selected_shipment_id}, null, null); require_condition(equal(response_status(shipment_readback_response), "200"), "Expected the endpoint's documented HTTP200 response; preserve pending state and reconcile any other outcome."); let shipment_readback = shipment_readback_response.body; require_condition(both(equal(text(field(shipment_readback, "id")), selected_shipment_id), equal(text(field(shipment_readback, "event_id")), expected_shipment_event_id)), "The final Shipment is missing or rebound; earlier saved state remains in the journal."); require_condition(both(equal(text(field(shipment_readback, "tracking_number")), desired_tracking_number), equal(text(field(shipment_readback, "shipment_status_id")), "2")), "The Shipment no longer matches the acknowledged tracking/status; inspect it instead of automatically restoring the change."); let recorded_components = items(parse_json(component_snapshot)); require_condition(deep_equal(field(shipment_readback, "components"), recorded_components), "Shipment components differ from the original saved snapshot. Inspect the packages; do not replace or automatically restore them."); print_value({"shipment_id": selected_shipment_id, "event_id": expected_shipment_event_id, "tracking_number": desired_tracking_number, "components_unchanged": "true"}); } finally { shipment_job.close(); } } if (require.main === module) main().catch(error => { console.error(error.message); process.exitCode = 1; }); module.exports = { main }; ``` ```python # Python 3; standard library only. Set EXHIBITDAY_API_KEY before running. import http.client import json import os import re import time import urllib.error import urllib.parse import urllib.request BASE = "https://api.exhibitday.com/v1" SPEC = json.loads("{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"read_shipment\":{\"method\":\"GET\",\"path\":\"/events/shipments/info\"},\"update_tracking\":{\"method\":\"PATCH\",\"path\":\"/events/shipments\"},\"verify_shipment\":{\"method\":\"GET\",\"path\":\"/events/shipments/info\"}}}") API_KEY = os.environ["EXHIBITDAY_API_KEY"] if any(ord(char) < 32 or ord(char) > 126 for char in API_KEY): raise RuntimeError("Use the API key as one ASCII header value without control characters") if not API_KEY.strip(): raise RuntimeError("Set EXHIBITDAY_API_KEY") def decode_json(text): if SPEC["preserveNumbers"]: # Quote JSON NUMBER tokens, never text inside a JSON string, to keep CSV decimals exact. text = re.sub(r'"(?:\\.|[^"\\])*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?', lambda m: m[0] if m[0].startswith('"') else json.dumps(m[0]), text) return json.loads(text) 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, key=None): route = SPEC["requests"][name] headers = {"Authorization": "Bearer " + API_KEY, "Accept": "application/json"} if route["method"] == "POST": if not key: raise RuntimeError("Persist a logical create key before sending POST") headers["Idempotency-Key"] = key data = None if body is None else json.dumps(body).encode("utf-8") if data is not None: headers["Content-Type"] = "application/json" query = urllib.parse.urlencode(params or {}) url = BASE + route["path"] + ("?" + query if query else "") # Only GET has automatic retries in this workflow. A PATCH or DELETE that got no response or a # server error is never resent blindly: it may already have been applied, so the caller reads the record first. resend = route["method"] == "GET" for attempt in range(5): try: status, raw, response_headers = transport(route["method"], url, headers, data) except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException): if not resend: raise ApiError(0, None, uncertain=True) if attempt == 4: raise time.sleep(2 ** attempt) continue response_headers = {k.lower(): v for k, v in response_headers.items()} result = None if status != 304 and raw: try: result = decode_json(raw.decode("utf-8")) except (ValueError, UnicodeError): if status < 400: raise RuntimeError("Expected a JSON success response") if status >= 500 and not resend: raise ApiError(status, result, uncertain=True) retry = resend and (status == 429 or status >= 500) if retry: if attempt == 4: raise RuntimeError("Retry limit reached; check the request outcome before starting a new create") delay = response_headers.get("retry-after", str(2 ** attempt)) time.sleep(max(0, float(delay))) continue if status >= 400: raise ApiError(status, result) return {"status": status, "body": result, "headers": response_headers, "raw": raw} raise RuntimeError("Retry limit reached") def both(left,right): return left and right def deep_equal(left,right): if type(left) is not type(right): return False if isinstance(left,dict): return left.keys()==right.keys() and all(deep_equal(left[k],right[k]) for k in left) if isinstance(left,list): return len(left)==len(right) and all(deep_equal(a,b) for a,b in zip(left,right)) return left==right def equal(left, right): return type(left) is type(right) and left == right def field(value, name): if not isinstance(value, dict) or name not in value: raise RuntimeError("Missing response field: " + name) return value[name] def is_present(value): return value is not None and value != "" def items(value): if not isinstance(value, list): raise RuntimeError("Expected a JSON array") return value """Strict private client journal reference; no transport or application dependency.""" from pathlib import Path import hashlib import os import re import secrets from urllib.parse import urlsplit PREAMBLE=b'EXHIBITDAY-GUIDE-JOURNAL 1\n' class JournalRefusal(RuntimeError): pass def utf8(value): if not isinstance(value,str):raise JournalRefusal('Journal fields are exact strings') return value.encode('utf-8',errors='strict') def strings(values): raw=bytearray() for value in values: item=utf8(value);raw.extend(str(len(item)).encode('ascii'));raw.extend(b':');raw.extend(item) return bytes(raw) def read_strings(raw): values=[];offset=0 while offsetlen(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)-offset:raise JournalRefusal('Incomplete journal frame; reconcile before retry') payload=raw[offset:offset+size];offset+=size if raw[offset:offset+1]!=b'\n' or digest(payload).encode('ascii')!=match[2]:raise JournalRefusal('Journal integrity check failed; reconcile before retry') records.append(read_strings(payload));offset+=1 return records class Journal: def __init__(self,path,base,workspace,slug,job,input_fingerprint,writes,mode="resume"): self.path=Path(path);self.lock=Path(str(self.path)+'.lock');self.fd=None;self.owned=False;self.identity=None;self.tainted=False;self.intents={};self.saved_values={} address=urlsplit(base) if address.scheme not in ('https','http')or not address.netloc or address.username is not None or address.query or address.fragment or not re.fullmatch('[a-z][a-z0-9-]*',slug):raise JournalRefusal('Use the actual API base and closed guide slug') if not job.strip() or not re.fullmatch('[1-9][0-9]*',workspace) or not re.fullmatch('[0-9A-F]{64}',input_fingerprint):raise JournalRefusal('Use an actual workspace, explicit stable job ID and exact input fingerprint') if mode not in ("new","resume"):raise JournalRefusal("Choose new or resume for this local job") self.allowed={};manifest=[] for step,method,route in writes: if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.allowed or method not in ('POST','PATCH','DELETE')or not re.fullmatch('/v1/[A-Za-z0-9_/-]+',route)or'//'in route:raise JournalRefusal('Use a closed unique write manifest') self.allowed[step]=(method,route);manifest.extend((step,method,route)) if not self.allowed:raise JournalRefusal('Only write workflows need a restart journal') self.header=['H','1',base,workspace,slug,job,input_fingerprint,digest(strings(manifest))] strings(self.header) try: self.fd=os.open(self.lock,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600);self.owned=True except FileExistsError:raise JournalRefusal('This journal is locked; do not run overlapping jobs or steal a stale lock') try: self.owner=secrets.token_hex(16);self.identity=os.fstat(self.fd) if os.write(self.fd,self.owner.encode('ascii'))!=len(self.owner):raise OSError('Incomplete lock identity write') os.fsync(self.fd) if self.path.is_symlink():raise JournalRefusal('Choose a private regular journal file') if mode=="resume" and not self.path.exists():raise JournalRefusal("Journal missing: stop and reconcile lost state before starting a new logical job") if mode=="new" and self.path.exists():raise JournalRefusal("A journal already exists; use resume for the same logical job") if mode=="new": with open(self.path,'xb',buffering=0)as target: target.write(PREAMBLE+frame(self.header));os.fsync(target.fileno()) records=decode(self.path.read_bytes()) if not records or records[0]!=self.header:raise JournalRefusal('Journal workspace/base/guide/job/input binding differs') for record in records[1:]:self.apply(record) if any(step not in self.saved_values for step in self.intents):raise JournalRefusal('A saved before-send intent lacks an ACK; stop and reconcile its outcome before retry') except BaseException: self.close();raise def apply(self,record): if not record:raise JournalRefusal('Empty journal record') if record[0]=='I': if len(record)!=6:raise JournalRefusal('Invalid intent shape') _,step,method,path,request_fingerprint,key=record if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.intents or self.allowed.get(step)!=(method,path)or not re.fullmatch('[0-9A-F]{64}',request_fingerprint)or any(name not in self.saved_values for name in self.intents):raise JournalRefusal('Invalid, future or repeated journal intent') if method=='POST'and not re.fullmatch('[0-9a-f]{32}',key)or method!='POST'and key!='':raise JournalRefusal('Invalid persisted action key') self.intents[step]={'method':method,'path':path,'request_fingerprint':request_fingerprint,'idempotency_key':key} elif record[0]=='A': if len(record)<3:raise JournalRefusal('Invalid ACK shape') _,step,count,*pairs=record if not re.fullmatch('0|[1-9][0-9]*',count)or len(pairs)!=2*int(count)or step not in self.intents or step in self.saved_values:raise JournalRefusal('ACK without exactly one prior intent') names=pairs[::2] if names!=sorted(set(names))or any(not re.fullmatch('[a-z][a-z0-9_]*',name)or name in ('api_key','exhibitday_api_key')for name in names):raise JournalRefusal('ACK saved fields must be unique sorted secret-free identifiers') self.saved_values[step]=dict(zip(names,pairs[1::2])) else:raise JournalRefusal('Unknown journal transition') def append(self,record): # The reader commits state only after complete length/digest recognition. # A torn append is retained and refused, never silently truncated. self.require_active();raw=frame(record) try: with open(self.path,'ab',buffering=0)as target: view=memoryview(raw) while view: written=target.write(view) if not written:raise OSError('Journal write did not advance') view=view[written:] os.fsync(target.fileno()) except BaseException: self.tainted=True;raise def require_active(self): if not self.owned or self.fd is None or self.identity is None or self.tainted:raise JournalRefusal('The journal scope is closed or its IO outcome needs reconciliation') current=self.lock.stat(follow_symlinks=False) if current.st_dev!=self.identity.st_dev or current.st_ino!=self.identity.st_ino or self.lock.read_text(encoding='ascii')!=self.owner:raise JournalRefusal('The journal lock was replaced; stop without deleting it') def acknowledged(self,step): self.require_active();return step in self.saved_values def saved(self,step): self.require_active() if step not in self.saved_values:raise JournalRefusal('No acknowledged state exists for this step') return dict(self.saved_values[step]) def begin(self,step,method,path,request_fingerprint): self.require_active() if step in self.intents:raise JournalRefusal('Never blindly repeat an existing action intent') key=secrets.token_hex(16)if method=='POST'else'' record=['I',step,method,path,request_fingerprint,key] # Validate on an isolated state before touching the file. old=dict(self.intents) try:self.apply(record) finally:self.intents=old self.append(record);self.apply(record) return dict(self.intents[step]) def acknowledge(self,step,saved): self.require_active() record=['A',step,str(len(saved))] for name,value in sorted(saved.items()):record.extend((name,value)) old={name:dict(value)for name,value in self.saved_values.items()} try:self.apply(record);strings(record) finally:self.saved_values=old self.append(record);self.apply(record) def close(self): if self.owned: if self.tainted: os.close(self.fd);self.fd=None;self.owned=False return # Retain this lock after failed journal IO; manual reconciliation is required. try:self.require_active() except BaseException: os.close(self.fd);self.fd=None;self.owned=False;raise os.close(self.fd);self.fd=None;self.owned=False self.lock.unlink() def __enter__(self):return self def __exit__(self,*args):self.close() def journal_values(value): if not isinstance(value, dict) or any(not isinstance(k, str) or not isinstance(v, str) for k,v in value.items()): raise JournalRefusal('Saved/fingerprint values must be exact string fields') return dict(value) def journal_acknowledge(job, step, saved): job.acknowledge(step,journal_values(saved)) def journal_acknowledged(job, step): return job.acknowledged(step) def journal_begin(job, step, method, path, request_fingerprint): return job.begin(step,method,path,request_fingerprint) def journal_fingerprint(value): return fingerprint(journal_values(value)) def journal_saved(job, step): return job.saved(step) def json_string(value): return json.dumps(value,ensure_ascii=False,allow_nan=False,separators=(",",":")) def open_journal(path, base, workspace, slug, job, input_fingerprint, writes, mode): return Journal(path,base,workspace,slug,job,input_fingerprint,writes,mode) def optional(name, fallback): value = os.environ.get(name) return fallback if value is None or value == "" else value def parse_json(value): return json.loads(value) def positive_id(value): if not re.fullmatch(r"[1-9][0-9]*", value) or int(value) > 9223372036854775807: raise RuntimeError("Use a positive record ID") return value def print_value(value): print(value if isinstance(value, str) else json.dumps(value, ensure_ascii=False)) def require_condition(value, message): if value is not True: raise RuntimeError(message) def required(name): value = os.environ.get(name) if value is None or not value.strip(): raise RuntimeError("Set " + name) return value def response_status(value): return str(value["status"]) def shipment_tracking_number(value): utf8(value) value = value.strip('\u0009\u000A\u000B\u000C\u000D\u0020\u0085\u00A0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u2028\u2029\u202F\u205F\u3000') if any(character in value for character in '<>\r\n'): raise JournalRefusal('Enter a single-line tracking number without angle brackets.') if not value or len(value.encode('utf-16-le')) // 2 > 125: raise JournalRefusal('Enter a nonblank tracking number of at most 125 UTF-16 code units.') return value def text(value): if value is None: return "" if isinstance(value, str): return value if isinstance(value, bool): return "true" if value else "false" if isinstance(value, int): return str(value) raise RuntimeError("Expected a scalar response value") def main(): expected_shipment_event_id = positive_id(required("EXHIBITDAY_EVENT_ID")) selected_shipment_id = positive_id(required("EXHIBITDAY_SHIPMENT_ID")) desired_tracking_number = shipment_tracking_number(required("EXHIBITDAY_TRACKING_NUMBER")) shipment_journal_path = required("EXHIBITDAY_JOURNAL") shipment_job_id = required("EXHIBITDAY_JOB_ID") shipment_job_mode = optional("EXHIBITDAY_JOB_MODE", "resume") shipment_workspace_response = call("workspace_binding", {}, None, None) require_condition(equal(response_status(shipment_workspace_response), "200"), "Expected the endpoint's documented HTTP200 response; preserve pending state and reconcile any other outcome.") shipment_workspace = shipment_workspace_response["body"] shipment_workspace_id = positive_id(text(field(shipment_workspace, "id"))) initial_shipment_response = call("read_shipment", {"id": selected_shipment_id, "$include_record_revision": "true"}, None, None) require_condition(equal(response_status(initial_shipment_response), "200"), "Expected the endpoint's documented HTTP200 response; preserve pending state and reconcile any other outcome.") initial_shipment = initial_shipment_response["body"] require_condition(both(equal(text(field(initial_shipment, "id")), selected_shipment_id), equal(text(field(initial_shipment, "event_id")), expected_shipment_event_id)), "The selected Shipment does not belong to the expected Event; no write was sent.") shipment_revision = text(field(initial_shipment, "record_revision")) require_condition(is_present(shipment_revision), "Read the actual Shipment with $include_record_revision=true before attempting the change.") original_components = items(field(initial_shipment, "components")) shipment_input_fingerprint = journal_fingerprint({"workflow_contract_sha256": "150EE3B0A50D2C1B961E315183D849281F9A38E47247AB7A5D526BB60983BA90", "event_id": expected_shipment_event_id, "shipment_id": selected_shipment_id, "tracking_number": desired_tracking_number, "shipment_status_id": "2"}) shipment_job = open_journal(shipment_journal_path, "https://api.exhibitday.com/v1", shipment_workspace_id, "shipment-tracking", shipment_job_id, shipment_input_fingerprint, [["update_tracking", "PATCH", "/v1/events/shipments"]], shipment_job_mode) try: component_snapshot = "" if journal_acknowledged(shipment_job, "update_tracking"): saved_shipment = journal_saved(shipment_job, "update_tracking") require_condition(both(equal(text(field(saved_shipment, "id")), selected_shipment_id), both(equal(text(field(saved_shipment, "event_id")), expected_shipment_event_id), both(equal(text(field(saved_shipment, "tracking_number")), desired_tracking_number), equal(text(field(saved_shipment, "shipment_status_id")), "2")))), "The acknowledged Shipment change belongs to another record, Event or desired tracking state.") component_snapshot = text(field(saved_shipment, "components_json")) else: component_snapshot = json_string(original_components) tracking_patch = {"id": selected_shipment_id, "tracking_number": desired_tracking_number, "shipment_status_id": "2", "expected_revision": shipment_revision} shipment_write_fingerprint = journal_fingerprint({"id": selected_shipment_id, "tracking_number": desired_tracking_number, "shipment_status_id": "2", "expected_revision": shipment_revision}) journal_begin(shipment_job, "update_tracking", "PATCH", "/v1/events/shipments", shipment_write_fingerprint) tracking_save_response = call("update_tracking", {}, tracking_patch, None) require_condition(equal(response_status(tracking_save_response), "200"), "Expected the endpoint's documented HTTP200 response; preserve pending state and reconcile any other outcome.") tracking_receipt = tracking_save_response["body"] saved_shipment_revision = text(field(tracking_receipt, "record_revision")) require_condition(is_present(saved_shipment_revision), "A checked save acknowledgement needs its actual returned record_revision.") journal_acknowledge(shipment_job, "update_tracking", {"id": selected_shipment_id, "event_id": expected_shipment_event_id, "tracking_number": desired_tracking_number, "shipment_status_id": "2", "record_revision": saved_shipment_revision, "components_json": component_snapshot}) shipment_readback_response = call("verify_shipment", {"id": selected_shipment_id}, None, None) require_condition(equal(response_status(shipment_readback_response), "200"), "Expected the endpoint's documented HTTP200 response; preserve pending state and reconcile any other outcome.") shipment_readback = shipment_readback_response["body"] require_condition(both(equal(text(field(shipment_readback, "id")), selected_shipment_id), equal(text(field(shipment_readback, "event_id")), expected_shipment_event_id)), "The final Shipment is missing or rebound; earlier saved state remains in the journal.") require_condition(both(equal(text(field(shipment_readback, "tracking_number")), desired_tracking_number), equal(text(field(shipment_readback, "shipment_status_id")), "2")), "The Shipment no longer matches the acknowledged tracking/status; inspect it instead of automatically restoring the change.") recorded_components = items(parse_json(component_snapshot)) require_condition(deep_equal(field(shipment_readback, "components"), recorded_components), "Shipment components differ from the original saved snapshot. Inspect the packages; do not replace or automatically restore them.") print_value({"shipment_id": selected_shipment_id, "event_id": expected_shipment_event_id, "tracking_number": desired_tracking_number, "components_unchanged": "true"}) finally: shipment_job.close() if __name__ == "__main__": main() ``` ```csharp // .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\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"read_shipment\":{\"method\":\"GET\",\"path\":\"/events/shipments/info\"},\"update_tracking\":{\"method\":\"PATCH\",\"path\":\"/events/shipments\"},\"verify_shipment\":{\"method\":\"GET\",\"path\":\"/events/shipments/info\"}}}"); static readonly string ApiKey = HeaderKey(Required("EXHIBITDAY_API_KEY")); static string HeaderKey(string value) { if(value.Any(c=>c<32||c>126))throw new Exception("Use the API key as one ASCII header value without control characters");return value; } static readonly HttpClient Client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false }) { Timeout = TimeSpan.FromSeconds(30) }; internal static Func> Send = request => Client.SendAsync(request); sealed class Result { public int Status; public JsonNode Body; public Dictionary Headers; public string Raw; } // 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(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 Call(string name, JsonObject query = null, JsonNode body = null, string key = null) { var route = Spec["requests"][name]; var method = Text(route["method"]); var headers = new Dictionary(StringComparer.OrdinalIgnoreCase) { ["Authorization"] = "Bearer " + ApiKey, ["Accept"] = "application/json" }; if (method == "POST") { if (string.IsNullOrEmpty(key)) throw new Exception("Persist a logical create key before sending POST"); headers["Idempotency-Key"] = key; } 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); // 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. var resend = method == "GET"; 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 Send(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 = resend && (status == 429 || status >= 500); 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, Raw = raw }; } } throw new Exception("Retry limit reached"); } static bool Both(bool left,bool right)=>left&&right; static bool DeepEqual(JsonNode left,JsonNode right)=>JsonNode.DeepEquals(left,right); static object Scalar(object value) { if(value is JsonValue json){if(json.TryGetValue(out var boolean))return boolean;if(json.TryGetValue(out var text))return text;return json.ToJsonString();}return value; } static bool Equal(object left,object right) => object.Equals(Scalar(left),Scalar(right)); static JsonNode Field(JsonNode value,string name) { if(value is not JsonObject obj || !obj.TryGetPropertyValue(name,out var item))throw new Exception("Missing response field: "+name);return item; } static bool IsPresent(string value) => value!=null && value!=""; static JsonArray Items(JsonNode value) => value as JsonArray ?? throw new Exception("Expected a JSON array"); public sealed class JournalRefusal : Exception { public JournalRefusal(string message) : base(message) {} } public static class JournalProtocol { public static readonly byte[] Preamble = Encoding.ASCII.GetBytes("EXHIBITDAY-GUIDE-JOURNAL 1\n"); static readonly UTF8Encoding Utf8 = new UTF8Encoding(false, true); static bool Match(string value,string pattern) => value != null && System.Text.RegularExpressions.Regex.IsMatch(value,"\\A(?:"+pattern+")\\z",System.Text.RegularExpressions.RegexOptions.CultureInvariant); public static bool Valid(string value,string pattern) => Match(value,pattern); static string Ascii(byte[] raw,int start,int count) { for(var i=start;i127)throw new JournalRefusal("Journal framing must be canonical ASCII");return Encoding.ASCII.GetString(raw,start,count); } public static byte[] Strings(IEnumerable values) { using var data=new MemoryStream(); foreach(var value in values){if(value==null)throw new JournalRefusal("Journal fields are exact strings");var item=Utf8.GetBytes(value);var prefix=Encoding.ASCII.GetBytes(item.Length.ToString(CultureInfo.InvariantCulture)+":");data.Write(prefix);data.Write(item);} return data.ToArray(); } public static List ReadStrings(byte[] raw) { var values=new List();var offset=0; while(offsetraw.Length-offset)throw new JournalRefusal("Incomplete journal string");values.Add(Utf8.GetString(raw,offset,(int)size));offset+=(int)size;} return values; } public static string Digest(byte[] raw)=>Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(raw)); public static string Fingerprint(IReadOnlyDictionary pairs) { var values=new List();foreach(var name in pairs.Keys.OrderBy(n=>n,StringComparer.Ordinal)){ if(!Match(name,"[A-Za-z0-9_.-]+")||new[]{"api_key","exhibitday_api_key"}.Contains(name.ToLowerInvariant()))throw new JournalRefusal("Use explicit secret-free fingerprint names");values.Add(name);values.Add(pairs[name]);} return Digest(Strings(values)); } public static byte[] Frame(IEnumerable values) { var payload=Strings(values);var header=Encoding.ASCII.GetBytes(payload.Length.ToString(CultureInfo.InvariantCulture)+" "+Digest(payload)+"\n"); using var data=new MemoryStream();data.Write(header);data.Write(payload);data.WriteByte(10);return data.ToArray(); } public static List> Decode(byte[] raw) { if(raw.Length>(); while(offset=raw.Length-offset)throw new JournalRefusal("Incomplete frame; reconcile before retry");var payload=raw.AsSpan(offset,(int)size).ToArray();offset+=(int)size; if(raw[offset]!=10||Digest(payload)!=split[1])throw new JournalRefusal("Journal integrity failed; reconcile before retry");records.Add(ReadStrings(payload));offset++;} return records; } } public sealed class Journal : IDisposable { readonly string path,lockPath,owner;readonly List header; readonly Dictionary allowed=new Dictionary(StringComparer.Ordinal); Dictionary> intents=new Dictionary>(StringComparer.Ordinal),savedValues=new Dictionary>(StringComparer.Ordinal); FileStream lockStream;bool owned,tainted;DateTime creation; static FileStream CreatePrivate(string target,FileAccess access,FileShare share) { var options=new FileStreamOptions{Mode=FileMode.CreateNew,Access=access,Share=share}; if(!OperatingSystem.IsWindows())options.UnixCreateMode=UnixFileMode.UserRead|UnixFileMode.UserWrite; return new FileStream(target,options); } public Journal(string path,string apiBase,string workspace,string slug,string job,string inputFingerprint,IEnumerable<(string Step,string Method,string Path)> writes,string mode="resume") { this.path=path;lockPath=path+".lock";owner=Convert.ToHexString(System.Security.Cryptography.RandomNumberGenerator.GetBytes(16)).ToLowerInvariant(); if(!Uri.TryCreate(apiBase,UriKind.Absolute,out var address)||address.Scheme!="https"&&address.Scheme!="http"||address.UserInfo.Length!=0||address.Query.Length!=0||address.Fragment.Length!=0||!JournalProtocol.Valid(slug,"[a-z][a-z0-9-]*"))throw new JournalRefusal("Use the actual API base and closed guide slug"); if(string.IsNullOrWhiteSpace(job)||!JournalProtocol.Valid(workspace,"[1-9][0-9]*")||!JournalProtocol.Valid(inputFingerprint,"[0-9A-F]{64}"))throw new JournalRefusal("Use actual workspace, stable explicit job ID and exact fingerprint"); if(mode!="new"&&mode!="resume")throw new JournalRefusal("Choose new or resume for this local job"); var manifest=new List();foreach(var write in writes){ if(!JournalProtocol.Valid(write.Step,"[a-z][a-z0-9_-]*")||allowed.ContainsKey(write.Step)||!new[]{"POST","PATCH","DELETE"}.Contains(write.Method)||!JournalProtocol.Valid(write.Path,"/v1/[A-Za-z0-9_/-]+")||write.Path.Contains("//"))throw new JournalRefusal("Use a closed unique write manifest"); allowed.Add(write.Step,(write.Method,write.Path));manifest.AddRange(new[]{write.Step,write.Method,write.Path});} if(allowed.Count==0)throw new JournalRefusal("Only write workflows need a restart journal"); header=new List{"H","1",apiBase,workspace,slug,job,inputFingerprint,JournalProtocol.Digest(JournalProtocol.Strings(manifest))};JournalProtocol.Strings(header); try{lockStream=CreatePrivate(lockPath,FileAccess.ReadWrite,FileShare.Read);owned=true;} catch(IOException)when(File.Exists(lockPath)){throw new JournalRefusal("This journal is locked; do not overlap jobs or steal a stale lock");} try{ var token=Encoding.ASCII.GetBytes(owner);lockStream.Write(token);lockStream.Flush(true);creation=File.GetCreationTimeUtc(lockPath); if(File.Exists(path)&&(File.GetAttributes(path)&FileAttributes.ReparsePoint)!=0)throw new JournalRefusal("Choose a private regular journal file"); if(mode=="resume"&&!File.Exists(path))throw new JournalRefusal("Journal missing: stop and reconcile lost state before starting a new logical job"); if(mode=="new"&&File.Exists(path))throw new JournalRefusal("Journal exists; use resume for the same logical job"); if(mode=="new"){using var output=CreatePrivate(path,FileAccess.Write,FileShare.None);output.Write(JournalProtocol.Preamble);output.Write(JournalProtocol.Frame(header));output.Flush(true);} var records=JournalProtocol.Decode(File.ReadAllBytes(path));if(records.Count==0||!records[0].SequenceEqual(header))throw new JournalRefusal("Journal workspace/base/guide/job/input binding differs"); foreach(var record in records.Skip(1))Apply(record);if(intents.Keys.Any(step=>!savedValues.ContainsKey(step)))throw new JournalRefusal("Saved intent lacks ACK; stop and reconcile before retry"); }catch{Dispose();throw;} } void Apply(IReadOnlyList record) { if(record.Count==0)throw new JournalRefusal("Empty journal record"); if(record[0]=="I"){ if(record.Count!=6)throw new JournalRefusal("Invalid intent shape");var step=record[1];var method=record[2];var route=record[3];var fingerprint=record[4];var key=record[5]; if(!JournalProtocol.Valid(step,"[a-z][a-z0-9_-]*")||intents.ContainsKey(step)||!allowed.TryGetValue(step,out var expected)||expected!=(method,route)||!JournalProtocol.Valid(fingerprint,"[0-9A-F]{64}")||intents.Keys.Any(name=>!savedValues.ContainsKey(name)))throw new JournalRefusal("Invalid, future or repeated intent"); if(method=="POST"&&!JournalProtocol.Valid(key,"[0-9a-f]{32}")||method!="POST"&&key!="")throw new JournalRefusal("Invalid persisted action key"); intents.Add(step,new Dictionary{{"method",method},{"path",route},{"request_fingerprint",fingerprint},{"idempotency_key",key}}); }else if(record[0]=="A"){ if(record.Count<3||!JournalProtocol.Valid(record[2],"0|[1-9][0-9]*")||!long.TryParse(record[2],NumberStyles.None,CultureInfo.InvariantCulture,out var count)||count!=(record.Count-3L)/2||record.Count%2!=1||!intents.ContainsKey(record[1])||savedValues.ContainsKey(record[1]))throw new JournalRefusal("ACK without exactly one prior intent"); var names=record.Skip(3).Where((_,index)=>index%2==0).ToArray(); if(!names.SequenceEqual(names.Distinct(StringComparer.Ordinal).OrderBy(name=>name,StringComparer.Ordinal))||names.Any(name=>!JournalProtocol.Valid(name,"[a-z][a-z0-9_]*")||name=="api_key"||name=="exhibitday_api_key"))throw new JournalRefusal("ACK fields must be unique sorted secret-free identifiers"); var saved=new Dictionary(StringComparer.Ordinal);for(var i=0;i record) { RequireActive();var raw=JournalProtocol.Frame(record); try{using var output=new FileStream(path,FileMode.Append,FileAccess.Write,FileShare.None);output.Write(raw);output.Flush(true);} catch{tainted=true;throw;} } public bool Acknowledged(string step){RequireActive();return savedValues.ContainsKey(step);} public Dictionary Saved(string step){RequireActive();if(!savedValues.ContainsKey(step))throw new JournalRefusal("No acknowledged state exists");return new Dictionary(savedValues[step],StringComparer.Ordinal);} public Dictionary Begin(string step,string method,string route,string requestFingerprint) { RequireActive();if(intents.ContainsKey(step))throw new JournalRefusal("Never blindly repeat an existing action"); var key=method=="POST"?Convert.ToHexString(System.Security.Cryptography.RandomNumberGenerator.GetBytes(16)).ToLowerInvariant():""; var record=new[]{"I",step,method,route,requestFingerprint,key};var previous=new Dictionary>(intents,StringComparer.Ordinal);try{Apply(record);}finally{intents=previous;} Append(record);Apply(record);return new Dictionary(intents[step],StringComparer.Ordinal); } public void Acknowledge(string step,IReadOnlyDictionary saved) { RequireActive();var record=new List{"A",step,saved.Count.ToString(CultureInfo.InvariantCulture)};foreach(var name in saved.Keys.OrderBy(name=>name,StringComparer.Ordinal))record.AddRange(new[]{name,saved[name]}); var previous=new Dictionary>(savedValues,StringComparer.Ordinal);try{Apply(record);JournalProtocol.Strings(record);}finally{savedValues=previous;} Append(record);Apply(record); } public void Dispose() { if(!owned)return;if(tainted){lockStream.Dispose();lockStream=null;owned=false;return;} try{RequireActive();}catch{lockStream.Dispose();lockStream=null;owned=false;throw;} lockStream.Dispose();lockStream=null;owned=false;File.Delete(lockPath); } } static Dictionary JournalValues(JsonNode value) { if(value is not JsonObject fields)throw new JournalRefusal("Saved/fingerprint values need an explicit object"); var result=new Dictionary(StringComparer.Ordinal); foreach(var field in fields){if(field.Value is not JsonValue item || !item.TryGetValue(out var text) || text==null)throw new JournalRefusal("Saved/fingerprint values must be exact strings");result.Add(field.Key,text);}return result; } static JsonObject JournalObject(IReadOnlyDictionary fields){var result=new JsonObject();foreach(var field in fields)result.Add(field.Key,JsonValue.Create(field.Value));return result;} static void JournalAcknowledge(Journal job,string step,JsonNode saved)=>job.Acknowledge(step,JournalValues(saved)); static bool JournalAcknowledged(Journal job,string step)=>job.Acknowledged(step); static JsonNode JournalBegin(Journal job,string step,string method,string path,string requestFingerprint)=>JournalObject(job.Begin(step,method,path,requestFingerprint)); static string JournalFingerprint(JsonNode value)=>JournalProtocol.Fingerprint(JournalValues(value)); static JsonNode JournalSaved(Journal job,string step)=>JournalObject(job.Saved(step)); static string JsonString(JsonNode value)=>value?.ToJsonString()??"null"; static Journal OpenJournal(string path,string apiBase,string workspace,string slug,string job,string inputFingerprint,JsonNode manifest,string mode) { if(manifest is not JsonArray rows)throw new JournalRefusal("A closed write manifest is required");var writes=new List<(string,string,string)>(); foreach(var row in rows){if(row is not JsonArray fields || fields.Count!=3)throw new JournalRefusal("Each write must bind its step/method/path");var values=fields.Select(value=>value is JsonValue item&&item.TryGetValue(out var text)&&text!=null?text:throw new JournalRefusal("Manifest values are exact strings")).ToArray();writes.Add((values[0],values[1],values[2]));} return new Journal(path,apiBase,workspace,slug,job,inputFingerprint,writes,mode); } static string Optional(string name,string fallback) { var value=Environment.GetEnvironmentVariable(name);return value==null||value==""?fallback:value; } static JsonNode ParseJson(string value)=>JsonNode.Parse(value); static string PositiveId(string value) { if(string.IsNullOrEmpty(value)||value[0]=='0'||!value.All(c=>c>='0'&&c<='9')||!long.TryParse(value,NumberStyles.None,CultureInfo.InvariantCulture,out var id)||id<=0)throw new Exception("Use a positive record ID");return value; } static void PrintValue(object value) => Console.WriteLine(value is string text ? text : JsonSerializer.Serialize(value)); static void RequireCondition(bool value,string message) { if(!value)throw new Exception(message); } static string ResponseStatus(Result value)=>value.Status.ToString(CultureInfo.InvariantCulture); static string ShipmentTrackingNumber(string value) { JournalProtocol.Strings(new[] { value }); value = value.Trim(); if (value.IndexOfAny(new[] { '<', '>', '\r', '\n' }) >= 0) throw new JournalRefusal("Enter a single-line tracking number without angle brackets."); if (value.Length == 0 || value.Length > 125) throw new JournalRefusal("Enter a nonblank tracking number of at most 125 UTF-16 code units."); return value; } static string Text(object value) => value==null?"":value is JsonNode node?Text(node):Convert.ToString(value,CultureInfo.InvariantCulture); internal static async Task Run() { var expected_shipment_event_id = PositiveId(Required("EXHIBITDAY_EVENT_ID")); var selected_shipment_id = PositiveId(Required("EXHIBITDAY_SHIPMENT_ID")); var desired_tracking_number = ShipmentTrackingNumber(Required("EXHIBITDAY_TRACKING_NUMBER")); var shipment_journal_path = Required("EXHIBITDAY_JOURNAL"); var shipment_job_id = Required("EXHIBITDAY_JOB_ID"); var shipment_job_mode = Optional("EXHIBITDAY_JOB_MODE", "resume"); var shipment_workspace_response = await Call("workspace_binding", new JsonObject { }, null, null); RequireCondition(Equal(ResponseStatus(shipment_workspace_response), "200"), "Expected the endpoint's documented HTTP200 response; preserve pending state and reconcile any other outcome."); var shipment_workspace = shipment_workspace_response.Body; var shipment_workspace_id = PositiveId(Text(Field(shipment_workspace, "id"))); var initial_shipment_response = await Call("read_shipment", new JsonObject { ["id"] = selected_shipment_id, ["$include_record_revision"] = "true" }, null, null); RequireCondition(Equal(ResponseStatus(initial_shipment_response), "200"), "Expected the endpoint's documented HTTP200 response; preserve pending state and reconcile any other outcome."); var initial_shipment = initial_shipment_response.Body; RequireCondition(Both(Equal(Text(Field(initial_shipment, "id")), selected_shipment_id), Equal(Text(Field(initial_shipment, "event_id")), expected_shipment_event_id)), "The selected Shipment does not belong to the expected Event; no write was sent."); var shipment_revision = Text(Field(initial_shipment, "record_revision")); RequireCondition(IsPresent(shipment_revision), "Read the actual Shipment with $include_record_revision=true before attempting the change."); var original_components = Items(Field(initial_shipment, "components")); var shipment_input_fingerprint = JournalFingerprint(new JsonObject { ["workflow_contract_sha256"] = "150EE3B0A50D2C1B961E315183D849281F9A38E47247AB7A5D526BB60983BA90", ["event_id"] = expected_shipment_event_id, ["shipment_id"] = selected_shipment_id, ["tracking_number"] = desired_tracking_number, ["shipment_status_id"] = "2" }); using (var shipment_job = OpenJournal(shipment_journal_path, "https://api.exhibitday.com/v1", shipment_workspace_id, "shipment-tracking", shipment_job_id, shipment_input_fingerprint, new JsonArray(new JsonArray("update_tracking", "PATCH", "/v1/events/shipments")), shipment_job_mode)) { var component_snapshot = ""; if (JournalAcknowledged(shipment_job, "update_tracking")) { var saved_shipment = JournalSaved(shipment_job, "update_tracking"); RequireCondition(Both(Equal(Text(Field(saved_shipment, "id")), selected_shipment_id), Both(Equal(Text(Field(saved_shipment, "event_id")), expected_shipment_event_id), Both(Equal(Text(Field(saved_shipment, "tracking_number")), desired_tracking_number), Equal(Text(Field(saved_shipment, "shipment_status_id")), "2")))), "The acknowledged Shipment change belongs to another record, Event or desired tracking state."); component_snapshot = Text(Field(saved_shipment, "components_json")); } else { component_snapshot = JsonString(original_components); var tracking_patch = new JsonObject { ["id"] = selected_shipment_id, ["tracking_number"] = desired_tracking_number, ["shipment_status_id"] = "2", ["expected_revision"] = shipment_revision }; var shipment_write_fingerprint = JournalFingerprint(new JsonObject { ["id"] = selected_shipment_id, ["tracking_number"] = desired_tracking_number, ["shipment_status_id"] = "2", ["expected_revision"] = shipment_revision }); JournalBegin(shipment_job, "update_tracking", "PATCH", "/v1/events/shipments", shipment_write_fingerprint); var tracking_save_response = await Call("update_tracking", new JsonObject { }, tracking_patch, null); RequireCondition(Equal(ResponseStatus(tracking_save_response), "200"), "Expected the endpoint's documented HTTP200 response; preserve pending state and reconcile any other outcome."); var tracking_receipt = tracking_save_response.Body; var saved_shipment_revision = Text(Field(tracking_receipt, "record_revision")); RequireCondition(IsPresent(saved_shipment_revision), "A checked save acknowledgement needs its actual returned record_revision."); JournalAcknowledge(shipment_job, "update_tracking", new JsonObject { ["id"] = selected_shipment_id, ["event_id"] = expected_shipment_event_id, ["tracking_number"] = desired_tracking_number, ["shipment_status_id"] = "2", ["record_revision"] = saved_shipment_revision, ["components_json"] = component_snapshot }); } var shipment_readback_response = await Call("verify_shipment", new JsonObject { ["id"] = selected_shipment_id }, null, null); RequireCondition(Equal(ResponseStatus(shipment_readback_response), "200"), "Expected the endpoint's documented HTTP200 response; preserve pending state and reconcile any other outcome."); var shipment_readback = shipment_readback_response.Body; RequireCondition(Both(Equal(Text(Field(shipment_readback, "id")), selected_shipment_id), Equal(Text(Field(shipment_readback, "event_id")), expected_shipment_event_id)), "The final Shipment is missing or rebound; earlier saved state remains in the journal."); RequireCondition(Both(Equal(Text(Field(shipment_readback, "tracking_number")), desired_tracking_number), Equal(Text(Field(shipment_readback, "shipment_status_id")), "2")), "The Shipment no longer matches the acknowledged tracking/status; inspect it instead of automatically restoring the change."); var recorded_components = Items(ParseJson(component_snapshot)); RequireCondition(DeepEqual(Field(shipment_readback, "components"), recorded_components), "Shipment components differ from the original saved snapshot. Inspect the packages; do not replace or automatically restore them."); PrintValue(new JsonObject { ["shipment_id"] = selected_shipment_id, ["event_id"] = expected_shipment_event_id, ["tracking_number"] = desired_tracking_number, ["components_unchanged"] = "true" }); } } static Task Main() => Run(); } ``` ```java // 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 SPEC = JSON.fromJson("{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"read_shipment\":{\"method\":\"GET\",\"path\":\"/events/shipments/info\"},\"update_tracking\":{\"method\":\"PATCH\",\"path\":\"/events/shipments\"},\"verify_shipment\":{\"method\":\"GET\",\"path\":\"/events/shipments/info\"}}}", Map.class); static final String API_KEY = headerKey(required("EXHIBITDAY_API_KEY")); static String headerKey(String value){if(value.chars().anyMatch(c->c<32||c>126))throw new IllegalArgumentException("Use the API key as one ASCII header value without control characters");return value;} static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).followRedirects(HttpClient.Redirect.NEVER).build(); interface RequestSender { HttpResponse send(HttpRequest request)throws IOException,InterruptedException; } static RequestSender SEND=request->CLIENT.send(request,HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); static class Result { int status; Object body; Map headers; String raw; Result(int s, Object b, Map h,String r) {status=s;body=b;headers=h;raw=r;} } // 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 obj(Object value) {return value==null?new LinkedHashMap<>(): (Map)value;} @SuppressWarnings("unchecked") static List list(Object value) {return value==null?Collections.emptyList():(List)value;} static Map map(Object... pairs) {Map result=new LinkedHashMap<>();for(int i=0;i query,Object body,String key) { Map route=obj(obj(SPEC.get("requests")).get(name));String method=text(route.get("method")); Map headers=map("Authorization","Bearer " + API_KEY,"Accept","application/json"); if(method.equals("POST")){if(key==null||key.isEmpty())throw new IllegalArgumentException("Persist a logical create key before sending POST");headers.put("Idempotency-Key",key);} 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); // 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. boolean resend=method.equals("GET"); 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 response; try {response=SEND.send(request.build());} 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();Object parsed=null; if(status!=304&&!response.body().isEmpty()) { try {parsed=JSON.fromJson(response.body(),Object.class);} catch(RuntimeException error){if(status<400)throw new IllegalStateException("Expected a JSON success response",error);} } Map 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=resend&&(status==429||status>=500); 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,response.body()); } throw new IllegalStateException("Retry limit reached"); } static boolean both(boolean left,boolean right){return left&&right;} static boolean deep_equal(Object left,Object right){ if(left==null||right==null)return left==right; if(left instanceof Number&&right instanceof Number)return new java.math.BigDecimal(left.toString()).compareTo(new java.math.BigDecimal(right.toString()))==0; if(left instanceof Map&&right instanceof Map){Map a=(Map)left,b=(Map)right;if(!a.keySet().equals(b.keySet()))return false;for(Object key:a.keySet())if(!deep_equal(a.get(key),b.get(key)))return false;return true;} if(left instanceof List&&right instanceof List){List a=(List)left,b=(List)right;if(a.size()!=b.size())return false;for(int i=0;i items(Object value){if(!(value instanceof List))throw new IllegalStateException("Expected a JSON array");return list(value);} // Private client restart state only. No transport, application or JSON interpreter. static final class Journal implements AutoCloseable { public static final class Refusal extends IllegalStateException { Refusal(String message){super(message);} } public static final byte[] PREAMBLE="EXHIBITDAY-GUIDE-JOURNAL 1\n".getBytes(StandardCharsets.US_ASCII); static boolean valid(String value,String pattern){return value!=null&&value.matches(pattern);} static byte[] utf8(String value)throws java.nio.charset.CharacterCodingException { if(value==null)throw new Refusal("Journal fields are exact strings"); java.nio.ByteBuffer encoded=StandardCharsets.UTF_8.newEncoder().onMalformedInput(java.nio.charset.CodingErrorAction.REPORT).onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT).encode(java.nio.CharBuffer.wrap(value));byte[] raw=new byte[encoded.remaining()];encoded.get(raw);return raw; } static String ascii(byte[] raw,int start,int count){for(int i=start;i127)throw new Refusal("Journal framing must be canonical ASCII");return new String(raw,start,count,StandardCharsets.US_ASCII);} public static byte[] strings(Collection values)throws IOException { ByteArrayOutputStream output=new ByteArrayOutputStream();for(String value:values){byte[] raw=utf8(value);output.write((raw.length+":").getBytes(StandardCharsets.US_ASCII));output.write(raw);}return output.toByteArray(); } static int find(byte[] raw,int offset,int value){for(int i=offset;i readStrings(byte[] raw)throws IOException { List values=new ArrayList<>();int offset=0; while(offset0)throw new Refusal("Incomplete journal string");int count=size.intValueExact(); values.add(StandardCharsets.UTF_8.newDecoder().onMalformedInput(java.nio.charset.CodingErrorAction.REPORT).onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT).decode(java.nio.ByteBuffer.wrap(raw,offset,count)).toString());offset+=count;} return values; } public static String digest(byte[] raw){try{byte[] hash=java.security.MessageDigest.getInstance("SHA-256").digest(raw);StringBuilder text=new StringBuilder();for(byte item:hash)text.append(String.format(Locale.ROOT,"%02X",item&255));return text.toString();}catch(java.security.NoSuchAlgorithmException error){throw new IllegalStateException(error);}} public static String fingerprint(Map pairs)throws IOException { List values=new ArrayList<>();for(String name:new TreeSet<>(pairs.keySet())){if(!valid(name,"[A-Za-z0-9_.-]+")||Arrays.asList("api_key","exhibitday_api_key").contains(name.toLowerCase(Locale.ROOT)))throw new Refusal("Use explicit secret-free fingerprint names");values.add(name);values.add(pairs.get(name));}return digest(strings(values)); } public static byte[] frame(Collection values)throws IOException {byte[] payload=strings(values);ByteArrayOutputStream output=new ByteArrayOutputStream();output.write((payload.length+" "+digest(payload)+"\n").getBytes(StandardCharsets.US_ASCII));output.write(payload);output.write(10);return output.toByteArray();} public static List> decode(byte[] raw)throws IOException { if(raw.length> records=new ArrayList<>(); while(offset=0)throw new Refusal("Incomplete frame; reconcile before retry");int count=size.intValueExact();byte[] payload=Arrays.copyOfRange(raw,offset,offset+count);offset+=count; if(raw[offset]!=10||!digest(payload).equals(fields[1]))throw new Refusal("Journal integrity failed; reconcile before retry");records.add(readStrings(payload));offset++;}return records; } static void writeAll(java.nio.channels.FileChannel target,byte[] raw)throws IOException {java.nio.ByteBuffer data=java.nio.ByteBuffer.wrap(raw);while(data.hasRemaining())if(target.write(data)<=0)throw new IOException("Journal write did not advance");} static java.nio.channels.FileChannel createPrivate(Path path,OpenOption... options)throws IOException { java.nio.file.attribute.FileAttribute[] attributes=FileSystems.getDefault().supportedFileAttributeViews().contains("posix")?new java.nio.file.attribute.FileAttribute[]{java.nio.file.attribute.PosixFilePermissions.asFileAttribute(java.nio.file.attribute.PosixFilePermissions.fromString("rw-------"))}:new java.nio.file.attribute.FileAttribute[0]; return java.nio.channels.FileChannel.open(path,new HashSet<>(Arrays.asList(options)),attributes); } final Path path,lockPath;final String owner;final List header; final Map> allowed=new LinkedHashMap<>();Map> intents=new LinkedHashMap<>(),savedValues=new LinkedHashMap<>(); java.nio.channels.FileChannel lock;boolean owned,tainted;Object fileKey;java.nio.file.attribute.FileTime creation; public Journal(Path path,String apiBase,String workspace,String slug,String job,String inputFingerprint,List> writes)throws IOException {this(path,apiBase,workspace,slug,job,inputFingerprint,writes,"resume");} public Journal(Path path,String apiBase,String workspace,String slug,String job,String inputFingerprint,List> writes,String mode)throws IOException { this.path=path;lockPath=Path.of(path.toString()+".lock");byte[] random=new byte[16];new java.security.SecureRandom().nextBytes(random);StringBuilder token=new StringBuilder();for(byte item:random)token.append(String.format(Locale.ROOT,"%02x",item&255));owner=token.toString(); URI address=URI.create(apiBase);if(!Arrays.asList("https","http").contains(address.getScheme())||address.getHost()==null||address.getUserInfo()!=null||address.getRawQuery()!=null||address.getRawFragment()!=null||!valid(slug,"[a-z][a-z0-9-]*"))throw new Refusal("Use actual API base and closed guide slug"); if(job==null||job.trim().isEmpty()||!valid(workspace,"[1-9][0-9]*")||!valid(inputFingerprint,"[0-9A-F]{64}"))throw new Refusal("Use actual workspace, stable explicit job ID and exact fingerprint"); if(!Arrays.asList("new","resume").contains(mode))throw new Refusal("Choose new or resume for this local job"); List manifest=new ArrayList<>();for(List item:writes){if(item.size()!=3)throw new Refusal("Invalid write manifest shape");String step=item.get(0),method=item.get(1),route=item.get(2); if(!valid(step,"[a-z][a-z0-9_-]*")||allowed.containsKey(step)||!Arrays.asList("POST","PATCH","DELETE").contains(method)||!valid(route,"/v1/[A-Za-z0-9_/-]+")||route.contains("//"))throw new Refusal("Use a closed unique write manifest");allowed.put(step,List.of(method,route));manifest.addAll(item);} if(allowed.isEmpty())throw new Refusal("Only write workflows need a restart journal");header=List.of("H","1",apiBase,workspace,slug,job,inputFingerprint,digest(strings(manifest)));strings(header); try{lock=createPrivate(lockPath,StandardOpenOption.CREATE_NEW,StandardOpenOption.READ,StandardOpenOption.WRITE);owned=true;}catch(FileAlreadyExistsException error){throw new Refusal("This journal is locked; do not overlap jobs or steal a stale lock");} try{writeAll(lock,owner.getBytes(StandardCharsets.US_ASCII));lock.force(true);java.nio.file.attribute.BasicFileAttributes identity=Files.readAttributes(lockPath,java.nio.file.attribute.BasicFileAttributes.class,LinkOption.NOFOLLOW_LINKS);fileKey=identity.fileKey();creation=identity.creationTime(); if(Files.isSymbolicLink(path))throw new Refusal("Choose a private regular journal file"); if(mode.equals("resume")&&!Files.exists(path))throw new Refusal("Journal missing: stop and reconcile lost state before starting a new logical job"); if(mode.equals("new")&&Files.exists(path))throw new Refusal("Journal exists; use resume for the same logical job"); if(mode.equals("new")){try(java.nio.channels.FileChannel target=createPrivate(path,StandardOpenOption.CREATE_NEW,StandardOpenOption.WRITE)){writeAll(target,PREAMBLE);writeAll(target,frame(header));target.force(true);}} List> records=decode(Files.readAllBytes(path));if(records.isEmpty()||!records.get(0).equals(header))throw new Refusal("Journal workspace/base/guide/job/input binding differs");for(List record:records.subList(1,records.size()))apply(record); if(intents.keySet().stream().anyMatch(step->!savedValues.containsKey(step)))throw new Refusal("Saved intent lacks ACK; stop and reconcile before retry"); }catch(IOException|RuntimeException error){close();throw error;} } void apply(List record){ if(record.isEmpty())throw new Refusal("Empty journal record"); if(record.get(0).equals("I")){ if(record.size()!=6)throw new Refusal("Invalid intent shape");String step=record.get(1),method=record.get(2),route=record.get(3),fingerprint=record.get(4),key=record.get(5); if(!valid(step,"[a-z][a-z0-9_-]*")||intents.containsKey(step)||!List.of(method,route).equals(allowed.get(step))||!valid(fingerprint,"[0-9A-F]{64}")||intents.keySet().stream().anyMatch(name->!savedValues.containsKey(name)))throw new Refusal("Invalid, future or repeated intent"); if(method.equals("POST")&&!valid(key,"[0-9a-f]{32}")||!method.equals("POST")&&!key.isEmpty())throw new Refusal("Invalid persisted action key");intents.put(step,new LinkedHashMap<>(Map.of("method",method,"path",route,"request_fingerprint",fingerprint,"idempotency_key",key))); }else if(record.get(0).equals("A")){ if(record.size()<3||!valid(record.get(2),"0|[1-9][0-9]*")||!new java.math.BigInteger(record.get(2)).multiply(java.math.BigInteger.TWO).equals(java.math.BigInteger.valueOf(record.size()-3))||!intents.containsKey(record.get(1))||savedValues.containsKey(record.get(1)))throw new Refusal("ACK without exactly one prior intent"); List names=new ArrayList<>();for(int i=3;i(new TreeSet<>(names)))||names.stream().anyMatch(name->!valid(name,"[a-z][a-z0-9_]*")||name.equals("api_key")||name.equals("exhibitday_api_key")))throw new Refusal("ACK fields must be unique sorted secret-free identifiers"); Map saved=new LinkedHashMap<>();for(int i=0;i record)throws IOException {requireActive();byte[] raw=frame(record);try(java.nio.channels.FileChannel target=java.nio.channels.FileChannel.open(path,StandardOpenOption.WRITE,StandardOpenOption.APPEND)){writeAll(target,raw);target.force(true);}catch(IOException|RuntimeException error){tainted=true;throw error;}} public boolean acknowledged(String step)throws IOException{requireActive();return savedValues.containsKey(step);} public Map saved(String step)throws IOException{requireActive();if(!savedValues.containsKey(step))throw new Refusal("No acknowledged state exists");return new LinkedHashMap<>(savedValues.get(step));} public Map begin(String step,String method,String route,String requestFingerprint)throws IOException { requireActive();if(intents.containsKey(step))throw new Refusal("Never blindly repeat an existing action");String key="";if(method.equals("POST")){byte[] bytes=new byte[16];new java.security.SecureRandom().nextBytes(bytes);StringBuilder text=new StringBuilder();for(byte item:bytes)text.append(String.format(Locale.ROOT,"%02x",item&255));key=text.toString();} List record=List.of("I",step,method,route,requestFingerprint,key);Map> previous=new LinkedHashMap<>(intents);try{apply(record);}finally{intents=previous;}append(record);apply(record);return new LinkedHashMap<>(intents.get(step)); } public void acknowledge(String step,Map saved)throws IOException { requireActive();List record=new ArrayList<>(List.of("A",step,Integer.toString(saved.size())));for(String name:new TreeSet<>(saved.keySet())){record.add(name);record.add(saved.get(name));} Map> previous=new LinkedHashMap<>(savedValues);try{apply(record);strings(record);}finally{savedValues=previous;}append(record);apply(record); } public void close()throws IOException { if(!owned)return;if(tainted){lock.close();lock=null;owned=false;return;} try{requireActive();}catch(IOException|RuntimeException error){lock.close();lock=null;owned=false;throw error;}lock.close();lock=null;owned=false;Files.delete(lockPath); } } static Map journal_values(Object value){if(!(value instanceof Map))throw new Journal.Refusal("Saved/fingerprint values need an explicit object");Map result=new LinkedHashMap<>();for(Map.Entry field:((Map)value).entrySet()){if(!(field.getKey() instanceof String)||!(field.getValue() instanceof String))throw new Journal.Refusal("Saved/fingerprint values must be exact strings");result.put((String)field.getKey(),(String)field.getValue());}return result;} static void journal_acknowledge(Journal job,String step,Object saved)throws IOException{job.acknowledge(step,journal_values(saved));} static boolean journal_acknowledged(Journal job,String step)throws IOException{return job.acknowledged(step);} static Object journal_begin(Journal job,String step,String method,String path,String requestFingerprint)throws IOException{return new LinkedHashMap(job.begin(step,method,path,requestFingerprint));} static String journal_fingerprint(Object value)throws IOException{return Journal.fingerprint(journal_values(value));} static Object journal_saved(Journal job,String step)throws IOException{return new LinkedHashMap(job.saved(step));} static String json_string(Object value){return new GsonBuilder().serializeNulls().create().toJson(value);} static Journal open_journal(String path,String base,String workspace,String slug,String job,String inputFingerprint,Object manifest,String mode)throws IOException { if(!(manifest instanceof List))throw new Journal.Refusal("A closed write manifest is required");List> writes=new ArrayList<>();for(Object row:(List)manifest){if(!(row instanceof List)||((List)row).size()!=3)throw new Journal.Refusal("Each write must bind step/method/path");List fields=new ArrayList<>();for(Object value:(List)row){if(!(value instanceof String))throw new Journal.Refusal("Manifest values are exact strings");fields.add((String)value);}writes.add(fields);}return new Journal(Path.of(path),base,workspace,slug,job,inputFingerprint,writes,mode); } static String optional(String name,String fallback){String value=System.getenv(name);return value==null||value.isEmpty()?fallback:value;} static Object parse_json(String value){return JSON.fromJson(value,Object.class);} static String positive_id(String value){try{if(value==null||!value.matches("[1-9][0-9]*")||Long.parseLong(value)<=0)throw new IllegalArgumentException();return value;}catch(RuntimeException error){throw new IllegalArgumentException("Use a positive record ID");}} static void print_value(Object value){try{String text=value instanceof String?(String)value:JSON.toJson(value);System.out.write((text+"\n").getBytes(StandardCharsets.UTF_8));}catch(IOException error){throw new UncheckedIOException(error);}} static void require_condition(boolean value,String message){if(!value)throw new IllegalStateException(message);} static String response_status(Result value){return Integer.toString(value.status);} static boolean shipment_tracking_space(char c) { return c >= 9 && c <= 13 || c == 32 || c == 0x85 || c == 0xA0 || c == 0x1680 || c >= 0x2000 && c <= 0x200A || c == 0x2028 || c == 0x2029 || c == 0x202F || c == 0x205F || c == 0x3000; } static String shipment_tracking_number(String value) throws IOException { Journal.strings(List.of(value)); int start = 0, end = value.length(); while (start < end && shipment_tracking_space(value.charAt(start))) start++; while (end > start && shipment_tracking_space(value.charAt(end - 1))) end--; value = value.substring(start, end); if (value.indexOf('<') >= 0 || value.indexOf('>') >= 0 || value.indexOf('\r') >= 0 || value.indexOf('\n') >= 0) throw new Journal.Refusal("Enter a single-line tracking number without angle brackets."); if (value.isEmpty() || value.length() > 125) throw new Journal.Refusal("Enter a nonblank tracking number of at most 125 UTF-16 code units."); return value; } static void run()throws Exception { String expected_shipment_event_id = positive_id(required("EXHIBITDAY_EVENT_ID")); String selected_shipment_id = positive_id(required("EXHIBITDAY_SHIPMENT_ID")); String desired_tracking_number = shipment_tracking_number(required("EXHIBITDAY_TRACKING_NUMBER")); String shipment_journal_path = required("EXHIBITDAY_JOURNAL"); String shipment_job_id = required("EXHIBITDAY_JOB_ID"); String shipment_job_mode = optional("EXHIBITDAY_JOB_MODE", "resume"); Result shipment_workspace_response = call("workspace_binding", map(), null, null); require_condition(equal(response_status(shipment_workspace_response), "200"), "Expected the endpoint's documented HTTP200 response; preserve pending state and reconcile any other outcome."); Object shipment_workspace = shipment_workspace_response.body; String shipment_workspace_id = positive_id(text(field(shipment_workspace, "id"))); Result initial_shipment_response = call("read_shipment", map("id", selected_shipment_id, "$include_record_revision", "true"), null, null); require_condition(equal(response_status(initial_shipment_response), "200"), "Expected the endpoint's documented HTTP200 response; preserve pending state and reconcile any other outcome."); Object initial_shipment = initial_shipment_response.body; require_condition(both(equal(text(field(initial_shipment, "id")), selected_shipment_id), equal(text(field(initial_shipment, "event_id")), expected_shipment_event_id)), "The selected Shipment does not belong to the expected Event; no write was sent."); String shipment_revision = text(field(initial_shipment, "record_revision")); require_condition(is_present(shipment_revision), "Read the actual Shipment with $include_record_revision=true before attempting the change."); List original_components = items(field(initial_shipment, "components")); String shipment_input_fingerprint = journal_fingerprint(map("workflow_contract_sha256", "150EE3B0A50D2C1B961E315183D849281F9A38E47247AB7A5D526BB60983BA90", "event_id", expected_shipment_event_id, "shipment_id", selected_shipment_id, "tracking_number", desired_tracking_number, "shipment_status_id", "2")); try (Journal shipment_job = open_journal(shipment_journal_path, "https://api.exhibitday.com/v1", shipment_workspace_id, "shipment-tracking", shipment_job_id, shipment_input_fingerprint, Arrays.asList(Arrays.asList("update_tracking", "PATCH", "/v1/events/shipments")), shipment_job_mode)) { String component_snapshot = ""; if (journal_acknowledged(shipment_job, "update_tracking")) { Object saved_shipment = journal_saved(shipment_job, "update_tracking"); require_condition(both(equal(text(field(saved_shipment, "id")), selected_shipment_id), both(equal(text(field(saved_shipment, "event_id")), expected_shipment_event_id), both(equal(text(field(saved_shipment, "tracking_number")), desired_tracking_number), equal(text(field(saved_shipment, "shipment_status_id")), "2")))), "The acknowledged Shipment change belongs to another record, Event or desired tracking state."); component_snapshot = text(field(saved_shipment, "components_json")); } else { component_snapshot = json_string(original_components); Object tracking_patch = map("id", selected_shipment_id, "tracking_number", desired_tracking_number, "shipment_status_id", "2", "expected_revision", shipment_revision); String shipment_write_fingerprint = journal_fingerprint(map("id", selected_shipment_id, "tracking_number", desired_tracking_number, "shipment_status_id", "2", "expected_revision", shipment_revision)); journal_begin(shipment_job, "update_tracking", "PATCH", "/v1/events/shipments", shipment_write_fingerprint); Result tracking_save_response = call("update_tracking", map(), tracking_patch, null); require_condition(equal(response_status(tracking_save_response), "200"), "Expected the endpoint's documented HTTP200 response; preserve pending state and reconcile any other outcome."); Object tracking_receipt = tracking_save_response.body; String saved_shipment_revision = text(field(tracking_receipt, "record_revision")); require_condition(is_present(saved_shipment_revision), "A checked save acknowledgement needs its actual returned record_revision."); journal_acknowledge(shipment_job, "update_tracking", map("id", selected_shipment_id, "event_id", expected_shipment_event_id, "tracking_number", desired_tracking_number, "shipment_status_id", "2", "record_revision", saved_shipment_revision, "components_json", component_snapshot)); } Result shipment_readback_response = call("verify_shipment", map("id", selected_shipment_id), null, null); require_condition(equal(response_status(shipment_readback_response), "200"), "Expected the endpoint's documented HTTP200 response; preserve pending state and reconcile any other outcome."); Object shipment_readback = shipment_readback_response.body; require_condition(both(equal(text(field(shipment_readback, "id")), selected_shipment_id), equal(text(field(shipment_readback, "event_id")), expected_shipment_event_id)), "The final Shipment is missing or rebound; earlier saved state remains in the journal."); require_condition(both(equal(text(field(shipment_readback, "tracking_number")), desired_tracking_number), equal(text(field(shipment_readback, "shipment_status_id")), "2")), "The Shipment no longer matches the acknowledged tracking/status; inspect it instead of automatically restoring the change."); List recorded_components = items(parse_json(component_snapshot)); require_condition(deep_equal(field(shipment_readback, "components"), recorded_components), "Shipment components differ from the original saved snapshot. Inspect the packages; do not replace or automatically restore them."); print_value(map("shipment_id", selected_shipment_id, "event_id", expected_shipment_event_id, "tracking_number", desired_tracking_number, "components_unchanged", "true")); } } public static void main(String[] args)throws Exception {run();} } ``` ```php $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, ?string $key = null): array { global $spec, $apiKey, $transport; $route = $spec['requests'][$name]; $headers = ['Authorization' => 'Bearer ' . $apiKey, 'Accept' => 'application/json']; if ($route['method'] === 'POST') { if ($key === null || $key === '') throw new RuntimeException('Persist a logical create key before sending POST'); $headers['Idempotency-Key'] = $key; // 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); // 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 = 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 = $resend && ($status === 429 || $status >= 500); 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, 'raw' => $raw]; } throw new RuntimeException('Retry limit reached'); } $transport = Closure::fromCallable('nativeTransport'); function both(bool $left,bool $right):bool{return $left&&$right;} function deep_equal(mixed $left,mixed $right):bool { if(is_object($left))$left=get_object_vars($left);if(is_object($right))$right=get_object_vars($right); if(gettype($left)!==gettype($right))return false; if(!is_array($left))return$left===$right; if(array_is_list($left)!==array_is_list($right)||count($left)!==count($right))return false; foreach($left as$key=>$value)if(!array_key_exists($key,$right)||!deep_equal($value,$right[$key]))return false; return true; } function equal(mixed $left,mixed $right):bool{return $left===$right;} function field(mixed $value,string $name):mixed{if(!is_array($value)||!array_key_exists($name,$value))throw new RuntimeException("Missing response field: ".$name);return $value[$name];} function is_present(?string $value):bool{return $value!==null&&$value!=="";} function items(mixed $value):array{if(!is_array($value)||!array_is_list($value))throw new RuntimeException("Expected a JSON array");return $value;} final class JournalRefusal extends RuntimeException {} final class JournalProtocol { public const PREAMBLE="EXHIBITDAY-GUIDE-JOURNAL 1\n"; public static function utf8(mixed $value):string {if(!is_string($value)||preg_match('//u',$value)!==1)throw new JournalRefusal('Journal fields must be exact valid UTF8 strings');return$value;} public static function strings(array $values):string {$raw='';foreach($values as$value){$item=self::utf8($value);$raw.=strlen($item).':'.$item;}return$raw;} private static function length(string $text,int $remaining):int {if(!preg_match('/\A(?:0|[1-9][0-9]*)\z/',$text))throw new JournalRefusal('Noncanonical string length');$maximum=(string)$remaining;if(strlen($text)>strlen($maximum)||(strlen($text)===strlen($maximum)&&strcmp($text,$maximum)>0))throw new JournalRefusal('Incomplete journal string/frame');return(int)$text;} public static function readStrings(string $raw):array {$values=[];$offset=0;while($offset=strlen($raw)-$offset)throw new JournalRefusal('Incomplete frame; reconcile before retry');$payload=substr($raw,$offset,$size);$offset+=$size;if($raw[$offset]!=="\n"||self::digest($payload)!==$match[2])throw new JournalRefusal('Journal integrity failed; reconcile before retry');$records[]=self::readStrings($payload);$offset++;}return$records;} public static function writeAll($file,string $raw):void {$offset=0;while($offsetpath=$path;$this->lockPath=$path.'.lock';$this->owner=bin2hex(random_bytes(16));$address=parse_url($base); if($address===false||!in_array($address['scheme']??null,['https','http'],true)||!isset($address['host'])||isset($address['user'])||isset($address['pass'])||isset($address['query'])||isset($address['fragment'])||!preg_match('/\A[a-z][a-z0-9-]*\z/',$slug))throw new JournalRefusal('Use actual API base and closed guide slug'); if(trim($job)===''||!preg_match('/\A[1-9][0-9]*\z/',$workspace)||!preg_match('/\A[0-9A-F]{64}\z/',$inputFingerprint))throw new JournalRefusal('Use actual workspace, stable explicit job ID and exact fingerprint'); if(!in_array($mode,['new','resume'],true))throw new JournalRefusal('Choose new or resume for this local job'); $manifest=[];foreach($writes as$write){if(!is_array($write)||!array_is_list($write)||count($write)!==3)throw new JournalRefusal('Invalid write manifest');[$step,$method,$route]=$write; if(!is_string($step)||!preg_match('/\A[a-z][a-z0-9_-]*\z/',$step)||isset($this->allowed[$step])||!in_array($method,['POST','PATCH','DELETE'],true)||!is_string($route)||!preg_match('~\A/v1/[A-Za-z0-9_/-]+\z~',$route)||str_contains($route,'//'))throw new JournalRefusal('Use a closed unique write manifest');$this->allowed[$step]=[$method,$route];array_push($manifest,$step,$method,$route);} if($this->allowed===[])throw new JournalRefusal('Only write workflows need restart journal');$this->header=['H','1',$base,$workspace,$slug,$job,$inputFingerprint,JournalProtocol::digest(JournalProtocol::strings($manifest))];JournalProtocol::strings($this->header); $this->file=JournalProtocol::createPrivate($this->lockPath);$this->owned=true; try{ JournalProtocol::writeAll($this->file,$this->owner);$identity=fstat($this->file);if($identity===false)throw new JournalRefusal('Cannot bind acquired lock identity');$this->identity=$identity; clearstatcache(true,$path);if(is_link($path))throw new JournalRefusal('Choose private regular journal file'); $exists=file_exists($path);if($mode==='resume'&&!$exists)throw new JournalRefusal('Journal missing: stop and reconcile lost state before starting a new logical job');if($mode==='new'&&$exists)throw new JournalRefusal('Journal exists; use resume for the same logical job'); if($mode==='new'){$target=JournalProtocol::createPrivate($path);try{JournalProtocol::writeAll($target,JournalProtocol::PREAMBLE.JournalProtocol::frame($this->header));}finally{fclose($target);}} $raw=file_get_contents($path);if($raw===false)throw new JournalRefusal('Cannot read journal');$records=JournalProtocol::decode($raw);if($records===[]||$records[0]!==$this->header)throw new JournalRefusal('Journal workspace/base/guide/job/input binding differs');foreach(array_slice($records,1)as$record)$this->apply($record); if(array_diff(array_keys($this->intents),array_keys($this->savedValues))!==[])throw new JournalRefusal('Saved intent lacks ACK; stop and reconcile before retry'); }catch(Throwable $error){$this->close();throw$error;} } private function apply(array $record):void { if(($record[0]??null)==='I'){ if(count($record)!==6)throw new JournalRefusal('Invalid intent shape');[,$step,$method,$route,$fingerprint,$key]=$record; if(!preg_match('/\A[a-z][a-z0-9_-]*\z/',$step)||isset($this->intents[$step])||($this->allowed[$step]??null)!==[$method,$route]||!preg_match('/\A[0-9A-F]{64}\z/',$fingerprint)||array_diff(array_keys($this->intents),array_keys($this->savedValues))!==[])throw new JournalRefusal('Invalid, future or repeated intent'); if(($method==='POST'&&!preg_match('/\A[0-9a-f]{32}\z/',$key))||($method!=='POST'&&$key!==''))throw new JournalRefusal('Invalid persisted action key');$this->intents[$step]=['method'=>$method,'path'=>$route,'request_fingerprint'=>$fingerprint,'idempotency_key'=>$key]; }elseif(($record[0]??null)==='A'){ if(count($record)<3)throw new JournalRefusal('Invalid ACK shape');[,$step,$count]=$record;$pairs=array_slice($record,3); if(!preg_match('/\A(?:0|[1-9][0-9]*)\z/',$count)||(string)intdiv(count($pairs),2)!==$count||count($pairs)%2!==0||!isset($this->intents[$step])||isset($this->savedValues[$step]))throw new JournalRefusal('ACK without exactly one prior intent'); $names=[];for($i=0;$i$name){if(!preg_match('/\A[a-z][a-z0-9_]*\z/',$name)||in_array($name,['api_key','exhibitday_api_key'],true))throw new JournalRefusal('Use secret-free ACK field names');$saved[$name]=$pairs[$i*2+1];}$this->savedValues[$step]=$saved; }else throw new JournalRefusal('Unknown journal transition'); } private function requireActive():void { if(!$this->owned||$this->file===null||$this->tainted)throw new JournalRefusal('Journal closed or IO outcome needs reconciliation');clearstatcache(true,$this->lockPath);$current=@lstat($this->lockPath);$token=@file_get_contents($this->lockPath); if($current===false||($current['dev']??null)!==($this->identity['dev']??null)||($current['ino']??null)!==($this->identity['ino']??null)||$token!==$this->owner)throw new JournalRefusal('Journal lock replaced; stop without deleting it'); } private function append(array $record):void { $this->requireActive();$raw=JournalProtocol::frame($record);$target=null; try{$target=@fopen($this->path,'ab');if($target===false)throw new JournalRefusal('Cannot append journal; stop and reconcile');JournalProtocol::writeAll($target,$raw);}catch(Throwable $error){$this->tainted=true;throw$error;}finally{if(is_resource($target))fclose($target);} } public function acknowledged(string $step):bool{$this->requireActive();return isset($this->savedValues[$step]);} public function saved(string $step):array{$this->requireActive();if(!isset($this->savedValues[$step]))throw new JournalRefusal('No acknowledged state exists');return$this->savedValues[$step];} public function beginAction(string $step,string $method,string $route,string $requestFingerprint):array { $this->requireActive();if(isset($this->intents[$step]))throw new JournalRefusal('Never blindly repeat an existing action');$key=$method==='POST'?bin2hex(random_bytes(16)):'';$record=['I',$step,$method,$route,$requestFingerprint,$key];$previous=$this->intents;try{$this->apply($record);}finally{$this->intents=$previous;}$this->append($record);$this->apply($record);return$this->intents[$step]; } public function acknowledge(string $step,array $saved):void { $this->requireActive();$record=['A',$step,(string)count($saved)];$names=array_keys($saved);sort($names,SORT_STRING);foreach($names as$name){$record[]=$name;$record[]=$saved[$name];}$previous=$this->savedValues;try{$this->apply($record);JournalProtocol::strings($record);}finally{$this->savedValues=$previous;}$this->append($record);$this->apply($record); } public function close():void { if(!$this->owned)return;if($this->tainted){fclose($this->file);$this->file=null;$this->owned=false;return;} try{$this->requireActive();}catch(Throwable $error){fclose($this->file);$this->file=null;$this->owned=false;throw$error;}fclose($this->file);$this->file=null;$this->owned=false;if(!unlink($this->lockPath))throw new JournalRefusal('Could not release owned journal lock'); } } function journal_values(mixed $value):array{if(!is_object($value))throw new JournalRefusal('Saved/fingerprint values need an explicit object');$result=get_object_vars($value);foreach($result as$name=>$item)if(!is_string($name)||!is_string($item))throw new JournalRefusal('Saved/fingerprint values must be exact strings');return$result;} function journal_acknowledge(GuideJournal $job,string $step,mixed $saved):void{$job->acknowledge($step,journal_values($saved));} function journal_acknowledged(GuideJournal $job,string $step):bool{return $job->acknowledged($step);} function journal_begin(GuideJournal $job,string $step,string $method,string $path,string $requestFingerprint):array{return $job->beginAction($step,$method,$path,$requestFingerprint);} function journal_fingerprint(mixed $value):string{return JournalProtocol::fingerprint(journal_values($value));} function journal_saved(GuideJournal $job,string $step):array{return $job->saved($step);} function json_string(mixed $value):string{return json_encode($value,JSON_THROW_ON_ERROR|JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);} function open_journal(string $path,string $base,string $workspace,string $slug,string $job,string $inputFingerprint,array $writes,string $mode):GuideJournal{return new GuideJournal($path,$base,$workspace,$slug,$job,$inputFingerprint,$writes,$mode);} function parse_json(string $value):mixed{return json_decode($value,true,512,JSON_THROW_ON_ERROR);} function positive_id(string $value):string{if(!preg_match("/^[1-9][0-9]*$/D",$value)||strlen($value)>19||(strlen($value)===19&&strcmp($value,"9223372036854775807")>0))throw new RuntimeException("Use a positive record ID");return $value;} function print_value(mixed $value):void{echo (is_string($value)?$value:json_encode($value,JSON_THROW_ON_ERROR))."\n";} function require_condition(bool $value,string $message):void{if(!$value)throw new RuntimeException($message);} function response_status(array $value):string{return(string)$value["status"];} function shipment_tracking_number(string $value): string { JournalProtocol::utf8($value); $value = preg_replace('~\A[\x{0009}-\x{000D}\x{0020}\x{0085}\x{00A0}\x{1680}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+|[\x{0009}-\x{000D}\x{0020}\x{0085}\x{00A0}\x{1680}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+\z~u', '', $value); if ($value === null || $value === '') throw new JournalRefusal('Enter a nonblank tracking number of at most 125 UTF-16 code units.'); if (strpbrk($value, "<>\r\n") !== false) throw new JournalRefusal('Enter a single-line tracking number without angle brackets.'); $units = preg_match_all('/./us', $value) + preg_match_all('/[\x{10000}-\x{10FFFF}]/u', $value); if ($units > 125) throw new JournalRefusal('Enter a nonblank tracking number of at most 125 UTF-16 code units.'); return $value; } function text(mixed $value):string{if($value===null)return "";if(is_string($value))return $value;if(is_bool($value))return $value?"true":"false";if(is_int($value))return (string)$value;throw new RuntimeException("Expected a scalar response value");} function main():void { $expected_shipment_event_id = positive_id(required('EXHIBITDAY_EVENT_ID')); $selected_shipment_id = positive_id(required('EXHIBITDAY_SHIPMENT_ID')); $desired_tracking_number = shipment_tracking_number(required('EXHIBITDAY_TRACKING_NUMBER')); $shipment_journal_path = required('EXHIBITDAY_JOURNAL'); $shipment_job_id = required('EXHIBITDAY_JOB_ID'); $shipment_job_mode = optional('EXHIBITDAY_JOB_MODE', 'resume'); $shipment_workspace_response = call('workspace_binding', [], null, null); require_condition(equal(response_status($shipment_workspace_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; preserve pending state and reconcile any other outcome.'); $shipment_workspace = $shipment_workspace_response["body"]; $shipment_workspace_id = positive_id(text(field($shipment_workspace, 'id'))); $initial_shipment_response = call('read_shipment', ['id' => $selected_shipment_id, '$include_record_revision' => 'true'], null, null); require_condition(equal(response_status($initial_shipment_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; preserve pending state and reconcile any other outcome.'); $initial_shipment = $initial_shipment_response["body"]; require_condition(both(equal(text(field($initial_shipment, 'id')), $selected_shipment_id), equal(text(field($initial_shipment, 'event_id')), $expected_shipment_event_id)), 'The selected Shipment does not belong to the expected Event; no write was sent.'); $shipment_revision = text(field($initial_shipment, 'record_revision')); require_condition(is_present($shipment_revision), 'Read the actual Shipment with $include_record_revision=true before attempting the change.'); $original_components = items(field($initial_shipment, 'components')); $shipment_input_fingerprint = journal_fingerprint((object)['workflow_contract_sha256' => '150EE3B0A50D2C1B961E315183D849281F9A38E47247AB7A5D526BB60983BA90', 'event_id' => $expected_shipment_event_id, 'shipment_id' => $selected_shipment_id, 'tracking_number' => $desired_tracking_number, 'shipment_status_id' => '2']); $shipment_job = open_journal($shipment_journal_path, 'https://api.exhibitday.com/v1', $shipment_workspace_id, 'shipment-tracking', $shipment_job_id, $shipment_input_fingerprint, [['update_tracking', 'PATCH', '/v1/events/shipments']], $shipment_job_mode); try { $component_snapshot = ''; if (journal_acknowledged($shipment_job, 'update_tracking')) { $saved_shipment = journal_saved($shipment_job, 'update_tracking'); require_condition(both(equal(text(field($saved_shipment, 'id')), $selected_shipment_id), both(equal(text(field($saved_shipment, 'event_id')), $expected_shipment_event_id), both(equal(text(field($saved_shipment, 'tracking_number')), $desired_tracking_number), equal(text(field($saved_shipment, 'shipment_status_id')), '2')))), 'The acknowledged Shipment change belongs to another record, Event or desired tracking state.'); $component_snapshot = text(field($saved_shipment, 'components_json')); } else { $component_snapshot = json_string($original_components); $tracking_patch = (object)['id' => $selected_shipment_id, 'tracking_number' => $desired_tracking_number, 'shipment_status_id' => '2', 'expected_revision' => $shipment_revision]; $shipment_write_fingerprint = journal_fingerprint((object)['id' => $selected_shipment_id, 'tracking_number' => $desired_tracking_number, 'shipment_status_id' => '2', 'expected_revision' => $shipment_revision]); journal_begin($shipment_job, 'update_tracking', 'PATCH', '/v1/events/shipments', $shipment_write_fingerprint); $tracking_save_response = call('update_tracking', [], $tracking_patch, null); require_condition(equal(response_status($tracking_save_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; preserve pending state and reconcile any other outcome.'); $tracking_receipt = $tracking_save_response["body"]; $saved_shipment_revision = text(field($tracking_receipt, 'record_revision')); require_condition(is_present($saved_shipment_revision), 'A checked save acknowledgement needs its actual returned record_revision.'); journal_acknowledge($shipment_job, 'update_tracking', (object)['id' => $selected_shipment_id, 'event_id' => $expected_shipment_event_id, 'tracking_number' => $desired_tracking_number, 'shipment_status_id' => '2', 'record_revision' => $saved_shipment_revision, 'components_json' => $component_snapshot]); } $shipment_readback_response = call('verify_shipment', ['id' => $selected_shipment_id], null, null); require_condition(equal(response_status($shipment_readback_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; preserve pending state and reconcile any other outcome.'); $shipment_readback = $shipment_readback_response["body"]; require_condition(both(equal(text(field($shipment_readback, 'id')), $selected_shipment_id), equal(text(field($shipment_readback, 'event_id')), $expected_shipment_event_id)), 'The final Shipment is missing or rebound; earlier saved state remains in the journal.'); require_condition(both(equal(text(field($shipment_readback, 'tracking_number')), $desired_tracking_number), equal(text(field($shipment_readback, 'shipment_status_id')), '2')), 'The Shipment no longer matches the acknowledged tracking/status; inspect it instead of automatically restoring the change.'); $recorded_components = items(parse_json($component_snapshot)); require_condition(deep_equal(field($shipment_readback, 'components'), $recorded_components), 'Shipment components differ from the original saved snapshot. Inspect the packages; do not replace or automatically restore them.'); print_value((object)['shipment_id' => $selected_shipment_id, 'event_id' => $expected_shipment_event_id, 'tracking_number' => $desired_tracking_number, 'components_unchanged' => 'true']); } finally { $shipment_job->close(); } } if (realpath($_SERVER['SCRIPT_FILENAME'] ?? '') === __FILE__) main(); ``` ```ruby # 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":true,"requests":{"workspace_binding":{"method":"GET","path":"/references/workspace_info"},"read_shipment":{"method":"GET","path":"/events/shipments/info"},"update_tracking":{"method":"PATCH","path":"/events/shipments"},"verify_shipment":{"method":"GET","path":"/events/shipments/info"}}}') API_KEY = ENV.fetch('EXHIBITDAY_API_KEY') raise 'Use the API key as one ASCII header value without control characters' if API_KEY.each_codepoint.any?{|point|point<32||point>126} 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, 'DELETE' => Net::HTTP::Delete }.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, key = nil) route = SPEC.fetch('requests').fetch(name) headers = { 'Authorization' => 'Bearer ' + API_KEY, 'Accept' => 'application/json' } if route.fetch('method') == 'POST' headers['Idempotency-Key'] = key || raise('Persist a logical create key before sending POST') # 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) # 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.fetch('method') == 'GET' 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 = resend && (status == 429 || (500..599).cover?(status)) 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, raw: raw } end raise 'Retry limit reached' end def both(left,right);left&&right;end def deep_equal(left,right) return false unless left.class==right.class if left.is_a?(Hash) return left.keys.sort==right.keys.sort&&left.all?{|key,value|deep_equal(value,right[key])} end return left.length==right.length&&left.zip(right).all?{|a,b|deep_equal(a,b)} if left.is_a?(Array) left==right end def equal(left,right) left.class==right.class && left==right end def field(value,name) raise "Missing response field: #{name}" unless value.is_a?(Hash) && value.key?(name) value.fetch(name) end def is_present(value) !value.nil? && value!="" end def items(value) raise "Expected a JSON array" unless value.is_a?(Array) value end require 'digest' require 'securerandom' require 'uri' # Private client restart state, with no transport or application dependency. module GuideJournalProtocol PREAMBLE="EXHIBITDAY-GUIDE-JOURNAL 1\n".b.freeze class Refusal < StandardError; end def self.utf8(value) raise Refusal,'Journal fields are exact strings' unless value.is_a?(String)&&value.valid_encoding? raw=value.encode(Encoding::UTF_8) raise Refusal,'Invalid UTF8 journal field' unless raw.valid_encoding? raw.b end def self.strings(values) values.map{|value|raw=utf8(value);raw.bytesize.to_s.b+':'.b+raw}.join.b end def self.read_strings(raw) values=[];offset=0 while offsetraw.bytesize-offset value=raw.byteslice(offset,size).dup.force_encoding(Encoding::UTF_8);raise Refusal,'Invalid UTF8 string' unless value.valid_encoding? values<=raw.bytesize-offset payload=raw.byteslice(offset,size);offset+=size raise Refusal,'Journal integrity failed; reconcile before retry' unless raw.getbyte(offset)==10&&digest(payload)==match[2] records<0 offset+=written end file.flush;file.fsync end end class GuideJournal P=GuideJournalProtocol def initialize(path,base,workspace,slug,job,input_fingerprint,writes,mode='resume') @path=path.dup;@lock_path=path+'.lock';@file=nil;@owned=false;@tainted=false;@intents={};@saved={};@allowed={} address=URI(base) raise P::Refusal,'Use actual API base and closed guide slug' unless ['https','http'].include?(address.scheme)&&address.host&&address.userinfo.nil?&&address.query.nil?&&address.fragment.nil?&&slug.match?(/\A[a-z][a-z0-9-]*\z/) raise P::Refusal,'Use actual workspace, stable explicit job ID and exact fingerprint' unless !job.strip.empty?&&workspace.match?(/\A[1-9][0-9]*\z/)&&input_fingerprint.match?(/\A[0-9A-F]{64}\z/) raise P::Refusal,'Choose new or resume for this local job' unless ['new','resume'].include?(mode) manifest=[] writes.each do|step,method,route| raise P::Refusal,'Use closed unique write manifest' unless step.match?(/\A[a-z][a-z0-9_-]*\z/)&&!@allowed.key?(step)&&['POST','PATCH','DELETE'].include?(method)&&route.match?(/\A\/v1\/[A-Za-z0-9_\/-]+\z/)&&!route.include?('//') @allowed[step.dup.freeze]=[method.dup.freeze,route.dup.freeze].freeze;manifest.concat([step,method,route]) end raise P::Refusal,'Only write workflows need a restart journal' if @allowed.empty? @header=['H','1',base,workspace,slug,job,input_fingerprint,P.digest(P.strings(manifest))].map{|value|value.dup.freeze}.freeze;P.strings(@header) begin @file=File.open(@lock_path,File::RDWR|File::CREAT|File::EXCL,0o600);@file.binmode;@owned=true rescue Errno::EEXIST raise P::Refusal,'This journal is locked; do not overlap jobs or steal a stale lock' end begin @owner=SecureRandom.hex(16).freeze;P.write_all(@file,@owner.b);@identity=@file.stat # Ruby's Windows fstat reports dev=0 while lstat reports the drive number. # Both expose the same exact inode. Retain it plus the initial path device; # compare like-for-like instead of treating the differing dev APIs as equal. named_identity=File.lstat(@lock_path);raise P::Refusal,'Lock identity did not bind' unless named_identity.ino==@identity.ino @path_device=named_identity.dev raise P::Refusal,'Choose a private regular journal file' if File.symlink?(@path) raise P::Refusal,'Journal missing: stop and reconcile lost state before starting a new logical job' if mode=='resume'&&!File.exist?(@path) raise P::Refusal,'Journal exists; use resume for the same logical job' if mode=='new'&&File.exist?(@path) if mode=='new' File.open(@path,File::WRONLY|File::CREAT|File::EXCL,0o600){|target|target.binmode;P.write_all(target,P::PREAMBLE+P.frame(@header))} end records=P.decode(File.binread(@path));raise P::Refusal,'Journal workspace/base/guide/job/input binding differs' if records.empty?||records[0]!=@header records.drop(1).each{|record|apply(record)} raise P::Refusal,'Saved intent lacks ACK; stop and reconcile before retry' if @intents.keys.any?{|step|!@saved.key?(step)} rescue Exception close;raise end end def apply(record) case record[0] when 'I' raise P::Refusal,'Invalid intent shape' unless record.length==6 _,step,method,route,fingerprint,key=record raise P::Refusal,'Invalid, future or repeated intent' unless step.match?(/\A[a-z][a-z0-9_-]*\z/)&&!@intents.key?(step)&&@allowed[step]==[method,route]&&fingerprint.match?(/\A[0-9A-F]{64}\z/)&&!@intents.keys.any?{|name|!@saved.key?(name)} raise P::Refusal,'Invalid persisted action key' unless (method=='POST'&&key.match?(/\A[0-9a-f]{32}\z/))||(method!='POST'&&key=='') @intents[step.dup.freeze]={'method'=>method.dup.freeze,'path'=>route.dup.freeze,'request_fingerprint'=>fingerprint.dup.freeze,'idempotency_key'=>key.dup.freeze}.freeze when 'A' raise P::Refusal,'Invalid ACK shape' unless record.length>=3 _,step,count,*pairs=record raise P::Refusal,'ACK without exactly one prior intent' unless count.match?(/\A(?:0|[1-9][0-9]*)\z/)&&pairs.length==2*count.to_i&&@intents.key?(step)&&!@saved.key?(step) names=pairs.each_slice(2).map(&:first) raise P::Refusal,'ACK fields must be unique sorted secret-free identifiers' unless names==names.uniq.sort&&names.all?{|name|name.match?(/\A[a-z][a-z0-9_]*\z/)&&!['api_key','exhibitday_api_key'].include?(name)} @saved[step.dup.freeze]=pairs.each_slice(2).to_h.transform_values{|value|value.dup.freeze}.freeze else raise P::Refusal,'Unknown journal transition' end end def require_active raise P::Refusal,'Journal is closed or IO outcome needs reconciliation' unless @owned&&@file&&!@tainted current=File.lstat(@lock_path) raise P::Refusal,'Journal lock replaced; stop without deleting it' unless current.dev==@path_device&¤t.ino==@identity.ino&&File.binread(@lock_path)==@owner.b end def append(record) require_active;raw=P.frame(record) begin File.open(@path,'ab'){|target|P.write_all(target,raw)} rescue Exception @tainted=true;raise end end def acknowledged(step);require_active;@saved.key?(step);end def saved(step) require_active;raise P::Refusal,'No acknowledged state exists' unless @saved.key?(step) @saved.fetch(step).transform_values(&:dup) end def begin_action(step,method,route,request_fingerprint) require_active;raise P::Refusal,'Never blindly repeat an action' if @intents.key?(step) record=['I',step,method,route,request_fingerprint,method=='POST'?SecureRandom.hex(16):''] previous=@intents.dup;begin;apply(record);ensure;@intents=previous;end append(record);apply(record);@intents.fetch(step).transform_values(&:dup) end def acknowledge(step,saved) require_active;record=['A',step,saved.length.to_s];saved.keys.sort.each{|name|record.concat([name,saved.fetch(name)])} previous=@saved.dup;begin;apply(record);P.strings(record);ensure;@saved=previous;end append(record);apply(record) end def close return unless @owned if @tainted;@file.close;@file=nil;@owned=false;return;end begin;require_active;rescue Exception;@file.close;@file=nil;@owned=false;raise;end @file.close;@file=nil;@owned=false;File.unlink(@lock_path) end end def journal_values(value) raise GuideJournalProtocol::Refusal,'Saved/fingerprint values must be exact strings' unless value.is_a?(Hash)&&value.all?{|name,item|name.is_a?(String)&&item.is_a?(String)} value.transform_values(&:dup) end def journal_acknowledge(job,step,saved);job.acknowledge(step,journal_values(saved));end def journal_acknowledged(job,step);job.acknowledged(step);end def journal_begin(job,step,method,path,request_fingerprint);job.begin_action(step,method,path,request_fingerprint);end def journal_fingerprint(value);GuideJournalProtocol.fingerprint(journal_values(value));end def journal_saved(job,step);job.saved(step);end def json_string(value) JSON.generate(value) end def open_journal(path,base,workspace,slug,job,input_fingerprint,writes,mode);GuideJournal.new(path,base,workspace,slug,job,input_fingerprint,writes,mode);end def optional(name,fallback) value=ENV[name] value.nil? || value.empty? ? fallback : value end def parse_json(value) JSON.parse(value) end def positive_id(value) raise "Use a positive record ID" unless /\A[1-9][0-9]*\z/.match?(value) && Integer(value)<=9223372036854775807 value end def print_value(value) STDOUT.binmode.write((value.is_a?(String)?value:JSON.generate(value))+"\n") end def require_condition(value,message) raise message unless value==true end def required(name) value=ENV[name] raise "Set #{name}" if value.nil? || value.strip.empty? value end def response_status(value);value.fetch(:status).to_s;end def shipment_tracking_number(value) GuideJournalProtocol.utf8(value) value = value.gsub(/\A[\u0009-\u000D\u0020\u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]+|[\u0009-\u000D\u0020\u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]+\z/, '') raise GuideJournalProtocol::Refusal, 'Enter a single-line tracking number without angle brackets.' if value.match?(/[<>\r\n]/) if value.empty? || value.encode('UTF-16LE').bytesize / 2 > 125 raise GuideJournalProtocol::Refusal, 'Enter a nonblank tracking number of at most 125 UTF-16 code units.' end value end def text(value) return "" if value.nil? return value.to_s if value.is_a?(String)||value.is_a?(Integer)||value==true||value==false raise "Expected a scalar response value" end def main expected_shipment_event_id = positive_id(required('EXHIBITDAY_EVENT_ID')) selected_shipment_id = positive_id(required('EXHIBITDAY_SHIPMENT_ID')) desired_tracking_number = shipment_tracking_number(required('EXHIBITDAY_TRACKING_NUMBER')) shipment_journal_path = required('EXHIBITDAY_JOURNAL') shipment_job_id = required('EXHIBITDAY_JOB_ID') shipment_job_mode = optional('EXHIBITDAY_JOB_MODE', 'resume') shipment_workspace_response = call('workspace_binding', {}, nil, nil) require_condition(equal(response_status(shipment_workspace_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; preserve pending state and reconcile any other outcome.') shipment_workspace = shipment_workspace_response.fetch(:body) shipment_workspace_id = positive_id(text(field(shipment_workspace, 'id'))) initial_shipment_response = call('read_shipment', {'id' => selected_shipment_id, '$include_record_revision' => 'true'}, nil, nil) require_condition(equal(response_status(initial_shipment_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; preserve pending state and reconcile any other outcome.') initial_shipment = initial_shipment_response.fetch(:body) require_condition(both(equal(text(field(initial_shipment, 'id')), selected_shipment_id), equal(text(field(initial_shipment, 'event_id')), expected_shipment_event_id)), 'The selected Shipment does not belong to the expected Event; no write was sent.') shipment_revision = text(field(initial_shipment, 'record_revision')) require_condition(is_present(shipment_revision), 'Read the actual Shipment with $include_record_revision=true before attempting the change.') original_components = items(field(initial_shipment, 'components')) shipment_input_fingerprint = journal_fingerprint({'workflow_contract_sha256' => '150EE3B0A50D2C1B961E315183D849281F9A38E47247AB7A5D526BB60983BA90', 'event_id' => expected_shipment_event_id, 'shipment_id' => selected_shipment_id, 'tracking_number' => desired_tracking_number, 'shipment_status_id' => '2'}) shipment_job = open_journal(shipment_journal_path, 'https://api.exhibitday.com/v1', shipment_workspace_id, 'shipment-tracking', shipment_job_id, shipment_input_fingerprint, [['update_tracking', 'PATCH', '/v1/events/shipments']], shipment_job_mode) begin component_snapshot = '' if journal_acknowledged(shipment_job, 'update_tracking') saved_shipment = journal_saved(shipment_job, 'update_tracking') require_condition(both(equal(text(field(saved_shipment, 'id')), selected_shipment_id), both(equal(text(field(saved_shipment, 'event_id')), expected_shipment_event_id), both(equal(text(field(saved_shipment, 'tracking_number')), desired_tracking_number), equal(text(field(saved_shipment, 'shipment_status_id')), '2')))), 'The acknowledged Shipment change belongs to another record, Event or desired tracking state.') component_snapshot = text(field(saved_shipment, 'components_json')) else component_snapshot = json_string(original_components) tracking_patch = {'id' => selected_shipment_id, 'tracking_number' => desired_tracking_number, 'shipment_status_id' => '2', 'expected_revision' => shipment_revision} shipment_write_fingerprint = journal_fingerprint({'id' => selected_shipment_id, 'tracking_number' => desired_tracking_number, 'shipment_status_id' => '2', 'expected_revision' => shipment_revision}) journal_begin(shipment_job, 'update_tracking', 'PATCH', '/v1/events/shipments', shipment_write_fingerprint) tracking_save_response = call('update_tracking', {}, tracking_patch, nil) require_condition(equal(response_status(tracking_save_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; preserve pending state and reconcile any other outcome.') tracking_receipt = tracking_save_response.fetch(:body) saved_shipment_revision = text(field(tracking_receipt, 'record_revision')) require_condition(is_present(saved_shipment_revision), 'A checked save acknowledgement needs its actual returned record_revision.') journal_acknowledge(shipment_job, 'update_tracking', {'id' => selected_shipment_id, 'event_id' => expected_shipment_event_id, 'tracking_number' => desired_tracking_number, 'shipment_status_id' => '2', 'record_revision' => saved_shipment_revision, 'components_json' => component_snapshot}) end shipment_readback_response = call('verify_shipment', {'id' => selected_shipment_id}, nil, nil) require_condition(equal(response_status(shipment_readback_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; preserve pending state and reconcile any other outcome.') shipment_readback = shipment_readback_response.fetch(:body) require_condition(both(equal(text(field(shipment_readback, 'id')), selected_shipment_id), equal(text(field(shipment_readback, 'event_id')), expected_shipment_event_id)), 'The final Shipment is missing or rebound; earlier saved state remains in the journal.') require_condition(both(equal(text(field(shipment_readback, 'tracking_number')), desired_tracking_number), equal(text(field(shipment_readback, 'shipment_status_id')), '2')), 'The Shipment no longer matches the acknowledged tracking/status; inspect it instead of automatically restoring the change.') recorded_components = items(parse_json(component_snapshot)) require_condition(deep_equal(field(shipment_readback, 'components'), recorded_components), 'Shipment components differ from the original saved snapshot. Inspect the packages; do not replace or automatically restore them.') print_value({'shipment_id' => selected_shipment_id, 'event_id' => expected_shipment_event_id, 'tracking_number' => desired_tracking_number, 'components_unchanged' => 'true'}) ensure shipment_job.close() end end main if $PROGRAM_NAME == __FILE__ ``` ```go // Go 1.18+; standard library only. Set EXHIBITDAY_API_KEY. package main import ( "bytes" "crypto/rand" "crypto/sha256" "encoding/hex" "regexp" "sort" "unicode/utf8" "encoding/json" "fmt" "io" "net/http" "net/url" "os" "strconv" "strings" "time" ) const base = "https://api.exhibitday.com/v1" const specification = "{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"read_shipment\":{\"method\":\"GET\",\"path\":\"/events/shipments/info\"},\"update_tracking\":{\"method\":\"PATCH\",\"path\":\"/events/shipments\"},\"verify_shipment\":{\"method\":\"GET\",\"path\":\"/events/shipments/info\"}}}" 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 }} var send = client.Do type result struct { status int; body any; headers http.Header; raw []byte } // 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 call(name string, query map[string]string, body any, key string) result { route := object(object(spec["requests"])[name]); method := text(route["method"]) headers := map[string]string{"Authorization": "Bearer " + apiKey, "Accept": "application/json"} if method == "POST" { if key == "" { panic("Persist a logical create key before sending POST") }; 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() } // 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 := method == "GET" 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 := send(request) if err != nil { if !resend { panic(apiError{0, "", "No response", true}) }; if attempt == 4 { panic(err) }; time.Sleep(time.Second*time.Duration(1<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 := resend && (response.StatusCode == 429 || response.StatusCode >= 500) if retry { if attempt == 4 { panic("Retry limit reached; check the outcome before starting a new create") } seconds := float64(int64(1)<= 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, raw} } panic("Retry limit reached") } func both(left,right bool)bool{return left&&right} func deep_equal(left,right any)bool{a,e:=json.Marshal(left);if e!=nil{panic(e)};b,e:=json.Marshal(right);if e!=nil{panic(e)};return string(a)==string(b)} func equal(left,right any)bool{switch a:=left.(type){case string:b,ok:=right.(string);return ok&&a==b;case bool:b,ok:=right.(bool);return ok&&a==b;case int64:b,ok:=right.(int64);return ok&&a==b};return left==nil&&right==nil} func field(value any,name string)any{obj,ok:=value.(map[string]any);if !ok{panic("Missing response object")};item,found:=obj[name];if !found{panic("Missing response field: "+name)};return item} func is_present(value string)bool{return value!=""} func items(value any)[]any{result,ok:=value.([]any);if !ok{panic("Expected a JSON array")};return result} // Private client restart state only; no API transport or workflow interpreter. const journalPreamble = "EXHIBITDAY-GUIDE-JOURNAL 1\n" type journalRefusal struct{ message string } func (e journalRefusal) Error() string { return e.message } func journalNeed(ok bool, message string) { if !ok { panic(journalRefusal{message}) } } func journalMatch(value, pattern string) bool { return regexp.MustCompile("\\A(?:"+pattern+")\\z").MatchString(value) } func journalStrings(values []string) []byte { var output bytes.Buffer for _,value:=range values { journalNeed(utf8.ValidString(value),"Journal fields must be valid UTF8 strings"); output.WriteString(strconv.Itoa(len(value))+":");output.WriteString(value) } return output.Bytes() } func journalReadStrings(raw []byte) []string { values:=[]string{};offset:=0 for offset=0,"Incomplete journal string length");end:=offset+relative;text:=string(raw[offset:end]);journalNeed(journalMatch(text,"0|[1-9][0-9]*"),"Noncanonical journal string length");size,err:=strconv.ParseUint(text,10,64);offset=end+1;journalNeed(err==nil&&size<=uint64(len(raw)-offset),"Incomplete journal string");count:=int(size);value:=string(raw[offset:offset+count]);journalNeed(utf8.ValidString(value),"Invalid UTF8 journal field");values=append(values,value);offset+=count } return values } func journalDigest(raw []byte) string { hash:=sha256.Sum256(raw);return strings.ToUpper(hex.EncodeToString(hash[:])) } func journalFingerprint(pairs map[string]string) string { names:=make([]string,0,len(pairs));for name:=range pairs { names=append(names,name) };sort.Strings(names);values:=[]string{} for _,name:=range names { lower:=strings.ToLower(name);journalNeed(journalMatch(name,"[A-Za-z0-9_.-]+")&&lower!="api_key"&&lower!="exhibitday_api_key","Use explicit secret-free fingerprint names");values=append(values,name,pairs[name]) } return journalDigest(journalStrings(values)) } func journalFrame(values []string) []byte { raw:=journalStrings(values);header:=[]byte(strconv.Itoa(len(raw))+" "+journalDigest(raw)+"\n");result:=append(header,raw...);return append(result,'\n') } func journalDecode(raw []byte) [][]string { journalNeed(bytes.HasPrefix(raw,[]byte(journalPreamble)),"Unknown or incomplete journal version");offset:=len(journalPreamble);records:=[][]string{} for offset=0,"Incomplete frame header; reconcile before retry");end:=offset+relative;header:=string(raw[offset:end]);journalNeed(journalMatch(header,"(0|[1-9][0-9]*) [0-9A-F]{64}"),"Invalid frame header");fields:=strings.Split(header," ");size,err:=strconv.ParseUint(fields[0],10,64);offset=end+1;journalNeed(err==nil&&size0 { count,err:=file.Write(raw);if err!=nil{return err};if count<=0{return io.ErrShortWrite};raw=raw[count:] } return file.Sync() } func journalWriteFile(path string,flags int,raw []byte) (err error) { file,err:=os.OpenFile(path,flags,0600);if err!=nil{return err};defer func(){closed:=file.Close();if err==nil{err=closed}}();return journalWriteAll(file,raw) } func journalCopy(source map[string]string) map[string]string { copy:=map[string]string{};for name,value:=range source{copy[name]=value};return copy } func journalCopyStates(source map[string]map[string]string) map[string]map[string]string { copy:=map[string]map[string]string{};for name,value:=range source{copy[name]=journalCopy(value)};return copy } type guideJournal struct { path,lockPath,owner string header []string allowed map[string][2]string intents,savedValues map[string]map[string]string file *os.File identity os.FileInfo owned,tainted bool } func openGuideJournal(path,base,workspace,slug,job,inputFingerprint string,writes [][3]string,modes ...string) (result *guideJournal) { mode:="resume";journalNeed(len(modes)<=1,"Choose one local job mode");if len(modes)==1{mode=modes[0]};journalNeed(mode=="new"||mode=="resume","Choose new or resume for this local job") address,err:=url.Parse(base);journalNeed(err==nil&&address.Hostname()!=""&&(address.Scheme=="https"||address.Scheme=="http")&&address.User==nil&&address.RawQuery==""&&address.Fragment==""&&journalMatch(slug,"[a-z][a-z0-9-]*"),"Use actual API base and closed guide slug") journalNeed(strings.TrimSpace(job)!=""&&journalMatch(workspace,"[1-9][0-9]*")&&journalMatch(inputFingerprint,"[0-9A-F]{64}"),"Use actual workspace, stable explicit job ID and exact fingerprint") j:=&guideJournal{path:path,lockPath:path+".lock",allowed:map[string][2]string{},intents:map[string]map[string]string{},savedValues:map[string]map[string]string{}} manifest:=[]string{};for _,write:=range writes { step,method,route:=write[0],write[1],write[2];_,exists:=j.allowed[step];journalNeed(journalMatch(step,"[a-z][a-z0-9_-]*")&&!exists&&(method=="POST"||method=="PATCH"||method=="DELETE")&&journalMatch(route,"/v1/[A-Za-z0-9_/-]+")&&!strings.Contains(route,"//"),"Use a closed unique write manifest");j.allowed[step]=[2]string{method,route};manifest=append(manifest,step,method,route) } journalNeed(len(j.allowed)>0,"Only write workflows need a restart journal");j.header=[]string{"H","1",base,workspace,slug,job,inputFingerprint,journalDigest(journalStrings(manifest))};journalStrings(j.header) j.file,err=os.OpenFile(j.lockPath,os.O_RDWR|os.O_CREATE|os.O_EXCL,0600);if err!=nil { if os.IsExist(err){panic(journalRefusal{"This journal is locked; do not overlap jobs or steal a stale lock"})};panic(err) };j.owned=true defer func(){ if observed:=recover();observed!=nil { j.Close();panic(observed) } }() random:=make([]byte,16);if _,err=io.ReadFull(rand.Reader,random);err!=nil{panic(err)};j.owner=hex.EncodeToString(random);if err=journalWriteAll(j.file,[]byte(j.owner));err!=nil{panic(err)};j.identity,err=j.file.Stat();if err!=nil{panic(err)} info,err:=os.Lstat(path);if err!=nil&&!os.IsNotExist(err){panic(err)};exists:=err==nil;if exists{journalNeed(info.Mode()&os.ModeSymlink==0,"Choose a private regular journal file")};journalNeed(mode!="resume"||exists,"Journal missing: stop and reconcile lost state before starting a new logical job");journalNeed(mode!="new"||!exists,"Journal exists; use resume for the same logical job");if mode=="new"{raw:=append([]byte(journalPreamble),journalFrame(j.header)...);if err=journalWriteFile(path,os.O_WRONLY|os.O_CREATE|os.O_EXCL,raw);err!=nil{panic(err)}} raw,err:=os.ReadFile(path);if err!=nil{panic(err)};records:=journalDecode(raw);journalNeed(len(records)>0&&stringsEqual(records[0],j.header),"Journal workspace/base/guide/job/input binding differs");for _,record:=range records[1:]{j.apply(record)};for step:=range j.intents{_,ok:=j.savedValues[step];journalNeed(ok,"Saved intent lacks ACK; stop and reconcile before retry")};return j } func stringsEqual(left,right []string) bool { if len(left)!=len(right){return false};for i,value:=range left{if value!=right[i]{return false}};return true } func (j *guideJournal) apply(record []string) { journalNeed(len(record)>0,"Empty journal record") if record[0]=="I" { journalNeed(len(record)==6,"Invalid intent shape");step,method,route,fingerprint,key:=record[1],record[2],record[3],record[4],record[5];_,exists:=j.intents[step];expected,allowed:=j.allowed[step];pending:=false;for name:=range j.intents{if _,ok:=j.savedValues[name];!ok{pending=true}} journalNeed(journalMatch(step,"[a-z][a-z0-9_-]*")&&!exists&&allowed&&expected==[2]string{method,route}&&journalMatch(fingerprint,"[0-9A-F]{64}")&&!pending,"Invalid, future or repeated intent");journalNeed(method=="POST"&&journalMatch(key,"[0-9a-f]{32}")||method!="POST"&&key=="","Invalid persisted action key");j.intents[step]=map[string]string{"method":method,"path":route,"request_fingerprint":fingerprint,"idempotency_key":key} }else if record[0]=="A" { journalNeed(len(record)>=3,"Invalid ACK shape");step,text:=record[1],record[2];count,err:=strconv.ParseUint(text,10,64);_,prior:=j.intents[step];_,done:=j.savedValues[step];journalNeed(journalMatch(text,"0|[1-9][0-9]*")&&err==nil&&len(record)%2==1&&count==uint64((len(record)-3)/2)&&prior&&!done,"ACK without exactly one prior intent");names:=[]string{};for i:=3;i0&&value[0]!='0';for _,ch:=range value{valid=valid&&ch>='0'&&ch<='9'};id,err:=strconv.ParseInt(value,10,64);if !valid||err!=nil||id<=0{panic("Use a positive record ID")};return value} func print_value(value any){if result,ok:=value.(string);ok{fmt.Println(result);return};raw,err:=json.Marshal(value);if err!=nil{panic(err)};fmt.Println(string(raw))} func require_condition(value bool,message string){if !value{panic(message)}} func response_status(value result)string{return strconv.Itoa(value.status)} func shipment_tracking_space(c rune) bool { return c >= 9 && c <= 13 || c == 32 || c == 0x85 || c == 0xA0 || c == 0x1680 || c >= 0x2000 && c <= 0x200A || c == 0x2028 || c == 0x2029 || c == 0x202F || c == 0x205F || c == 0x3000 } func shipment_tracking_number(value string) string { journalNeed(utf8.ValidString(value), "Use valid UTF-8 tracking text.") value = strings.TrimFunc(value, shipment_tracking_space) journalNeed(!strings.ContainsAny(value, "<>\r\n"), "Enter a single-line tracking number without angle brackets.") units := 0 for _, character := range value { units++ if character > 0xFFFF { units++ } } journalNeed(value != "" && units <= 125, "Enter a nonblank tracking number of at most 125 UTF-16 code units.") return value } func workflow() { expected_shipment_event_id := positive_id(required("EXHIBITDAY_EVENT_ID")) selected_shipment_id := positive_id(required("EXHIBITDAY_SHIPMENT_ID")) desired_tracking_number := shipment_tracking_number(required("EXHIBITDAY_TRACKING_NUMBER")) shipment_journal_path := required("EXHIBITDAY_JOURNAL") shipment_job_id := required("EXHIBITDAY_JOB_ID") shipment_job_mode := optional("EXHIBITDAY_JOB_MODE", "resume") shipment_workspace_response := call("workspace_binding", map[string]string{}, nil, "") require_condition(equal(response_status(shipment_workspace_response), "200"), "Expected the endpoint's documented HTTP200 response; preserve pending state and reconcile any other outcome.") shipment_workspace := shipment_workspace_response.body shipment_workspace_id := positive_id(text(field(shipment_workspace, "id"))) initial_shipment_response := call("read_shipment", map[string]string{"id": selected_shipment_id, "$include_record_revision": "true"}, nil, "") require_condition(equal(response_status(initial_shipment_response), "200"), "Expected the endpoint's documented HTTP200 response; preserve pending state and reconcile any other outcome.") initial_shipment := initial_shipment_response.body require_condition(both(equal(text(field(initial_shipment, "id")), selected_shipment_id), equal(text(field(initial_shipment, "event_id")), expected_shipment_event_id)), "The selected Shipment does not belong to the expected Event; no write was sent.") shipment_revision := text(field(initial_shipment, "record_revision")) require_condition(is_present(shipment_revision), "Read the actual Shipment with $include_record_revision=true before attempting the change.") original_components := items(field(initial_shipment, "components")) shipment_input_fingerprint := journal_fingerprint(map[string]any{"workflow_contract_sha256": "150EE3B0A50D2C1B961E315183D849281F9A38E47247AB7A5D526BB60983BA90", "event_id": expected_shipment_event_id, "shipment_id": selected_shipment_id, "tracking_number": desired_tracking_number, "shipment_status_id": "2"}) func() { shipment_job := open_journal(shipment_journal_path, "https://api.exhibitday.com/v1", shipment_workspace_id, "shipment-tracking", shipment_job_id, shipment_input_fingerprint, []any{[]any{"update_tracking", "PATCH", "/v1/events/shipments"}}, shipment_job_mode) defer shipment_job.Close() component_snapshot := "" if journal_acknowledged(shipment_job, "update_tracking") { saved_shipment := journal_saved(shipment_job, "update_tracking") require_condition(both(equal(text(field(saved_shipment, "id")), selected_shipment_id), both(equal(text(field(saved_shipment, "event_id")), expected_shipment_event_id), both(equal(text(field(saved_shipment, "tracking_number")), desired_tracking_number), equal(text(field(saved_shipment, "shipment_status_id")), "2")))), "The acknowledged Shipment change belongs to another record, Event or desired tracking state.") component_snapshot = text(field(saved_shipment, "components_json")) } else { component_snapshot = json_string(original_components) tracking_patch := map[string]any{"id": selected_shipment_id, "tracking_number": desired_tracking_number, "shipment_status_id": "2", "expected_revision": shipment_revision} shipment_write_fingerprint := journal_fingerprint(map[string]any{"id": selected_shipment_id, "tracking_number": desired_tracking_number, "shipment_status_id": "2", "expected_revision": shipment_revision}) journal_begin(shipment_job, "update_tracking", "PATCH", "/v1/events/shipments", shipment_write_fingerprint) tracking_save_response := call("update_tracking", map[string]string{}, tracking_patch, "") require_condition(equal(response_status(tracking_save_response), "200"), "Expected the endpoint's documented HTTP200 response; preserve pending state and reconcile any other outcome.") tracking_receipt := tracking_save_response.body saved_shipment_revision := text(field(tracking_receipt, "record_revision")) require_condition(is_present(saved_shipment_revision), "A checked save acknowledgement needs its actual returned record_revision.") journal_acknowledge(shipment_job, "update_tracking", map[string]any{"id": selected_shipment_id, "event_id": expected_shipment_event_id, "tracking_number": desired_tracking_number, "shipment_status_id": "2", "record_revision": saved_shipment_revision, "components_json": component_snapshot}) } shipment_readback_response := call("verify_shipment", map[string]string{"id": selected_shipment_id}, nil, "") require_condition(equal(response_status(shipment_readback_response), "200"), "Expected the endpoint's documented HTTP200 response; preserve pending state and reconcile any other outcome.") shipment_readback := shipment_readback_response.body require_condition(both(equal(text(field(shipment_readback, "id")), selected_shipment_id), equal(text(field(shipment_readback, "event_id")), expected_shipment_event_id)), "The final Shipment is missing or rebound; earlier saved state remains in the journal.") require_condition(both(equal(text(field(shipment_readback, "tracking_number")), desired_tracking_number), equal(text(field(shipment_readback, "shipment_status_id")), "2")), "The Shipment no longer matches the acknowledged tracking/status; inspect it instead of automatically restoring the change.") recorded_components := items(parse_json(component_snapshot)) require_condition(deep_equal(field(shipment_readback, "components"), recorded_components), "Shipment components differ from the original saved snapshot. Inspect the packages; do not replace or automatically restore them.") print_value(map[string]any{"shipment_id": selected_shipment_id, "event_id": expected_shipment_event_id, "tracking_number": desired_tracking_number, "components_unchanged": "true"}) }() } func header_key(value string)string{for _,ch:=range value{if ch<32||ch>126{panic("Use the API key as one ASCII header value without control characters")}};return value} func main(){apiKey=header_key(required("EXHIBITDAY_API_KEY"));if err:=json.Unmarshal([]byte(specification),&spec);err!=nil{panic(err)};workflow()} ``` #### Example response Response 200 — OK 304 — Not Modified 400 — Bad Request 401 — Unauthorized 404 — Not Found 409 — Conflict 429 — Too Many Requests 500 — Internal Server Error Example Successful request ```json { "id": 7001, "event_id": 5001, "event_name": "Spring Expo 2030", "carrier": null, "tracking_url": null, "shipment_status": "Shipped", "payment_status": { "id": 0, "name": "N/A" }, "dimensions_unit": "in", "weight_unit": "lb", "components": [ { "id": 12002, "component_type_id": null, "component_type": "Not Specified", "description": "Display stand case", "tracking_number": "PACKAGE-1001", "dimensions_length": 48.0, "dimensions_width": 24.0, "dimensions_height": 18.0, "weight": 65.0 }, { "id": 12003, "component_type_id": null, "component_type": "Not Specified", "description": "Brochure carton", "tracking_number": "PACKAGE-1002", "dimensions_length": 20.0, "dimensions_width": 16.0, "dimensions_height": 12.0, "weight": 18.50 } ], "cost": { "amount": 0.00, "cost_center_breakdown": [] }, "name": "Exhibit freight", "tracking_number": "TEST-ANNUAL-EXPO-001", "carrier_id": null, "other_carrier_name": null, "pickup_date": null, "delivery_date": null, "pickup_location": null, "delivery_location": null, "notes": "", "payment_status_id": 0, "payment_due_date": null, "next_payment_due_date": null, "payment_notes": null, "invoice_attachment": null, "shipment_status_id": 2, "service_level": null, "shipment_reference_number": null, "pickup_contact_name": null, "pickup_contact_email": null, "pickup_contact_phone": null, "pickup_instructions": null, "delivery_contact_name": null, "delivery_contact_email": null, "delivery_contact_phone": null, "delivery_instructions": null, "packing_handling_requirements": null, "received_by": null, "delivery_exception_notes": null } ``` Note: The Shipment as read after the update. It shows Shipped status and the new Shipment tracking number. Both original packages keep all their fields. Note: There is no response body. Keep using your cached response. ```json { "status_code": 400, "status": "Bad Request", "message": "X-HTTP-Method-Override: hTTP method override is not supported.", "error_code": "invalid_request", "errors": [ "Send the documented HTTP method directly. X-HTTP-Method-Override cannot change a request's HTTP method." ], "error_params": [ "X-HTTP-Method-Override" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "No API key was provided. Send your key in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "missing_api_key", "errors": [ "Copy the key from Workspace Settings > API & Integrations > API Access in ExhibitDay." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "The API key is not valid. Check that you copied the whole key from Workspace Settings > API & Integrations > API Access, then send it in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "invalid_api_key", "errors": [ "Check that you sent the whole key. If it was regenerated, use the current key from Workspace Settings > API & Integrations > API Access." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "Access to the ExhibitDay API is not enabled for your workspace. Please contact support@exhibitday.com to enable API Access. Once access is enabled, send your key in the Authorization header as 'Bearer YOUR_API_KEY'.", "error_code": "api_access_disabled", "errors": [ "Nothing was read or changed." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 404, "status": "Not Found", "message": "Shipment not found. Invalid Shipment ID: 12345.", "error_code": "not_found", "errors": [ "Shipment not found. Invalid Shipment ID: 12345." ], "error_params": [ "id" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "The invoice attachment or its owning record changed or has conflicting saved information. Retrieve the current record before retrying.", "error_code": "record_changed", "errors": [ "The invoice attachment or its owning record changed or has conflicting saved information. Retrieve the current record before retrying." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "The Shipment or its related scope changed. Read its current state and decide whether to retry; this request was rolled back.", "error_code": "record_changed", "errors": [ "The Shipment or its related scope changed. Read its current state and decide whether to retry; this request was rolled back." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 429, "status": "Too Many Requests", "message": "Error 429 - Too Many Requests", "error_code": "rate_limited", "errors": [ "Error 429 - Too Many Requests" ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "An unexpected error occurred. Please try again later." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` Note: Use the request_id from your own response when contacting support. ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "Check whether your change was saved before trying again." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` #### Things to keep in mind - Every Shipment request uses the Shipment's own ID. The Event ID is a check that you picked the right Shipment. - The program always sets the status to Shipped (status 2). #### If a run stops - Keep the journal private. It records what the program tried to save and which save it confirmed. - To continue a run with no unresolved save, use `EXHIBITDAY_JOB_MODE=resume` with the same job ID, journal path and inputs. - A resumed run skips an acknowledged update and compares the current packages with the original list saved in the journal. - If a save stops with a conflict, a lost response or a missing revision, check the Shipment in ExhibitDay before running the program again. - If you still need a change after checking the old run, use `EXHIBITDAY_JOB_MODE=new` with a new job ID and journal path. - Run only one copy per journal. - If a crash leaves a `.lock` file, make sure no copy using that journal is running or can start. Then remove the lock file and keep the journal. #### Related guides - [Avoid Overwriting Someone Else's Changes](https://api.exhibitday.com/Help/V1?guide=update-records-safely) - [Handle Errors and Retry Failed Requests](https://api.exhibitday.com/Help/V1?guide=errors-and-retries) ### Record Show Results: Leads and Objective Ratings Guide page: https://api.exhibitday.com/Help/V1?guide=show-results-objectives Record a show's lead count and how well an Objective was met. Example use case The show has ended and you want to record the number of leads and how well an Objective was met. What you'll end up with A saved lead count and a saved rating for one Objective, with both results checked afterward. Before you start Have a workspace API key, an Event ID and an Objective ID from that Event. Your plan and key must allow ROI and Budget View access, and the Event's ROI area must allow edits. Good to know The Event and Objective are saved separately. Use each record's own revision. #### At a glance Time to try About 10 minutes Effect on your data Updates records Endpoints 5 The program updates the Event lead count and one Objective rating and writes a private local journal. - [`GET /v1/references/workspace_info`](https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-workspace_info) - [`GET /v1/events/info`](https://api.exhibitday.com/Help/V1?epf=1#get-v1-events-info) - [`GET /v1/events/objectives/info`](https://api.exhibitday.com/Help/V1?epf=1&topic=objectives#get-v1-events-objectives-info) - [`PATCH /v1/events`](https://api.exhibitday.com/Help/V1?epf=1#patch-v1-events) - [`PATCH /v1/events/objectives`](https://api.exhibitday.com/Help/V1?epf=1&topic=objectives#patch-v1-events-objectives) #### How it works 1. The program reads the Event and Objective and checks that they belong together. 2. It saves your lead count and rating separately, using each record's own revision. 3. It reads both records again to check the saved values. #### Record the lead count and Objective rating The examples below set 48 leads and an Objective rating of 8 on a test Event. Your values come from `EXHIBITDAY_LEAD_COUNT` and `EXHIBITDAY_ACHIEVEMENT_RATING`. **Manual example.** If you need the Objective ID, [list Objectives for the Event](https://api.exhibitday.com/Help/V1?epf=1&topic=objectives#get-v1-events-objectives). Use the returned Objective `id`. The program starts with this ID. `curl -X GET "https://api.exhibitday.com/v1/events/objectives?filter_by_event_id=5001" -H "Authorization: Bearer YOUR_API_KEY"` **Check:** Choose an Objective whose `event_id` matches your Event. #### Step 1: Confirm the workspace Check where the key will make changes so you can confirm the workspace. ```bash curl -X GET "https://api.exhibitday.com/v1/references/workspace_info" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "id": 98765 } ``` **Check:** Confirm id is the workspace you intended to use. #### Step 2: Read the Event and its revision Read the current lead count and Event revision before changing the count. ```bash curl -X GET "https://api.exhibitday.com/v1/events/info?id=5001&%24include_record_revision=true" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "id": 5001, "roi_num_leads": 12, "roo_score": null, "record_revision": "COPY_EVENT_REVISION_FROM_YOUR_READ" } ``` **Check:** Confirm the Event ID and keep this record_revision for the Event PATCH. #### Step 3: Read the Objective and its revision Read the selected Objective before assigning its achievement rating. ```bash curl -X GET "https://api.exhibitday.com/v1/events/objectives/info?id=8001&%24include_record_revision=true" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "id": 8001, "event_id": 5001, "achievement_rating": null, "record_revision": "COPY_OBJECTIVE_REVISION_FROM_YOUR_READ" } ``` **Check:** Confirm event_id matches the selected Event. Keep this record_revision for the Objective PATCH. #### Step 4: Save the lead count Send roi_num_leads with the Event revision to guard against a conflicting change. ```bash curl -X PATCH "https://api.exhibitday.com/v1/events" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" --data-binary "{\"id\":5001,\"roi_num_leads\":\"$env.EXHIBITDAY_LEAD_COUNT\",\"expected_revision\":\"COPY_EVENT_REVISION_FROM_YOUR_READ\"}" ``` Example response ```json { "status_code": 200, "status": "OK", "message": "Event Update Successful. Event properties that were changed: roi_num_leads", "errors": [], "record_revision": "NEW_EVENT_REVISION" } ``` **Check:** Look for record_revision in the acknowledgement. The Objective rating is a separate save. #### Step 5: Save the Objective rating Send achievement_rating with the Objective revision and leave importance unchanged. ```bash curl -X PATCH "https://api.exhibitday.com/v1/events/objectives" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" --data-binary "{\"id\":8001,\"achievement_rating\":\"$env.EXHIBITDAY_ACHIEVEMENT_RATING\",\"expected_revision\":\"COPY_OBJECTIVE_REVISION_FROM_YOUR_READ\"}" ``` Example response ```json { "status_code": 200, "status": "OK", "message": "Objective updated.", "errors": [], "record_revision": "NEW_OBJECTIVE_REVISION" } ``` **Check:** Look for the Objective's record_revision. A failure here can leave the earlier lead count saved. #### Step 6: Verify the Event lead count Read the Event again to check the count that was saved. ```bash curl -X GET "https://api.exhibitday.com/v1/events/info?id=5001" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "id": 5001, "roi_num_leads": 48, "roo_score": 8.0 } ``` **Check:** Confirm the Event ID and the new lead count. ExhibitDay calculates roo_score separately. #### Step 7: Verify the Objective rating Read the Objective again to confirm the rating and its Event association. ```bash curl -X GET "https://api.exhibitday.com/v1/events/objectives/info?id=8001" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "id": 8001, "event_id": 5001, "achievement_rating": 8 } ``` **Check:** Confirm the Objective ID, Event ID and the achievement rating you supplied. **Careful.** A conflict or lost response can occur after the lead count was saved. Read both records before deciding whether to make another change. #### Try it #### Before running the example | Variable | What to put in it | Required? | | --- | --- | --- | | `EXHIBITDAY_API_KEY` | Your workspace API key. | Yes | | `EXHIBITDAY_EVENT_ID` | The ID of an existing Event you can edit. | Yes | | `EXHIBITDAY_OBJECTIVE_ID` | The ID of an existing Objective on that Event. | Yes | | `EXHIBITDAY_LEAD_COUNT` | The number of leads from the show, a whole number (0 or more). | Yes | | `EXHIBITDAY_ACHIEVEMENT_RATING` | How well the Objective was met, a whole number from 0 through 10. | Yes | | `EXHIBITDAY_JOB_ID` | A stable ID for this logical change. | Yes | | `EXHIBITDAY_JOURNAL` | A private local path for this job's journal. | Yes | | `EXHIBITDAY_JOB_MODE` | Use new for a genuinely new job or resume with the existing journal. The default is resume. | No | **Careful.** This example changes data in your workspace. Use a test Event. #### Bash ``` export EXHIBITDAY_API_KEY='YOUR_API_KEY' export EXHIBITDAY_EVENT_ID='5001' export EXHIBITDAY_OBJECTIVE_ID='8001' export EXHIBITDAY_LEAD_COUNT='48' export EXHIBITDAY_ACHIEVEMENT_RATING='8' ``` #### PowerShell ``` $env:EXHIBITDAY_API_KEY = 'YOUR_API_KEY' $env:EXHIBITDAY_EVENT_ID = '5001' $env:EXHIBITDAY_OBJECTIVE_ID = '8001' $env:EXHIBITDAY_LEAD_COUNT = '48' $env:EXHIBITDAY_ACHIEVEMENT_RATING = '8' ``` Use your own test Event and Objective IDs, lead count and rating. Set a private journal path and job ID. Set `EXHIBITDAY_JOB_MODE=new` for a new job, then run the complete example in your language. #### Complete example program Code Samples ```bash #!/usr/bin/env bash # Requires Bash, curl and Python3. No API key is written into the program. python3 - <<'EXHIBITDAY_PY' # Python 3; standard library only. Set EXHIBITDAY_API_KEY before running. import http.client import json import os import re import time import urllib.error import urllib.parse import urllib.request BASE = "https://api.exhibitday.com/v1" SPEC = json.loads("{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"read_event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"read_objective\":{\"method\":\"GET\",\"path\":\"/events/objectives/info\"},\"save_leads\":{\"method\":\"PATCH\",\"path\":\"/events\"},\"rate_objective\":{\"method\":\"PATCH\",\"path\":\"/events/objectives\"},\"verify_event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"verify_objective\":{\"method\":\"GET\",\"path\":\"/events/objectives/info\"}}}") API_KEY = os.environ["EXHIBITDAY_API_KEY"] if any(ord(char) < 32 or ord(char) > 126 for char in API_KEY): raise RuntimeError("Use the API key as one ASCII header value without control characters") if not API_KEY.strip(): raise RuntimeError("Set EXHIBITDAY_API_KEY") def decode_json(text): if SPEC["preserveNumbers"]: # Quote JSON NUMBER tokens, never text inside a JSON string, to keep CSV decimals exact. text = re.sub(r'"(?:\\.|[^"\\])*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?', lambda m: m[0] if m[0].startswith('"') else json.dumps(m[0]), text) return json.loads(text) from pathlib import Path # This terminal version uses curl for HTTP and Python's standard library for JSON/CSV. import subprocess import tempfile def transport(method, url, headers, data): with tempfile.TemporaryDirectory(prefix="exhibitday-guide-") as directory: folder = Path(directory) # curl may leave no output file for a valid bodyless304 response. (folder / "body").write_bytes(b"") command = ["curl", "--disable", "--silent", "--show-error", "--request", method, "--url", url, "--max-time", "30", "--dump-header", str(folder / "headers"), "--output", str(folder / "body"), "--write-out", "%{http_code}"] for name, value in headers.items(): command += ["--header", name + ": " + value] if data is not None: (folder / "request").write_bytes(data) command += ["--data-binary", "@" + str(folder / "request")] result = subprocess.run(command, capture_output=True, text=True) if result.returncode: raise urllib.error.URLError(result.stderr.strip()) response_headers = {} blocks = (folder / "headers").read_text(encoding="iso-8859-1").replace("\r\n", "\n").strip().split("\n\n") for line in blocks[-1].splitlines()[1:]: name, separator, value = line.partition(":") if separator: response_headers[name] = value.strip() return int(result.stdout), (folder / "body").read_bytes(), response_headers class ApiError(RuntimeError): """An API error response. Branch on error_code (and status), never on the message text. uncertain is True when a PATCH or DELETE got no response or a server error: it may or may not have been applied.""" def __init__(self, status, body, uncertain=False): self.status = status self.uncertain = uncertain self.error_code = body.get("error_code") if isinstance(body, dict) else None super().__init__(f"{body.get('error_code')} {body.get('error_params')}: {body.get('errors')} (request {body.get('request_id')})" if isinstance(body, dict) else "HTTP " + str(status) if status else "No response") def call(name, params=None, body=None, key=None): route = SPEC["requests"][name] headers = {"Authorization": "Bearer " + API_KEY, "Accept": "application/json"} if route["method"] == "POST": if not key: raise RuntimeError("Persist a logical create key before sending POST") headers["Idempotency-Key"] = key data = None if body is None else json.dumps(body).encode("utf-8") if data is not None: headers["Content-Type"] = "application/json" query = urllib.parse.urlencode(params or {}) url = BASE + route["path"] + ("?" + query if query else "") # Only GET has automatic retries in this workflow. A PATCH or DELETE that got no response or a # server error is never resent blindly: it may already have been applied, so the caller reads the record first. resend = route["method"] == "GET" for attempt in range(5): try: status, raw, response_headers = transport(route["method"], url, headers, data) except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException): if not resend: raise ApiError(0, None, uncertain=True) if attempt == 4: raise time.sleep(2 ** attempt) continue response_headers = {k.lower(): v for k, v in response_headers.items()} result = None if status != 304 and raw: try: result = decode_json(raw.decode("utf-8")) except (ValueError, UnicodeError): if status < 400: raise RuntimeError("Expected a JSON success response") if status >= 500 and not resend: raise ApiError(status, result, uncertain=True) retry = resend and (status == 429 or status >= 500) if retry: if attempt == 4: raise RuntimeError("Retry limit reached; check the request outcome before starting a new create") delay = response_headers.get("retry-after", str(2 ** attempt)) time.sleep(max(0, float(delay))) continue if status >= 400: raise ApiError(status, result) return {"status": status, "body": result, "headers": response_headers, "raw": raw} raise RuntimeError("Retry limit reached") def both(left,right): return left and right def bounded_whole_number(value, name, maximum): if not re.fullmatch(r"0|[1-9][0-9]*", value) or len(value)>len(maximum) or (len(value)==len(maximum) and value>maximum): raise RuntimeError(name+" must be a whole number from 0 through "+maximum) return value 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] 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 offsetlen(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)-offset:raise JournalRefusal('Incomplete journal frame; reconcile before retry') payload=raw[offset:offset+size];offset+=size if raw[offset:offset+1]!=b'\n' or digest(payload).encode('ascii')!=match[2]:raise JournalRefusal('Journal integrity check failed; reconcile before retry') records.append(read_strings(payload));offset+=1 return records class Journal: def __init__(self,path,base,workspace,slug,job,input_fingerprint,writes,mode="resume"): self.path=Path(path);self.lock=Path(str(self.path)+'.lock');self.fd=None;self.owned=False;self.identity=None;self.tainted=False;self.intents={};self.saved_values={} address=urlsplit(base) if address.scheme not in ('https','http')or not address.netloc or address.username is not None or address.query or address.fragment or not re.fullmatch('[a-z][a-z0-9-]*',slug):raise JournalRefusal('Use the actual API base and closed guide slug') if not job.strip() or not re.fullmatch('[1-9][0-9]*',workspace) or not re.fullmatch('[0-9A-F]{64}',input_fingerprint):raise JournalRefusal('Use an actual workspace, explicit stable job ID and exact input fingerprint') if mode not in ("new","resume"):raise JournalRefusal("Choose new or resume for this local job") self.allowed={};manifest=[] for step,method,route in writes: if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.allowed or method not in ('POST','PATCH','DELETE')or not re.fullmatch('/v1/[A-Za-z0-9_/-]+',route)or'//'in route:raise JournalRefusal('Use a closed unique write manifest') self.allowed[step]=(method,route);manifest.extend((step,method,route)) if not self.allowed:raise JournalRefusal('Only write workflows need a restart journal') self.header=['H','1',base,workspace,slug,job,input_fingerprint,digest(strings(manifest))] strings(self.header) try: self.fd=os.open(self.lock,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600);self.owned=True except FileExistsError:raise JournalRefusal('This journal is locked; do not run overlapping jobs or steal a stale lock') try: self.owner=secrets.token_hex(16);self.identity=os.fstat(self.fd) if os.write(self.fd,self.owner.encode('ascii'))!=len(self.owner):raise OSError('Incomplete lock identity write') os.fsync(self.fd) if self.path.is_symlink():raise JournalRefusal('Choose a private regular journal file') if mode=="resume" and not self.path.exists():raise JournalRefusal("Journal missing: stop and reconcile lost state before starting a new logical job") if mode=="new" and self.path.exists():raise JournalRefusal("A journal already exists; use resume for the same logical job") if mode=="new": with open(self.path,'xb',buffering=0)as target: target.write(PREAMBLE+frame(self.header));os.fsync(target.fileno()) records=decode(self.path.read_bytes()) if not records or records[0]!=self.header:raise JournalRefusal('Journal workspace/base/guide/job/input binding differs') for record in records[1:]:self.apply(record) if any(step not in self.saved_values for step in self.intents):raise JournalRefusal('A saved before-send intent lacks an ACK; stop and reconcile its outcome before retry') except BaseException: self.close();raise def apply(self,record): if not record:raise JournalRefusal('Empty journal record') if record[0]=='I': if len(record)!=6:raise JournalRefusal('Invalid intent shape') _,step,method,path,request_fingerprint,key=record if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.intents or self.allowed.get(step)!=(method,path)or not re.fullmatch('[0-9A-F]{64}',request_fingerprint)or any(name not in self.saved_values for name in self.intents):raise JournalRefusal('Invalid, future or repeated journal intent') if method=='POST'and not re.fullmatch('[0-9a-f]{32}',key)or method!='POST'and key!='':raise JournalRefusal('Invalid persisted action key') self.intents[step]={'method':method,'path':path,'request_fingerprint':request_fingerprint,'idempotency_key':key} elif record[0]=='A': if len(record)<3:raise JournalRefusal('Invalid ACK shape') _,step,count,*pairs=record if not re.fullmatch('0|[1-9][0-9]*',count)or len(pairs)!=2*int(count)or step not in self.intents or step in self.saved_values:raise JournalRefusal('ACK without exactly one prior intent') names=pairs[::2] if names!=sorted(set(names))or any(not re.fullmatch('[a-z][a-z0-9_]*',name)or name in ('api_key','exhibitday_api_key')for name in names):raise JournalRefusal('ACK saved fields must be unique sorted secret-free identifiers') self.saved_values[step]=dict(zip(names,pairs[1::2])) else:raise JournalRefusal('Unknown journal transition') def append(self,record): # The reader commits state only after complete length/digest recognition. # A torn append is retained and refused, never silently truncated. self.require_active();raw=frame(record) try: with open(self.path,'ab',buffering=0)as target: view=memoryview(raw) while view: written=target.write(view) if not written:raise OSError('Journal write did not advance') view=view[written:] os.fsync(target.fileno()) except BaseException: self.tainted=True;raise def require_active(self): if not self.owned or self.fd is None or self.identity is None or self.tainted:raise JournalRefusal('The journal scope is closed or its IO outcome needs reconciliation') current=self.lock.stat(follow_symlinks=False) if current.st_dev!=self.identity.st_dev or current.st_ino!=self.identity.st_ino or self.lock.read_text(encoding='ascii')!=self.owner:raise JournalRefusal('The journal lock was replaced; stop without deleting it') def acknowledged(self,step): self.require_active();return step in self.saved_values def saved(self,step): self.require_active() if step not in self.saved_values:raise JournalRefusal('No acknowledged state exists for this step') return dict(self.saved_values[step]) def begin(self,step,method,path,request_fingerprint): self.require_active() if step in self.intents:raise JournalRefusal('Never blindly repeat an existing action intent') key=secrets.token_hex(16)if method=='POST'else'' record=['I',step,method,path,request_fingerprint,key] # Validate on an isolated state before touching the file. old=dict(self.intents) try:self.apply(record) finally:self.intents=old self.append(record);self.apply(record) return dict(self.intents[step]) def acknowledge(self,step,saved): self.require_active() record=['A',step,str(len(saved))] for name,value in sorted(saved.items()):record.extend((name,value)) old={name:dict(value)for name,value in self.saved_values.items()} try:self.apply(record);strings(record) finally:self.saved_values=old self.append(record);self.apply(record) def close(self): if self.owned: if self.tainted: os.close(self.fd);self.fd=None;self.owned=False return # Retain this lock after failed journal IO; manual reconciliation is required. try:self.require_active() except BaseException: os.close(self.fd);self.fd=None;self.owned=False;raise os.close(self.fd);self.fd=None;self.owned=False self.lock.unlink() def __enter__(self):return self def __exit__(self,*args):self.close() def journal_values(value): if not isinstance(value, dict) or any(not isinstance(k, str) or not isinstance(v, str) for k,v in value.items()): raise JournalRefusal('Saved/fingerprint values must be exact string fields') return dict(value) def journal_acknowledge(job, step, saved): job.acknowledge(step,journal_values(saved)) def journal_acknowledged(job, step): return job.acknowledged(step) def journal_begin(job, step, method, path, request_fingerprint): return job.begin(step,method,path,request_fingerprint) def journal_fingerprint(value): return fingerprint(journal_values(value)) def journal_saved(job, step): return job.saved(step) def 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 positive_id(value): if not re.fullmatch(r"[1-9][0-9]*", value) or int(value) > 9223372036854775807: raise RuntimeError("Use a positive record ID") return value def print_value(value): print(value if isinstance(value, str) else json.dumps(value, ensure_ascii=False)) def require_condition(value, message): if value is not True: raise RuntimeError(message) def required(name): value = os.environ.get(name) if value is None or not value.strip(): raise RuntimeError("Set " + name) return value def response_status(value): return str(value["status"]) def 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(): results_event_id = positive_id(required("EXHIBITDAY_EVENT_ID")) results_objective_id = positive_id(required("EXHIBITDAY_OBJECTIVE_ID")) results_lead_count = bounded_whole_number(required("EXHIBITDAY_LEAD_COUNT"), "EXHIBITDAY_LEAD_COUNT", "9223372036854775807") results_rating = bounded_whole_number(required("EXHIBITDAY_ACHIEVEMENT_RATING"), "EXHIBITDAY_ACHIEVEMENT_RATING", "10") results_journal_path = required("EXHIBITDAY_JOURNAL") results_job_id = required("EXHIBITDAY_JOB_ID") results_job_mode = optional("EXHIBITDAY_JOB_MODE", "resume") results_workspace_response = call("workspace_binding", {}, None, None) require_condition(equal(response_status(results_workspace_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome.") results_workspace = results_workspace_response["body"] results_workspace_id = positive_id(text(field(results_workspace, "id"))) results_event_response = call("read_event", {"id": results_event_id, "$include_record_revision": "true"}, None, None) require_condition(equal(response_status(results_event_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome.") results_event = results_event_response["body"] require_condition(equal(text(field(results_event, "id")), results_event_id), "Read the exact selected Event before recording results.") results_leads_revision = text(field(results_event, "record_revision")) require_condition(is_present(results_leads_revision), "The Event read needs its own actual record_revision.") results_objective_response = call("read_objective", {"id": results_objective_id, "$include_record_revision": "true"}, None, None) require_condition(equal(response_status(results_objective_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome.") results_objective = results_objective_response["body"] require_condition(both(equal(text(field(results_objective, "id")), results_objective_id), equal(text(field(results_objective, "event_id")), results_event_id)), "The Objective does not belong to the selected Event; no write was sent.") results_objective_revision = text(field(results_objective, "record_revision")) require_condition(is_present(results_objective_revision), "The Objective read needs its own actual record_revision.") results_input_fingerprint = journal_fingerprint({"workflow_contract_sha256": "94A1426B8C4D275633E918271BB2A2683E06A442317C472320B2E446E00ABCF6", "event_id": results_event_id, "objective_id": results_objective_id, "roi_num_leads": results_lead_count, "achievement_rating": results_rating}) results_job = open_journal(results_journal_path, "https://api.exhibitday.com/v1", results_workspace_id, "show-results-objectives", results_job_id, results_input_fingerprint, [["save_leads", "PATCH", "/v1/events"], ["rate_objective", "PATCH", "/v1/events/objectives"]], results_job_mode) try: require_condition(either(not_value(journal_acknowledged(results_job, "rate_objective")), journal_acknowledged(results_job, "save_leads")), "A future results step is acknowledged before its prerequisite. Stop and reconcile the journal.") if journal_acknowledged(results_job, "save_leads"): results_leads_saved = journal_saved(results_job, "save_leads") require_condition(both(equal(text(field(results_leads_saved, "id")), results_event_id), equal(text(field(results_leads_saved, "roi_num_leads")), results_lead_count)), "Acknowledged results state does not match the selected record and intended value; stop and reconcile.") else: results_leads_patch = {"id": results_event_id, "roi_num_leads": results_lead_count, "expected_revision": results_leads_revision} results_leads_fingerprint = journal_fingerprint({"id": results_event_id, "roi_num_leads": results_lead_count, "expected_revision": results_leads_revision}) journal_begin(results_job, "save_leads", "PATCH", "/v1/events", results_leads_fingerprint) results_leads_save_response = call("save_leads", {}, results_leads_patch, None) require_condition(equal(response_status(results_leads_save_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome.") results_leads_receipt = results_leads_save_response["body"] results_leads_after_revision = text(field(results_leads_receipt, "record_revision")) require_condition(is_present(results_leads_after_revision), "A checked save acknowledgement requires its own returned record_revision.") journal_acknowledge(results_job, "save_leads", {"id": results_event_id, "roi_num_leads": results_lead_count, "record_revision": results_leads_after_revision}) if journal_acknowledged(results_job, "rate_objective"): results_objective_saved = journal_saved(results_job, "rate_objective") require_condition(both(both(equal(text(field(results_objective_saved, "id")), results_objective_id), equal(text(field(results_objective_saved, "achievement_rating")), results_rating)), equal(text(field(results_objective_saved, "event_id")), results_event_id)), "Acknowledged results state does not match the selected record and intended value; stop and reconcile.") else: results_objective_patch = {"id": results_objective_id, "achievement_rating": results_rating, "expected_revision": results_objective_revision} results_objective_fingerprint = journal_fingerprint({"id": results_objective_id, "achievement_rating": results_rating, "expected_revision": results_objective_revision}) journal_begin(results_job, "rate_objective", "PATCH", "/v1/events/objectives", results_objective_fingerprint) results_objective_save_response = call("rate_objective", {}, results_objective_patch, None) require_condition(equal(response_status(results_objective_save_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome.") results_objective_receipt = results_objective_save_response["body"] results_objective_after_revision = text(field(results_objective_receipt, "record_revision")) require_condition(is_present(results_objective_after_revision), "A checked save acknowledgement requires its own returned record_revision.") journal_acknowledge(results_job, "rate_objective", {"id": results_objective_id, "achievement_rating": results_rating, "record_revision": results_objective_after_revision, "event_id": results_event_id}) results_event_verify_response = call("verify_event", {"id": results_event_id}, None, None) require_condition(equal(response_status(results_event_verify_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome.") results_event_verified = results_event_verify_response["body"] require_condition(both(equal(text(field(results_event_verified, "id")), results_event_id), equal(text(field(results_event_verified, "roi_num_leads")), results_lead_count)), "The final Event no longer has the acknowledged leads value; inspect it instead of automatically restoring it.") results_objective_verify_response = call("verify_objective", {"id": results_objective_id}, None, None) require_condition(equal(response_status(results_objective_verify_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome.") results_objective_verified = results_objective_verify_response["body"] require_condition(both(equal(text(field(results_objective_verified, "id")), results_objective_id), both(equal(text(field(results_objective_verified, "event_id")), results_event_id), equal(text(field(results_objective_verified, "achievement_rating")), results_rating))), "The final Objective is missing, rebound or has another rating; earlier saved steps remain in the journal.") print_value({"event_id": results_event_id, "objective_id": results_objective_id, "roi_num_leads": results_lead_count, "achievement_rating": results_rating}) finally: results_job.close() if __name__ == "__main__": main() EXHIBITDAY_PY ``` ```javascript // Server-side Node.js with fetch; built-in modules only. Set EXHIBITDAY_API_KEY. const BASE = "https://api.exhibitday.com/v1"; const SPEC = JSON.parse("{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"read_event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"read_objective\":{\"method\":\"GET\",\"path\":\"/events/objectives/info\"},\"save_leads\":{\"method\":\"PATCH\",\"path\":\"/events\"},\"rate_objective\":{\"method\":\"PATCH\",\"path\":\"/events/objectives\"},\"verify_event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"verify_objective\":{\"method\":\"GET\",\"path\":\"/events/objectives/info\"}}}"); const API_KEY = process.env.EXHIBITDAY_API_KEY; if (!API_KEY || !API_KEY.trim()) throw new Error("Set EXHIBITDAY_API_KEY"); if (/[^\x20-\x7e]/.test(API_KEY)) throw new Error("Use the API key as one ASCII header value without control characters"); 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, errors: result.errors, error_params: result.error_params, 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, key = null) { const route = SPEC.requests[name]; const headers = { Authorization: "Bearer " + API_KEY, Accept: "application/json" }; if (route.method === "POST") { if (!key) throw new Error("Persist a logical create key before sending POST"); headers["Idempotency-Key"] = key; } 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 : ""); // 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. const resend = route.method === "GET"; 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 = resend && (response.status === 429 || response.status >= 500); 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, raw }; } throw new Error("Retry limit reached"); } function both(left,right) { return left && right; } function bounded_whole_number(value,name,maximum) { if (!/^(?:0|[1-9][0-9]*)(?![\s\S])/.test(value) || value.length>maximum.length || (value.length===maximum.length && value>maximum)) throw new Error(name+" must be a whole number from 0 through "+maximum); return value; } function either(left, right) { if (typeof left !== "boolean" || typeof right !== "boolean") throw new Error("Expected Boolean criteria"); return left || right; } function equal(left, right) { return typeof left === typeof right && left === right; } function field(value, name) { if (!value || Array.isArray(value) || typeof value !== "object" || !Object.hasOwn(value, name)) throw new Error("Missing response field: " + name); return value[name]; } function is_present(value) { return value !== null && value !== undefined && value !== ""; } 'use strict'; // Private client restart state. No HTTP or application dependency. const fs = require('node:fs'); const crypto = require('node:crypto'); const PREAMBLE = Buffer.from('EXHIBITDAY-GUIDE-JOURNAL 1\n', 'ascii'); class JournalRefusal extends Error {} function ascii(raw) { if (raw.some(value => value > 127)) throw new JournalRefusal('Journal framing must be canonical ASCII'); return raw.toString('ascii'); } function utf8(value) { if (typeof value !== 'string') throw new JournalRefusal('Journal fields are exact strings'); for (const unit of value) if (unit.length === 1 && unit.charCodeAt(0) >= 0xd800 && unit.charCodeAt(0) <= 0xdfff) throw new JournalRefusal('Invalid Unicode journal field'); return Buffer.from(value, 'utf8'); } function strings(values) { const parts = []; for (const value of values) { const raw = utf8(value); parts.push(Buffer.from(String(raw.length) + ':', 'ascii'), raw); } return Buffer.concat(parts); } function readStrings(raw) { const values = []; let offset = 0; while (offset < raw.length) { const end = raw.indexOf(58, offset); if (end < 0) throw new JournalRefusal('Incomplete journal string length'); const length = ascii(raw.subarray(offset, end)); if (!/^(0|[1-9][0-9]*)$/.test(length)) throw new JournalRefusal('Noncanonical journal string length'); const size = BigInt(length); offset = end + 1; if (size > BigInt(raw.length - offset)) throw new JournalRefusal('Incomplete journal string'); const count = Number(size); values.push(new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(raw.subarray(offset, offset + count))); offset += count; } return values; } function digest(raw) { return crypto.createHash('sha256').update(raw).digest('hex').toUpperCase(); } function fingerprint(pairs) { const values = []; for (const name of Object.keys(pairs).sort()) { if (!/^[A-Za-z0-9_.-]+$/.test(name) || ['api_key', 'exhibitday_api_key'].includes(name.toLowerCase())) throw new JournalRefusal('Use explicit secret-free fingerprint field names'); values.push(name, pairs[name]); } return digest(strings(values)); } function frame(values) { const raw = strings(values); return Buffer.concat([Buffer.from(String(raw.length) + ' ' + digest(raw) + '\n', 'ascii'), raw, Buffer.from('\n')]); } function decode(raw) { if (!raw.subarray(0, PREAMBLE.length).equals(PREAMBLE)) throw new JournalRefusal('Unknown or incomplete journal version'); let offset = PREAMBLE.length; const records = []; while (offset < raw.length) { const end = raw.indexOf(10, offset); if (end < 0) throw new JournalRefusal('Incomplete journal frame header; reconcile before retry'); const match = /^(0|[1-9][0-9]*) ([0-9A-F]{64})$/.exec(ascii(raw.subarray(offset, end))); if (!match) throw new JournalRefusal('Invalid journal frame header'); const size = BigInt(match[1]); offset = end + 1; if (size >= BigInt(raw.length - offset)) throw new JournalRefusal('Incomplete journal frame; reconcile before retry'); const count = Number(size), payload = raw.subarray(offset, offset + count); offset += count; if (raw[offset] !== 10 || digest(payload) !== match[2]) throw new JournalRefusal('Journal integrity check failed; reconcile before retry'); records.push(readStrings(payload)); offset++; } return records; } function writeAll(fd, raw) { let offset = 0; while (offset < raw.length) { const count = fs.writeSync(fd, raw, offset, raw.length - offset); if (!count) throw new Error('Journal write did not advance'); offset += count; } } function same(left, right) { return left.length === right.length && left.every((value, index) => value === right[index]); } class Journal { constructor(path, base, workspace, slug, job, inputFingerprint, writes, mode = 'resume') { this.path = path; this.lock = path + '.lock'; this.fd = null; this.owned = false; this.identity = null; this.tainted = false; this.intents = new Map(); this.savedValues = new Map(); this.allowed = new Map(); if (!['new', 'resume'].includes(mode)) throw new JournalRefusal('Choose new or resume for this local job'); const address = new URL(base); if (!['https:', 'http:'].includes(address.protocol) || !address.hostname || address.username || address.password || address.search || address.hash || !/^[a-z][a-z0-9-]*$/.test(slug)) throw new JournalRefusal('Use the actual API base and closed guide slug'); if (!job.trim() || !/^[1-9][0-9]*$/.test(workspace) || !/^[0-9A-F]{64}$/.test(inputFingerprint)) throw new JournalRefusal('Use an actual workspace, stable explicit job ID and exact input fingerprint'); const manifest = []; for (const [step, method, route] of writes) { if (!/^[a-z][a-z0-9_-]*$/.test(step) || this.allowed.has(step) || !['POST', 'PATCH', 'DELETE'].includes(method) || !/^\/v1\/[A-Za-z0-9_/-]+$/.test(route) || route.includes('//')) throw new JournalRefusal('Use a closed unique write manifest'); this.allowed.set(step, [method, route]); manifest.push(step, method, route); } if (!this.allowed.size) throw new JournalRefusal('Only write workflows need a restart journal'); this.header = ['H', '1', base, workspace, slug, job, inputFingerprint, digest(strings(manifest))]; strings(this.header); try { this.fd = fs.openSync(this.lock, 'wx', 0o600); this.owned = true; } catch (error) { if (error.code === 'EEXIST') throw new JournalRefusal('This journal is locked; do not overlap jobs or steal a stale lock'); throw error; } try { this.owner = crypto.randomBytes(16).toString('hex'); this.identity = fs.fstatSync(this.fd, { bigint: true }); writeAll(this.fd, Buffer.from(this.owner, 'ascii')); fs.fsyncSync(this.fd); let exists = true; try { if (fs.lstatSync(path).isSymbolicLink()) throw new JournalRefusal('Choose a private regular journal file'); } catch (error) { if (error.code === 'ENOENT') exists = false; else throw error; } if (mode === 'resume' && !exists) throw new JournalRefusal('Journal missing: stop and reconcile lost state before starting a new logical job'); if (mode === 'new' && exists) throw new JournalRefusal('Journal already exists; use resume for the same logical job'); if (mode === 'new') { const target = fs.openSync(path, 'wx', 0o600); try { writeAll(target, Buffer.concat([PREAMBLE, frame(this.header)])); fs.fsyncSync(target); } finally { fs.closeSync(target); } } const records = decode(fs.readFileSync(path)); if (!records.length || !same(records[0], this.header)) throw new JournalRefusal('Journal workspace/base/guide/job/input binding differs'); for (const record of records.slice(1)) this.apply(record); if ([...this.intents.keys()].some(step => !this.savedValues.has(step))) throw new JournalRefusal('Saved before-send intent lacks ACK; stop and reconcile before retry'); } catch (error) { this.close(); throw error; } } apply(record) { if (record[0] === 'I') { if (record.length !== 6) throw new JournalRefusal('Invalid intent shape'); const [, step, method, path, requestFingerprint, key] = record; if (!/^[a-z][a-z0-9_-]*$/.test(step) || this.intents.has(step) || !this.allowed.has(step) || !same(this.allowed.get(step), [method, path]) || !/^[0-9A-F]{64}$/.test(requestFingerprint) || [...this.intents.keys()].some(name => !this.savedValues.has(name))) throw new JournalRefusal('Invalid, future or repeated intent'); if ((method === 'POST' && !/^[0-9a-f]{32}$/.test(key)) || (method !== 'POST' && key !== '')) throw new JournalRefusal('Invalid persisted action key'); this.intents.set(step, { method, path, request_fingerprint: requestFingerprint, idempotency_key: key }); } else if (record[0] === 'A') { const [, step, count, ...pairs] = record; if (record.length < 3 || !/^(0|[1-9][0-9]*)$/.test(count) || BigInt(pairs.length) !== 2n * BigInt(count) || !this.intents.has(step) || this.savedValues.has(step)) throw new JournalRefusal('ACK without exactly one prior intent'); const names = pairs.filter((_, index) => index % 2 === 0); if (!same(names, [...new Set(names)].sort()) || names.some(name => !/^[a-z][a-z0-9_]*$/.test(name) || ['api_key', 'exhibitday_api_key'].includes(name))) throw new JournalRefusal('ACK fields must be unique sorted secret-free identifiers'); this.savedValues.set(step, Object.fromEntries(names.map((name, index) => [name, pairs[index * 2 + 1]]))); } else throw new JournalRefusal('Unknown journal transition'); } requireActive() { if (!this.owned || this.fd === null || this.identity === null || this.tainted) throw new JournalRefusal('Journal is closed or its IO outcome needs reconciliation'); const current = fs.lstatSync(this.lock, { bigint: true }); if (current.dev !== this.identity.dev || current.ino !== this.identity.ino || ascii(fs.readFileSync(this.lock)) !== this.owner) throw new JournalRefusal('Journal lock was replaced; stop without deleting it'); } append(record) { this.requireActive(); const raw = frame(record); let target; try { target = fs.openSync(this.path, 'a'); writeAll(target, raw); fs.fsyncSync(target); } catch (error) { this.tainted = true; throw error; } finally { if (target !== undefined) fs.closeSync(target); } } acknowledged(step) { this.requireActive(); return this.savedValues.has(step); } saved(step) { this.requireActive(); if (!this.savedValues.has(step)) throw new JournalRefusal('No acknowledged state exists'); return { ...this.savedValues.get(step) }; } begin(step, method, path, requestFingerprint) { this.requireActive(); if (this.intents.has(step)) throw new JournalRefusal('Never blindly repeat an existing action'); const key = method === 'POST' ? crypto.randomBytes(16).toString('hex') : '', record = ['I', step, method, path, requestFingerprint, key]; const old = new Map(this.intents); try { this.apply(record); } finally { this.intents = old; } this.append(record); this.apply(record); return { ...this.intents.get(step) }; } acknowledge(step, saved) { this.requireActive(); const names = Object.keys(saved).sort(), record = ['A', step, String(names.length)]; for (const name of names) record.push(name, saved[name]); const old = new Map(this.savedValues); try { this.apply(record); strings(record); } finally { this.savedValues = old; } this.append(record); this.apply(record); } close() { if (!this.owned) return; if (this.tainted) { fs.closeSync(this.fd); this.fd = null; this.owned = false; return; } try { this.requireActive(); } catch (error) { fs.closeSync(this.fd); this.fd = null; this.owned = false; throw error; } fs.closeSync(this.fd); this.fd = null; this.owned = false; fs.unlinkSync(this.lock); } } function journal_values(value) { if (!value || typeof value !== 'object' || Array.isArray(value) || Object.values(value).some(item=>typeof item!=='string')) throw new JournalRefusal('Saved/fingerprint values must be exact strings'); return {...value}; } function journal_acknowledge(job,step,saved) { job.acknowledge(step,journal_values(saved)); } function journal_acknowledged(job,step) { return job.acknowledged(step); } function journal_begin(job,step,method,path,requestFingerprint) { return job.begin(step,method,path,requestFingerprint); } function journal_fingerprint(value) { return fingerprint(journal_values(value)); } function journal_saved(job,step) { return job.saved(step); } function not_value(value) { if (typeof value !== "boolean") throw new Error("Expected a Boolean"); return !value; } function open_journal(path,base,workspace,slug,job,inputFingerprint,writes,mode) { return new Journal(path,base,workspace,slug,job,inputFingerprint,writes,mode); } function optional(name, fallback) { const value = process.env[name]; return value === undefined || value === "" ? fallback : value; } function positive_id(value) { if (!/^[1-9][0-9]*$/.test(value) || BigInt(value) > 9223372036854775807n) throw new Error("Use a positive record ID"); return value; } function print_value(value) { console.log(typeof value === "string" ? value : JSON.stringify(value)); } function require_condition(value, message) { if (value !== true) throw new Error(message); } function required(name) { const value = process.env[name]; if (value === undefined || !value.trim()) throw new Error("Set " + name); return value; } function response_status(value) { return String(value.status); } function text(value) { if (value === null || value === undefined) return ""; if (["string", "boolean", "bigint"].includes(typeof value)) return String(value); throw new Error("Expected a scalar response value"); } async function main() { let results_event_id = positive_id(required("EXHIBITDAY_EVENT_ID")); let results_objective_id = positive_id(required("EXHIBITDAY_OBJECTIVE_ID")); let results_lead_count = bounded_whole_number(required("EXHIBITDAY_LEAD_COUNT"), "EXHIBITDAY_LEAD_COUNT", "9223372036854775807"); let results_rating = bounded_whole_number(required("EXHIBITDAY_ACHIEVEMENT_RATING"), "EXHIBITDAY_ACHIEVEMENT_RATING", "10"); let results_journal_path = required("EXHIBITDAY_JOURNAL"); let results_job_id = required("EXHIBITDAY_JOB_ID"); let results_job_mode = optional("EXHIBITDAY_JOB_MODE", "resume"); let results_workspace_response = await call("workspace_binding", {}, null, null); require_condition(equal(response_status(results_workspace_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome."); let results_workspace = results_workspace_response.body; let results_workspace_id = positive_id(text(field(results_workspace, "id"))); let results_event_response = await call("read_event", {"id": results_event_id, "$include_record_revision": "true"}, null, null); require_condition(equal(response_status(results_event_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome."); let results_event = results_event_response.body; require_condition(equal(text(field(results_event, "id")), results_event_id), "Read the exact selected Event before recording results."); let results_leads_revision = text(field(results_event, "record_revision")); require_condition(is_present(results_leads_revision), "The Event read needs its own actual record_revision."); let results_objective_response = await call("read_objective", {"id": results_objective_id, "$include_record_revision": "true"}, null, null); require_condition(equal(response_status(results_objective_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome."); let results_objective = results_objective_response.body; require_condition(both(equal(text(field(results_objective, "id")), results_objective_id), equal(text(field(results_objective, "event_id")), results_event_id)), "The Objective does not belong to the selected Event; no write was sent."); let results_objective_revision = text(field(results_objective, "record_revision")); require_condition(is_present(results_objective_revision), "The Objective read needs its own actual record_revision."); let results_input_fingerprint = journal_fingerprint({"workflow_contract_sha256": "94A1426B8C4D275633E918271BB2A2683E06A442317C472320B2E446E00ABCF6", "event_id": results_event_id, "objective_id": results_objective_id, "roi_num_leads": results_lead_count, "achievement_rating": results_rating}); let results_job = open_journal(results_journal_path, "https://api.exhibitday.com/v1", results_workspace_id, "show-results-objectives", results_job_id, results_input_fingerprint, [["save_leads", "PATCH", "/v1/events"], ["rate_objective", "PATCH", "/v1/events/objectives"]], results_job_mode); try { require_condition(either(not_value(journal_acknowledged(results_job, "rate_objective")), journal_acknowledged(results_job, "save_leads")), "A future results step is acknowledged before its prerequisite. Stop and reconcile the journal."); if (journal_acknowledged(results_job, "save_leads")) { let results_leads_saved = journal_saved(results_job, "save_leads"); require_condition(both(equal(text(field(results_leads_saved, "id")), results_event_id), equal(text(field(results_leads_saved, "roi_num_leads")), results_lead_count)), "Acknowledged results state does not match the selected record and intended value; stop and reconcile."); } else { let results_leads_patch = {"id": results_event_id, "roi_num_leads": results_lead_count, "expected_revision": results_leads_revision}; let results_leads_fingerprint = journal_fingerprint({"id": results_event_id, "roi_num_leads": results_lead_count, "expected_revision": results_leads_revision}); journal_begin(results_job, "save_leads", "PATCH", "/v1/events", results_leads_fingerprint); let results_leads_save_response = await call("save_leads", {}, results_leads_patch, null); require_condition(equal(response_status(results_leads_save_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome."); let results_leads_receipt = results_leads_save_response.body; let results_leads_after_revision = text(field(results_leads_receipt, "record_revision")); require_condition(is_present(results_leads_after_revision), "A checked save acknowledgement requires its own returned record_revision."); journal_acknowledge(results_job, "save_leads", {"id": results_event_id, "roi_num_leads": results_lead_count, "record_revision": results_leads_after_revision}); } if (journal_acknowledged(results_job, "rate_objective")) { let results_objective_saved = journal_saved(results_job, "rate_objective"); require_condition(both(both(equal(text(field(results_objective_saved, "id")), results_objective_id), equal(text(field(results_objective_saved, "achievement_rating")), results_rating)), equal(text(field(results_objective_saved, "event_id")), results_event_id)), "Acknowledged results state does not match the selected record and intended value; stop and reconcile."); } else { let results_objective_patch = {"id": results_objective_id, "achievement_rating": results_rating, "expected_revision": results_objective_revision}; let results_objective_fingerprint = journal_fingerprint({"id": results_objective_id, "achievement_rating": results_rating, "expected_revision": results_objective_revision}); journal_begin(results_job, "rate_objective", "PATCH", "/v1/events/objectives", results_objective_fingerprint); let results_objective_save_response = await call("rate_objective", {}, results_objective_patch, null); require_condition(equal(response_status(results_objective_save_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome."); let results_objective_receipt = results_objective_save_response.body; let results_objective_after_revision = text(field(results_objective_receipt, "record_revision")); require_condition(is_present(results_objective_after_revision), "A checked save acknowledgement requires its own returned record_revision."); journal_acknowledge(results_job, "rate_objective", {"id": results_objective_id, "achievement_rating": results_rating, "record_revision": results_objective_after_revision, "event_id": results_event_id}); } let results_event_verify_response = await call("verify_event", {"id": results_event_id}, null, null); require_condition(equal(response_status(results_event_verify_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome."); let results_event_verified = results_event_verify_response.body; require_condition(both(equal(text(field(results_event_verified, "id")), results_event_id), equal(text(field(results_event_verified, "roi_num_leads")), results_lead_count)), "The final Event no longer has the acknowledged leads value; inspect it instead of automatically restoring it."); let results_objective_verify_response = await call("verify_objective", {"id": results_objective_id}, null, null); require_condition(equal(response_status(results_objective_verify_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome."); let results_objective_verified = results_objective_verify_response.body; require_condition(both(equal(text(field(results_objective_verified, "id")), results_objective_id), both(equal(text(field(results_objective_verified, "event_id")), results_event_id), equal(text(field(results_objective_verified, "achievement_rating")), results_rating))), "The final Objective is missing, rebound or has another rating; earlier saved steps remain in the journal."); print_value({"event_id": results_event_id, "objective_id": results_objective_id, "roi_num_leads": results_lead_count, "achievement_rating": results_rating}); } finally { results_job.close(); } } if (require.main === module) main().catch(error => { console.error(error.message); process.exitCode = 1; }); module.exports = { main }; ``` ```python # Python 3; standard library only. Set EXHIBITDAY_API_KEY before running. import http.client import json import os import re import time import urllib.error import urllib.parse import urllib.request BASE = "https://api.exhibitday.com/v1" SPEC = json.loads("{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"read_event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"read_objective\":{\"method\":\"GET\",\"path\":\"/events/objectives/info\"},\"save_leads\":{\"method\":\"PATCH\",\"path\":\"/events\"},\"rate_objective\":{\"method\":\"PATCH\",\"path\":\"/events/objectives\"},\"verify_event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"verify_objective\":{\"method\":\"GET\",\"path\":\"/events/objectives/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) 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, key=None): route = SPEC["requests"][name] headers = {"Authorization": "Bearer " + API_KEY, "Accept": "application/json"} if route["method"] == "POST": if not key: raise RuntimeError("Persist a logical create key before sending POST") headers["Idempotency-Key"] = key data = None if body is None else json.dumps(body).encode("utf-8") if data is not None: headers["Content-Type"] = "application/json" query = urllib.parse.urlencode(params or {}) url = BASE + route["path"] + ("?" + query if query else "") # Only GET has automatic retries in this workflow. A PATCH or DELETE that got no response or a # server error is never resent blindly: it may already have been applied, so the caller reads the record first. resend = route["method"] == "GET" for attempt in range(5): try: status, raw, response_headers = transport(route["method"], url, headers, data) except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException): if not resend: raise ApiError(0, None, uncertain=True) if attempt == 4: raise time.sleep(2 ** attempt) continue response_headers = {k.lower(): v for k, v in response_headers.items()} result = None if status != 304 and raw: try: result = decode_json(raw.decode("utf-8")) except (ValueError, UnicodeError): if status < 400: raise RuntimeError("Expected a JSON success response") if status >= 500 and not resend: raise ApiError(status, result, uncertain=True) retry = resend and (status == 429 or status >= 500) if retry: if attempt == 4: raise RuntimeError("Retry limit reached; check the request outcome before starting a new create") delay = response_headers.get("retry-after", str(2 ** attempt)) time.sleep(max(0, float(delay))) continue if status >= 400: raise ApiError(status, result) return {"status": status, "body": result, "headers": response_headers, "raw": raw} raise RuntimeError("Retry limit reached") def both(left,right): return left and right def bounded_whole_number(value, name, maximum): if not re.fullmatch(r"0|[1-9][0-9]*", value) or len(value)>len(maximum) or (len(value)==len(maximum) and value>maximum): raise RuntimeError(name+" must be a whole number from 0 through "+maximum) return value 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] 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 offsetlen(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)-offset:raise JournalRefusal('Incomplete journal frame; reconcile before retry') payload=raw[offset:offset+size];offset+=size if raw[offset:offset+1]!=b'\n' or digest(payload).encode('ascii')!=match[2]:raise JournalRefusal('Journal integrity check failed; reconcile before retry') records.append(read_strings(payload));offset+=1 return records class Journal: def __init__(self,path,base,workspace,slug,job,input_fingerprint,writes,mode="resume"): self.path=Path(path);self.lock=Path(str(self.path)+'.lock');self.fd=None;self.owned=False;self.identity=None;self.tainted=False;self.intents={};self.saved_values={} address=urlsplit(base) if address.scheme not in ('https','http')or not address.netloc or address.username is not None or address.query or address.fragment or not re.fullmatch('[a-z][a-z0-9-]*',slug):raise JournalRefusal('Use the actual API base and closed guide slug') if not job.strip() or not re.fullmatch('[1-9][0-9]*',workspace) or not re.fullmatch('[0-9A-F]{64}',input_fingerprint):raise JournalRefusal('Use an actual workspace, explicit stable job ID and exact input fingerprint') if mode not in ("new","resume"):raise JournalRefusal("Choose new or resume for this local job") self.allowed={};manifest=[] for step,method,route in writes: if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.allowed or method not in ('POST','PATCH','DELETE')or not re.fullmatch('/v1/[A-Za-z0-9_/-]+',route)or'//'in route:raise JournalRefusal('Use a closed unique write manifest') self.allowed[step]=(method,route);manifest.extend((step,method,route)) if not self.allowed:raise JournalRefusal('Only write workflows need a restart journal') self.header=['H','1',base,workspace,slug,job,input_fingerprint,digest(strings(manifest))] strings(self.header) try: self.fd=os.open(self.lock,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600);self.owned=True except FileExistsError:raise JournalRefusal('This journal is locked; do not run overlapping jobs or steal a stale lock') try: self.owner=secrets.token_hex(16);self.identity=os.fstat(self.fd) if os.write(self.fd,self.owner.encode('ascii'))!=len(self.owner):raise OSError('Incomplete lock identity write') os.fsync(self.fd) if self.path.is_symlink():raise JournalRefusal('Choose a private regular journal file') if mode=="resume" and not self.path.exists():raise JournalRefusal("Journal missing: stop and reconcile lost state before starting a new logical job") if mode=="new" and self.path.exists():raise JournalRefusal("A journal already exists; use resume for the same logical job") if mode=="new": with open(self.path,'xb',buffering=0)as target: target.write(PREAMBLE+frame(self.header));os.fsync(target.fileno()) records=decode(self.path.read_bytes()) if not records or records[0]!=self.header:raise JournalRefusal('Journal workspace/base/guide/job/input binding differs') for record in records[1:]:self.apply(record) if any(step not in self.saved_values for step in self.intents):raise JournalRefusal('A saved before-send intent lacks an ACK; stop and reconcile its outcome before retry') except BaseException: self.close();raise def apply(self,record): if not record:raise JournalRefusal('Empty journal record') if record[0]=='I': if len(record)!=6:raise JournalRefusal('Invalid intent shape') _,step,method,path,request_fingerprint,key=record if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.intents or self.allowed.get(step)!=(method,path)or not re.fullmatch('[0-9A-F]{64}',request_fingerprint)or any(name not in self.saved_values for name in self.intents):raise JournalRefusal('Invalid, future or repeated journal intent') if method=='POST'and not re.fullmatch('[0-9a-f]{32}',key)or method!='POST'and key!='':raise JournalRefusal('Invalid persisted action key') self.intents[step]={'method':method,'path':path,'request_fingerprint':request_fingerprint,'idempotency_key':key} elif record[0]=='A': if len(record)<3:raise JournalRefusal('Invalid ACK shape') _,step,count,*pairs=record if not re.fullmatch('0|[1-9][0-9]*',count)or len(pairs)!=2*int(count)or step not in self.intents or step in self.saved_values:raise JournalRefusal('ACK without exactly one prior intent') names=pairs[::2] if names!=sorted(set(names))or any(not re.fullmatch('[a-z][a-z0-9_]*',name)or name in ('api_key','exhibitday_api_key')for name in names):raise JournalRefusal('ACK saved fields must be unique sorted secret-free identifiers') self.saved_values[step]=dict(zip(names,pairs[1::2])) else:raise JournalRefusal('Unknown journal transition') def append(self,record): # The reader commits state only after complete length/digest recognition. # A torn append is retained and refused, never silently truncated. self.require_active();raw=frame(record) try: with open(self.path,'ab',buffering=0)as target: view=memoryview(raw) while view: written=target.write(view) if not written:raise OSError('Journal write did not advance') view=view[written:] os.fsync(target.fileno()) except BaseException: self.tainted=True;raise def require_active(self): if not self.owned or self.fd is None or self.identity is None or self.tainted:raise JournalRefusal('The journal scope is closed or its IO outcome needs reconciliation') current=self.lock.stat(follow_symlinks=False) if current.st_dev!=self.identity.st_dev or current.st_ino!=self.identity.st_ino or self.lock.read_text(encoding='ascii')!=self.owner:raise JournalRefusal('The journal lock was replaced; stop without deleting it') def acknowledged(self,step): self.require_active();return step in self.saved_values def saved(self,step): self.require_active() if step not in self.saved_values:raise JournalRefusal('No acknowledged state exists for this step') return dict(self.saved_values[step]) def begin(self,step,method,path,request_fingerprint): self.require_active() if step in self.intents:raise JournalRefusal('Never blindly repeat an existing action intent') key=secrets.token_hex(16)if method=='POST'else'' record=['I',step,method,path,request_fingerprint,key] # Validate on an isolated state before touching the file. old=dict(self.intents) try:self.apply(record) finally:self.intents=old self.append(record);self.apply(record) return dict(self.intents[step]) def acknowledge(self,step,saved): self.require_active() record=['A',step,str(len(saved))] for name,value in sorted(saved.items()):record.extend((name,value)) old={name:dict(value)for name,value in self.saved_values.items()} try:self.apply(record);strings(record) finally:self.saved_values=old self.append(record);self.apply(record) def close(self): if self.owned: if self.tainted: os.close(self.fd);self.fd=None;self.owned=False return # Retain this lock after failed journal IO; manual reconciliation is required. try:self.require_active() except BaseException: os.close(self.fd);self.fd=None;self.owned=False;raise os.close(self.fd);self.fd=None;self.owned=False self.lock.unlink() def __enter__(self):return self def __exit__(self,*args):self.close() def journal_values(value): if not isinstance(value, dict) or any(not isinstance(k, str) or not isinstance(v, str) for k,v in value.items()): raise JournalRefusal('Saved/fingerprint values must be exact string fields') return dict(value) def journal_acknowledge(job, step, saved): job.acknowledge(step,journal_values(saved)) def journal_acknowledged(job, step): return job.acknowledged(step) def journal_begin(job, step, method, path, request_fingerprint): return job.begin(step,method,path,request_fingerprint) def journal_fingerprint(value): return fingerprint(journal_values(value)) def journal_saved(job, step): return job.saved(step) def 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 positive_id(value): if not re.fullmatch(r"[1-9][0-9]*", value) or int(value) > 9223372036854775807: raise RuntimeError("Use a positive record ID") return value def print_value(value): print(value if isinstance(value, str) else json.dumps(value, ensure_ascii=False)) def require_condition(value, message): if value is not True: raise RuntimeError(message) def required(name): value = os.environ.get(name) if value is None or not value.strip(): raise RuntimeError("Set " + name) return value def response_status(value): return str(value["status"]) def 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(): results_event_id = positive_id(required("EXHIBITDAY_EVENT_ID")) results_objective_id = positive_id(required("EXHIBITDAY_OBJECTIVE_ID")) results_lead_count = bounded_whole_number(required("EXHIBITDAY_LEAD_COUNT"), "EXHIBITDAY_LEAD_COUNT", "9223372036854775807") results_rating = bounded_whole_number(required("EXHIBITDAY_ACHIEVEMENT_RATING"), "EXHIBITDAY_ACHIEVEMENT_RATING", "10") results_journal_path = required("EXHIBITDAY_JOURNAL") results_job_id = required("EXHIBITDAY_JOB_ID") results_job_mode = optional("EXHIBITDAY_JOB_MODE", "resume") results_workspace_response = call("workspace_binding", {}, None, None) require_condition(equal(response_status(results_workspace_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome.") results_workspace = results_workspace_response["body"] results_workspace_id = positive_id(text(field(results_workspace, "id"))) results_event_response = call("read_event", {"id": results_event_id, "$include_record_revision": "true"}, None, None) require_condition(equal(response_status(results_event_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome.") results_event = results_event_response["body"] require_condition(equal(text(field(results_event, "id")), results_event_id), "Read the exact selected Event before recording results.") results_leads_revision = text(field(results_event, "record_revision")) require_condition(is_present(results_leads_revision), "The Event read needs its own actual record_revision.") results_objective_response = call("read_objective", {"id": results_objective_id, "$include_record_revision": "true"}, None, None) require_condition(equal(response_status(results_objective_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome.") results_objective = results_objective_response["body"] require_condition(both(equal(text(field(results_objective, "id")), results_objective_id), equal(text(field(results_objective, "event_id")), results_event_id)), "The Objective does not belong to the selected Event; no write was sent.") results_objective_revision = text(field(results_objective, "record_revision")) require_condition(is_present(results_objective_revision), "The Objective read needs its own actual record_revision.") results_input_fingerprint = journal_fingerprint({"workflow_contract_sha256": "94A1426B8C4D275633E918271BB2A2683E06A442317C472320B2E446E00ABCF6", "event_id": results_event_id, "objective_id": results_objective_id, "roi_num_leads": results_lead_count, "achievement_rating": results_rating}) results_job = open_journal(results_journal_path, "https://api.exhibitday.com/v1", results_workspace_id, "show-results-objectives", results_job_id, results_input_fingerprint, [["save_leads", "PATCH", "/v1/events"], ["rate_objective", "PATCH", "/v1/events/objectives"]], results_job_mode) try: require_condition(either(not_value(journal_acknowledged(results_job, "rate_objective")), journal_acknowledged(results_job, "save_leads")), "A future results step is acknowledged before its prerequisite. Stop and reconcile the journal.") if journal_acknowledged(results_job, "save_leads"): results_leads_saved = journal_saved(results_job, "save_leads") require_condition(both(equal(text(field(results_leads_saved, "id")), results_event_id), equal(text(field(results_leads_saved, "roi_num_leads")), results_lead_count)), "Acknowledged results state does not match the selected record and intended value; stop and reconcile.") else: results_leads_patch = {"id": results_event_id, "roi_num_leads": results_lead_count, "expected_revision": results_leads_revision} results_leads_fingerprint = journal_fingerprint({"id": results_event_id, "roi_num_leads": results_lead_count, "expected_revision": results_leads_revision}) journal_begin(results_job, "save_leads", "PATCH", "/v1/events", results_leads_fingerprint) results_leads_save_response = call("save_leads", {}, results_leads_patch, None) require_condition(equal(response_status(results_leads_save_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome.") results_leads_receipt = results_leads_save_response["body"] results_leads_after_revision = text(field(results_leads_receipt, "record_revision")) require_condition(is_present(results_leads_after_revision), "A checked save acknowledgement requires its own returned record_revision.") journal_acknowledge(results_job, "save_leads", {"id": results_event_id, "roi_num_leads": results_lead_count, "record_revision": results_leads_after_revision}) if journal_acknowledged(results_job, "rate_objective"): results_objective_saved = journal_saved(results_job, "rate_objective") require_condition(both(both(equal(text(field(results_objective_saved, "id")), results_objective_id), equal(text(field(results_objective_saved, "achievement_rating")), results_rating)), equal(text(field(results_objective_saved, "event_id")), results_event_id)), "Acknowledged results state does not match the selected record and intended value; stop and reconcile.") else: results_objective_patch = {"id": results_objective_id, "achievement_rating": results_rating, "expected_revision": results_objective_revision} results_objective_fingerprint = journal_fingerprint({"id": results_objective_id, "achievement_rating": results_rating, "expected_revision": results_objective_revision}) journal_begin(results_job, "rate_objective", "PATCH", "/v1/events/objectives", results_objective_fingerprint) results_objective_save_response = call("rate_objective", {}, results_objective_patch, None) require_condition(equal(response_status(results_objective_save_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome.") results_objective_receipt = results_objective_save_response["body"] results_objective_after_revision = text(field(results_objective_receipt, "record_revision")) require_condition(is_present(results_objective_after_revision), "A checked save acknowledgement requires its own returned record_revision.") journal_acknowledge(results_job, "rate_objective", {"id": results_objective_id, "achievement_rating": results_rating, "record_revision": results_objective_after_revision, "event_id": results_event_id}) results_event_verify_response = call("verify_event", {"id": results_event_id}, None, None) require_condition(equal(response_status(results_event_verify_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome.") results_event_verified = results_event_verify_response["body"] require_condition(both(equal(text(field(results_event_verified, "id")), results_event_id), equal(text(field(results_event_verified, "roi_num_leads")), results_lead_count)), "The final Event no longer has the acknowledged leads value; inspect it instead of automatically restoring it.") results_objective_verify_response = call("verify_objective", {"id": results_objective_id}, None, None) require_condition(equal(response_status(results_objective_verify_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome.") results_objective_verified = results_objective_verify_response["body"] require_condition(both(equal(text(field(results_objective_verified, "id")), results_objective_id), both(equal(text(field(results_objective_verified, "event_id")), results_event_id), equal(text(field(results_objective_verified, "achievement_rating")), results_rating))), "The final Objective is missing, rebound or has another rating; earlier saved steps remain in the journal.") print_value({"event_id": results_event_id, "objective_id": results_objective_id, "roi_num_leads": results_lead_count, "achievement_rating": results_rating}) finally: results_job.close() if __name__ == "__main__": main() ``` ```csharp // .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\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"read_event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"read_objective\":{\"method\":\"GET\",\"path\":\"/events/objectives/info\"},\"save_leads\":{\"method\":\"PATCH\",\"path\":\"/events\"},\"rate_objective\":{\"method\":\"PATCH\",\"path\":\"/events/objectives\"},\"verify_event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"verify_objective\":{\"method\":\"GET\",\"path\":\"/events/objectives/info\"}}}"); static readonly string ApiKey = HeaderKey(Required("EXHIBITDAY_API_KEY")); static string HeaderKey(string value) { if(value.Any(c=>c<32||c>126))throw new Exception("Use the API key as one ASCII header value without control characters");return value; } static readonly HttpClient Client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false }) { Timeout = TimeSpan.FromSeconds(30) }; internal static Func> Send = request => Client.SendAsync(request); sealed class Result { public int Status; public JsonNode Body; public Dictionary Headers; public string Raw; } // 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(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 Call(string name, JsonObject query = null, JsonNode body = null, string key = null) { var route = Spec["requests"][name]; var method = Text(route["method"]); var headers = new Dictionary(StringComparer.OrdinalIgnoreCase) { ["Authorization"] = "Bearer " + ApiKey, ["Accept"] = "application/json" }; if (method == "POST") { if (string.IsNullOrEmpty(key)) throw new Exception("Persist a logical create key before sending POST"); headers["Idempotency-Key"] = key; } 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); // 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. var resend = method == "GET"; 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 Send(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 = resend && (status == 429 || status >= 500); 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, Raw = raw }; } } throw new Exception("Retry limit reached"); } static bool Both(bool left,bool right)=>left&&right; static string BoundedWholeNumber(string value,string name,string maximum) { if(string.IsNullOrEmpty(value)||(value.Length>1&&value[0]=='0')||!value.All(c=>c>='0'&&c<='9')||value.Length>maximum.Length||(value.Length==maximum.Length&&string.CompareOrdinal(value,maximum)>0))throw new Exception(name+" must be a whole number from 0 through "+maximum);return value; } static bool Either(bool left,bool right) => left || right; static object Scalar(object value) { if(value is JsonValue json){if(json.TryGetValue(out var boolean))return boolean;if(json.TryGetValue(out var text))return text;return json.ToJsonString();}return value; } static bool Equal(object left,object right) => object.Equals(Scalar(left),Scalar(right)); static JsonNode Field(JsonNode value,string name) { if(value is not JsonObject obj || !obj.TryGetPropertyValue(name,out var item))throw new Exception("Missing response field: "+name);return item; } static bool IsPresent(string value) => value!=null && value!=""; public sealed class JournalRefusal : Exception { public JournalRefusal(string message) : base(message) {} } public static class JournalProtocol { public static readonly byte[] Preamble = Encoding.ASCII.GetBytes("EXHIBITDAY-GUIDE-JOURNAL 1\n"); static readonly UTF8Encoding Utf8 = new UTF8Encoding(false, true); static bool Match(string value,string pattern) => value != null && System.Text.RegularExpressions.Regex.IsMatch(value,"\\A(?:"+pattern+")\\z",System.Text.RegularExpressions.RegexOptions.CultureInvariant); public static bool Valid(string value,string pattern) => Match(value,pattern); static string Ascii(byte[] raw,int start,int count) { for(var i=start;i127)throw new JournalRefusal("Journal framing must be canonical ASCII");return Encoding.ASCII.GetString(raw,start,count); } public static byte[] Strings(IEnumerable values) { using var data=new MemoryStream(); foreach(var value in values){if(value==null)throw new JournalRefusal("Journal fields are exact strings");var item=Utf8.GetBytes(value);var prefix=Encoding.ASCII.GetBytes(item.Length.ToString(CultureInfo.InvariantCulture)+":");data.Write(prefix);data.Write(item);} return data.ToArray(); } public static List ReadStrings(byte[] raw) { var values=new List();var offset=0; while(offsetraw.Length-offset)throw new JournalRefusal("Incomplete journal string");values.Add(Utf8.GetString(raw,offset,(int)size));offset+=(int)size;} return values; } public static string Digest(byte[] raw)=>Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(raw)); public static string Fingerprint(IReadOnlyDictionary pairs) { var values=new List();foreach(var name in pairs.Keys.OrderBy(n=>n,StringComparer.Ordinal)){ if(!Match(name,"[A-Za-z0-9_.-]+")||new[]{"api_key","exhibitday_api_key"}.Contains(name.ToLowerInvariant()))throw new JournalRefusal("Use explicit secret-free fingerprint names");values.Add(name);values.Add(pairs[name]);} return Digest(Strings(values)); } public static byte[] Frame(IEnumerable values) { var payload=Strings(values);var header=Encoding.ASCII.GetBytes(payload.Length.ToString(CultureInfo.InvariantCulture)+" "+Digest(payload)+"\n"); using var data=new MemoryStream();data.Write(header);data.Write(payload);data.WriteByte(10);return data.ToArray(); } public static List> Decode(byte[] raw) { if(raw.Length>(); while(offset=raw.Length-offset)throw new JournalRefusal("Incomplete frame; reconcile before retry");var payload=raw.AsSpan(offset,(int)size).ToArray();offset+=(int)size; if(raw[offset]!=10||Digest(payload)!=split[1])throw new JournalRefusal("Journal integrity failed; reconcile before retry");records.Add(ReadStrings(payload));offset++;} return records; } } public sealed class Journal : IDisposable { readonly string path,lockPath,owner;readonly List header; readonly Dictionary allowed=new Dictionary(StringComparer.Ordinal); Dictionary> intents=new Dictionary>(StringComparer.Ordinal),savedValues=new Dictionary>(StringComparer.Ordinal); FileStream lockStream;bool owned,tainted;DateTime creation; static FileStream CreatePrivate(string target,FileAccess access,FileShare share) { var options=new FileStreamOptions{Mode=FileMode.CreateNew,Access=access,Share=share}; if(!OperatingSystem.IsWindows())options.UnixCreateMode=UnixFileMode.UserRead|UnixFileMode.UserWrite; return new FileStream(target,options); } public Journal(string path,string apiBase,string workspace,string slug,string job,string inputFingerprint,IEnumerable<(string Step,string Method,string Path)> writes,string mode="resume") { this.path=path;lockPath=path+".lock";owner=Convert.ToHexString(System.Security.Cryptography.RandomNumberGenerator.GetBytes(16)).ToLowerInvariant(); if(!Uri.TryCreate(apiBase,UriKind.Absolute,out var address)||address.Scheme!="https"&&address.Scheme!="http"||address.UserInfo.Length!=0||address.Query.Length!=0||address.Fragment.Length!=0||!JournalProtocol.Valid(slug,"[a-z][a-z0-9-]*"))throw new JournalRefusal("Use the actual API base and closed guide slug"); if(string.IsNullOrWhiteSpace(job)||!JournalProtocol.Valid(workspace,"[1-9][0-9]*")||!JournalProtocol.Valid(inputFingerprint,"[0-9A-F]{64}"))throw new JournalRefusal("Use actual workspace, stable explicit job ID and exact fingerprint"); if(mode!="new"&&mode!="resume")throw new JournalRefusal("Choose new or resume for this local job"); var manifest=new List();foreach(var write in writes){ if(!JournalProtocol.Valid(write.Step,"[a-z][a-z0-9_-]*")||allowed.ContainsKey(write.Step)||!new[]{"POST","PATCH","DELETE"}.Contains(write.Method)||!JournalProtocol.Valid(write.Path,"/v1/[A-Za-z0-9_/-]+")||write.Path.Contains("//"))throw new JournalRefusal("Use a closed unique write manifest"); allowed.Add(write.Step,(write.Method,write.Path));manifest.AddRange(new[]{write.Step,write.Method,write.Path});} if(allowed.Count==0)throw new JournalRefusal("Only write workflows need a restart journal"); header=new List{"H","1",apiBase,workspace,slug,job,inputFingerprint,JournalProtocol.Digest(JournalProtocol.Strings(manifest))};JournalProtocol.Strings(header); try{lockStream=CreatePrivate(lockPath,FileAccess.ReadWrite,FileShare.Read);owned=true;} catch(IOException)when(File.Exists(lockPath)){throw new JournalRefusal("This journal is locked; do not overlap jobs or steal a stale lock");} try{ var token=Encoding.ASCII.GetBytes(owner);lockStream.Write(token);lockStream.Flush(true);creation=File.GetCreationTimeUtc(lockPath); if(File.Exists(path)&&(File.GetAttributes(path)&FileAttributes.ReparsePoint)!=0)throw new JournalRefusal("Choose a private regular journal file"); if(mode=="resume"&&!File.Exists(path))throw new JournalRefusal("Journal missing: stop and reconcile lost state before starting a new logical job"); if(mode=="new"&&File.Exists(path))throw new JournalRefusal("Journal exists; use resume for the same logical job"); if(mode=="new"){using var output=CreatePrivate(path,FileAccess.Write,FileShare.None);output.Write(JournalProtocol.Preamble);output.Write(JournalProtocol.Frame(header));output.Flush(true);} var records=JournalProtocol.Decode(File.ReadAllBytes(path));if(records.Count==0||!records[0].SequenceEqual(header))throw new JournalRefusal("Journal workspace/base/guide/job/input binding differs"); foreach(var record in records.Skip(1))Apply(record);if(intents.Keys.Any(step=>!savedValues.ContainsKey(step)))throw new JournalRefusal("Saved intent lacks ACK; stop and reconcile before retry"); }catch{Dispose();throw;} } void Apply(IReadOnlyList record) { if(record.Count==0)throw new JournalRefusal("Empty journal record"); if(record[0]=="I"){ if(record.Count!=6)throw new JournalRefusal("Invalid intent shape");var step=record[1];var method=record[2];var route=record[3];var fingerprint=record[4];var key=record[5]; if(!JournalProtocol.Valid(step,"[a-z][a-z0-9_-]*")||intents.ContainsKey(step)||!allowed.TryGetValue(step,out var expected)||expected!=(method,route)||!JournalProtocol.Valid(fingerprint,"[0-9A-F]{64}")||intents.Keys.Any(name=>!savedValues.ContainsKey(name)))throw new JournalRefusal("Invalid, future or repeated intent"); if(method=="POST"&&!JournalProtocol.Valid(key,"[0-9a-f]{32}")||method!="POST"&&key!="")throw new JournalRefusal("Invalid persisted action key"); intents.Add(step,new Dictionary{{"method",method},{"path",route},{"request_fingerprint",fingerprint},{"idempotency_key",key}}); }else if(record[0]=="A"){ if(record.Count<3||!JournalProtocol.Valid(record[2],"0|[1-9][0-9]*")||!long.TryParse(record[2],NumberStyles.None,CultureInfo.InvariantCulture,out var count)||count!=(record.Count-3L)/2||record.Count%2!=1||!intents.ContainsKey(record[1])||savedValues.ContainsKey(record[1]))throw new JournalRefusal("ACK without exactly one prior intent"); var names=record.Skip(3).Where((_,index)=>index%2==0).ToArray(); if(!names.SequenceEqual(names.Distinct(StringComparer.Ordinal).OrderBy(name=>name,StringComparer.Ordinal))||names.Any(name=>!JournalProtocol.Valid(name,"[a-z][a-z0-9_]*")||name=="api_key"||name=="exhibitday_api_key"))throw new JournalRefusal("ACK fields must be unique sorted secret-free identifiers"); var saved=new Dictionary(StringComparer.Ordinal);for(var i=0;i record) { RequireActive();var raw=JournalProtocol.Frame(record); try{using var output=new FileStream(path,FileMode.Append,FileAccess.Write,FileShare.None);output.Write(raw);output.Flush(true);} catch{tainted=true;throw;} } public bool Acknowledged(string step){RequireActive();return savedValues.ContainsKey(step);} public Dictionary Saved(string step){RequireActive();if(!savedValues.ContainsKey(step))throw new JournalRefusal("No acknowledged state exists");return new Dictionary(savedValues[step],StringComparer.Ordinal);} public Dictionary Begin(string step,string method,string route,string requestFingerprint) { RequireActive();if(intents.ContainsKey(step))throw new JournalRefusal("Never blindly repeat an existing action"); var key=method=="POST"?Convert.ToHexString(System.Security.Cryptography.RandomNumberGenerator.GetBytes(16)).ToLowerInvariant():""; var record=new[]{"I",step,method,route,requestFingerprint,key};var previous=new Dictionary>(intents,StringComparer.Ordinal);try{Apply(record);}finally{intents=previous;} Append(record);Apply(record);return new Dictionary(intents[step],StringComparer.Ordinal); } public void Acknowledge(string step,IReadOnlyDictionary saved) { RequireActive();var record=new List{"A",step,saved.Count.ToString(CultureInfo.InvariantCulture)};foreach(var name in saved.Keys.OrderBy(name=>name,StringComparer.Ordinal))record.AddRange(new[]{name,saved[name]}); var previous=new Dictionary>(savedValues,StringComparer.Ordinal);try{Apply(record);JournalProtocol.Strings(record);}finally{savedValues=previous;} Append(record);Apply(record); } public void Dispose() { if(!owned)return;if(tainted){lockStream.Dispose();lockStream=null;owned=false;return;} try{RequireActive();}catch{lockStream.Dispose();lockStream=null;owned=false;throw;} lockStream.Dispose();lockStream=null;owned=false;File.Delete(lockPath); } } static Dictionary JournalValues(JsonNode value) { if(value is not JsonObject fields)throw new JournalRefusal("Saved/fingerprint values need an explicit object"); var result=new Dictionary(StringComparer.Ordinal); foreach(var field in fields){if(field.Value is not JsonValue item || !item.TryGetValue(out var text) || text==null)throw new JournalRefusal("Saved/fingerprint values must be exact strings");result.Add(field.Key,text);}return result; } static JsonObject JournalObject(IReadOnlyDictionary fields){var result=new JsonObject();foreach(var field in fields)result.Add(field.Key,JsonValue.Create(field.Value));return result;} static void JournalAcknowledge(Journal job,string step,JsonNode saved)=>job.Acknowledge(step,JournalValues(saved)); static bool JournalAcknowledged(Journal job,string step)=>job.Acknowledged(step); static JsonNode JournalBegin(Journal job,string step,string method,string path,string requestFingerprint)=>JournalObject(job.Begin(step,method,path,requestFingerprint)); static string JournalFingerprint(JsonNode value)=>JournalProtocol.Fingerprint(JournalValues(value)); static JsonNode JournalSaved(Journal job,string step)=>JournalObject(job.Saved(step)); static bool NotValue(bool value) => !value; static Journal OpenJournal(string path,string apiBase,string workspace,string slug,string job,string inputFingerprint,JsonNode manifest,string mode) { if(manifest is not JsonArray rows)throw new JournalRefusal("A closed write manifest is required");var writes=new List<(string,string,string)>(); foreach(var row in rows){if(row is not JsonArray fields || fields.Count!=3)throw new JournalRefusal("Each write must bind its step/method/path");var values=fields.Select(value=>value is JsonValue item&&item.TryGetValue(out var text)&&text!=null?text:throw new JournalRefusal("Manifest values are exact strings")).ToArray();writes.Add((values[0],values[1],values[2]));} return new Journal(path,apiBase,workspace,slug,job,inputFingerprint,writes,mode); } static string Optional(string name,string fallback) { var value=Environment.GetEnvironmentVariable(name);return value==null||value==""?fallback:value; } static string PositiveId(string value) { if(string.IsNullOrEmpty(value)||value[0]=='0'||!value.All(c=>c>='0'&&c<='9')||!long.TryParse(value,NumberStyles.None,CultureInfo.InvariantCulture,out var id)||id<=0)throw new Exception("Use a positive record ID");return value; } static void PrintValue(object value) => Console.WriteLine(value is string text ? text : JsonSerializer.Serialize(value)); static void RequireCondition(bool value,string message) { if(!value)throw new Exception(message); } static string ResponseStatus(Result value)=>value.Status.ToString(CultureInfo.InvariantCulture); static string Text(object value) => value==null?"":value is JsonNode node?Text(node):Convert.ToString(value,CultureInfo.InvariantCulture); internal static async Task Run() { var results_event_id = PositiveId(Required("EXHIBITDAY_EVENT_ID")); var results_objective_id = PositiveId(Required("EXHIBITDAY_OBJECTIVE_ID")); var results_lead_count = BoundedWholeNumber(Required("EXHIBITDAY_LEAD_COUNT"), "EXHIBITDAY_LEAD_COUNT", "9223372036854775807"); var results_rating = BoundedWholeNumber(Required("EXHIBITDAY_ACHIEVEMENT_RATING"), "EXHIBITDAY_ACHIEVEMENT_RATING", "10"); var results_journal_path = Required("EXHIBITDAY_JOURNAL"); var results_job_id = Required("EXHIBITDAY_JOB_ID"); var results_job_mode = Optional("EXHIBITDAY_JOB_MODE", "resume"); var results_workspace_response = await Call("workspace_binding", new JsonObject { }, null, null); RequireCondition(Equal(ResponseStatus(results_workspace_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome."); var results_workspace = results_workspace_response.Body; var results_workspace_id = PositiveId(Text(Field(results_workspace, "id"))); var results_event_response = await Call("read_event", new JsonObject { ["id"] = results_event_id, ["$include_record_revision"] = "true" }, null, null); RequireCondition(Equal(ResponseStatus(results_event_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome."); var results_event = results_event_response.Body; RequireCondition(Equal(Text(Field(results_event, "id")), results_event_id), "Read the exact selected Event before recording results."); var results_leads_revision = Text(Field(results_event, "record_revision")); RequireCondition(IsPresent(results_leads_revision), "The Event read needs its own actual record_revision."); var results_objective_response = await Call("read_objective", new JsonObject { ["id"] = results_objective_id, ["$include_record_revision"] = "true" }, null, null); RequireCondition(Equal(ResponseStatus(results_objective_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome."); var results_objective = results_objective_response.Body; RequireCondition(Both(Equal(Text(Field(results_objective, "id")), results_objective_id), Equal(Text(Field(results_objective, "event_id")), results_event_id)), "The Objective does not belong to the selected Event; no write was sent."); var results_objective_revision = Text(Field(results_objective, "record_revision")); RequireCondition(IsPresent(results_objective_revision), "The Objective read needs its own actual record_revision."); var results_input_fingerprint = JournalFingerprint(new JsonObject { ["workflow_contract_sha256"] = "94A1426B8C4D275633E918271BB2A2683E06A442317C472320B2E446E00ABCF6", ["event_id"] = results_event_id, ["objective_id"] = results_objective_id, ["roi_num_leads"] = results_lead_count, ["achievement_rating"] = results_rating }); using (var results_job = OpenJournal(results_journal_path, "https://api.exhibitday.com/v1", results_workspace_id, "show-results-objectives", results_job_id, results_input_fingerprint, new JsonArray(new JsonArray("save_leads", "PATCH", "/v1/events"), new JsonArray("rate_objective", "PATCH", "/v1/events/objectives")), results_job_mode)) { RequireCondition(Either(NotValue(JournalAcknowledged(results_job, "rate_objective")), JournalAcknowledged(results_job, "save_leads")), "A future results step is acknowledged before its prerequisite. Stop and reconcile the journal."); if (JournalAcknowledged(results_job, "save_leads")) { var results_leads_saved = JournalSaved(results_job, "save_leads"); RequireCondition(Both(Equal(Text(Field(results_leads_saved, "id")), results_event_id), Equal(Text(Field(results_leads_saved, "roi_num_leads")), results_lead_count)), "Acknowledged results state does not match the selected record and intended value; stop and reconcile."); } else { var results_leads_patch = new JsonObject { ["id"] = results_event_id, ["roi_num_leads"] = results_lead_count, ["expected_revision"] = results_leads_revision }; var results_leads_fingerprint = JournalFingerprint(new JsonObject { ["id"] = results_event_id, ["roi_num_leads"] = results_lead_count, ["expected_revision"] = results_leads_revision }); JournalBegin(results_job, "save_leads", "PATCH", "/v1/events", results_leads_fingerprint); var results_leads_save_response = await Call("save_leads", new JsonObject { }, results_leads_patch, null); RequireCondition(Equal(ResponseStatus(results_leads_save_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome."); var results_leads_receipt = results_leads_save_response.Body; var results_leads_after_revision = Text(Field(results_leads_receipt, "record_revision")); RequireCondition(IsPresent(results_leads_after_revision), "A checked save acknowledgement requires its own returned record_revision."); JournalAcknowledge(results_job, "save_leads", new JsonObject { ["id"] = results_event_id, ["roi_num_leads"] = results_lead_count, ["record_revision"] = results_leads_after_revision }); } if (JournalAcknowledged(results_job, "rate_objective")) { var results_objective_saved = JournalSaved(results_job, "rate_objective"); RequireCondition(Both(Both(Equal(Text(Field(results_objective_saved, "id")), results_objective_id), Equal(Text(Field(results_objective_saved, "achievement_rating")), results_rating)), Equal(Text(Field(results_objective_saved, "event_id")), results_event_id)), "Acknowledged results state does not match the selected record and intended value; stop and reconcile."); } else { var results_objective_patch = new JsonObject { ["id"] = results_objective_id, ["achievement_rating"] = results_rating, ["expected_revision"] = results_objective_revision }; var results_objective_fingerprint = JournalFingerprint(new JsonObject { ["id"] = results_objective_id, ["achievement_rating"] = results_rating, ["expected_revision"] = results_objective_revision }); JournalBegin(results_job, "rate_objective", "PATCH", "/v1/events/objectives", results_objective_fingerprint); var results_objective_save_response = await Call("rate_objective", new JsonObject { }, results_objective_patch, null); RequireCondition(Equal(ResponseStatus(results_objective_save_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome."); var results_objective_receipt = results_objective_save_response.Body; var results_objective_after_revision = Text(Field(results_objective_receipt, "record_revision")); RequireCondition(IsPresent(results_objective_after_revision), "A checked save acknowledgement requires its own returned record_revision."); JournalAcknowledge(results_job, "rate_objective", new JsonObject { ["id"] = results_objective_id, ["achievement_rating"] = results_rating, ["record_revision"] = results_objective_after_revision, ["event_id"] = results_event_id }); } var results_event_verify_response = await Call("verify_event", new JsonObject { ["id"] = results_event_id }, null, null); RequireCondition(Equal(ResponseStatus(results_event_verify_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome."); var results_event_verified = results_event_verify_response.Body; RequireCondition(Both(Equal(Text(Field(results_event_verified, "id")), results_event_id), Equal(Text(Field(results_event_verified, "roi_num_leads")), results_lead_count)), "The final Event no longer has the acknowledged leads value; inspect it instead of automatically restoring it."); var results_objective_verify_response = await Call("verify_objective", new JsonObject { ["id"] = results_objective_id }, null, null); RequireCondition(Equal(ResponseStatus(results_objective_verify_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome."); var results_objective_verified = results_objective_verify_response.Body; RequireCondition(Both(Equal(Text(Field(results_objective_verified, "id")), results_objective_id), Both(Equal(Text(Field(results_objective_verified, "event_id")), results_event_id), Equal(Text(Field(results_objective_verified, "achievement_rating")), results_rating))), "The final Objective is missing, rebound or has another rating; earlier saved steps remain in the journal."); PrintValue(new JsonObject { ["event_id"] = results_event_id, ["objective_id"] = results_objective_id, ["roi_num_leads"] = results_lead_count, ["achievement_rating"] = results_rating }); } } static Task Main() => Run(); } ``` ```java // 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 SPEC = JSON.fromJson("{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"read_event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"read_objective\":{\"method\":\"GET\",\"path\":\"/events/objectives/info\"},\"save_leads\":{\"method\":\"PATCH\",\"path\":\"/events\"},\"rate_objective\":{\"method\":\"PATCH\",\"path\":\"/events/objectives\"},\"verify_event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"verify_objective\":{\"method\":\"GET\",\"path\":\"/events/objectives/info\"}}}", Map.class); static final String API_KEY = headerKey(required("EXHIBITDAY_API_KEY")); static String headerKey(String value){if(value.chars().anyMatch(c->c<32||c>126))throw new IllegalArgumentException("Use the API key as one ASCII header value without control characters");return value;} static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).followRedirects(HttpClient.Redirect.NEVER).build(); interface RequestSender { HttpResponse send(HttpRequest request)throws IOException,InterruptedException; } static RequestSender SEND=request->CLIENT.send(request,HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); static class Result { int status; Object body; Map headers; String raw; Result(int s, Object b, Map h,String r) {status=s;body=b;headers=h;raw=r;} } // 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 obj(Object value) {return value==null?new LinkedHashMap<>(): (Map)value;} @SuppressWarnings("unchecked") static List list(Object value) {return value==null?Collections.emptyList():(List)value;} static Map map(Object... pairs) {Map result=new LinkedHashMap<>();for(int i=0;i query,Object body,String key) { Map route=obj(obj(SPEC.get("requests")).get(name));String method=text(route.get("method")); Map headers=map("Authorization","Bearer " + API_KEY,"Accept","application/json"); if(method.equals("POST")){if(key==null||key.isEmpty())throw new IllegalArgumentException("Persist a logical create key before sending POST");headers.put("Idempotency-Key",key);} 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); // 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. boolean resend=method.equals("GET"); 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 response; try {response=SEND.send(request.build());} 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();Object parsed=null; if(status!=304&&!response.body().isEmpty()) { try {parsed=JSON.fromJson(response.body(),Object.class);} catch(RuntimeException error){if(status<400)throw new IllegalStateException("Expected a JSON success response",error);} } Map 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=resend&&(status==429||status>=500); 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,response.body()); } throw new IllegalStateException("Retry limit reached"); } static boolean both(boolean left,boolean right){return left&&right;} static String bounded_whole_number(String value,String name,String maximum){if(!value.matches("0|[1-9][0-9]*")||value.length()>maximum.length()||(value.length()==maximum.length()&&value.compareTo(maximum)>0))throw new IllegalArgumentException(name+" must be a whole number from 0 through "+maximum);return value;} static boolean either(boolean left,boolean right){return left||right;} static boolean equal(Object left,Object right){return Objects.equals(left,right);} static Object field(Object value,String name){if(!(value instanceof Map)||!obj(value).containsKey(name))throw new IllegalStateException("Missing response field: "+name);return obj(value).get(name);} static boolean is_present(String value){return value!=null&&!value.isEmpty();} // Private client restart state only. No transport, application or JSON interpreter. static final class Journal implements AutoCloseable { public static final class Refusal extends IllegalStateException { Refusal(String message){super(message);} } public static final byte[] PREAMBLE="EXHIBITDAY-GUIDE-JOURNAL 1\n".getBytes(StandardCharsets.US_ASCII); static boolean valid(String value,String pattern){return value!=null&&value.matches(pattern);} static byte[] utf8(String value)throws java.nio.charset.CharacterCodingException { if(value==null)throw new Refusal("Journal fields are exact strings"); java.nio.ByteBuffer encoded=StandardCharsets.UTF_8.newEncoder().onMalformedInput(java.nio.charset.CodingErrorAction.REPORT).onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT).encode(java.nio.CharBuffer.wrap(value));byte[] raw=new byte[encoded.remaining()];encoded.get(raw);return raw; } static String ascii(byte[] raw,int start,int count){for(int i=start;i127)throw new Refusal("Journal framing must be canonical ASCII");return new String(raw,start,count,StandardCharsets.US_ASCII);} public static byte[] strings(Collection values)throws IOException { ByteArrayOutputStream output=new ByteArrayOutputStream();for(String value:values){byte[] raw=utf8(value);output.write((raw.length+":").getBytes(StandardCharsets.US_ASCII));output.write(raw);}return output.toByteArray(); } static int find(byte[] raw,int offset,int value){for(int i=offset;i readStrings(byte[] raw)throws IOException { List values=new ArrayList<>();int offset=0; while(offset0)throw new Refusal("Incomplete journal string");int count=size.intValueExact(); values.add(StandardCharsets.UTF_8.newDecoder().onMalformedInput(java.nio.charset.CodingErrorAction.REPORT).onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT).decode(java.nio.ByteBuffer.wrap(raw,offset,count)).toString());offset+=count;} return values; } public static String digest(byte[] raw){try{byte[] hash=java.security.MessageDigest.getInstance("SHA-256").digest(raw);StringBuilder text=new StringBuilder();for(byte item:hash)text.append(String.format(Locale.ROOT,"%02X",item&255));return text.toString();}catch(java.security.NoSuchAlgorithmException error){throw new IllegalStateException(error);}} public static String fingerprint(Map pairs)throws IOException { List values=new ArrayList<>();for(String name:new TreeSet<>(pairs.keySet())){if(!valid(name,"[A-Za-z0-9_.-]+")||Arrays.asList("api_key","exhibitday_api_key").contains(name.toLowerCase(Locale.ROOT)))throw new Refusal("Use explicit secret-free fingerprint names");values.add(name);values.add(pairs.get(name));}return digest(strings(values)); } public static byte[] frame(Collection values)throws IOException {byte[] payload=strings(values);ByteArrayOutputStream output=new ByteArrayOutputStream();output.write((payload.length+" "+digest(payload)+"\n").getBytes(StandardCharsets.US_ASCII));output.write(payload);output.write(10);return output.toByteArray();} public static List> decode(byte[] raw)throws IOException { if(raw.length> records=new ArrayList<>(); while(offset=0)throw new Refusal("Incomplete frame; reconcile before retry");int count=size.intValueExact();byte[] payload=Arrays.copyOfRange(raw,offset,offset+count);offset+=count; if(raw[offset]!=10||!digest(payload).equals(fields[1]))throw new Refusal("Journal integrity failed; reconcile before retry");records.add(readStrings(payload));offset++;}return records; } static void writeAll(java.nio.channels.FileChannel target,byte[] raw)throws IOException {java.nio.ByteBuffer data=java.nio.ByteBuffer.wrap(raw);while(data.hasRemaining())if(target.write(data)<=0)throw new IOException("Journal write did not advance");} static java.nio.channels.FileChannel createPrivate(Path path,OpenOption... options)throws IOException { java.nio.file.attribute.FileAttribute[] attributes=FileSystems.getDefault().supportedFileAttributeViews().contains("posix")?new java.nio.file.attribute.FileAttribute[]{java.nio.file.attribute.PosixFilePermissions.asFileAttribute(java.nio.file.attribute.PosixFilePermissions.fromString("rw-------"))}:new java.nio.file.attribute.FileAttribute[0]; return java.nio.channels.FileChannel.open(path,new HashSet<>(Arrays.asList(options)),attributes); } final Path path,lockPath;final String owner;final List header; final Map> allowed=new LinkedHashMap<>();Map> intents=new LinkedHashMap<>(),savedValues=new LinkedHashMap<>(); java.nio.channels.FileChannel lock;boolean owned,tainted;Object fileKey;java.nio.file.attribute.FileTime creation; public Journal(Path path,String apiBase,String workspace,String slug,String job,String inputFingerprint,List> writes)throws IOException {this(path,apiBase,workspace,slug,job,inputFingerprint,writes,"resume");} public Journal(Path path,String apiBase,String workspace,String slug,String job,String inputFingerprint,List> writes,String mode)throws IOException { this.path=path;lockPath=Path.of(path.toString()+".lock");byte[] random=new byte[16];new java.security.SecureRandom().nextBytes(random);StringBuilder token=new StringBuilder();for(byte item:random)token.append(String.format(Locale.ROOT,"%02x",item&255));owner=token.toString(); URI address=URI.create(apiBase);if(!Arrays.asList("https","http").contains(address.getScheme())||address.getHost()==null||address.getUserInfo()!=null||address.getRawQuery()!=null||address.getRawFragment()!=null||!valid(slug,"[a-z][a-z0-9-]*"))throw new Refusal("Use actual API base and closed guide slug"); if(job==null||job.trim().isEmpty()||!valid(workspace,"[1-9][0-9]*")||!valid(inputFingerprint,"[0-9A-F]{64}"))throw new Refusal("Use actual workspace, stable explicit job ID and exact fingerprint"); if(!Arrays.asList("new","resume").contains(mode))throw new Refusal("Choose new or resume for this local job"); List manifest=new ArrayList<>();for(List item:writes){if(item.size()!=3)throw new Refusal("Invalid write manifest shape");String step=item.get(0),method=item.get(1),route=item.get(2); if(!valid(step,"[a-z][a-z0-9_-]*")||allowed.containsKey(step)||!Arrays.asList("POST","PATCH","DELETE").contains(method)||!valid(route,"/v1/[A-Za-z0-9_/-]+")||route.contains("//"))throw new Refusal("Use a closed unique write manifest");allowed.put(step,List.of(method,route));manifest.addAll(item);} if(allowed.isEmpty())throw new Refusal("Only write workflows need a restart journal");header=List.of("H","1",apiBase,workspace,slug,job,inputFingerprint,digest(strings(manifest)));strings(header); try{lock=createPrivate(lockPath,StandardOpenOption.CREATE_NEW,StandardOpenOption.READ,StandardOpenOption.WRITE);owned=true;}catch(FileAlreadyExistsException error){throw new Refusal("This journal is locked; do not overlap jobs or steal a stale lock");} try{writeAll(lock,owner.getBytes(StandardCharsets.US_ASCII));lock.force(true);java.nio.file.attribute.BasicFileAttributes identity=Files.readAttributes(lockPath,java.nio.file.attribute.BasicFileAttributes.class,LinkOption.NOFOLLOW_LINKS);fileKey=identity.fileKey();creation=identity.creationTime(); if(Files.isSymbolicLink(path))throw new Refusal("Choose a private regular journal file"); if(mode.equals("resume")&&!Files.exists(path))throw new Refusal("Journal missing: stop and reconcile lost state before starting a new logical job"); if(mode.equals("new")&&Files.exists(path))throw new Refusal("Journal exists; use resume for the same logical job"); if(mode.equals("new")){try(java.nio.channels.FileChannel target=createPrivate(path,StandardOpenOption.CREATE_NEW,StandardOpenOption.WRITE)){writeAll(target,PREAMBLE);writeAll(target,frame(header));target.force(true);}} List> records=decode(Files.readAllBytes(path));if(records.isEmpty()||!records.get(0).equals(header))throw new Refusal("Journal workspace/base/guide/job/input binding differs");for(List record:records.subList(1,records.size()))apply(record); if(intents.keySet().stream().anyMatch(step->!savedValues.containsKey(step)))throw new Refusal("Saved intent lacks ACK; stop and reconcile before retry"); }catch(IOException|RuntimeException error){close();throw error;} } void apply(List record){ if(record.isEmpty())throw new Refusal("Empty journal record"); if(record.get(0).equals("I")){ if(record.size()!=6)throw new Refusal("Invalid intent shape");String step=record.get(1),method=record.get(2),route=record.get(3),fingerprint=record.get(4),key=record.get(5); if(!valid(step,"[a-z][a-z0-9_-]*")||intents.containsKey(step)||!List.of(method,route).equals(allowed.get(step))||!valid(fingerprint,"[0-9A-F]{64}")||intents.keySet().stream().anyMatch(name->!savedValues.containsKey(name)))throw new Refusal("Invalid, future or repeated intent"); if(method.equals("POST")&&!valid(key,"[0-9a-f]{32}")||!method.equals("POST")&&!key.isEmpty())throw new Refusal("Invalid persisted action key");intents.put(step,new LinkedHashMap<>(Map.of("method",method,"path",route,"request_fingerprint",fingerprint,"idempotency_key",key))); }else if(record.get(0).equals("A")){ if(record.size()<3||!valid(record.get(2),"0|[1-9][0-9]*")||!new java.math.BigInteger(record.get(2)).multiply(java.math.BigInteger.TWO).equals(java.math.BigInteger.valueOf(record.size()-3))||!intents.containsKey(record.get(1))||savedValues.containsKey(record.get(1)))throw new Refusal("ACK without exactly one prior intent"); List names=new ArrayList<>();for(int i=3;i(new TreeSet<>(names)))||names.stream().anyMatch(name->!valid(name,"[a-z][a-z0-9_]*")||name.equals("api_key")||name.equals("exhibitday_api_key")))throw new Refusal("ACK fields must be unique sorted secret-free identifiers"); Map saved=new LinkedHashMap<>();for(int i=0;i record)throws IOException {requireActive();byte[] raw=frame(record);try(java.nio.channels.FileChannel target=java.nio.channels.FileChannel.open(path,StandardOpenOption.WRITE,StandardOpenOption.APPEND)){writeAll(target,raw);target.force(true);}catch(IOException|RuntimeException error){tainted=true;throw error;}} public boolean acknowledged(String step)throws IOException{requireActive();return savedValues.containsKey(step);} public Map saved(String step)throws IOException{requireActive();if(!savedValues.containsKey(step))throw new Refusal("No acknowledged state exists");return new LinkedHashMap<>(savedValues.get(step));} public Map begin(String step,String method,String route,String requestFingerprint)throws IOException { requireActive();if(intents.containsKey(step))throw new Refusal("Never blindly repeat an existing action");String key="";if(method.equals("POST")){byte[] bytes=new byte[16];new java.security.SecureRandom().nextBytes(bytes);StringBuilder text=new StringBuilder();for(byte item:bytes)text.append(String.format(Locale.ROOT,"%02x",item&255));key=text.toString();} List record=List.of("I",step,method,route,requestFingerprint,key);Map> previous=new LinkedHashMap<>(intents);try{apply(record);}finally{intents=previous;}append(record);apply(record);return new LinkedHashMap<>(intents.get(step)); } public void acknowledge(String step,Map saved)throws IOException { requireActive();List record=new ArrayList<>(List.of("A",step,Integer.toString(saved.size())));for(String name:new TreeSet<>(saved.keySet())){record.add(name);record.add(saved.get(name));} Map> previous=new LinkedHashMap<>(savedValues);try{apply(record);strings(record);}finally{savedValues=previous;}append(record);apply(record); } public void close()throws IOException { if(!owned)return;if(tainted){lock.close();lock=null;owned=false;return;} try{requireActive();}catch(IOException|RuntimeException error){lock.close();lock=null;owned=false;throw error;}lock.close();lock=null;owned=false;Files.delete(lockPath); } } static Map journal_values(Object value){if(!(value instanceof Map))throw new Journal.Refusal("Saved/fingerprint values need an explicit object");Map result=new LinkedHashMap<>();for(Map.Entry field:((Map)value).entrySet()){if(!(field.getKey() instanceof String)||!(field.getValue() instanceof String))throw new Journal.Refusal("Saved/fingerprint values must be exact strings");result.put((String)field.getKey(),(String)field.getValue());}return result;} static void journal_acknowledge(Journal job,String step,Object saved)throws IOException{job.acknowledge(step,journal_values(saved));} static boolean journal_acknowledged(Journal job,String step)throws IOException{return job.acknowledged(step);} static Object journal_begin(Journal job,String step,String method,String path,String requestFingerprint)throws IOException{return new LinkedHashMap(job.begin(step,method,path,requestFingerprint));} static String journal_fingerprint(Object value)throws IOException{return Journal.fingerprint(journal_values(value));} static Object journal_saved(Journal job,String step)throws IOException{return new LinkedHashMap(job.saved(step));} static boolean not_value(boolean value){return !value;} static Journal open_journal(String path,String base,String workspace,String slug,String job,String inputFingerprint,Object manifest,String mode)throws IOException { if(!(manifest instanceof List))throw new Journal.Refusal("A closed write manifest is required");List> writes=new ArrayList<>();for(Object row:(List)manifest){if(!(row instanceof List)||((List)row).size()!=3)throw new Journal.Refusal("Each write must bind step/method/path");List fields=new ArrayList<>();for(Object value:(List)row){if(!(value instanceof String))throw new Journal.Refusal("Manifest values are exact strings");fields.add((String)value);}writes.add(fields);}return new Journal(Path.of(path),base,workspace,slug,job,inputFingerprint,writes,mode); } static String optional(String name,String fallback){String value=System.getenv(name);return value==null||value.isEmpty()?fallback:value;} static String positive_id(String value){try{if(value==null||!value.matches("[1-9][0-9]*")||Long.parseLong(value)<=0)throw new IllegalArgumentException();return value;}catch(RuntimeException error){throw new IllegalArgumentException("Use a positive record ID");}} static void print_value(Object value){try{String text=value instanceof String?(String)value:JSON.toJson(value);System.out.write((text+"\n").getBytes(StandardCharsets.UTF_8));}catch(IOException error){throw new UncheckedIOException(error);}} static void require_condition(boolean value,String message){if(!value)throw new IllegalStateException(message);} static String response_status(Result value){return Integer.toString(value.status);} static void run()throws Exception { String results_event_id = positive_id(required("EXHIBITDAY_EVENT_ID")); String results_objective_id = positive_id(required("EXHIBITDAY_OBJECTIVE_ID")); String results_lead_count = bounded_whole_number(required("EXHIBITDAY_LEAD_COUNT"), "EXHIBITDAY_LEAD_COUNT", "9223372036854775807"); String results_rating = bounded_whole_number(required("EXHIBITDAY_ACHIEVEMENT_RATING"), "EXHIBITDAY_ACHIEVEMENT_RATING", "10"); String results_journal_path = required("EXHIBITDAY_JOURNAL"); String results_job_id = required("EXHIBITDAY_JOB_ID"); String results_job_mode = optional("EXHIBITDAY_JOB_MODE", "resume"); Result results_workspace_response = call("workspace_binding", map(), null, null); require_condition(equal(response_status(results_workspace_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome."); Object results_workspace = results_workspace_response.body; String results_workspace_id = positive_id(text(field(results_workspace, "id"))); Result results_event_response = call("read_event", map("id", results_event_id, "$include_record_revision", "true"), null, null); require_condition(equal(response_status(results_event_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome."); Object results_event = results_event_response.body; require_condition(equal(text(field(results_event, "id")), results_event_id), "Read the exact selected Event before recording results."); String results_leads_revision = text(field(results_event, "record_revision")); require_condition(is_present(results_leads_revision), "The Event read needs its own actual record_revision."); Result results_objective_response = call("read_objective", map("id", results_objective_id, "$include_record_revision", "true"), null, null); require_condition(equal(response_status(results_objective_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome."); Object results_objective = results_objective_response.body; require_condition(both(equal(text(field(results_objective, "id")), results_objective_id), equal(text(field(results_objective, "event_id")), results_event_id)), "The Objective does not belong to the selected Event; no write was sent."); String results_objective_revision = text(field(results_objective, "record_revision")); require_condition(is_present(results_objective_revision), "The Objective read needs its own actual record_revision."); String results_input_fingerprint = journal_fingerprint(map("workflow_contract_sha256", "94A1426B8C4D275633E918271BB2A2683E06A442317C472320B2E446E00ABCF6", "event_id", results_event_id, "objective_id", results_objective_id, "roi_num_leads", results_lead_count, "achievement_rating", results_rating)); try (Journal results_job = open_journal(results_journal_path, "https://api.exhibitday.com/v1", results_workspace_id, "show-results-objectives", results_job_id, results_input_fingerprint, Arrays.asList(Arrays.asList("save_leads", "PATCH", "/v1/events"), Arrays.asList("rate_objective", "PATCH", "/v1/events/objectives")), results_job_mode)) { require_condition(either(not_value(journal_acknowledged(results_job, "rate_objective")), journal_acknowledged(results_job, "save_leads")), "A future results step is acknowledged before its prerequisite. Stop and reconcile the journal."); if (journal_acknowledged(results_job, "save_leads")) { Object results_leads_saved = journal_saved(results_job, "save_leads"); require_condition(both(equal(text(field(results_leads_saved, "id")), results_event_id), equal(text(field(results_leads_saved, "roi_num_leads")), results_lead_count)), "Acknowledged results state does not match the selected record and intended value; stop and reconcile."); } else { Object results_leads_patch = map("id", results_event_id, "roi_num_leads", results_lead_count, "expected_revision", results_leads_revision); String results_leads_fingerprint = journal_fingerprint(map("id", results_event_id, "roi_num_leads", results_lead_count, "expected_revision", results_leads_revision)); journal_begin(results_job, "save_leads", "PATCH", "/v1/events", results_leads_fingerprint); Result results_leads_save_response = call("save_leads", map(), results_leads_patch, null); require_condition(equal(response_status(results_leads_save_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome."); Object results_leads_receipt = results_leads_save_response.body; String results_leads_after_revision = text(field(results_leads_receipt, "record_revision")); require_condition(is_present(results_leads_after_revision), "A checked save acknowledgement requires its own returned record_revision."); journal_acknowledge(results_job, "save_leads", map("id", results_event_id, "roi_num_leads", results_lead_count, "record_revision", results_leads_after_revision)); } if (journal_acknowledged(results_job, "rate_objective")) { Object results_objective_saved = journal_saved(results_job, "rate_objective"); require_condition(both(both(equal(text(field(results_objective_saved, "id")), results_objective_id), equal(text(field(results_objective_saved, "achievement_rating")), results_rating)), equal(text(field(results_objective_saved, "event_id")), results_event_id)), "Acknowledged results state does not match the selected record and intended value; stop and reconcile."); } else { Object results_objective_patch = map("id", results_objective_id, "achievement_rating", results_rating, "expected_revision", results_objective_revision); String results_objective_fingerprint = journal_fingerprint(map("id", results_objective_id, "achievement_rating", results_rating, "expected_revision", results_objective_revision)); journal_begin(results_job, "rate_objective", "PATCH", "/v1/events/objectives", results_objective_fingerprint); Result results_objective_save_response = call("rate_objective", map(), results_objective_patch, null); require_condition(equal(response_status(results_objective_save_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome."); Object results_objective_receipt = results_objective_save_response.body; String results_objective_after_revision = text(field(results_objective_receipt, "record_revision")); require_condition(is_present(results_objective_after_revision), "A checked save acknowledgement requires its own returned record_revision."); journal_acknowledge(results_job, "rate_objective", map("id", results_objective_id, "achievement_rating", results_rating, "record_revision", results_objective_after_revision, "event_id", results_event_id)); } Result results_event_verify_response = call("verify_event", map("id", results_event_id), null, null); require_condition(equal(response_status(results_event_verify_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome."); Object results_event_verified = results_event_verify_response.body; require_condition(both(equal(text(field(results_event_verified, "id")), results_event_id), equal(text(field(results_event_verified, "roi_num_leads")), results_lead_count)), "The final Event no longer has the acknowledged leads value; inspect it instead of automatically restoring it."); Result results_objective_verify_response = call("verify_objective", map("id", results_objective_id), null, null); require_condition(equal(response_status(results_objective_verify_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome."); Object results_objective_verified = results_objective_verify_response.body; require_condition(both(equal(text(field(results_objective_verified, "id")), results_objective_id), both(equal(text(field(results_objective_verified, "event_id")), results_event_id), equal(text(field(results_objective_verified, "achievement_rating")), results_rating))), "The final Objective is missing, rebound or has another rating; earlier saved steps remain in the journal."); print_value(map("event_id", results_event_id, "objective_id", results_objective_id, "roi_num_leads", results_lead_count, "achievement_rating", results_rating)); } } public static void main(String[] args)throws Exception {run();} } ``` ```php $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, ?string $key = null): array { global $spec, $apiKey, $transport; $route = $spec['requests'][$name]; $headers = ['Authorization' => 'Bearer ' . $apiKey, 'Accept' => 'application/json']; if ($route['method'] === 'POST') { if ($key === null || $key === '') throw new RuntimeException('Persist a logical create key before sending POST'); $headers['Idempotency-Key'] = $key; // 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); // 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 = 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 = $resend && ($status === 429 || $status >= 500); 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, 'raw' => $raw]; } throw new RuntimeException('Retry limit reached'); } $transport = Closure::fromCallable('nativeTransport'); function both(bool $left,bool $right):bool{return $left&&$right;} function bounded_whole_number(string $value,string $name,string $maximum):string{if(!preg_match("/^(?:0|[1-9][0-9]*)$/D",$value)||strlen($value)>strlen($maximum)||(strlen($value)===strlen($maximum)&&strcmp($value,$maximum)>0))throw new RuntimeException($name." must be a whole number from 0 through ".$maximum);return $value;} function either(bool $left,bool $right):bool{return $left||$right;} function equal(mixed $left,mixed $right):bool{return $left===$right;} function field(mixed $value,string $name):mixed{if(!is_array($value)||!array_key_exists($name,$value))throw new RuntimeException("Missing response field: ".$name);return $value[$name];} function is_present(?string $value):bool{return $value!==null&&$value!=="";} final class JournalRefusal extends RuntimeException {} final class JournalProtocol { public const PREAMBLE="EXHIBITDAY-GUIDE-JOURNAL 1\n"; public static function utf8(mixed $value):string {if(!is_string($value)||preg_match('//u',$value)!==1)throw new JournalRefusal('Journal fields must be exact valid UTF8 strings');return$value;} public static function strings(array $values):string {$raw='';foreach($values as$value){$item=self::utf8($value);$raw.=strlen($item).':'.$item;}return$raw;} private static function length(string $text,int $remaining):int {if(!preg_match('/\A(?:0|[1-9][0-9]*)\z/',$text))throw new JournalRefusal('Noncanonical string length');$maximum=(string)$remaining;if(strlen($text)>strlen($maximum)||(strlen($text)===strlen($maximum)&&strcmp($text,$maximum)>0))throw new JournalRefusal('Incomplete journal string/frame');return(int)$text;} public static function readStrings(string $raw):array {$values=[];$offset=0;while($offset=strlen($raw)-$offset)throw new JournalRefusal('Incomplete frame; reconcile before retry');$payload=substr($raw,$offset,$size);$offset+=$size;if($raw[$offset]!=="\n"||self::digest($payload)!==$match[2])throw new JournalRefusal('Journal integrity failed; reconcile before retry');$records[]=self::readStrings($payload);$offset++;}return$records;} public static function writeAll($file,string $raw):void {$offset=0;while($offsetpath=$path;$this->lockPath=$path.'.lock';$this->owner=bin2hex(random_bytes(16));$address=parse_url($base); if($address===false||!in_array($address['scheme']??null,['https','http'],true)||!isset($address['host'])||isset($address['user'])||isset($address['pass'])||isset($address['query'])||isset($address['fragment'])||!preg_match('/\A[a-z][a-z0-9-]*\z/',$slug))throw new JournalRefusal('Use actual API base and closed guide slug'); if(trim($job)===''||!preg_match('/\A[1-9][0-9]*\z/',$workspace)||!preg_match('/\A[0-9A-F]{64}\z/',$inputFingerprint))throw new JournalRefusal('Use actual workspace, stable explicit job ID and exact fingerprint'); if(!in_array($mode,['new','resume'],true))throw new JournalRefusal('Choose new or resume for this local job'); $manifest=[];foreach($writes as$write){if(!is_array($write)||!array_is_list($write)||count($write)!==3)throw new JournalRefusal('Invalid write manifest');[$step,$method,$route]=$write; if(!is_string($step)||!preg_match('/\A[a-z][a-z0-9_-]*\z/',$step)||isset($this->allowed[$step])||!in_array($method,['POST','PATCH','DELETE'],true)||!is_string($route)||!preg_match('~\A/v1/[A-Za-z0-9_/-]+\z~',$route)||str_contains($route,'//'))throw new JournalRefusal('Use a closed unique write manifest');$this->allowed[$step]=[$method,$route];array_push($manifest,$step,$method,$route);} if($this->allowed===[])throw new JournalRefusal('Only write workflows need restart journal');$this->header=['H','1',$base,$workspace,$slug,$job,$inputFingerprint,JournalProtocol::digest(JournalProtocol::strings($manifest))];JournalProtocol::strings($this->header); $this->file=JournalProtocol::createPrivate($this->lockPath);$this->owned=true; try{ JournalProtocol::writeAll($this->file,$this->owner);$identity=fstat($this->file);if($identity===false)throw new JournalRefusal('Cannot bind acquired lock identity');$this->identity=$identity; clearstatcache(true,$path);if(is_link($path))throw new JournalRefusal('Choose private regular journal file'); $exists=file_exists($path);if($mode==='resume'&&!$exists)throw new JournalRefusal('Journal missing: stop and reconcile lost state before starting a new logical job');if($mode==='new'&&$exists)throw new JournalRefusal('Journal exists; use resume for the same logical job'); if($mode==='new'){$target=JournalProtocol::createPrivate($path);try{JournalProtocol::writeAll($target,JournalProtocol::PREAMBLE.JournalProtocol::frame($this->header));}finally{fclose($target);}} $raw=file_get_contents($path);if($raw===false)throw new JournalRefusal('Cannot read journal');$records=JournalProtocol::decode($raw);if($records===[]||$records[0]!==$this->header)throw new JournalRefusal('Journal workspace/base/guide/job/input binding differs');foreach(array_slice($records,1)as$record)$this->apply($record); if(array_diff(array_keys($this->intents),array_keys($this->savedValues))!==[])throw new JournalRefusal('Saved intent lacks ACK; stop and reconcile before retry'); }catch(Throwable $error){$this->close();throw$error;} } private function apply(array $record):void { if(($record[0]??null)==='I'){ if(count($record)!==6)throw new JournalRefusal('Invalid intent shape');[,$step,$method,$route,$fingerprint,$key]=$record; if(!preg_match('/\A[a-z][a-z0-9_-]*\z/',$step)||isset($this->intents[$step])||($this->allowed[$step]??null)!==[$method,$route]||!preg_match('/\A[0-9A-F]{64}\z/',$fingerprint)||array_diff(array_keys($this->intents),array_keys($this->savedValues))!==[])throw new JournalRefusal('Invalid, future or repeated intent'); if(($method==='POST'&&!preg_match('/\A[0-9a-f]{32}\z/',$key))||($method!=='POST'&&$key!==''))throw new JournalRefusal('Invalid persisted action key');$this->intents[$step]=['method'=>$method,'path'=>$route,'request_fingerprint'=>$fingerprint,'idempotency_key'=>$key]; }elseif(($record[0]??null)==='A'){ if(count($record)<3)throw new JournalRefusal('Invalid ACK shape');[,$step,$count]=$record;$pairs=array_slice($record,3); if(!preg_match('/\A(?:0|[1-9][0-9]*)\z/',$count)||(string)intdiv(count($pairs),2)!==$count||count($pairs)%2!==0||!isset($this->intents[$step])||isset($this->savedValues[$step]))throw new JournalRefusal('ACK without exactly one prior intent'); $names=[];for($i=0;$i$name){if(!preg_match('/\A[a-z][a-z0-9_]*\z/',$name)||in_array($name,['api_key','exhibitday_api_key'],true))throw new JournalRefusal('Use secret-free ACK field names');$saved[$name]=$pairs[$i*2+1];}$this->savedValues[$step]=$saved; }else throw new JournalRefusal('Unknown journal transition'); } private function requireActive():void { if(!$this->owned||$this->file===null||$this->tainted)throw new JournalRefusal('Journal closed or IO outcome needs reconciliation');clearstatcache(true,$this->lockPath);$current=@lstat($this->lockPath);$token=@file_get_contents($this->lockPath); if($current===false||($current['dev']??null)!==($this->identity['dev']??null)||($current['ino']??null)!==($this->identity['ino']??null)||$token!==$this->owner)throw new JournalRefusal('Journal lock replaced; stop without deleting it'); } private function append(array $record):void { $this->requireActive();$raw=JournalProtocol::frame($record);$target=null; try{$target=@fopen($this->path,'ab');if($target===false)throw new JournalRefusal('Cannot append journal; stop and reconcile');JournalProtocol::writeAll($target,$raw);}catch(Throwable $error){$this->tainted=true;throw$error;}finally{if(is_resource($target))fclose($target);} } public function acknowledged(string $step):bool{$this->requireActive();return isset($this->savedValues[$step]);} public function saved(string $step):array{$this->requireActive();if(!isset($this->savedValues[$step]))throw new JournalRefusal('No acknowledged state exists');return$this->savedValues[$step];} public function beginAction(string $step,string $method,string $route,string $requestFingerprint):array { $this->requireActive();if(isset($this->intents[$step]))throw new JournalRefusal('Never blindly repeat an existing action');$key=$method==='POST'?bin2hex(random_bytes(16)):'';$record=['I',$step,$method,$route,$requestFingerprint,$key];$previous=$this->intents;try{$this->apply($record);}finally{$this->intents=$previous;}$this->append($record);$this->apply($record);return$this->intents[$step]; } public function acknowledge(string $step,array $saved):void { $this->requireActive();$record=['A',$step,(string)count($saved)];$names=array_keys($saved);sort($names,SORT_STRING);foreach($names as$name){$record[]=$name;$record[]=$saved[$name];}$previous=$this->savedValues;try{$this->apply($record);JournalProtocol::strings($record);}finally{$this->savedValues=$previous;}$this->append($record);$this->apply($record); } public function close():void { if(!$this->owned)return;if($this->tainted){fclose($this->file);$this->file=null;$this->owned=false;return;} try{$this->requireActive();}catch(Throwable $error){fclose($this->file);$this->file=null;$this->owned=false;throw$error;}fclose($this->file);$this->file=null;$this->owned=false;if(!unlink($this->lockPath))throw new JournalRefusal('Could not release owned journal lock'); } } function journal_values(mixed $value):array{if(!is_object($value))throw new JournalRefusal('Saved/fingerprint values need an explicit object');$result=get_object_vars($value);foreach($result as$name=>$item)if(!is_string($name)||!is_string($item))throw new JournalRefusal('Saved/fingerprint values must be exact strings');return$result;} function journal_acknowledge(GuideJournal $job,string $step,mixed $saved):void{$job->acknowledge($step,journal_values($saved));} function journal_acknowledged(GuideJournal $job,string $step):bool{return $job->acknowledged($step);} function journal_begin(GuideJournal $job,string $step,string $method,string $path,string $requestFingerprint):array{return $job->beginAction($step,$method,$path,$requestFingerprint);} function journal_fingerprint(mixed $value):string{return JournalProtocol::fingerprint(journal_values($value));} function journal_saved(GuideJournal $job,string $step):array{return $job->saved($step);} function not_value(bool $value):bool{return !$value;} function open_journal(string $path,string $base,string $workspace,string $slug,string $job,string $inputFingerprint,array $writes,string $mode):GuideJournal{return new GuideJournal($path,$base,$workspace,$slug,$job,$inputFingerprint,$writes,$mode);} function positive_id(string $value):string{if(!preg_match("/^[1-9][0-9]*$/D",$value)||strlen($value)>19||(strlen($value)===19&&strcmp($value,"9223372036854775807")>0))throw new RuntimeException("Use a positive record ID");return $value;} function print_value(mixed $value):void{echo (is_string($value)?$value:json_encode($value,JSON_THROW_ON_ERROR))."\n";} function require_condition(bool $value,string $message):void{if(!$value)throw new RuntimeException($message);} function response_status(array $value):string{return(string)$value["status"];} function text(mixed $value):string{if($value===null)return "";if(is_string($value))return $value;if(is_bool($value))return $value?"true":"false";if(is_int($value))return (string)$value;throw new RuntimeException("Expected a scalar response value");} function main():void { $results_event_id = positive_id(required('EXHIBITDAY_EVENT_ID')); $results_objective_id = positive_id(required('EXHIBITDAY_OBJECTIVE_ID')); $results_lead_count = bounded_whole_number(required('EXHIBITDAY_LEAD_COUNT'), 'EXHIBITDAY_LEAD_COUNT', '9223372036854775807'); $results_rating = bounded_whole_number(required('EXHIBITDAY_ACHIEVEMENT_RATING'), 'EXHIBITDAY_ACHIEVEMENT_RATING', '10'); $results_journal_path = required('EXHIBITDAY_JOURNAL'); $results_job_id = required('EXHIBITDAY_JOB_ID'); $results_job_mode = optional('EXHIBITDAY_JOB_MODE', 'resume'); $results_workspace_response = call('workspace_binding', [], null, null); require_condition(equal(response_status($results_workspace_response), '200'), 'Expected the endpoint\'s documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome.'); $results_workspace = $results_workspace_response["body"]; $results_workspace_id = positive_id(text(field($results_workspace, 'id'))); $results_event_response = call('read_event', ['id' => $results_event_id, '$include_record_revision' => 'true'], null, null); require_condition(equal(response_status($results_event_response), '200'), 'Expected the endpoint\'s documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome.'); $results_event = $results_event_response["body"]; require_condition(equal(text(field($results_event, 'id')), $results_event_id), 'Read the exact selected Event before recording results.'); $results_leads_revision = text(field($results_event, 'record_revision')); require_condition(is_present($results_leads_revision), 'The Event read needs its own actual record_revision.'); $results_objective_response = call('read_objective', ['id' => $results_objective_id, '$include_record_revision' => 'true'], null, null); require_condition(equal(response_status($results_objective_response), '200'), 'Expected the endpoint\'s documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome.'); $results_objective = $results_objective_response["body"]; require_condition(both(equal(text(field($results_objective, 'id')), $results_objective_id), equal(text(field($results_objective, 'event_id')), $results_event_id)), 'The Objective does not belong to the selected Event; no write was sent.'); $results_objective_revision = text(field($results_objective, 'record_revision')); require_condition(is_present($results_objective_revision), 'The Objective read needs its own actual record_revision.'); $results_input_fingerprint = journal_fingerprint((object)['workflow_contract_sha256' => '94A1426B8C4D275633E918271BB2A2683E06A442317C472320B2E446E00ABCF6', 'event_id' => $results_event_id, 'objective_id' => $results_objective_id, 'roi_num_leads' => $results_lead_count, 'achievement_rating' => $results_rating]); $results_job = open_journal($results_journal_path, 'https://api.exhibitday.com/v1', $results_workspace_id, 'show-results-objectives', $results_job_id, $results_input_fingerprint, [['save_leads', 'PATCH', '/v1/events'], ['rate_objective', 'PATCH', '/v1/events/objectives']], $results_job_mode); try { require_condition(either(not_value(journal_acknowledged($results_job, 'rate_objective')), journal_acknowledged($results_job, 'save_leads')), 'A future results step is acknowledged before its prerequisite. Stop and reconcile the journal.'); if (journal_acknowledged($results_job, 'save_leads')) { $results_leads_saved = journal_saved($results_job, 'save_leads'); require_condition(both(equal(text(field($results_leads_saved, 'id')), $results_event_id), equal(text(field($results_leads_saved, 'roi_num_leads')), $results_lead_count)), 'Acknowledged results state does not match the selected record and intended value; stop and reconcile.'); } else { $results_leads_patch = (object)['id' => $results_event_id, 'roi_num_leads' => $results_lead_count, 'expected_revision' => $results_leads_revision]; $results_leads_fingerprint = journal_fingerprint((object)['id' => $results_event_id, 'roi_num_leads' => $results_lead_count, 'expected_revision' => $results_leads_revision]); journal_begin($results_job, 'save_leads', 'PATCH', '/v1/events', $results_leads_fingerprint); $results_leads_save_response = call('save_leads', [], $results_leads_patch, null); require_condition(equal(response_status($results_leads_save_response), '200'), 'Expected the endpoint\'s documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome.'); $results_leads_receipt = $results_leads_save_response["body"]; $results_leads_after_revision = text(field($results_leads_receipt, 'record_revision')); require_condition(is_present($results_leads_after_revision), 'A checked save acknowledgement requires its own returned record_revision.'); journal_acknowledge($results_job, 'save_leads', (object)['id' => $results_event_id, 'roi_num_leads' => $results_lead_count, 'record_revision' => $results_leads_after_revision]); } if (journal_acknowledged($results_job, 'rate_objective')) { $results_objective_saved = journal_saved($results_job, 'rate_objective'); require_condition(both(both(equal(text(field($results_objective_saved, 'id')), $results_objective_id), equal(text(field($results_objective_saved, 'achievement_rating')), $results_rating)), equal(text(field($results_objective_saved, 'event_id')), $results_event_id)), 'Acknowledged results state does not match the selected record and intended value; stop and reconcile.'); } else { $results_objective_patch = (object)['id' => $results_objective_id, 'achievement_rating' => $results_rating, 'expected_revision' => $results_objective_revision]; $results_objective_fingerprint = journal_fingerprint((object)['id' => $results_objective_id, 'achievement_rating' => $results_rating, 'expected_revision' => $results_objective_revision]); journal_begin($results_job, 'rate_objective', 'PATCH', '/v1/events/objectives', $results_objective_fingerprint); $results_objective_save_response = call('rate_objective', [], $results_objective_patch, null); require_condition(equal(response_status($results_objective_save_response), '200'), 'Expected the endpoint\'s documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome.'); $results_objective_receipt = $results_objective_save_response["body"]; $results_objective_after_revision = text(field($results_objective_receipt, 'record_revision')); require_condition(is_present($results_objective_after_revision), 'A checked save acknowledgement requires its own returned record_revision.'); journal_acknowledge($results_job, 'rate_objective', (object)['id' => $results_objective_id, 'achievement_rating' => $results_rating, 'record_revision' => $results_objective_after_revision, 'event_id' => $results_event_id]); } $results_event_verify_response = call('verify_event', ['id' => $results_event_id], null, null); require_condition(equal(response_status($results_event_verify_response), '200'), 'Expected the endpoint\'s documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome.'); $results_event_verified = $results_event_verify_response["body"]; require_condition(both(equal(text(field($results_event_verified, 'id')), $results_event_id), equal(text(field($results_event_verified, 'roi_num_leads')), $results_lead_count)), 'The final Event no longer has the acknowledged leads value; inspect it instead of automatically restoring it.'); $results_objective_verify_response = call('verify_objective', ['id' => $results_objective_id], null, null); require_condition(equal(response_status($results_objective_verify_response), '200'), 'Expected the endpoint\'s documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome.'); $results_objective_verified = $results_objective_verify_response["body"]; require_condition(both(equal(text(field($results_objective_verified, 'id')), $results_objective_id), both(equal(text(field($results_objective_verified, 'event_id')), $results_event_id), equal(text(field($results_objective_verified, 'achievement_rating')), $results_rating))), 'The final Objective is missing, rebound or has another rating; earlier saved steps remain in the journal.'); print_value((object)['event_id' => $results_event_id, 'objective_id' => $results_objective_id, 'roi_num_leads' => $results_lead_count, 'achievement_rating' => $results_rating]); } finally { $results_job->close(); } } if (realpath($_SERVER['SCRIPT_FILENAME'] ?? '') === __FILE__) main(); ``` ```ruby # 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":true,"requests":{"workspace_binding":{"method":"GET","path":"/references/workspace_info"},"read_event":{"method":"GET","path":"/events/info"},"read_objective":{"method":"GET","path":"/events/objectives/info"},"save_leads":{"method":"PATCH","path":"/events"},"rate_objective":{"method":"PATCH","path":"/events/objectives"},"verify_event":{"method":"GET","path":"/events/info"},"verify_objective":{"method":"GET","path":"/events/objectives/info"}}}') API_KEY = ENV.fetch('EXHIBITDAY_API_KEY') raise 'Use the API key as one ASCII header value without control characters' if API_KEY.each_codepoint.any?{|point|point<32||point>126} 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, 'DELETE' => Net::HTTP::Delete }.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, key = nil) route = SPEC.fetch('requests').fetch(name) headers = { 'Authorization' => 'Bearer ' + API_KEY, 'Accept' => 'application/json' } if route.fetch('method') == 'POST' headers['Idempotency-Key'] = key || raise('Persist a logical create key before sending POST') # 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) # 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.fetch('method') == 'GET' 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 = resend && (status == 429 || (500..599).cover?(status)) 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, raw: raw } end raise 'Retry limit reached' end def both(left,right);left&&right;end def bounded_whole_number(value,name,maximum) unless /\A(?:0|[1-9][0-9]*)\z/.match?(value) && (value.lengthraw.bytesize-offset value=raw.byteslice(offset,size).dup.force_encoding(Encoding::UTF_8);raise Refusal,'Invalid UTF8 string' unless value.valid_encoding? values<=raw.bytesize-offset payload=raw.byteslice(offset,size);offset+=size raise Refusal,'Journal integrity failed; reconcile before retry' unless raw.getbyte(offset)==10&&digest(payload)==match[2] records<0 offset+=written end file.flush;file.fsync end end class GuideJournal P=GuideJournalProtocol def initialize(path,base,workspace,slug,job,input_fingerprint,writes,mode='resume') @path=path.dup;@lock_path=path+'.lock';@file=nil;@owned=false;@tainted=false;@intents={};@saved={};@allowed={} address=URI(base) raise P::Refusal,'Use actual API base and closed guide slug' unless ['https','http'].include?(address.scheme)&&address.host&&address.userinfo.nil?&&address.query.nil?&&address.fragment.nil?&&slug.match?(/\A[a-z][a-z0-9-]*\z/) raise P::Refusal,'Use actual workspace, stable explicit job ID and exact fingerprint' unless !job.strip.empty?&&workspace.match?(/\A[1-9][0-9]*\z/)&&input_fingerprint.match?(/\A[0-9A-F]{64}\z/) raise P::Refusal,'Choose new or resume for this local job' unless ['new','resume'].include?(mode) manifest=[] writes.each do|step,method,route| raise P::Refusal,'Use closed unique write manifest' unless step.match?(/\A[a-z][a-z0-9_-]*\z/)&&!@allowed.key?(step)&&['POST','PATCH','DELETE'].include?(method)&&route.match?(/\A\/v1\/[A-Za-z0-9_\/-]+\z/)&&!route.include?('//') @allowed[step.dup.freeze]=[method.dup.freeze,route.dup.freeze].freeze;manifest.concat([step,method,route]) end raise P::Refusal,'Only write workflows need a restart journal' if @allowed.empty? @header=['H','1',base,workspace,slug,job,input_fingerprint,P.digest(P.strings(manifest))].map{|value|value.dup.freeze}.freeze;P.strings(@header) begin @file=File.open(@lock_path,File::RDWR|File::CREAT|File::EXCL,0o600);@file.binmode;@owned=true rescue Errno::EEXIST raise P::Refusal,'This journal is locked; do not overlap jobs or steal a stale lock' end begin @owner=SecureRandom.hex(16).freeze;P.write_all(@file,@owner.b);@identity=@file.stat # Ruby's Windows fstat reports dev=0 while lstat reports the drive number. # Both expose the same exact inode. Retain it plus the initial path device; # compare like-for-like instead of treating the differing dev APIs as equal. named_identity=File.lstat(@lock_path);raise P::Refusal,'Lock identity did not bind' unless named_identity.ino==@identity.ino @path_device=named_identity.dev raise P::Refusal,'Choose a private regular journal file' if File.symlink?(@path) raise P::Refusal,'Journal missing: stop and reconcile lost state before starting a new logical job' if mode=='resume'&&!File.exist?(@path) raise P::Refusal,'Journal exists; use resume for the same logical job' if mode=='new'&&File.exist?(@path) if mode=='new' File.open(@path,File::WRONLY|File::CREAT|File::EXCL,0o600){|target|target.binmode;P.write_all(target,P::PREAMBLE+P.frame(@header))} end records=P.decode(File.binread(@path));raise P::Refusal,'Journal workspace/base/guide/job/input binding differs' if records.empty?||records[0]!=@header records.drop(1).each{|record|apply(record)} raise P::Refusal,'Saved intent lacks ACK; stop and reconcile before retry' if @intents.keys.any?{|step|!@saved.key?(step)} rescue Exception close;raise end end def apply(record) case record[0] when 'I' raise P::Refusal,'Invalid intent shape' unless record.length==6 _,step,method,route,fingerprint,key=record raise P::Refusal,'Invalid, future or repeated intent' unless step.match?(/\A[a-z][a-z0-9_-]*\z/)&&!@intents.key?(step)&&@allowed[step]==[method,route]&&fingerprint.match?(/\A[0-9A-F]{64}\z/)&&!@intents.keys.any?{|name|!@saved.key?(name)} raise P::Refusal,'Invalid persisted action key' unless (method=='POST'&&key.match?(/\A[0-9a-f]{32}\z/))||(method!='POST'&&key=='') @intents[step.dup.freeze]={'method'=>method.dup.freeze,'path'=>route.dup.freeze,'request_fingerprint'=>fingerprint.dup.freeze,'idempotency_key'=>key.dup.freeze}.freeze when 'A' raise P::Refusal,'Invalid ACK shape' unless record.length>=3 _,step,count,*pairs=record raise P::Refusal,'ACK without exactly one prior intent' unless count.match?(/\A(?:0|[1-9][0-9]*)\z/)&&pairs.length==2*count.to_i&&@intents.key?(step)&&!@saved.key?(step) names=pairs.each_slice(2).map(&:first) raise P::Refusal,'ACK fields must be unique sorted secret-free identifiers' unless names==names.uniq.sort&&names.all?{|name|name.match?(/\A[a-z][a-z0-9_]*\z/)&&!['api_key','exhibitday_api_key'].include?(name)} @saved[step.dup.freeze]=pairs.each_slice(2).to_h.transform_values{|value|value.dup.freeze}.freeze else raise P::Refusal,'Unknown journal transition' end end def require_active raise P::Refusal,'Journal is closed or IO outcome needs reconciliation' unless @owned&&@file&&!@tainted current=File.lstat(@lock_path) raise P::Refusal,'Journal lock replaced; stop without deleting it' unless current.dev==@path_device&¤t.ino==@identity.ino&&File.binread(@lock_path)==@owner.b end def append(record) require_active;raw=P.frame(record) begin File.open(@path,'ab'){|target|P.write_all(target,raw)} rescue Exception @tainted=true;raise end end def acknowledged(step);require_active;@saved.key?(step);end def saved(step) require_active;raise P::Refusal,'No acknowledged state exists' unless @saved.key?(step) @saved.fetch(step).transform_values(&:dup) end def begin_action(step,method,route,request_fingerprint) require_active;raise P::Refusal,'Never blindly repeat an action' if @intents.key?(step) record=['I',step,method,route,request_fingerprint,method=='POST'?SecureRandom.hex(16):''] previous=@intents.dup;begin;apply(record);ensure;@intents=previous;end append(record);apply(record);@intents.fetch(step).transform_values(&:dup) end def acknowledge(step,saved) require_active;record=['A',step,saved.length.to_s];saved.keys.sort.each{|name|record.concat([name,saved.fetch(name)])} previous=@saved.dup;begin;apply(record);P.strings(record);ensure;@saved=previous;end append(record);apply(record) end def close return unless @owned if @tainted;@file.close;@file=nil;@owned=false;return;end begin;require_active;rescue Exception;@file.close;@file=nil;@owned=false;raise;end @file.close;@file=nil;@owned=false;File.unlink(@lock_path) end end def journal_values(value) raise GuideJournalProtocol::Refusal,'Saved/fingerprint values must be exact strings' unless value.is_a?(Hash)&&value.all?{|name,item|name.is_a?(String)&&item.is_a?(String)} value.transform_values(&:dup) end def journal_acknowledge(job,step,saved);job.acknowledge(step,journal_values(saved));end def journal_acknowledged(job,step);job.acknowledged(step);end def journal_begin(job,step,method,path,request_fingerprint);job.begin_action(step,method,path,request_fingerprint);end def journal_fingerprint(value);GuideJournalProtocol.fingerprint(journal_values(value));end def journal_saved(job,step);job.saved(step);end def not_value(value) raise "Expected a Boolean" unless value==true || value==false !value end def open_journal(path,base,workspace,slug,job,input_fingerprint,writes,mode);GuideJournal.new(path,base,workspace,slug,job,input_fingerprint,writes,mode);end def optional(name,fallback) value=ENV[name] value.nil? || value.empty? ? fallback : value end def positive_id(value) raise "Use a positive record ID" unless /\A[1-9][0-9]*\z/.match?(value) && Integer(value)<=9223372036854775807 value end def print_value(value) STDOUT.binmode.write((value.is_a?(String)?value:JSON.generate(value))+"\n") end def require_condition(value,message) raise message unless value==true end def required(name) value=ENV[name] raise "Set #{name}" if value.nil? || value.strip.empty? value end def response_status(value);value.fetch(:status).to_s;end def text(value) return "" if value.nil? return value.to_s if value.is_a?(String)||value.is_a?(Integer)||value==true||value==false raise "Expected a scalar response value" end def main results_event_id = positive_id(required('EXHIBITDAY_EVENT_ID')) results_objective_id = positive_id(required('EXHIBITDAY_OBJECTIVE_ID')) results_lead_count = bounded_whole_number(required('EXHIBITDAY_LEAD_COUNT'), 'EXHIBITDAY_LEAD_COUNT', '9223372036854775807') results_rating = bounded_whole_number(required('EXHIBITDAY_ACHIEVEMENT_RATING'), 'EXHIBITDAY_ACHIEVEMENT_RATING', '10') results_journal_path = required('EXHIBITDAY_JOURNAL') results_job_id = required('EXHIBITDAY_JOB_ID') results_job_mode = optional('EXHIBITDAY_JOB_MODE', 'resume') results_workspace_response = call('workspace_binding', {}, nil, nil) require_condition(equal(response_status(results_workspace_response), '200'), 'Expected the endpoint\'s documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome.') results_workspace = results_workspace_response.fetch(:body) results_workspace_id = positive_id(text(field(results_workspace, 'id'))) results_event_response = call('read_event', {'id' => results_event_id, '$include_record_revision' => 'true'}, nil, nil) require_condition(equal(response_status(results_event_response), '200'), 'Expected the endpoint\'s documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome.') results_event = results_event_response.fetch(:body) require_condition(equal(text(field(results_event, 'id')), results_event_id), 'Read the exact selected Event before recording results.') results_leads_revision = text(field(results_event, 'record_revision')) require_condition(is_present(results_leads_revision), 'The Event read needs its own actual record_revision.') results_objective_response = call('read_objective', {'id' => results_objective_id, '$include_record_revision' => 'true'}, nil, nil) require_condition(equal(response_status(results_objective_response), '200'), 'Expected the endpoint\'s documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome.') results_objective = results_objective_response.fetch(:body) require_condition(both(equal(text(field(results_objective, 'id')), results_objective_id), equal(text(field(results_objective, 'event_id')), results_event_id)), 'The Objective does not belong to the selected Event; no write was sent.') results_objective_revision = text(field(results_objective, 'record_revision')) require_condition(is_present(results_objective_revision), 'The Objective read needs its own actual record_revision.') results_input_fingerprint = journal_fingerprint({'workflow_contract_sha256' => '94A1426B8C4D275633E918271BB2A2683E06A442317C472320B2E446E00ABCF6', 'event_id' => results_event_id, 'objective_id' => results_objective_id, 'roi_num_leads' => results_lead_count, 'achievement_rating' => results_rating}) results_job = open_journal(results_journal_path, 'https://api.exhibitday.com/v1', results_workspace_id, 'show-results-objectives', results_job_id, results_input_fingerprint, [['save_leads', 'PATCH', '/v1/events'], ['rate_objective', 'PATCH', '/v1/events/objectives']], results_job_mode) begin require_condition(either(not_value(journal_acknowledged(results_job, 'rate_objective')), journal_acknowledged(results_job, 'save_leads')), 'A future results step is acknowledged before its prerequisite. Stop and reconcile the journal.') if journal_acknowledged(results_job, 'save_leads') results_leads_saved = journal_saved(results_job, 'save_leads') require_condition(both(equal(text(field(results_leads_saved, 'id')), results_event_id), equal(text(field(results_leads_saved, 'roi_num_leads')), results_lead_count)), 'Acknowledged results state does not match the selected record and intended value; stop and reconcile.') else results_leads_patch = {'id' => results_event_id, 'roi_num_leads' => results_lead_count, 'expected_revision' => results_leads_revision} results_leads_fingerprint = journal_fingerprint({'id' => results_event_id, 'roi_num_leads' => results_lead_count, 'expected_revision' => results_leads_revision}) journal_begin(results_job, 'save_leads', 'PATCH', '/v1/events', results_leads_fingerprint) results_leads_save_response = call('save_leads', {}, results_leads_patch, nil) require_condition(equal(response_status(results_leads_save_response), '200'), 'Expected the endpoint\'s documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome.') results_leads_receipt = results_leads_save_response.fetch(:body) results_leads_after_revision = text(field(results_leads_receipt, 'record_revision')) require_condition(is_present(results_leads_after_revision), 'A checked save acknowledgement requires its own returned record_revision.') journal_acknowledge(results_job, 'save_leads', {'id' => results_event_id, 'roi_num_leads' => results_lead_count, 'record_revision' => results_leads_after_revision}) end if journal_acknowledged(results_job, 'rate_objective') results_objective_saved = journal_saved(results_job, 'rate_objective') require_condition(both(both(equal(text(field(results_objective_saved, 'id')), results_objective_id), equal(text(field(results_objective_saved, 'achievement_rating')), results_rating)), equal(text(field(results_objective_saved, 'event_id')), results_event_id)), 'Acknowledged results state does not match the selected record and intended value; stop and reconcile.') else results_objective_patch = {'id' => results_objective_id, 'achievement_rating' => results_rating, 'expected_revision' => results_objective_revision} results_objective_fingerprint = journal_fingerprint({'id' => results_objective_id, 'achievement_rating' => results_rating, 'expected_revision' => results_objective_revision}) journal_begin(results_job, 'rate_objective', 'PATCH', '/v1/events/objectives', results_objective_fingerprint) results_objective_save_response = call('rate_objective', {}, results_objective_patch, nil) require_condition(equal(response_status(results_objective_save_response), '200'), 'Expected the endpoint\'s documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome.') results_objective_receipt = results_objective_save_response.fetch(:body) results_objective_after_revision = text(field(results_objective_receipt, 'record_revision')) require_condition(is_present(results_objective_after_revision), 'A checked save acknowledgement requires its own returned record_revision.') journal_acknowledge(results_job, 'rate_objective', {'id' => results_objective_id, 'achievement_rating' => results_rating, 'record_revision' => results_objective_after_revision, 'event_id' => results_event_id}) end results_event_verify_response = call('verify_event', {'id' => results_event_id}, nil, nil) require_condition(equal(response_status(results_event_verify_response), '200'), 'Expected the endpoint\'s documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome.') results_event_verified = results_event_verify_response.fetch(:body) require_condition(both(equal(text(field(results_event_verified, 'id')), results_event_id), equal(text(field(results_event_verified, 'roi_num_leads')), results_lead_count)), 'The final Event no longer has the acknowledged leads value; inspect it instead of automatically restoring it.') results_objective_verify_response = call('verify_objective', {'id' => results_objective_id}, nil, nil) require_condition(equal(response_status(results_objective_verify_response), '200'), 'Expected the endpoint\'s documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome.') results_objective_verified = results_objective_verify_response.fetch(:body) require_condition(both(equal(text(field(results_objective_verified, 'id')), results_objective_id), both(equal(text(field(results_objective_verified, 'event_id')), results_event_id), equal(text(field(results_objective_verified, 'achievement_rating')), results_rating))), 'The final Objective is missing, rebound or has another rating; earlier saved steps remain in the journal.') print_value({'event_id' => results_event_id, 'objective_id' => results_objective_id, 'roi_num_leads' => results_lead_count, 'achievement_rating' => results_rating}) ensure results_job.close() end end main if $PROGRAM_NAME == __FILE__ ``` ```go // Go 1.18+; standard library only. Set EXHIBITDAY_API_KEY. package main import ( "bytes" "crypto/rand" "crypto/sha256" "encoding/hex" "regexp" "sort" "unicode/utf8" "encoding/json" "fmt" "io" "net/http" "net/url" "os" "strconv" "strings" "time" ) const base = "https://api.exhibitday.com/v1" const specification = "{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"read_event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"read_objective\":{\"method\":\"GET\",\"path\":\"/events/objectives/info\"},\"save_leads\":{\"method\":\"PATCH\",\"path\":\"/events\"},\"rate_objective\":{\"method\":\"PATCH\",\"path\":\"/events/objectives\"},\"verify_event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"verify_objective\":{\"method\":\"GET\",\"path\":\"/events/objectives/info\"}}}" 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 }} var send = client.Do type result struct { status int; body any; headers http.Header; raw []byte } // 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 call(name string, query map[string]string, body any, key string) result { route := object(object(spec["requests"])[name]); method := text(route["method"]) headers := map[string]string{"Authorization": "Bearer " + apiKey, "Accept": "application/json"} if method == "POST" { if key == "" { panic("Persist a logical create key before sending POST") }; 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() } // 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 := method == "GET" 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 := send(request) if err != nil { if !resend { panic(apiError{0, "", "No response", true}) }; if attempt == 4 { panic(err) }; time.Sleep(time.Second*time.Duration(1<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 := resend && (response.StatusCode == 429 || response.StatusCode >= 500) if retry { if attempt == 4 { panic("Retry limit reached; check the outcome before starting a new create") } seconds := float64(int64(1)<= 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, raw} } panic("Retry limit reached") } func both(left,right bool)bool{return left&&right} func bounded_whole_number(value,name,maximum string)string{valid:=len(value)>0&&(len(value)==1||value[0]!='0');for _,ch:=range value{valid=valid&&ch>='0'&&ch<='9'};if !valid||len(value)>len(maximum)||(len(value)==len(maximum)&&value>maximum){panic(name+" must be a whole number from 0 through "+maximum)};return value} func either(left,right bool)bool{return left||right} func equal(left,right any)bool{switch a:=left.(type){case string:b,ok:=right.(string);return ok&&a==b;case bool:b,ok:=right.(bool);return ok&&a==b;case int64:b,ok:=right.(int64);return ok&&a==b};return left==nil&&right==nil} func field(value any,name string)any{obj,ok:=value.(map[string]any);if !ok{panic("Missing response object")};item,found:=obj[name];if !found{panic("Missing response field: "+name)};return item} func is_present(value string)bool{return value!=""} // Private client restart state only; no API transport or workflow interpreter. const journalPreamble = "EXHIBITDAY-GUIDE-JOURNAL 1\n" type journalRefusal struct{ message string } func (e journalRefusal) Error() string { return e.message } func journalNeed(ok bool, message string) { if !ok { panic(journalRefusal{message}) } } func journalMatch(value, pattern string) bool { return regexp.MustCompile("\\A(?:"+pattern+")\\z").MatchString(value) } func journalStrings(values []string) []byte { var output bytes.Buffer for _,value:=range values { journalNeed(utf8.ValidString(value),"Journal fields must be valid UTF8 strings"); output.WriteString(strconv.Itoa(len(value))+":");output.WriteString(value) } return output.Bytes() } func journalReadStrings(raw []byte) []string { values:=[]string{};offset:=0 for offset=0,"Incomplete journal string length");end:=offset+relative;text:=string(raw[offset:end]);journalNeed(journalMatch(text,"0|[1-9][0-9]*"),"Noncanonical journal string length");size,err:=strconv.ParseUint(text,10,64);offset=end+1;journalNeed(err==nil&&size<=uint64(len(raw)-offset),"Incomplete journal string");count:=int(size);value:=string(raw[offset:offset+count]);journalNeed(utf8.ValidString(value),"Invalid UTF8 journal field");values=append(values,value);offset+=count } return values } func journalDigest(raw []byte) string { hash:=sha256.Sum256(raw);return strings.ToUpper(hex.EncodeToString(hash[:])) } func journalFingerprint(pairs map[string]string) string { names:=make([]string,0,len(pairs));for name:=range pairs { names=append(names,name) };sort.Strings(names);values:=[]string{} for _,name:=range names { lower:=strings.ToLower(name);journalNeed(journalMatch(name,"[A-Za-z0-9_.-]+")&&lower!="api_key"&&lower!="exhibitday_api_key","Use explicit secret-free fingerprint names");values=append(values,name,pairs[name]) } return journalDigest(journalStrings(values)) } func journalFrame(values []string) []byte { raw:=journalStrings(values);header:=[]byte(strconv.Itoa(len(raw))+" "+journalDigest(raw)+"\n");result:=append(header,raw...);return append(result,'\n') } func journalDecode(raw []byte) [][]string { journalNeed(bytes.HasPrefix(raw,[]byte(journalPreamble)),"Unknown or incomplete journal version");offset:=len(journalPreamble);records:=[][]string{} for offset=0,"Incomplete frame header; reconcile before retry");end:=offset+relative;header:=string(raw[offset:end]);journalNeed(journalMatch(header,"(0|[1-9][0-9]*) [0-9A-F]{64}"),"Invalid frame header");fields:=strings.Split(header," ");size,err:=strconv.ParseUint(fields[0],10,64);offset=end+1;journalNeed(err==nil&&size0 { count,err:=file.Write(raw);if err!=nil{return err};if count<=0{return io.ErrShortWrite};raw=raw[count:] } return file.Sync() } func journalWriteFile(path string,flags int,raw []byte) (err error) { file,err:=os.OpenFile(path,flags,0600);if err!=nil{return err};defer func(){closed:=file.Close();if err==nil{err=closed}}();return journalWriteAll(file,raw) } func journalCopy(source map[string]string) map[string]string { copy:=map[string]string{};for name,value:=range source{copy[name]=value};return copy } func journalCopyStates(source map[string]map[string]string) map[string]map[string]string { copy:=map[string]map[string]string{};for name,value:=range source{copy[name]=journalCopy(value)};return copy } type guideJournal struct { path,lockPath,owner string header []string allowed map[string][2]string intents,savedValues map[string]map[string]string file *os.File identity os.FileInfo owned,tainted bool } func openGuideJournal(path,base,workspace,slug,job,inputFingerprint string,writes [][3]string,modes ...string) (result *guideJournal) { mode:="resume";journalNeed(len(modes)<=1,"Choose one local job mode");if len(modes)==1{mode=modes[0]};journalNeed(mode=="new"||mode=="resume","Choose new or resume for this local job") address,err:=url.Parse(base);journalNeed(err==nil&&address.Hostname()!=""&&(address.Scheme=="https"||address.Scheme=="http")&&address.User==nil&&address.RawQuery==""&&address.Fragment==""&&journalMatch(slug,"[a-z][a-z0-9-]*"),"Use actual API base and closed guide slug") journalNeed(strings.TrimSpace(job)!=""&&journalMatch(workspace,"[1-9][0-9]*")&&journalMatch(inputFingerprint,"[0-9A-F]{64}"),"Use actual workspace, stable explicit job ID and exact fingerprint") j:=&guideJournal{path:path,lockPath:path+".lock",allowed:map[string][2]string{},intents:map[string]map[string]string{},savedValues:map[string]map[string]string{}} manifest:=[]string{};for _,write:=range writes { step,method,route:=write[0],write[1],write[2];_,exists:=j.allowed[step];journalNeed(journalMatch(step,"[a-z][a-z0-9_-]*")&&!exists&&(method=="POST"||method=="PATCH"||method=="DELETE")&&journalMatch(route,"/v1/[A-Za-z0-9_/-]+")&&!strings.Contains(route,"//"),"Use a closed unique write manifest");j.allowed[step]=[2]string{method,route};manifest=append(manifest,step,method,route) } journalNeed(len(j.allowed)>0,"Only write workflows need a restart journal");j.header=[]string{"H","1",base,workspace,slug,job,inputFingerprint,journalDigest(journalStrings(manifest))};journalStrings(j.header) j.file,err=os.OpenFile(j.lockPath,os.O_RDWR|os.O_CREATE|os.O_EXCL,0600);if err!=nil { if os.IsExist(err){panic(journalRefusal{"This journal is locked; do not overlap jobs or steal a stale lock"})};panic(err) };j.owned=true defer func(){ if observed:=recover();observed!=nil { j.Close();panic(observed) } }() random:=make([]byte,16);if _,err=io.ReadFull(rand.Reader,random);err!=nil{panic(err)};j.owner=hex.EncodeToString(random);if err=journalWriteAll(j.file,[]byte(j.owner));err!=nil{panic(err)};j.identity,err=j.file.Stat();if err!=nil{panic(err)} info,err:=os.Lstat(path);if err!=nil&&!os.IsNotExist(err){panic(err)};exists:=err==nil;if exists{journalNeed(info.Mode()&os.ModeSymlink==0,"Choose a private regular journal file")};journalNeed(mode!="resume"||exists,"Journal missing: stop and reconcile lost state before starting a new logical job");journalNeed(mode!="new"||!exists,"Journal exists; use resume for the same logical job");if mode=="new"{raw:=append([]byte(journalPreamble),journalFrame(j.header)...);if err=journalWriteFile(path,os.O_WRONLY|os.O_CREATE|os.O_EXCL,raw);err!=nil{panic(err)}} raw,err:=os.ReadFile(path);if err!=nil{panic(err)};records:=journalDecode(raw);journalNeed(len(records)>0&&stringsEqual(records[0],j.header),"Journal workspace/base/guide/job/input binding differs");for _,record:=range records[1:]{j.apply(record)};for step:=range j.intents{_,ok:=j.savedValues[step];journalNeed(ok,"Saved intent lacks ACK; stop and reconcile before retry")};return j } func stringsEqual(left,right []string) bool { if len(left)!=len(right){return false};for i,value:=range left{if value!=right[i]{return false}};return true } func (j *guideJournal) apply(record []string) { journalNeed(len(record)>0,"Empty journal record") if record[0]=="I" { journalNeed(len(record)==6,"Invalid intent shape");step,method,route,fingerprint,key:=record[1],record[2],record[3],record[4],record[5];_,exists:=j.intents[step];expected,allowed:=j.allowed[step];pending:=false;for name:=range j.intents{if _,ok:=j.savedValues[name];!ok{pending=true}} journalNeed(journalMatch(step,"[a-z][a-z0-9_-]*")&&!exists&&allowed&&expected==[2]string{method,route}&&journalMatch(fingerprint,"[0-9A-F]{64}")&&!pending,"Invalid, future or repeated intent");journalNeed(method=="POST"&&journalMatch(key,"[0-9a-f]{32}")||method!="POST"&&key=="","Invalid persisted action key");j.intents[step]=map[string]string{"method":method,"path":route,"request_fingerprint":fingerprint,"idempotency_key":key} }else if record[0]=="A" { journalNeed(len(record)>=3,"Invalid ACK shape");step,text:=record[1],record[2];count,err:=strconv.ParseUint(text,10,64);_,prior:=j.intents[step];_,done:=j.savedValues[step];journalNeed(journalMatch(text,"0|[1-9][0-9]*")&&err==nil&&len(record)%2==1&&count==uint64((len(record)-3)/2)&&prior&&!done,"ACK without exactly one prior intent");names:=[]string{};for i:=3;i0&&value[0]!='0';for _,ch:=range value{valid=valid&&ch>='0'&&ch<='9'};id,err:=strconv.ParseInt(value,10,64);if !valid||err!=nil||id<=0{panic("Use a positive record ID")};return value} func print_value(value any){if result,ok:=value.(string);ok{fmt.Println(result);return};raw,err:=json.Marshal(value);if err!=nil{panic(err)};fmt.Println(string(raw))} func require_condition(value bool,message string){if !value{panic(message)}} func response_status(value result)string{return strconv.Itoa(value.status)} func workflow() { results_event_id := positive_id(required("EXHIBITDAY_EVENT_ID")) results_objective_id := positive_id(required("EXHIBITDAY_OBJECTIVE_ID")) results_lead_count := bounded_whole_number(required("EXHIBITDAY_LEAD_COUNT"), "EXHIBITDAY_LEAD_COUNT", "9223372036854775807") results_rating := bounded_whole_number(required("EXHIBITDAY_ACHIEVEMENT_RATING"), "EXHIBITDAY_ACHIEVEMENT_RATING", "10") results_journal_path := required("EXHIBITDAY_JOURNAL") results_job_id := required("EXHIBITDAY_JOB_ID") results_job_mode := optional("EXHIBITDAY_JOB_MODE", "resume") results_workspace_response := call("workspace_binding", map[string]string{}, nil, "") require_condition(equal(response_status(results_workspace_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome.") results_workspace := results_workspace_response.body results_workspace_id := positive_id(text(field(results_workspace, "id"))) results_event_response := call("read_event", map[string]string{"id": results_event_id, "$include_record_revision": "true"}, nil, "") require_condition(equal(response_status(results_event_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome.") results_event := results_event_response.body require_condition(equal(text(field(results_event, "id")), results_event_id), "Read the exact selected Event before recording results.") results_leads_revision := text(field(results_event, "record_revision")) require_condition(is_present(results_leads_revision), "The Event read needs its own actual record_revision.") results_objective_response := call("read_objective", map[string]string{"id": results_objective_id, "$include_record_revision": "true"}, nil, "") require_condition(equal(response_status(results_objective_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome.") results_objective := results_objective_response.body require_condition(both(equal(text(field(results_objective, "id")), results_objective_id), equal(text(field(results_objective, "event_id")), results_event_id)), "The Objective does not belong to the selected Event; no write was sent.") results_objective_revision := text(field(results_objective, "record_revision")) require_condition(is_present(results_objective_revision), "The Objective read needs its own actual record_revision.") results_input_fingerprint := journal_fingerprint(map[string]any{"workflow_contract_sha256": "94A1426B8C4D275633E918271BB2A2683E06A442317C472320B2E446E00ABCF6", "event_id": results_event_id, "objective_id": results_objective_id, "roi_num_leads": results_lead_count, "achievement_rating": results_rating}) func() { results_job := open_journal(results_journal_path, "https://api.exhibitday.com/v1", results_workspace_id, "show-results-objectives", results_job_id, results_input_fingerprint, []any{[]any{"save_leads", "PATCH", "/v1/events"}, []any{"rate_objective", "PATCH", "/v1/events/objectives"}}, results_job_mode) defer results_job.Close() require_condition(either(not_value(journal_acknowledged(results_job, "rate_objective")), journal_acknowledged(results_job, "save_leads")), "A future results step is acknowledged before its prerequisite. Stop and reconcile the journal.") if journal_acknowledged(results_job, "save_leads") { results_leads_saved := journal_saved(results_job, "save_leads") require_condition(both(equal(text(field(results_leads_saved, "id")), results_event_id), equal(text(field(results_leads_saved, "roi_num_leads")), results_lead_count)), "Acknowledged results state does not match the selected record and intended value; stop and reconcile.") } else { results_leads_patch := map[string]any{"id": results_event_id, "roi_num_leads": results_lead_count, "expected_revision": results_leads_revision} results_leads_fingerprint := journal_fingerprint(map[string]any{"id": results_event_id, "roi_num_leads": results_lead_count, "expected_revision": results_leads_revision}) journal_begin(results_job, "save_leads", "PATCH", "/v1/events", results_leads_fingerprint) results_leads_save_response := call("save_leads", map[string]string{}, results_leads_patch, "") require_condition(equal(response_status(results_leads_save_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome.") results_leads_receipt := results_leads_save_response.body results_leads_after_revision := text(field(results_leads_receipt, "record_revision")) require_condition(is_present(results_leads_after_revision), "A checked save acknowledgement requires its own returned record_revision.") journal_acknowledge(results_job, "save_leads", map[string]any{"id": results_event_id, "roi_num_leads": results_lead_count, "record_revision": results_leads_after_revision}) } if journal_acknowledged(results_job, "rate_objective") { results_objective_saved := journal_saved(results_job, "rate_objective") require_condition(both(both(equal(text(field(results_objective_saved, "id")), results_objective_id), equal(text(field(results_objective_saved, "achievement_rating")), results_rating)), equal(text(field(results_objective_saved, "event_id")), results_event_id)), "Acknowledged results state does not match the selected record and intended value; stop and reconcile.") } else { results_objective_patch := map[string]any{"id": results_objective_id, "achievement_rating": results_rating, "expected_revision": results_objective_revision} results_objective_fingerprint := journal_fingerprint(map[string]any{"id": results_objective_id, "achievement_rating": results_rating, "expected_revision": results_objective_revision}) journal_begin(results_job, "rate_objective", "PATCH", "/v1/events/objectives", results_objective_fingerprint) results_objective_save_response := call("rate_objective", map[string]string{}, results_objective_patch, "") require_condition(equal(response_status(results_objective_save_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome.") results_objective_receipt := results_objective_save_response.body results_objective_after_revision := text(field(results_objective_receipt, "record_revision")) require_condition(is_present(results_objective_after_revision), "A checked save acknowledgement requires its own returned record_revision.") journal_acknowledge(results_job, "rate_objective", map[string]any{"id": results_objective_id, "achievement_rating": results_rating, "record_revision": results_objective_after_revision, "event_id": results_event_id}) } results_event_verify_response := call("verify_event", map[string]string{"id": results_event_id}, nil, "") require_condition(equal(response_status(results_event_verify_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome.") results_event_verified := results_event_verify_response.body require_condition(both(equal(text(field(results_event_verified, "id")), results_event_id), equal(text(field(results_event_verified, "roi_num_leads")), results_lead_count)), "The final Event no longer has the acknowledged leads value; inspect it instead of automatically restoring it.") results_objective_verify_response := call("verify_objective", map[string]string{"id": results_objective_id}, nil, "") require_condition(equal(response_status(results_objective_verify_response), "200"), "Expected the endpoint's documented HTTP200 acknowledgement. Preserve pending state and reconcile any other outcome.") results_objective_verified := results_objective_verify_response.body require_condition(both(equal(text(field(results_objective_verified, "id")), results_objective_id), both(equal(text(field(results_objective_verified, "event_id")), results_event_id), equal(text(field(results_objective_verified, "achievement_rating")), results_rating))), "The final Objective is missing, rebound or has another rating; earlier saved steps remain in the journal.") print_value(map[string]any{"event_id": results_event_id, "objective_id": results_objective_id, "roi_num_leads": results_lead_count, "achievement_rating": results_rating}) }() } func header_key(value string)string{for _,ch:=range value{if ch<32||ch>126{panic("Use the API key as one ASCII header value without control characters")}};return value} func main(){apiKey=header_key(required("EXHIBITDAY_API_KEY"));if err:=json.Unmarshal([]byte(specification),&spec);err!=nil{panic(err)};workflow()} ``` #### Example response Response 200 — OK 304 — Not Modified 400 — Bad Request 401 — Unauthorized 404 — Not Found 409 — Conflict 429 — Too Many Requests 500 — Internal Server Error Example Successful request ```json { "id": 8001, "event_id": 5001, "event_name": "Spring Expo 2030", "objective_type_id": 1, "objective_type": "Lead Generation", "name": "Lead Generation", "importance_id": 2, "importance": "Medium", "achievement_rating": 8, "objective_created_timestamp": "2030-01-03T14:30:00Z" } ``` Note: The Objective as read after the save. It shows achievement rating 8. The Event read before it already showed 48 leads. Note: There is no response body. Keep using your cached response. ```json { "status_code": 400, "status": "Bad Request", "message": "X-HTTP-Method-Override: hTTP method override is not supported.", "error_code": "invalid_request", "errors": [ "Send the documented HTTP method directly. X-HTTP-Method-Override cannot change a request's HTTP method." ], "error_params": [ "X-HTTP-Method-Override" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "No API key was provided. Send your key in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "missing_api_key", "errors": [ "Copy the key from Workspace Settings > API & Integrations > API Access in ExhibitDay." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "The API key is not valid. Check that you copied the whole key from Workspace Settings > API & Integrations > API Access, then send it in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "invalid_api_key", "errors": [ "Check that you sent the whole key. If it was regenerated, use the current key from Workspace Settings > API & Integrations > API Access." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "Access to the ExhibitDay API is not enabled for your workspace. Please contact support@exhibitday.com to enable API Access. Once access is enabled, send your key in the Authorization header as 'Bearer YOUR_API_KEY'.", "error_code": "api_access_disabled", "errors": [ "Nothing was read or changed." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "The API key is not valid for this request. Send your current key in the Authorization header as 'Bearer YOUR_API_KEY'.", "error_code": "invalid_api_key", "errors": [ "The API key is not valid for this request. Send your current key in the Authorization header as 'Bearer YOUR_API_KEY'." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "Access to the ExhibitDay API is not enabled for your workspace. Please contact support@exhibitday.com to enable API Access. Once access is enabled, send your key in the Authorization header as 'Bearer YOUR_API_KEY'.", "error_code": "api_access_disabled", "errors": [ "Access to the ExhibitDay API is not enabled for your workspace. Please contact support@exhibitday.com to enable API Access. Once access is enabled, send your key in the Authorization header as 'Bearer YOUR_API_KEY'." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 404, "status": "Not Found", "message": "Event Objective not found. Invalid Event Objective ID: 12345.", "error_code": "not_found", "errors": [ "Event Objective not found. Invalid Event Objective ID: 12345." ], "error_params": [ "id" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 404, "status": "Not Found", "message": "Event Objective not found. Invalid Event Objective ID: 12345.", "error_code": "not_found", "errors": [ "Event Objective not found. Invalid Event Objective ID: 12345." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "The Objective entries changed while they were being read. Send the GET request again.", "error_code": "record_changed", "errors": [ "The Objective entries changed while they were being read. Send the GET request again." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 429, "status": "Too Many Requests", "message": "Error 429 - Too Many Requests", "error_code": "rate_limited", "errors": [ "Error 429 - Too Many Requests" ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "An unexpected error occurred. Please try again later." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "An unexpected error occurred. Please try again later." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` Note: Use the request_id from your own response when contacting support. ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "Check whether your change was saved before trying again." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` #### Things to keep in mind - An achievement rating is a whole number from 0 through 10. - ExhibitDay calculates the read-only ROO score from rated Objectives and their importance. - Other Objectives can affect the score. It can be null if the score cannot be calculated or the key cannot read ROI results. #### If a run stops - Keep the journal private. It records what the program tried to save and which save it confirmed. - To continue a run with no unresolved save, use `EXHIBITDAY_JOB_MODE=resume` with the same job ID, journal path and inputs. - A resumed run skips acknowledged saves. It stops if an Objective save is recorded without the lead count save. - If a save stops with a conflict, a lost response or a missing revision, check the Event and Objective in ExhibitDay before running the program again. - If you still need a change after checking the old run, use `EXHIBITDAY_JOB_MODE=new` with a new job ID and journal path. - Run only one copy per journal. - If a crash leaves a `.lock` file, make sure no copy using that journal is running or can start. Then remove the lock file and keep the journal. #### Related guides - [Avoid Overwriting Someone Else's Changes](https://api.exhibitday.com/Help/V1?guide=update-records-safely) - [Handle Errors and Retry Failed Requests](https://api.exhibitday.com/Help/V1?guide=errors-and-retries) ### Copy Tasks from a Previous Event Guide page: https://api.exhibitday.com/Help/V1?guide=reuse-event-plan Copy last year's Tasks into this year's Event instead of rebuilding the checklist. Example use case You're planning this year's show and want to reuse part of the previous Event's checklist. What you'll end up with New Tasks in the target Event and a mapping from each selected source Task to its copy. Before you start Have a workspace API key and two different Event IDs in the same workspace. The Premium or Enterprise plan and current Task-board permissions must allow reading source Tasks and creating Tasks in the target. Good to know The original Tasks stay in place. New Tasks start incomplete. Source sections, comments and completion history are left behind. #### At a glance Time to try About 10 minutes Effect on your data Creates records Endpoints 4 The program copies selected Tasks into the target Event and writes a private local journal. - [`GET /v1/references/workspace_info`](https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-workspace_info) - [`GET /v1/events/info`](https://api.exhibitday.com/Help/V1?epf=1#get-v1-events-info) - [`POST /v1/tasks/import_from_event`](https://api.exhibitday.com/Help/V1?epf=2#post-v1-tasks-import_from_event) - [`GET /v1/tasks/info`](https://api.exhibitday.com/Help/V1?epf=2#get-v1-tasks-info) #### How it works 1. Choose two different Events and the Tasks you want to copy. 2. The program confirms both Events, then copies the selected Tasks into the target. 3. It records the source and copy IDs and reads each copy to verify it. #### Copy and verify the selected Tasks The examples below follow one import into a different Event. The program skips the import on resume when the journal already has a checked response. **Manual example.** To find IDs, [list Tasks for the source Event](https://api.exhibitday.com/Help/V1?epf=2#get-v1-tasks). Read every page you need and choose the Task IDs. The program starts with the IDs you supply. `curl -X GET "https://api.exhibitday.com/v1/tasks?filter_by_event_id=12345" -H "Authorization: Bearer YOUR_API_KEY"` **Check:** Use distinct IDs from the source Event. #### Step 1: Confirm the workspace Check where the key will make changes so you can confirm the workspace. ```bash curl -X GET "https://api.exhibitday.com/v1/references/workspace_info" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "id": 98765 } ``` **Check:** Confirm id is the workspace you intended to use. #### Step 2: Read the source Event Confirm which earlier Event holds the Tasks you want to copy. ```bash curl -X GET "https://api.exhibitday.com/v1/events/info?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "id": 12345 } ``` **Check:** Confirm id is the source Event. Use Task IDs from this Event. #### Step 3: Read the target Event Confirm where the copied Tasks will go. ```bash curl -X GET "https://api.exhibitday.com/v1/events/info?id=23456" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "id": 23456 } ``` **Check:** Confirm id is the target Event and differs from the source Event ID. #### Step 4: Import the selected Tasks Send the source, target and selected Task IDs with the options you want to retain. ```bash curl -X POST "https://api.exhibitday.com/v1/tasks/import_from_event" -H "Authorization: Bearer YOUR_API_KEY" -H "Idempotency-Key: YOUR_PERSISTED_IMPORT_KEY" -H "Content-Type: application/json" --data-binary "{\"source_event_id\":12345,\"event_id\":23456,\"task_ids\":\"[34567]\",\"task_section_id\":\"\",\"keep_assignees\":false,\"due_date_mode\":\"none\",\"keep_attachments\":false}" ``` Example response ```json { "source_event_id": 12345, "event_id": 23456, "tasks_copied": 1, "tasks": [ { "source_task_id": 34567, "id": 45678 } ] } ``` **Check:** Confirm source_event_id, event_id and tasks_copied. Keep each source_task_id and new id, along with the file counts. #### Step 5: Verify the copied Tasks Read each new Task by the ID returned in the import response. ```bash curl -X GET "https://api.exhibitday.com/v1/tasks/info?id=45678" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "id": 45678, "event": { "id": 23456 } } ``` **Check:** Confirm id is the returned new Task ID and event.id is the target Event ID. **Careful.** If a response is lost, the import may or may not have happened. The program stops. Check the target Event before deciding whether a new import is needed. #### Choose what to retain | Option | Behavior | | --- | --- | | `task_section_id` | Choose an existing section under the target Event, or leave the setting blank for Uncategorized. | | `keep_assignees` | Defaults to false, so copies are unassigned and have no tagged people. True keeps current eligible assignees and tags. An unavailable assignee stops the import. The import sends no new assignment or tagging emails. | | `due_date_mode` | Use none to leave due dates empty, same_date to keep each saved due date, or same_offset to place each due date the same number of days before or after the target Event's start as it was relative to the source Event's start. An out-of-range result refuses the import. Use lowercase in the program. | | `keep_attachments` | Defaults to false. True adds the saved attachments to the new Tasks and copies their files in the background. Files that cannot be copied, such as files with an unsupported name, are not added. | #### Try it **Careful.** This example changes data in your workspace. Use a test Event. #### Before running the example | Variable | What to put in it | Required? | | --- | --- | --- | | `EXHIBITDAY_API_KEY` | Your workspace API key. | Yes | | `EXHIBITDAY_SOURCE_EVENT_ID` | The ID of the previous Event. | Yes | | `EXHIBITDAY_EVENT_ID` | The ID of a different target Event in the same workspace. | Yes | | `EXHIBITDAY_TASK_IDS` | A nonempty JSON array of distinct positive integer IDs, such as [34567]. | Yes | | `EXHIBITDAY_JOB_ID` | A stable ID for this logical change. | Yes | | `EXHIBITDAY_JOURNAL` | A private local path for this job's journal. | Yes | | `EXHIBITDAY_TASK_SECTION_ID` | Leave blank or supply a target section ID. | No | | `EXHIBITDAY_KEEP_ASSIGNEES` | Use true to keep eligible assignments and tags. | No | | `EXHIBITDAY_DUE_DATE_MODE` | Use none, same_date or same_offset. | No | | `EXHIBITDAY_KEEP_ATTACHMENTS` | Use true to copy readable saved attachments. | No | | `EXHIBITDAY_JOB_MODE` | Use new for a genuinely new job or resume with the existing journal. The default is resume. | No | #### Bash ``` export EXHIBITDAY_API_KEY='YOUR_API_KEY' export EXHIBITDAY_SOURCE_EVENT_ID='12345' export EXHIBITDAY_EVENT_ID='23456' export EXHIBITDAY_TASK_IDS='[34567]' ``` #### PowerShell ``` $env:EXHIBITDAY_API_KEY = 'YOUR_API_KEY' $env:EXHIBITDAY_SOURCE_EVENT_ID = '12345' $env:EXHIBITDAY_EVENT_ID = '23456' $env:EXHIBITDAY_TASK_IDS = '[34567]' ``` Use your own source, target and Task IDs. Set a private journal path and job ID. Set `EXHIBITDAY_JOB_MODE=new` for a new job. Then copy the complete example program below in your language and run it. #### Complete example program Code Samples ```bash #!/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\"},\"source\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"target\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"import_tasks\":{\"method\":\"POST\",\"path\":\"/tasks/import_from_event\"},\"verify_task\":{\"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("Persist a logical create key before sending POST") headers["Idempotency-Key"] = key data = None if body is None else json.dumps(body).encode("utf-8") if data is not None: headers["Content-Type"] = "application/json" query = urllib.parse.urlencode(params or {}) url = BASE + route["path"] + ("?" + query if query else "") # Only GET has automatic retries in this workflow. A PATCH or DELETE that got no response or a # server error is never resent blindly: it may already have been applied, so the caller reads the record first. resend = route["method"] == "GET" for attempt in range(5): try: status, raw, response_headers = transport(route["method"], url, headers, data) except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException): if not resend: raise ApiError(0, None, uncertain=True) if attempt == 4: raise time.sleep(2 ** attempt) continue response_headers = {k.lower(): v for k, v in response_headers.items()} result = None if status != 304 and raw: try: result = decode_json(raw.decode("utf-8")) except (ValueError, UnicodeError): if status < 400: raise RuntimeError("Expected a JSON success response") if status >= 500 and not resend: raise ApiError(status, result, uncertain=True) retry = resend and (status == 429 or status >= 500) if retry: if attempt == 4: raise RuntimeError("Retry limit reached; check the request outcome before starting a new create") delay = response_headers.get("retry-after", str(2 ** attempt)) time.sleep(max(0, float(delay))) continue if status >= 400: raise ApiError(status, result) return {"status": status, "body": result, "headers": response_headers, "raw": raw} raise RuntimeError("Retry limit reached") def both(left,right): return left and right def items(value): if not isinstance(value, list): raise RuntimeError("Expected a JSON array") return value def count(value): return len(items(value)) 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] 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 offsetlen(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)-offset:raise JournalRefusal('Incomplete journal frame; reconcile before retry') payload=raw[offset:offset+size];offset+=size if raw[offset:offset+1]!=b'\n' or digest(payload).encode('ascii')!=match[2]:raise JournalRefusal('Journal integrity check failed; reconcile before retry') records.append(read_strings(payload));offset+=1 return records class Journal: def __init__(self,path,base,workspace,slug,job,input_fingerprint,writes,mode="resume"): self.path=Path(path);self.lock=Path(str(self.path)+'.lock');self.fd=None;self.owned=False;self.identity=None;self.tainted=False;self.intents={};self.saved_values={} address=urlsplit(base) if address.scheme not in ('https','http')or not address.netloc or address.username is not None or address.query or address.fragment or not re.fullmatch('[a-z][a-z0-9-]*',slug):raise JournalRefusal('Use the actual API base and closed guide slug') if not job.strip() or not re.fullmatch('[1-9][0-9]*',workspace) or not re.fullmatch('[0-9A-F]{64}',input_fingerprint):raise JournalRefusal('Use an actual workspace, explicit stable job ID and exact input fingerprint') if mode not in ("new","resume"):raise JournalRefusal("Choose new or resume for this local job") self.allowed={};manifest=[] for step,method,route in writes: if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.allowed or method not in ('POST','PATCH','DELETE')or not re.fullmatch('/v1/[A-Za-z0-9_/-]+',route)or'//'in route:raise JournalRefusal('Use a closed unique write manifest') self.allowed[step]=(method,route);manifest.extend((step,method,route)) if not self.allowed:raise JournalRefusal('Only write workflows need a restart journal') self.header=['H','1',base,workspace,slug,job,input_fingerprint,digest(strings(manifest))] strings(self.header) try: self.fd=os.open(self.lock,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600);self.owned=True except FileExistsError:raise JournalRefusal('This journal is locked; do not run overlapping jobs or steal a stale lock') try: self.owner=secrets.token_hex(16);self.identity=os.fstat(self.fd) if os.write(self.fd,self.owner.encode('ascii'))!=len(self.owner):raise OSError('Incomplete lock identity write') os.fsync(self.fd) if self.path.is_symlink():raise JournalRefusal('Choose a private regular journal file') if mode=="resume" and not self.path.exists():raise JournalRefusal("Journal missing: stop and reconcile lost state before starting a new logical job") if mode=="new" and self.path.exists():raise JournalRefusal("A journal already exists; use resume for the same logical job") if mode=="new": with open(self.path,'xb',buffering=0)as target: target.write(PREAMBLE+frame(self.header));os.fsync(target.fileno()) records=decode(self.path.read_bytes()) if not records or records[0]!=self.header:raise JournalRefusal('Journal workspace/base/guide/job/input binding differs') for record in records[1:]:self.apply(record) if any(step not in self.saved_values for step in self.intents):raise JournalRefusal('A saved before-send intent lacks an ACK; stop and reconcile its outcome before retry') except BaseException: self.close();raise def apply(self,record): if not record:raise JournalRefusal('Empty journal record') if record[0]=='I': if len(record)!=6:raise JournalRefusal('Invalid intent shape') _,step,method,path,request_fingerprint,key=record if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.intents or self.allowed.get(step)!=(method,path)or not re.fullmatch('[0-9A-F]{64}',request_fingerprint)or any(name not in self.saved_values for name in self.intents):raise JournalRefusal('Invalid, future or repeated journal intent') if method=='POST'and not re.fullmatch('[0-9a-f]{32}',key)or method!='POST'and key!='':raise JournalRefusal('Invalid persisted action key') self.intents[step]={'method':method,'path':path,'request_fingerprint':request_fingerprint,'idempotency_key':key} elif record[0]=='A': if len(record)<3:raise JournalRefusal('Invalid ACK shape') _,step,count,*pairs=record if not re.fullmatch('0|[1-9][0-9]*',count)or len(pairs)!=2*int(count)or step not in self.intents or step in self.saved_values:raise JournalRefusal('ACK without exactly one prior intent') names=pairs[::2] if names!=sorted(set(names))or any(not re.fullmatch('[a-z][a-z0-9_]*',name)or name in ('api_key','exhibitday_api_key')for name in names):raise JournalRefusal('ACK saved fields must be unique sorted secret-free identifiers') self.saved_values[step]=dict(zip(names,pairs[1::2])) else:raise JournalRefusal('Unknown journal transition') def append(self,record): # The reader commits state only after complete length/digest recognition. # A torn append is retained and refused, never silently truncated. self.require_active();raw=frame(record) try: with open(self.path,'ab',buffering=0)as target: view=memoryview(raw) while view: written=target.write(view) if not written:raise OSError('Journal write did not advance') view=view[written:] os.fsync(target.fileno()) except BaseException: self.tainted=True;raise def require_active(self): if not self.owned or self.fd is None or self.identity is None or self.tainted:raise JournalRefusal('The journal scope is closed or its IO outcome needs reconciliation') current=self.lock.stat(follow_symlinks=False) if current.st_dev!=self.identity.st_dev or current.st_ino!=self.identity.st_ino or self.lock.read_text(encoding='ascii')!=self.owner:raise JournalRefusal('The journal lock was replaced; stop without deleting it') def acknowledged(self,step): self.require_active();return step in self.saved_values def saved(self,step): self.require_active() if step not in self.saved_values:raise JournalRefusal('No acknowledged state exists for this step') return dict(self.saved_values[step]) def begin(self,step,method,path,request_fingerprint): self.require_active() if step in self.intents:raise JournalRefusal('Never blindly repeat an existing action intent') key=secrets.token_hex(16)if method=='POST'else'' record=['I',step,method,path,request_fingerprint,key] # Validate on an isolated state before touching the file. old=dict(self.intents) try:self.apply(record) finally:self.intents=old self.append(record);self.apply(record) return dict(self.intents[step]) def acknowledge(self,step,saved): self.require_active() record=['A',step,str(len(saved))] for name,value in sorted(saved.items()):record.extend((name,value)) old={name:dict(value)for name,value in self.saved_values.items()} try:self.apply(record);strings(record) finally:self.saved_values=old self.append(record);self.apply(record) def close(self): if self.owned: if self.tainted: os.close(self.fd);self.fd=None;self.owned=False return # Retain this lock after failed journal IO; manual reconciliation is required. try:self.require_active() except BaseException: os.close(self.fd);self.fd=None;self.owned=False;raise os.close(self.fd);self.fd=None;self.owned=False self.lock.unlink() def __enter__(self):return self def __exit__(self,*args):self.close() def journal_values(value): if not isinstance(value, dict) or any(not isinstance(k, str) or not isinstance(v, str) for k,v in value.items()): raise JournalRefusal('Saved/fingerprint values must be exact string fields') return dict(value) def journal_acknowledge(job, step, saved): job.acknowledge(step,journal_values(saved)) def journal_acknowledged(job, step): return job.acknowledged(step) def journal_begin(job, step, method, path, request_fingerprint): return job.begin(step,method,path,request_fingerprint) def journal_fingerprint(value): return fingerprint(journal_values(value)) def journal_saved(job, step): return job.saved(step) def json_string(value): return json.dumps(value,ensure_ascii=False,allow_nan=False,separators=(",",":")) def 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 remember_id(seen, value): if value in seen: return False seen.add(value) return True 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 task_id_array(value): if re.fullmatch('[ \\t\\r\\n]*\\[[ \\t\\r\\n]*(?:[1-9][0-9]*[ \\t\\r\\n]*(?:,[ \\t\\r\\n]*[1-9][0-9]*[ \\t\\r\\n]*)*)?\\][ \\t\\r\\n]*', value) is None: raise RuntimeError('Use a JSON array of numeric positive Task IDs; no strings, fractions or exponents.') body = value.strip()[1:-1].strip() return [positive_id(item.strip()) for item in body.split(',')] if body else [] 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(): import_source_id = positive_id(required("EXHIBITDAY_SOURCE_EVENT_ID")) import_target_id = positive_id(required("EXHIBITDAY_EVENT_ID")) require_condition(not_value(equal(import_source_id, import_target_id)), "Choose different source and target Events.") import_task_ids_json = required("EXHIBITDAY_TASK_IDS") import_task_ids = task_id_array(import_task_ids_json) require_condition(not_value(is_empty(import_task_ids)), "Choose a nonempty numeric Task ID array from the source Event.") import_requested_ids = new_id_set() for import_selected_task in items(import_task_ids): import_selected_id = positive_id(text(import_selected_task)) require_condition(remember_id(import_requested_ids, import_selected_id), "Select distinct source Task IDs.") import_section_id = optional("EXHIBITDAY_TASK_SECTION_ID", "") if is_present(import_section_id): import_section_id = positive_id(import_section_id) import_keep_assignees = optional("EXHIBITDAY_KEEP_ASSIGNEES", "false") import_keep_files = optional("EXHIBITDAY_KEEP_ATTACHMENTS", "false") import_due_mode = optional("EXHIBITDAY_DUE_DATE_MODE", "none") require_condition(either(equal(import_keep_assignees, "true"), equal(import_keep_assignees, "false")), "Use literal true or false for the client Boolean options.") require_condition(either(equal(import_keep_files, "true"), equal(import_keep_files, "false")), "Use literal true or false for the client Boolean options.") require_condition(either(equal(import_due_mode, "none"), either(equal(import_due_mode, "same_date"), equal(import_due_mode, "same_offset"))), "Use none, same_date or same_offset for this client's due-date mode.") import_journal_path = required("EXHIBITDAY_JOURNAL") import_job_id = required("EXHIBITDAY_JOB_ID") import_job_mode = optional("EXHIBITDAY_JOB_MODE", "resume") import_workspace_response = call("workspace_binding", {}, None, None) require_condition(equal(response_status(import_workspace_response), "200"), "Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome.") import_workspace = import_workspace_response["body"] import_workspace_id = positive_id(text(field(import_workspace, "id"))) import_source_response = call("source", {"id": import_source_id}, None, None) require_condition(equal(response_status(import_source_response), "200"), "Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome.") import_source_event = import_source_response["body"] require_condition(equal(text(field(import_source_event, "id")), import_source_id), "Read the exact source and target Events before copying Tasks.") import_target_response = call("target", {"id": import_target_id}, None, None) require_condition(equal(response_status(import_target_response), "200"), "Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome.") import_target_event = import_target_response["body"] require_condition(equal(text(field(import_target_event, "id")), import_target_id), "Read the exact source and target Events before copying Tasks.") import_input_fingerprint = journal_fingerprint({"workflow_contract_sha256": "093C5C392110864D42C6DAAC78ED03CD194F117A1DB3CA4815BDA003407D6B06", "request": journal_fingerprint({"source_event_id": import_source_id, "event_id": import_target_id, "task_ids": import_task_ids_json, "task_section_id": import_section_id, "keep_assignees": import_keep_assignees, "due_date_mode": import_due_mode, "keep_attachments": import_keep_files})}) import_job = open_journal(import_journal_path, "https://api.exhibitday.com/v1", import_workspace_id, "reuse-event-plan", import_job_id, import_input_fingerprint, [["import_tasks", "POST", "/v1/tasks/import_from_event"]], import_job_mode) try: import_saved_pairs = parse_json("[]") if journal_acknowledged(import_job, "import_tasks"): import_saved = journal_saved(import_job, "import_tasks") require_condition(both(equal(text(field(import_saved, "source_event_id")), import_source_id), equal(text(field(import_saved, "event_id")), import_target_id)), "Saved import state belongs to different Events; stop and reconcile.") import_saved_pairs = parse_json(text(field(import_saved, "tasks"))) else: import_request_fingerprint = journal_fingerprint({"source_event_id": import_source_id, "event_id": import_target_id, "task_ids": import_task_ids_json, "task_section_id": import_section_id, "keep_assignees": import_keep_assignees, "due_date_mode": import_due_mode, "keep_attachments": import_keep_files}) import_intent = journal_begin(import_job, "import_tasks", "POST", "/v1/tasks/import_from_event", import_request_fingerprint) import_response = call("import_tasks", {}, {"source_event_id": import_source_id, "event_id": import_target_id, "task_ids": import_task_ids_json, "task_section_id": import_section_id, "keep_assignees": equal(import_keep_assignees, "true"), "due_date_mode": import_due_mode, "keep_attachments": equal(import_keep_files, "true")}, text(field(import_intent, "idempotency_key"))) require_condition(equal(response_status(import_response), "200"), "Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome.") import_receipt = import_response["body"] require_condition(both(equal(text(field(import_receipt, "source_event_id")), import_source_id), equal(text(field(import_receipt, "event_id")), import_target_id)), "The import acknowledgement belongs to a different source or target Event.") import_saved_pairs = field(import_receipt, "tasks") require_condition(equal(text(field(import_receipt, "tasks_copied")), text(count(import_task_ids))), "The acknowledged copied-task count differs from the selected Tasks.") import_saved_pairs_receipt_rows = items(import_saved_pairs) require_condition(equal(count(import_saved_pairs_receipt_rows), count(import_task_ids)), "Some selected Tasks were not imported (the response warnings name them); review them before continuing.") import_saved_pairs_receipt_seen_source = new_id_set() import_saved_pairs_receipt_seen_new = new_id_set() for import_saved_pairs_receipt_row in items(import_saved_pairs_receipt_rows): import_saved_pairs_receipt_source_id = positive_id(text(field(import_saved_pairs_receipt_row, "source_task_id"))) import_saved_pairs_receipt_new_id = positive_id(text(field(import_saved_pairs_receipt_row, "id"))) require_condition(not_value(remember_id(import_requested_ids, import_saved_pairs_receipt_source_id)), "An import pair refers to a Task outside the explicit source selection.") require_condition(both(remember_id(import_saved_pairs_receipt_seen_source, import_saved_pairs_receipt_source_id), remember_id(import_saved_pairs_receipt_seen_new, import_saved_pairs_receipt_new_id)), "Each selected source Task and each new Task ID must appear once in the import receipt.") journal_acknowledge(import_job, "import_tasks", {"source_event_id": import_source_id, "event_id": import_target_id, "tasks": json_string(import_saved_pairs), "tasks_copied": text(field(import_receipt, "tasks_copied"))}) import_saved_pairs_verify_rows = items(import_saved_pairs) require_condition(equal(count(import_saved_pairs_verify_rows), count(import_task_ids)), "Some selected Tasks were not imported (the response warnings name them); review them before continuing.") import_saved_pairs_verify_seen_source = new_id_set() import_saved_pairs_verify_seen_new = new_id_set() for import_saved_pairs_verify_row in items(import_saved_pairs_verify_rows): import_saved_pairs_verify_source_id = positive_id(text(field(import_saved_pairs_verify_row, "source_task_id"))) import_saved_pairs_verify_new_id = positive_id(text(field(import_saved_pairs_verify_row, "id"))) require_condition(not_value(remember_id(import_requested_ids, import_saved_pairs_verify_source_id)), "An import pair refers to a Task outside the explicit source selection.") require_condition(both(remember_id(import_saved_pairs_verify_seen_source, import_saved_pairs_verify_source_id), remember_id(import_saved_pairs_verify_seen_new, import_saved_pairs_verify_new_id)), "Each selected source Task and each new Task ID must appear once in the import receipt.") import_saved_pairs_task_response = call("verify_task", {"id": import_saved_pairs_verify_new_id}, None, None) require_condition(equal(response_status(import_saved_pairs_task_response), "200"), "Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome.") import_saved_pairs_task = import_saved_pairs_task_response["body"] require_condition(equal(text(field(import_saved_pairs_task, "id")), import_saved_pairs_verify_new_id), "A captured imported Task is missing or replaced; stop rather than importing a replacement.") import_saved_pairs_event = field(import_saved_pairs_task, "event") require_condition(equal(text(field(import_saved_pairs_event, "id")), import_target_id), "A copied Task is no longer under the selected target Event; do not silently re-import it.") print_value({"source_event_id": import_source_id, "event_id": import_target_id, "tasks_verified": text(count(import_task_ids))}) finally: import_job.close() if __name__ == "__main__": main() EXHIBITDAY_PY ``` ```javascript // Server-side Node.js with fetch; built-in modules only. Set EXHIBITDAY_API_KEY. const BASE = "https://api.exhibitday.com/v1"; const SPEC = JSON.parse("{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"source\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"target\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"import_tasks\":{\"method\":\"POST\",\"path\":\"/tasks/import_from_event\"},\"verify_task\":{\"method\":\"GET\",\"path\":\"/tasks/info\"}}}"); const API_KEY = process.env.EXHIBITDAY_API_KEY; if (!API_KEY || !API_KEY.trim()) throw new Error("Set EXHIBITDAY_API_KEY"); if (/[^\x20-\x7e]/.test(API_KEY)) throw new Error("Use the API key as one ASCII header value without control characters"); 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, errors: result.errors, error_params: result.error_params, 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, key = null) { const route = SPEC.requests[name]; const headers = { Authorization: "Bearer " + API_KEY, Accept: "application/json" }; if (route.method === "POST") { if (!key) throw new Error("Persist a logical create key before sending POST"); headers["Idempotency-Key"] = key; } 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 : ""); // 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. const resend = route.method === "GET"; 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 = resend && (response.status === 429 || response.status >= 500); 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, raw }; } throw new Error("Retry limit reached"); } function both(left,right) { return left && right; } function items(value) { if (!Array.isArray(value)) throw new Error("Expected a JSON array"); return value; } function count(value) { return BigInt(items(value).length); } function either(left, right) { if (typeof left !== "boolean" || typeof right !== "boolean") throw new Error("Expected Boolean criteria"); return left || right; } function equal(left, right) { return typeof left === typeof right && left === right; } function field(value, name) { if (!value || Array.isArray(value) || typeof value !== "object" || !Object.hasOwn(value, name)) throw new Error("Missing response field: " + name); return value[name]; } function is_empty(value) { return count(value) === 0n; } function is_present(value) { return value !== null && value !== undefined && value !== ""; } 'use strict'; // Private client restart state. No HTTP or application dependency. const fs = require('node:fs'); const crypto = require('node:crypto'); const PREAMBLE = Buffer.from('EXHIBITDAY-GUIDE-JOURNAL 1\n', 'ascii'); class JournalRefusal extends Error {} function ascii(raw) { if (raw.some(value => value > 127)) throw new JournalRefusal('Journal framing must be canonical ASCII'); return raw.toString('ascii'); } function utf8(value) { if (typeof value !== 'string') throw new JournalRefusal('Journal fields are exact strings'); for (const unit of value) if (unit.length === 1 && unit.charCodeAt(0) >= 0xd800 && unit.charCodeAt(0) <= 0xdfff) throw new JournalRefusal('Invalid Unicode journal field'); return Buffer.from(value, 'utf8'); } function strings(values) { const parts = []; for (const value of values) { const raw = utf8(value); parts.push(Buffer.from(String(raw.length) + ':', 'ascii'), raw); } return Buffer.concat(parts); } function readStrings(raw) { const values = []; let offset = 0; while (offset < raw.length) { const end = raw.indexOf(58, offset); if (end < 0) throw new JournalRefusal('Incomplete journal string length'); const length = ascii(raw.subarray(offset, end)); if (!/^(0|[1-9][0-9]*)$/.test(length)) throw new JournalRefusal('Noncanonical journal string length'); const size = BigInt(length); offset = end + 1; if (size > BigInt(raw.length - offset)) throw new JournalRefusal('Incomplete journal string'); const count = Number(size); values.push(new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(raw.subarray(offset, offset + count))); offset += count; } return values; } function digest(raw) { return crypto.createHash('sha256').update(raw).digest('hex').toUpperCase(); } function fingerprint(pairs) { const values = []; for (const name of Object.keys(pairs).sort()) { if (!/^[A-Za-z0-9_.-]+$/.test(name) || ['api_key', 'exhibitday_api_key'].includes(name.toLowerCase())) throw new JournalRefusal('Use explicit secret-free fingerprint field names'); values.push(name, pairs[name]); } return digest(strings(values)); } function frame(values) { const raw = strings(values); return Buffer.concat([Buffer.from(String(raw.length) + ' ' + digest(raw) + '\n', 'ascii'), raw, Buffer.from('\n')]); } function decode(raw) { if (!raw.subarray(0, PREAMBLE.length).equals(PREAMBLE)) throw new JournalRefusal('Unknown or incomplete journal version'); let offset = PREAMBLE.length; const records = []; while (offset < raw.length) { const end = raw.indexOf(10, offset); if (end < 0) throw new JournalRefusal('Incomplete journal frame header; reconcile before retry'); const match = /^(0|[1-9][0-9]*) ([0-9A-F]{64})$/.exec(ascii(raw.subarray(offset, end))); if (!match) throw new JournalRefusal('Invalid journal frame header'); const size = BigInt(match[1]); offset = end + 1; if (size >= BigInt(raw.length - offset)) throw new JournalRefusal('Incomplete journal frame; reconcile before retry'); const count = Number(size), payload = raw.subarray(offset, offset + count); offset += count; if (raw[offset] !== 10 || digest(payload) !== match[2]) throw new JournalRefusal('Journal integrity check failed; reconcile before retry'); records.push(readStrings(payload)); offset++; } return records; } function writeAll(fd, raw) { let offset = 0; while (offset < raw.length) { const count = fs.writeSync(fd, raw, offset, raw.length - offset); if (!count) throw new Error('Journal write did not advance'); offset += count; } } function same(left, right) { return left.length === right.length && left.every((value, index) => value === right[index]); } class Journal { constructor(path, base, workspace, slug, job, inputFingerprint, writes, mode = 'resume') { this.path = path; this.lock = path + '.lock'; this.fd = null; this.owned = false; this.identity = null; this.tainted = false; this.intents = new Map(); this.savedValues = new Map(); this.allowed = new Map(); if (!['new', 'resume'].includes(mode)) throw new JournalRefusal('Choose new or resume for this local job'); const address = new URL(base); if (!['https:', 'http:'].includes(address.protocol) || !address.hostname || address.username || address.password || address.search || address.hash || !/^[a-z][a-z0-9-]*$/.test(slug)) throw new JournalRefusal('Use the actual API base and closed guide slug'); if (!job.trim() || !/^[1-9][0-9]*$/.test(workspace) || !/^[0-9A-F]{64}$/.test(inputFingerprint)) throw new JournalRefusal('Use an actual workspace, stable explicit job ID and exact input fingerprint'); const manifest = []; for (const [step, method, route] of writes) { if (!/^[a-z][a-z0-9_-]*$/.test(step) || this.allowed.has(step) || !['POST', 'PATCH', 'DELETE'].includes(method) || !/^\/v1\/[A-Za-z0-9_/-]+$/.test(route) || route.includes('//')) throw new JournalRefusal('Use a closed unique write manifest'); this.allowed.set(step, [method, route]); manifest.push(step, method, route); } if (!this.allowed.size) throw new JournalRefusal('Only write workflows need a restart journal'); this.header = ['H', '1', base, workspace, slug, job, inputFingerprint, digest(strings(manifest))]; strings(this.header); try { this.fd = fs.openSync(this.lock, 'wx', 0o600); this.owned = true; } catch (error) { if (error.code === 'EEXIST') throw new JournalRefusal('This journal is locked; do not overlap jobs or steal a stale lock'); throw error; } try { this.owner = crypto.randomBytes(16).toString('hex'); this.identity = fs.fstatSync(this.fd, { bigint: true }); writeAll(this.fd, Buffer.from(this.owner, 'ascii')); fs.fsyncSync(this.fd); let exists = true; try { if (fs.lstatSync(path).isSymbolicLink()) throw new JournalRefusal('Choose a private regular journal file'); } catch (error) { if (error.code === 'ENOENT') exists = false; else throw error; } if (mode === 'resume' && !exists) throw new JournalRefusal('Journal missing: stop and reconcile lost state before starting a new logical job'); if (mode === 'new' && exists) throw new JournalRefusal('Journal already exists; use resume for the same logical job'); if (mode === 'new') { const target = fs.openSync(path, 'wx', 0o600); try { writeAll(target, Buffer.concat([PREAMBLE, frame(this.header)])); fs.fsyncSync(target); } finally { fs.closeSync(target); } } const records = decode(fs.readFileSync(path)); if (!records.length || !same(records[0], this.header)) throw new JournalRefusal('Journal workspace/base/guide/job/input binding differs'); for (const record of records.slice(1)) this.apply(record); if ([...this.intents.keys()].some(step => !this.savedValues.has(step))) throw new JournalRefusal('Saved before-send intent lacks ACK; stop and reconcile before retry'); } catch (error) { this.close(); throw error; } } apply(record) { if (record[0] === 'I') { if (record.length !== 6) throw new JournalRefusal('Invalid intent shape'); const [, step, method, path, requestFingerprint, key] = record; if (!/^[a-z][a-z0-9_-]*$/.test(step) || this.intents.has(step) || !this.allowed.has(step) || !same(this.allowed.get(step), [method, path]) || !/^[0-9A-F]{64}$/.test(requestFingerprint) || [...this.intents.keys()].some(name => !this.savedValues.has(name))) throw new JournalRefusal('Invalid, future or repeated intent'); if ((method === 'POST' && !/^[0-9a-f]{32}$/.test(key)) || (method !== 'POST' && key !== '')) throw new JournalRefusal('Invalid persisted action key'); this.intents.set(step, { method, path, request_fingerprint: requestFingerprint, idempotency_key: key }); } else if (record[0] === 'A') { const [, step, count, ...pairs] = record; if (record.length < 3 || !/^(0|[1-9][0-9]*)$/.test(count) || BigInt(pairs.length) !== 2n * BigInt(count) || !this.intents.has(step) || this.savedValues.has(step)) throw new JournalRefusal('ACK without exactly one prior intent'); const names = pairs.filter((_, index) => index % 2 === 0); if (!same(names, [...new Set(names)].sort()) || names.some(name => !/^[a-z][a-z0-9_]*$/.test(name) || ['api_key', 'exhibitday_api_key'].includes(name))) throw new JournalRefusal('ACK fields must be unique sorted secret-free identifiers'); this.savedValues.set(step, Object.fromEntries(names.map((name, index) => [name, pairs[index * 2 + 1]]))); } else throw new JournalRefusal('Unknown journal transition'); } requireActive() { if (!this.owned || this.fd === null || this.identity === null || this.tainted) throw new JournalRefusal('Journal is closed or its IO outcome needs reconciliation'); const current = fs.lstatSync(this.lock, { bigint: true }); if (current.dev !== this.identity.dev || current.ino !== this.identity.ino || ascii(fs.readFileSync(this.lock)) !== this.owner) throw new JournalRefusal('Journal lock was replaced; stop without deleting it'); } append(record) { this.requireActive(); const raw = frame(record); let target; try { target = fs.openSync(this.path, 'a'); writeAll(target, raw); fs.fsyncSync(target); } catch (error) { this.tainted = true; throw error; } finally { if (target !== undefined) fs.closeSync(target); } } acknowledged(step) { this.requireActive(); return this.savedValues.has(step); } saved(step) { this.requireActive(); if (!this.savedValues.has(step)) throw new JournalRefusal('No acknowledged state exists'); return { ...this.savedValues.get(step) }; } begin(step, method, path, requestFingerprint) { this.requireActive(); if (this.intents.has(step)) throw new JournalRefusal('Never blindly repeat an existing action'); const key = method === 'POST' ? crypto.randomBytes(16).toString('hex') : '', record = ['I', step, method, path, requestFingerprint, key]; const old = new Map(this.intents); try { this.apply(record); } finally { this.intents = old; } this.append(record); this.apply(record); return { ...this.intents.get(step) }; } acknowledge(step, saved) { this.requireActive(); const names = Object.keys(saved).sort(), record = ['A', step, String(names.length)]; for (const name of names) record.push(name, saved[name]); const old = new Map(this.savedValues); try { this.apply(record); strings(record); } finally { this.savedValues = old; } this.append(record); this.apply(record); } close() { if (!this.owned) return; if (this.tainted) { fs.closeSync(this.fd); this.fd = null; this.owned = false; return; } try { this.requireActive(); } catch (error) { fs.closeSync(this.fd); this.fd = null; this.owned = false; throw error; } fs.closeSync(this.fd); this.fd = null; this.owned = false; fs.unlinkSync(this.lock); } } function journal_values(value) { if (!value || typeof value !== 'object' || Array.isArray(value) || Object.values(value).some(item=>typeof item!=='string')) throw new JournalRefusal('Saved/fingerprint values must be exact strings'); return {...value}; } function journal_acknowledge(job,step,saved) { job.acknowledge(step,journal_values(saved)); } function journal_acknowledged(job,step) { return job.acknowledged(step); } function journal_begin(job,step,method,path,requestFingerprint) { return job.begin(step,method,path,requestFingerprint); } function journal_fingerprint(value) { return fingerprint(journal_values(value)); } function journal_saved(job,step) { return job.saved(step); } function json_string(value) { return JSON.stringify(value); } function new_id_set() { return new Set(); } function not_value(value) { if (typeof value !== "boolean") throw new Error("Expected a Boolean"); return !value; } function open_journal(path,base,workspace,slug,job,inputFingerprint,writes,mode) { return new Journal(path,base,workspace,slug,job,inputFingerprint,writes,mode); } function optional(name, fallback) { const value = process.env[name]; return value === undefined || value === "" ? fallback : value; } function parse_json(value) { return JSON.parse(value); } function positive_id(value) { if (!/^[1-9][0-9]*$/.test(value) || BigInt(value) > 9223372036854775807n) throw new Error("Use a positive record ID"); return value; } function print_value(value) { console.log(typeof value === "string" ? value : JSON.stringify(value)); } function remember_id(seen, value) { if (seen.has(value)) return false; seen.add(value); return true; } function require_condition(value, message) { if (value !== true) throw new Error(message); } function required(name) { const value = process.env[name]; if (value === undefined || !value.trim()) throw new Error("Set " + name); return value; } function response_status(value) { return String(value.status); } function task_id_array(value) { if (!new RegExp("^[ \\t\\r\\n]*\\[[ \\t\\r\\n]*(?:[1-9][0-9]*[ \\t\\r\\n]*(?:,[ \\t\\r\\n]*[1-9][0-9]*[ \\t\\r\\n]*)*)?\\][ \\t\\r\\n]*$").test(value)) throw new Error("Use a JSON array of numeric positive Task IDs; no strings, fractions or exponents."); const body=value.trim().slice(1,-1).trim(); return body ? body.split(',').map(item=>positive_id(item.trim())) : []; } function text(value) { if (value === null || value === undefined) return ""; if (["string", "boolean", "bigint"].includes(typeof value)) return String(value); throw new Error("Expected a scalar response value"); } async function main() { let import_source_id = positive_id(required("EXHIBITDAY_SOURCE_EVENT_ID")); let import_target_id = positive_id(required("EXHIBITDAY_EVENT_ID")); require_condition(not_value(equal(import_source_id, import_target_id)), "Choose different source and target Events."); let import_task_ids_json = required("EXHIBITDAY_TASK_IDS"); let import_task_ids = task_id_array(import_task_ids_json); require_condition(not_value(is_empty(import_task_ids)), "Choose a nonempty numeric Task ID array from the source Event."); let import_requested_ids = new_id_set(); for (const import_selected_task of items(import_task_ids)) { let import_selected_id = positive_id(text(import_selected_task)); require_condition(remember_id(import_requested_ids, import_selected_id), "Select distinct source Task IDs."); } let import_section_id = optional("EXHIBITDAY_TASK_SECTION_ID", ""); if (is_present(import_section_id)) { import_section_id = positive_id(import_section_id); } let import_keep_assignees = optional("EXHIBITDAY_KEEP_ASSIGNEES", "false"); let import_keep_files = optional("EXHIBITDAY_KEEP_ATTACHMENTS", "false"); let import_due_mode = optional("EXHIBITDAY_DUE_DATE_MODE", "none"); require_condition(either(equal(import_keep_assignees, "true"), equal(import_keep_assignees, "false")), "Use literal true or false for the client Boolean options."); require_condition(either(equal(import_keep_files, "true"), equal(import_keep_files, "false")), "Use literal true or false for the client Boolean options."); require_condition(either(equal(import_due_mode, "none"), either(equal(import_due_mode, "same_date"), equal(import_due_mode, "same_offset"))), "Use none, same_date or same_offset for this client's due-date mode."); let import_journal_path = required("EXHIBITDAY_JOURNAL"); let import_job_id = required("EXHIBITDAY_JOB_ID"); let import_job_mode = optional("EXHIBITDAY_JOB_MODE", "resume"); let import_workspace_response = await call("workspace_binding", {}, null, null); require_condition(equal(response_status(import_workspace_response), "200"), "Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome."); let import_workspace = import_workspace_response.body; let import_workspace_id = positive_id(text(field(import_workspace, "id"))); let import_source_response = await call("source", {"id": import_source_id}, null, null); require_condition(equal(response_status(import_source_response), "200"), "Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome."); let import_source_event = import_source_response.body; require_condition(equal(text(field(import_source_event, "id")), import_source_id), "Read the exact source and target Events before copying Tasks."); let import_target_response = await call("target", {"id": import_target_id}, null, null); require_condition(equal(response_status(import_target_response), "200"), "Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome."); let import_target_event = import_target_response.body; require_condition(equal(text(field(import_target_event, "id")), import_target_id), "Read the exact source and target Events before copying Tasks."); let import_input_fingerprint = journal_fingerprint({"workflow_contract_sha256": "093C5C392110864D42C6DAAC78ED03CD194F117A1DB3CA4815BDA003407D6B06", "request": journal_fingerprint({"source_event_id": import_source_id, "event_id": import_target_id, "task_ids": import_task_ids_json, "task_section_id": import_section_id, "keep_assignees": import_keep_assignees, "due_date_mode": import_due_mode, "keep_attachments": import_keep_files})}); let import_job = open_journal(import_journal_path, "https://api.exhibitday.com/v1", import_workspace_id, "reuse-event-plan", import_job_id, import_input_fingerprint, [["import_tasks", "POST", "/v1/tasks/import_from_event"]], import_job_mode); try { let import_saved_pairs = parse_json("[]"); if (journal_acknowledged(import_job, "import_tasks")) { let import_saved = journal_saved(import_job, "import_tasks"); require_condition(both(equal(text(field(import_saved, "source_event_id")), import_source_id), equal(text(field(import_saved, "event_id")), import_target_id)), "Saved import state belongs to different Events; stop and reconcile."); import_saved_pairs = parse_json(text(field(import_saved, "tasks"))); } else { let import_request_fingerprint = journal_fingerprint({"source_event_id": import_source_id, "event_id": import_target_id, "task_ids": import_task_ids_json, "task_section_id": import_section_id, "keep_assignees": import_keep_assignees, "due_date_mode": import_due_mode, "keep_attachments": import_keep_files}); let import_intent = journal_begin(import_job, "import_tasks", "POST", "/v1/tasks/import_from_event", import_request_fingerprint); let import_response = await call("import_tasks", {}, {"source_event_id": import_source_id, "event_id": import_target_id, "task_ids": import_task_ids_json, "task_section_id": import_section_id, "keep_assignees": equal(import_keep_assignees, "true"), "due_date_mode": import_due_mode, "keep_attachments": equal(import_keep_files, "true")}, text(field(import_intent, "idempotency_key"))); require_condition(equal(response_status(import_response), "200"), "Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome."); let import_receipt = import_response.body; require_condition(both(equal(text(field(import_receipt, "source_event_id")), import_source_id), equal(text(field(import_receipt, "event_id")), import_target_id)), "The import acknowledgement belongs to a different source or target Event."); import_saved_pairs = field(import_receipt, "tasks"); require_condition(equal(text(field(import_receipt, "tasks_copied")), text(count(import_task_ids))), "The acknowledged copied-task count differs from the selected Tasks."); let import_saved_pairs_receipt_rows = items(import_saved_pairs); require_condition(equal(count(import_saved_pairs_receipt_rows), count(import_task_ids)), "Some selected Tasks were not imported (the response warnings name them); review them before continuing."); let import_saved_pairs_receipt_seen_source = new_id_set(); let import_saved_pairs_receipt_seen_new = new_id_set(); for (const import_saved_pairs_receipt_row of items(import_saved_pairs_receipt_rows)) { let import_saved_pairs_receipt_source_id = positive_id(text(field(import_saved_pairs_receipt_row, "source_task_id"))); let import_saved_pairs_receipt_new_id = positive_id(text(field(import_saved_pairs_receipt_row, "id"))); require_condition(not_value(remember_id(import_requested_ids, import_saved_pairs_receipt_source_id)), "An import pair refers to a Task outside the explicit source selection."); require_condition(both(remember_id(import_saved_pairs_receipt_seen_source, import_saved_pairs_receipt_source_id), remember_id(import_saved_pairs_receipt_seen_new, import_saved_pairs_receipt_new_id)), "Each selected source Task and each new Task ID must appear once in the import receipt."); } journal_acknowledge(import_job, "import_tasks", {"source_event_id": import_source_id, "event_id": import_target_id, "tasks": json_string(import_saved_pairs), "tasks_copied": text(field(import_receipt, "tasks_copied"))}); } let import_saved_pairs_verify_rows = items(import_saved_pairs); require_condition(equal(count(import_saved_pairs_verify_rows), count(import_task_ids)), "Some selected Tasks were not imported (the response warnings name them); review them before continuing."); let import_saved_pairs_verify_seen_source = new_id_set(); let import_saved_pairs_verify_seen_new = new_id_set(); for (const import_saved_pairs_verify_row of items(import_saved_pairs_verify_rows)) { let import_saved_pairs_verify_source_id = positive_id(text(field(import_saved_pairs_verify_row, "source_task_id"))); let import_saved_pairs_verify_new_id = positive_id(text(field(import_saved_pairs_verify_row, "id"))); require_condition(not_value(remember_id(import_requested_ids, import_saved_pairs_verify_source_id)), "An import pair refers to a Task outside the explicit source selection."); require_condition(both(remember_id(import_saved_pairs_verify_seen_source, import_saved_pairs_verify_source_id), remember_id(import_saved_pairs_verify_seen_new, import_saved_pairs_verify_new_id)), "Each selected source Task and each new Task ID must appear once in the import receipt."); let import_saved_pairs_task_response = await call("verify_task", {"id": import_saved_pairs_verify_new_id}, null, null); require_condition(equal(response_status(import_saved_pairs_task_response), "200"), "Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome."); let import_saved_pairs_task = import_saved_pairs_task_response.body; require_condition(equal(text(field(import_saved_pairs_task, "id")), import_saved_pairs_verify_new_id), "A captured imported Task is missing or replaced; stop rather than importing a replacement."); let import_saved_pairs_event = field(import_saved_pairs_task, "event"); require_condition(equal(text(field(import_saved_pairs_event, "id")), import_target_id), "A copied Task is no longer under the selected target Event; do not silently re-import it."); } print_value({"source_event_id": import_source_id, "event_id": import_target_id, "tasks_verified": text(count(import_task_ids))}); } finally { import_job.close(); } } if (require.main === module) main().catch(error => { console.error(error.message); process.exitCode = 1; }); module.exports = { main }; ``` ```python # 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\"},\"source\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"target\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"import_tasks\":{\"method\":\"POST\",\"path\":\"/tasks/import_from_event\"},\"verify_task\":{\"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) 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, key=None): route = SPEC["requests"][name] headers = {"Authorization": "Bearer " + API_KEY, "Accept": "application/json"} if route["method"] == "POST": if not key: raise RuntimeError("Persist a logical create key before sending POST") headers["Idempotency-Key"] = key data = None if body is None else json.dumps(body).encode("utf-8") if data is not None: headers["Content-Type"] = "application/json" query = urllib.parse.urlencode(params or {}) url = BASE + route["path"] + ("?" + query if query else "") # Only GET has automatic retries in this workflow. A PATCH or DELETE that got no response or a # server error is never resent blindly: it may already have been applied, so the caller reads the record first. resend = route["method"] == "GET" for attempt in range(5): try: status, raw, response_headers = transport(route["method"], url, headers, data) except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException): if not resend: raise ApiError(0, None, uncertain=True) if attempt == 4: raise time.sleep(2 ** attempt) continue response_headers = {k.lower(): v for k, v in response_headers.items()} result = None if status != 304 and raw: try: result = decode_json(raw.decode("utf-8")) except (ValueError, UnicodeError): if status < 400: raise RuntimeError("Expected a JSON success response") if status >= 500 and not resend: raise ApiError(status, result, uncertain=True) retry = resend and (status == 429 or status >= 500) if retry: if attempt == 4: raise RuntimeError("Retry limit reached; check the request outcome before starting a new create") delay = response_headers.get("retry-after", str(2 ** attempt)) time.sleep(max(0, float(delay))) continue if status >= 400: raise ApiError(status, result) return {"status": status, "body": result, "headers": response_headers, "raw": raw} raise RuntimeError("Retry limit reached") def both(left,right): return left and right def items(value): if not isinstance(value, list): raise RuntimeError("Expected a JSON array") return value def count(value): return len(items(value)) 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] 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 offsetlen(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)-offset:raise JournalRefusal('Incomplete journal frame; reconcile before retry') payload=raw[offset:offset+size];offset+=size if raw[offset:offset+1]!=b'\n' or digest(payload).encode('ascii')!=match[2]:raise JournalRefusal('Journal integrity check failed; reconcile before retry') records.append(read_strings(payload));offset+=1 return records class Journal: def __init__(self,path,base,workspace,slug,job,input_fingerprint,writes,mode="resume"): self.path=Path(path);self.lock=Path(str(self.path)+'.lock');self.fd=None;self.owned=False;self.identity=None;self.tainted=False;self.intents={};self.saved_values={} address=urlsplit(base) if address.scheme not in ('https','http')or not address.netloc or address.username is not None or address.query or address.fragment or not re.fullmatch('[a-z][a-z0-9-]*',slug):raise JournalRefusal('Use the actual API base and closed guide slug') if not job.strip() or not re.fullmatch('[1-9][0-9]*',workspace) or not re.fullmatch('[0-9A-F]{64}',input_fingerprint):raise JournalRefusal('Use an actual workspace, explicit stable job ID and exact input fingerprint') if mode not in ("new","resume"):raise JournalRefusal("Choose new or resume for this local job") self.allowed={};manifest=[] for step,method,route in writes: if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.allowed or method not in ('POST','PATCH','DELETE')or not re.fullmatch('/v1/[A-Za-z0-9_/-]+',route)or'//'in route:raise JournalRefusal('Use a closed unique write manifest') self.allowed[step]=(method,route);manifest.extend((step,method,route)) if not self.allowed:raise JournalRefusal('Only write workflows need a restart journal') self.header=['H','1',base,workspace,slug,job,input_fingerprint,digest(strings(manifest))] strings(self.header) try: self.fd=os.open(self.lock,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600);self.owned=True except FileExistsError:raise JournalRefusal('This journal is locked; do not run overlapping jobs or steal a stale lock') try: self.owner=secrets.token_hex(16);self.identity=os.fstat(self.fd) if os.write(self.fd,self.owner.encode('ascii'))!=len(self.owner):raise OSError('Incomplete lock identity write') os.fsync(self.fd) if self.path.is_symlink():raise JournalRefusal('Choose a private regular journal file') if mode=="resume" and not self.path.exists():raise JournalRefusal("Journal missing: stop and reconcile lost state before starting a new logical job") if mode=="new" and self.path.exists():raise JournalRefusal("A journal already exists; use resume for the same logical job") if mode=="new": with open(self.path,'xb',buffering=0)as target: target.write(PREAMBLE+frame(self.header));os.fsync(target.fileno()) records=decode(self.path.read_bytes()) if not records or records[0]!=self.header:raise JournalRefusal('Journal workspace/base/guide/job/input binding differs') for record in records[1:]:self.apply(record) if any(step not in self.saved_values for step in self.intents):raise JournalRefusal('A saved before-send intent lacks an ACK; stop and reconcile its outcome before retry') except BaseException: self.close();raise def apply(self,record): if not record:raise JournalRefusal('Empty journal record') if record[0]=='I': if len(record)!=6:raise JournalRefusal('Invalid intent shape') _,step,method,path,request_fingerprint,key=record if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.intents or self.allowed.get(step)!=(method,path)or not re.fullmatch('[0-9A-F]{64}',request_fingerprint)or any(name not in self.saved_values for name in self.intents):raise JournalRefusal('Invalid, future or repeated journal intent') if method=='POST'and not re.fullmatch('[0-9a-f]{32}',key)or method!='POST'and key!='':raise JournalRefusal('Invalid persisted action key') self.intents[step]={'method':method,'path':path,'request_fingerprint':request_fingerprint,'idempotency_key':key} elif record[0]=='A': if len(record)<3:raise JournalRefusal('Invalid ACK shape') _,step,count,*pairs=record if not re.fullmatch('0|[1-9][0-9]*',count)or len(pairs)!=2*int(count)or step not in self.intents or step in self.saved_values:raise JournalRefusal('ACK without exactly one prior intent') names=pairs[::2] if names!=sorted(set(names))or any(not re.fullmatch('[a-z][a-z0-9_]*',name)or name in ('api_key','exhibitday_api_key')for name in names):raise JournalRefusal('ACK saved fields must be unique sorted secret-free identifiers') self.saved_values[step]=dict(zip(names,pairs[1::2])) else:raise JournalRefusal('Unknown journal transition') def append(self,record): # The reader commits state only after complete length/digest recognition. # A torn append is retained and refused, never silently truncated. self.require_active();raw=frame(record) try: with open(self.path,'ab',buffering=0)as target: view=memoryview(raw) while view: written=target.write(view) if not written:raise OSError('Journal write did not advance') view=view[written:] os.fsync(target.fileno()) except BaseException: self.tainted=True;raise def require_active(self): if not self.owned or self.fd is None or self.identity is None or self.tainted:raise JournalRefusal('The journal scope is closed or its IO outcome needs reconciliation') current=self.lock.stat(follow_symlinks=False) if current.st_dev!=self.identity.st_dev or current.st_ino!=self.identity.st_ino or self.lock.read_text(encoding='ascii')!=self.owner:raise JournalRefusal('The journal lock was replaced; stop without deleting it') def acknowledged(self,step): self.require_active();return step in self.saved_values def saved(self,step): self.require_active() if step not in self.saved_values:raise JournalRefusal('No acknowledged state exists for this step') return dict(self.saved_values[step]) def begin(self,step,method,path,request_fingerprint): self.require_active() if step in self.intents:raise JournalRefusal('Never blindly repeat an existing action intent') key=secrets.token_hex(16)if method=='POST'else'' record=['I',step,method,path,request_fingerprint,key] # Validate on an isolated state before touching the file. old=dict(self.intents) try:self.apply(record) finally:self.intents=old self.append(record);self.apply(record) return dict(self.intents[step]) def acknowledge(self,step,saved): self.require_active() record=['A',step,str(len(saved))] for name,value in sorted(saved.items()):record.extend((name,value)) old={name:dict(value)for name,value in self.saved_values.items()} try:self.apply(record);strings(record) finally:self.saved_values=old self.append(record);self.apply(record) def close(self): if self.owned: if self.tainted: os.close(self.fd);self.fd=None;self.owned=False return # Retain this lock after failed journal IO; manual reconciliation is required. try:self.require_active() except BaseException: os.close(self.fd);self.fd=None;self.owned=False;raise os.close(self.fd);self.fd=None;self.owned=False self.lock.unlink() def __enter__(self):return self def __exit__(self,*args):self.close() def journal_values(value): if not isinstance(value, dict) or any(not isinstance(k, str) or not isinstance(v, str) for k,v in value.items()): raise JournalRefusal('Saved/fingerprint values must be exact string fields') return dict(value) def journal_acknowledge(job, step, saved): job.acknowledge(step,journal_values(saved)) def journal_acknowledged(job, step): return job.acknowledged(step) def journal_begin(job, step, method, path, request_fingerprint): return job.begin(step,method,path,request_fingerprint) def journal_fingerprint(value): return fingerprint(journal_values(value)) def journal_saved(job, step): return job.saved(step) def json_string(value): return json.dumps(value,ensure_ascii=False,allow_nan=False,separators=(",",":")) def 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 remember_id(seen, value): if value in seen: return False seen.add(value) return True 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 task_id_array(value): if re.fullmatch('[ \\t\\r\\n]*\\[[ \\t\\r\\n]*(?:[1-9][0-9]*[ \\t\\r\\n]*(?:,[ \\t\\r\\n]*[1-9][0-9]*[ \\t\\r\\n]*)*)?\\][ \\t\\r\\n]*', value) is None: raise RuntimeError('Use a JSON array of numeric positive Task IDs; no strings, fractions or exponents.') body = value.strip()[1:-1].strip() return [positive_id(item.strip()) for item in body.split(',')] if body else [] 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(): import_source_id = positive_id(required("EXHIBITDAY_SOURCE_EVENT_ID")) import_target_id = positive_id(required("EXHIBITDAY_EVENT_ID")) require_condition(not_value(equal(import_source_id, import_target_id)), "Choose different source and target Events.") import_task_ids_json = required("EXHIBITDAY_TASK_IDS") import_task_ids = task_id_array(import_task_ids_json) require_condition(not_value(is_empty(import_task_ids)), "Choose a nonempty numeric Task ID array from the source Event.") import_requested_ids = new_id_set() for import_selected_task in items(import_task_ids): import_selected_id = positive_id(text(import_selected_task)) require_condition(remember_id(import_requested_ids, import_selected_id), "Select distinct source Task IDs.") import_section_id = optional("EXHIBITDAY_TASK_SECTION_ID", "") if is_present(import_section_id): import_section_id = positive_id(import_section_id) import_keep_assignees = optional("EXHIBITDAY_KEEP_ASSIGNEES", "false") import_keep_files = optional("EXHIBITDAY_KEEP_ATTACHMENTS", "false") import_due_mode = optional("EXHIBITDAY_DUE_DATE_MODE", "none") require_condition(either(equal(import_keep_assignees, "true"), equal(import_keep_assignees, "false")), "Use literal true or false for the client Boolean options.") require_condition(either(equal(import_keep_files, "true"), equal(import_keep_files, "false")), "Use literal true or false for the client Boolean options.") require_condition(either(equal(import_due_mode, "none"), either(equal(import_due_mode, "same_date"), equal(import_due_mode, "same_offset"))), "Use none, same_date or same_offset for this client's due-date mode.") import_journal_path = required("EXHIBITDAY_JOURNAL") import_job_id = required("EXHIBITDAY_JOB_ID") import_job_mode = optional("EXHIBITDAY_JOB_MODE", "resume") import_workspace_response = call("workspace_binding", {}, None, None) require_condition(equal(response_status(import_workspace_response), "200"), "Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome.") import_workspace = import_workspace_response["body"] import_workspace_id = positive_id(text(field(import_workspace, "id"))) import_source_response = call("source", {"id": import_source_id}, None, None) require_condition(equal(response_status(import_source_response), "200"), "Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome.") import_source_event = import_source_response["body"] require_condition(equal(text(field(import_source_event, "id")), import_source_id), "Read the exact source and target Events before copying Tasks.") import_target_response = call("target", {"id": import_target_id}, None, None) require_condition(equal(response_status(import_target_response), "200"), "Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome.") import_target_event = import_target_response["body"] require_condition(equal(text(field(import_target_event, "id")), import_target_id), "Read the exact source and target Events before copying Tasks.") import_input_fingerprint = journal_fingerprint({"workflow_contract_sha256": "093C5C392110864D42C6DAAC78ED03CD194F117A1DB3CA4815BDA003407D6B06", "request": journal_fingerprint({"source_event_id": import_source_id, "event_id": import_target_id, "task_ids": import_task_ids_json, "task_section_id": import_section_id, "keep_assignees": import_keep_assignees, "due_date_mode": import_due_mode, "keep_attachments": import_keep_files})}) import_job = open_journal(import_journal_path, "https://api.exhibitday.com/v1", import_workspace_id, "reuse-event-plan", import_job_id, import_input_fingerprint, [["import_tasks", "POST", "/v1/tasks/import_from_event"]], import_job_mode) try: import_saved_pairs = parse_json("[]") if journal_acknowledged(import_job, "import_tasks"): import_saved = journal_saved(import_job, "import_tasks") require_condition(both(equal(text(field(import_saved, "source_event_id")), import_source_id), equal(text(field(import_saved, "event_id")), import_target_id)), "Saved import state belongs to different Events; stop and reconcile.") import_saved_pairs = parse_json(text(field(import_saved, "tasks"))) else: import_request_fingerprint = journal_fingerprint({"source_event_id": import_source_id, "event_id": import_target_id, "task_ids": import_task_ids_json, "task_section_id": import_section_id, "keep_assignees": import_keep_assignees, "due_date_mode": import_due_mode, "keep_attachments": import_keep_files}) import_intent = journal_begin(import_job, "import_tasks", "POST", "/v1/tasks/import_from_event", import_request_fingerprint) import_response = call("import_tasks", {}, {"source_event_id": import_source_id, "event_id": import_target_id, "task_ids": import_task_ids_json, "task_section_id": import_section_id, "keep_assignees": equal(import_keep_assignees, "true"), "due_date_mode": import_due_mode, "keep_attachments": equal(import_keep_files, "true")}, text(field(import_intent, "idempotency_key"))) require_condition(equal(response_status(import_response), "200"), "Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome.") import_receipt = import_response["body"] require_condition(both(equal(text(field(import_receipt, "source_event_id")), import_source_id), equal(text(field(import_receipt, "event_id")), import_target_id)), "The import acknowledgement belongs to a different source or target Event.") import_saved_pairs = field(import_receipt, "tasks") require_condition(equal(text(field(import_receipt, "tasks_copied")), text(count(import_task_ids))), "The acknowledged copied-task count differs from the selected Tasks.") import_saved_pairs_receipt_rows = items(import_saved_pairs) require_condition(equal(count(import_saved_pairs_receipt_rows), count(import_task_ids)), "Some selected Tasks were not imported (the response warnings name them); review them before continuing.") import_saved_pairs_receipt_seen_source = new_id_set() import_saved_pairs_receipt_seen_new = new_id_set() for import_saved_pairs_receipt_row in items(import_saved_pairs_receipt_rows): import_saved_pairs_receipt_source_id = positive_id(text(field(import_saved_pairs_receipt_row, "source_task_id"))) import_saved_pairs_receipt_new_id = positive_id(text(field(import_saved_pairs_receipt_row, "id"))) require_condition(not_value(remember_id(import_requested_ids, import_saved_pairs_receipt_source_id)), "An import pair refers to a Task outside the explicit source selection.") require_condition(both(remember_id(import_saved_pairs_receipt_seen_source, import_saved_pairs_receipt_source_id), remember_id(import_saved_pairs_receipt_seen_new, import_saved_pairs_receipt_new_id)), "Each selected source Task and each new Task ID must appear once in the import receipt.") journal_acknowledge(import_job, "import_tasks", {"source_event_id": import_source_id, "event_id": import_target_id, "tasks": json_string(import_saved_pairs), "tasks_copied": text(field(import_receipt, "tasks_copied"))}) import_saved_pairs_verify_rows = items(import_saved_pairs) require_condition(equal(count(import_saved_pairs_verify_rows), count(import_task_ids)), "Some selected Tasks were not imported (the response warnings name them); review them before continuing.") import_saved_pairs_verify_seen_source = new_id_set() import_saved_pairs_verify_seen_new = new_id_set() for import_saved_pairs_verify_row in items(import_saved_pairs_verify_rows): import_saved_pairs_verify_source_id = positive_id(text(field(import_saved_pairs_verify_row, "source_task_id"))) import_saved_pairs_verify_new_id = positive_id(text(field(import_saved_pairs_verify_row, "id"))) require_condition(not_value(remember_id(import_requested_ids, import_saved_pairs_verify_source_id)), "An import pair refers to a Task outside the explicit source selection.") require_condition(both(remember_id(import_saved_pairs_verify_seen_source, import_saved_pairs_verify_source_id), remember_id(import_saved_pairs_verify_seen_new, import_saved_pairs_verify_new_id)), "Each selected source Task and each new Task ID must appear once in the import receipt.") import_saved_pairs_task_response = call("verify_task", {"id": import_saved_pairs_verify_new_id}, None, None) require_condition(equal(response_status(import_saved_pairs_task_response), "200"), "Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome.") import_saved_pairs_task = import_saved_pairs_task_response["body"] require_condition(equal(text(field(import_saved_pairs_task, "id")), import_saved_pairs_verify_new_id), "A captured imported Task is missing or replaced; stop rather than importing a replacement.") import_saved_pairs_event = field(import_saved_pairs_task, "event") require_condition(equal(text(field(import_saved_pairs_event, "id")), import_target_id), "A copied Task is no longer under the selected target Event; do not silently re-import it.") print_value({"source_event_id": import_source_id, "event_id": import_target_id, "tasks_verified": text(count(import_task_ids))}) finally: import_job.close() if __name__ == "__main__": main() ``` ```csharp // .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\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"source\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"target\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"import_tasks\":{\"method\":\"POST\",\"path\":\"/tasks/import_from_event\"},\"verify_task\":{\"method\":\"GET\",\"path\":\"/tasks/info\"}}}"); static readonly string ApiKey = HeaderKey(Required("EXHIBITDAY_API_KEY")); static string HeaderKey(string value) { if(value.Any(c=>c<32||c>126))throw new Exception("Use the API key as one ASCII header value without control characters");return value; } static readonly HttpClient Client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false }) { Timeout = TimeSpan.FromSeconds(30) }; internal static Func> Send = request => Client.SendAsync(request); sealed class Result { public int Status; public JsonNode Body; public Dictionary Headers; public string Raw; } // 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(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 Call(string name, JsonObject query = null, JsonNode body = null, string key = null) { var route = Spec["requests"][name]; var method = Text(route["method"]); var headers = new Dictionary(StringComparer.OrdinalIgnoreCase) { ["Authorization"] = "Bearer " + ApiKey, ["Accept"] = "application/json" }; if (method == "POST") { if (string.IsNullOrEmpty(key)) throw new Exception("Persist a logical create key before sending POST"); headers["Idempotency-Key"] = key; } 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); // 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. var resend = method == "GET"; 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 Send(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 = resend && (status == 429 || status >= 500); 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, Raw = raw }; } } throw new Exception("Retry limit reached"); } static bool Both(bool left,bool right)=>left&&right; static JsonArray Items(JsonNode value) => value as JsonArray ?? throw new Exception("Expected a JSON array"); static long Count(JsonNode value) => Items(value).Count; static bool Either(bool left,bool right) => left || right; static object Scalar(object value) { if(value is JsonValue json){if(json.TryGetValue(out var boolean))return boolean;if(json.TryGetValue(out var text))return text;return json.ToJsonString();}return value; } static bool Equal(object left,object right) => object.Equals(Scalar(left),Scalar(right)); static JsonNode Field(JsonNode value,string name) { if(value is not JsonObject obj || !obj.TryGetPropertyValue(name,out var item))throw new Exception("Missing response field: "+name);return item; } static bool IsEmpty(JsonNode value) => Count(value)==0; static bool IsPresent(string value) => value!=null && value!=""; public sealed class JournalRefusal : Exception { public JournalRefusal(string message) : base(message) {} } public static class JournalProtocol { public static readonly byte[] Preamble = Encoding.ASCII.GetBytes("EXHIBITDAY-GUIDE-JOURNAL 1\n"); static readonly UTF8Encoding Utf8 = new UTF8Encoding(false, true); static bool Match(string value,string pattern) => value != null && System.Text.RegularExpressions.Regex.IsMatch(value,"\\A(?:"+pattern+")\\z",System.Text.RegularExpressions.RegexOptions.CultureInvariant); public static bool Valid(string value,string pattern) => Match(value,pattern); static string Ascii(byte[] raw,int start,int count) { for(var i=start;i127)throw new JournalRefusal("Journal framing must be canonical ASCII");return Encoding.ASCII.GetString(raw,start,count); } public static byte[] Strings(IEnumerable values) { using var data=new MemoryStream(); foreach(var value in values){if(value==null)throw new JournalRefusal("Journal fields are exact strings");var item=Utf8.GetBytes(value);var prefix=Encoding.ASCII.GetBytes(item.Length.ToString(CultureInfo.InvariantCulture)+":");data.Write(prefix);data.Write(item);} return data.ToArray(); } public static List ReadStrings(byte[] raw) { var values=new List();var offset=0; while(offsetraw.Length-offset)throw new JournalRefusal("Incomplete journal string");values.Add(Utf8.GetString(raw,offset,(int)size));offset+=(int)size;} return values; } public static string Digest(byte[] raw)=>Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(raw)); public static string Fingerprint(IReadOnlyDictionary pairs) { var values=new List();foreach(var name in pairs.Keys.OrderBy(n=>n,StringComparer.Ordinal)){ if(!Match(name,"[A-Za-z0-9_.-]+")||new[]{"api_key","exhibitday_api_key"}.Contains(name.ToLowerInvariant()))throw new JournalRefusal("Use explicit secret-free fingerprint names");values.Add(name);values.Add(pairs[name]);} return Digest(Strings(values)); } public static byte[] Frame(IEnumerable values) { var payload=Strings(values);var header=Encoding.ASCII.GetBytes(payload.Length.ToString(CultureInfo.InvariantCulture)+" "+Digest(payload)+"\n"); using var data=new MemoryStream();data.Write(header);data.Write(payload);data.WriteByte(10);return data.ToArray(); } public static List> Decode(byte[] raw) { if(raw.Length>(); while(offset=raw.Length-offset)throw new JournalRefusal("Incomplete frame; reconcile before retry");var payload=raw.AsSpan(offset,(int)size).ToArray();offset+=(int)size; if(raw[offset]!=10||Digest(payload)!=split[1])throw new JournalRefusal("Journal integrity failed; reconcile before retry");records.Add(ReadStrings(payload));offset++;} return records; } } public sealed class Journal : IDisposable { readonly string path,lockPath,owner;readonly List header; readonly Dictionary allowed=new Dictionary(StringComparer.Ordinal); Dictionary> intents=new Dictionary>(StringComparer.Ordinal),savedValues=new Dictionary>(StringComparer.Ordinal); FileStream lockStream;bool owned,tainted;DateTime creation; static FileStream CreatePrivate(string target,FileAccess access,FileShare share) { var options=new FileStreamOptions{Mode=FileMode.CreateNew,Access=access,Share=share}; if(!OperatingSystem.IsWindows())options.UnixCreateMode=UnixFileMode.UserRead|UnixFileMode.UserWrite; return new FileStream(target,options); } public Journal(string path,string apiBase,string workspace,string slug,string job,string inputFingerprint,IEnumerable<(string Step,string Method,string Path)> writes,string mode="resume") { this.path=path;lockPath=path+".lock";owner=Convert.ToHexString(System.Security.Cryptography.RandomNumberGenerator.GetBytes(16)).ToLowerInvariant(); if(!Uri.TryCreate(apiBase,UriKind.Absolute,out var address)||address.Scheme!="https"&&address.Scheme!="http"||address.UserInfo.Length!=0||address.Query.Length!=0||address.Fragment.Length!=0||!JournalProtocol.Valid(slug,"[a-z][a-z0-9-]*"))throw new JournalRefusal("Use the actual API base and closed guide slug"); if(string.IsNullOrWhiteSpace(job)||!JournalProtocol.Valid(workspace,"[1-9][0-9]*")||!JournalProtocol.Valid(inputFingerprint,"[0-9A-F]{64}"))throw new JournalRefusal("Use actual workspace, stable explicit job ID and exact fingerprint"); if(mode!="new"&&mode!="resume")throw new JournalRefusal("Choose new or resume for this local job"); var manifest=new List();foreach(var write in writes){ if(!JournalProtocol.Valid(write.Step,"[a-z][a-z0-9_-]*")||allowed.ContainsKey(write.Step)||!new[]{"POST","PATCH","DELETE"}.Contains(write.Method)||!JournalProtocol.Valid(write.Path,"/v1/[A-Za-z0-9_/-]+")||write.Path.Contains("//"))throw new JournalRefusal("Use a closed unique write manifest"); allowed.Add(write.Step,(write.Method,write.Path));manifest.AddRange(new[]{write.Step,write.Method,write.Path});} if(allowed.Count==0)throw new JournalRefusal("Only write workflows need a restart journal"); header=new List{"H","1",apiBase,workspace,slug,job,inputFingerprint,JournalProtocol.Digest(JournalProtocol.Strings(manifest))};JournalProtocol.Strings(header); try{lockStream=CreatePrivate(lockPath,FileAccess.ReadWrite,FileShare.Read);owned=true;} catch(IOException)when(File.Exists(lockPath)){throw new JournalRefusal("This journal is locked; do not overlap jobs or steal a stale lock");} try{ var token=Encoding.ASCII.GetBytes(owner);lockStream.Write(token);lockStream.Flush(true);creation=File.GetCreationTimeUtc(lockPath); if(File.Exists(path)&&(File.GetAttributes(path)&FileAttributes.ReparsePoint)!=0)throw new JournalRefusal("Choose a private regular journal file"); if(mode=="resume"&&!File.Exists(path))throw new JournalRefusal("Journal missing: stop and reconcile lost state before starting a new logical job"); if(mode=="new"&&File.Exists(path))throw new JournalRefusal("Journal exists; use resume for the same logical job"); if(mode=="new"){using var output=CreatePrivate(path,FileAccess.Write,FileShare.None);output.Write(JournalProtocol.Preamble);output.Write(JournalProtocol.Frame(header));output.Flush(true);} var records=JournalProtocol.Decode(File.ReadAllBytes(path));if(records.Count==0||!records[0].SequenceEqual(header))throw new JournalRefusal("Journal workspace/base/guide/job/input binding differs"); foreach(var record in records.Skip(1))Apply(record);if(intents.Keys.Any(step=>!savedValues.ContainsKey(step)))throw new JournalRefusal("Saved intent lacks ACK; stop and reconcile before retry"); }catch{Dispose();throw;} } void Apply(IReadOnlyList record) { if(record.Count==0)throw new JournalRefusal("Empty journal record"); if(record[0]=="I"){ if(record.Count!=6)throw new JournalRefusal("Invalid intent shape");var step=record[1];var method=record[2];var route=record[3];var fingerprint=record[4];var key=record[5]; if(!JournalProtocol.Valid(step,"[a-z][a-z0-9_-]*")||intents.ContainsKey(step)||!allowed.TryGetValue(step,out var expected)||expected!=(method,route)||!JournalProtocol.Valid(fingerprint,"[0-9A-F]{64}")||intents.Keys.Any(name=>!savedValues.ContainsKey(name)))throw new JournalRefusal("Invalid, future or repeated intent"); if(method=="POST"&&!JournalProtocol.Valid(key,"[0-9a-f]{32}")||method!="POST"&&key!="")throw new JournalRefusal("Invalid persisted action key"); intents.Add(step,new Dictionary{{"method",method},{"path",route},{"request_fingerprint",fingerprint},{"idempotency_key",key}}); }else if(record[0]=="A"){ if(record.Count<3||!JournalProtocol.Valid(record[2],"0|[1-9][0-9]*")||!long.TryParse(record[2],NumberStyles.None,CultureInfo.InvariantCulture,out var count)||count!=(record.Count-3L)/2||record.Count%2!=1||!intents.ContainsKey(record[1])||savedValues.ContainsKey(record[1]))throw new JournalRefusal("ACK without exactly one prior intent"); var names=record.Skip(3).Where((_,index)=>index%2==0).ToArray(); if(!names.SequenceEqual(names.Distinct(StringComparer.Ordinal).OrderBy(name=>name,StringComparer.Ordinal))||names.Any(name=>!JournalProtocol.Valid(name,"[a-z][a-z0-9_]*")||name=="api_key"||name=="exhibitday_api_key"))throw new JournalRefusal("ACK fields must be unique sorted secret-free identifiers"); var saved=new Dictionary(StringComparer.Ordinal);for(var i=0;i record) { RequireActive();var raw=JournalProtocol.Frame(record); try{using var output=new FileStream(path,FileMode.Append,FileAccess.Write,FileShare.None);output.Write(raw);output.Flush(true);} catch{tainted=true;throw;} } public bool Acknowledged(string step){RequireActive();return savedValues.ContainsKey(step);} public Dictionary Saved(string step){RequireActive();if(!savedValues.ContainsKey(step))throw new JournalRefusal("No acknowledged state exists");return new Dictionary(savedValues[step],StringComparer.Ordinal);} public Dictionary Begin(string step,string method,string route,string requestFingerprint) { RequireActive();if(intents.ContainsKey(step))throw new JournalRefusal("Never blindly repeat an existing action"); var key=method=="POST"?Convert.ToHexString(System.Security.Cryptography.RandomNumberGenerator.GetBytes(16)).ToLowerInvariant():""; var record=new[]{"I",step,method,route,requestFingerprint,key};var previous=new Dictionary>(intents,StringComparer.Ordinal);try{Apply(record);}finally{intents=previous;} Append(record);Apply(record);return new Dictionary(intents[step],StringComparer.Ordinal); } public void Acknowledge(string step,IReadOnlyDictionary saved) { RequireActive();var record=new List{"A",step,saved.Count.ToString(CultureInfo.InvariantCulture)};foreach(var name in saved.Keys.OrderBy(name=>name,StringComparer.Ordinal))record.AddRange(new[]{name,saved[name]}); var previous=new Dictionary>(savedValues,StringComparer.Ordinal);try{Apply(record);JournalProtocol.Strings(record);}finally{savedValues=previous;} Append(record);Apply(record); } public void Dispose() { if(!owned)return;if(tainted){lockStream.Dispose();lockStream=null;owned=false;return;} try{RequireActive();}catch{lockStream.Dispose();lockStream=null;owned=false;throw;} lockStream.Dispose();lockStream=null;owned=false;File.Delete(lockPath); } } static Dictionary JournalValues(JsonNode value) { if(value is not JsonObject fields)throw new JournalRefusal("Saved/fingerprint values need an explicit object"); var result=new Dictionary(StringComparer.Ordinal); foreach(var field in fields){if(field.Value is not JsonValue item || !item.TryGetValue(out var text) || text==null)throw new JournalRefusal("Saved/fingerprint values must be exact strings");result.Add(field.Key,text);}return result; } static JsonObject JournalObject(IReadOnlyDictionary fields){var result=new JsonObject();foreach(var field in fields)result.Add(field.Key,JsonValue.Create(field.Value));return result;} static void JournalAcknowledge(Journal job,string step,JsonNode saved)=>job.Acknowledge(step,JournalValues(saved)); static bool JournalAcknowledged(Journal job,string step)=>job.Acknowledged(step); static JsonNode JournalBegin(Journal job,string step,string method,string path,string requestFingerprint)=>JournalObject(job.Begin(step,method,path,requestFingerprint)); static string JournalFingerprint(JsonNode value)=>JournalProtocol.Fingerprint(JournalValues(value)); static JsonNode JournalSaved(Journal job,string step)=>JournalObject(job.Saved(step)); static string JsonString(JsonNode value)=>value?.ToJsonString()??"null"; static HashSet NewIdSet() => new HashSet(StringComparer.Ordinal); static bool NotValue(bool value) => !value; static Journal OpenJournal(string path,string apiBase,string workspace,string slug,string job,string inputFingerprint,JsonNode manifest,string mode) { if(manifest is not JsonArray rows)throw new JournalRefusal("A closed write manifest is required");var writes=new List<(string,string,string)>(); foreach(var row in rows){if(row is not JsonArray fields || fields.Count!=3)throw new JournalRefusal("Each write must bind its step/method/path");var values=fields.Select(value=>value is JsonValue item&&item.TryGetValue(out var text)&&text!=null?text:throw new JournalRefusal("Manifest values are exact strings")).ToArray();writes.Add((values[0],values[1],values[2]));} return new Journal(path,apiBase,workspace,slug,job,inputFingerprint,writes,mode); } static string Optional(string name,string fallback) { var value=Environment.GetEnvironmentVariable(name);return value==null||value==""?fallback:value; } static JsonNode ParseJson(string value)=>JsonNode.Parse(value); static string PositiveId(string value) { if(string.IsNullOrEmpty(value)||value[0]=='0'||!value.All(c=>c>='0'&&c<='9')||!long.TryParse(value,NumberStyles.None,CultureInfo.InvariantCulture,out var id)||id<=0)throw new Exception("Use a positive record ID");return value; } static void PrintValue(object value) => Console.WriteLine(value is string text ? text : JsonSerializer.Serialize(value)); static bool RememberId(HashSet seen,string value) => seen.Add(value); static void RequireCondition(bool value,string message) { if(!value)throw new Exception(message); } static string ResponseStatus(Result value)=>value.Status.ToString(CultureInfo.InvariantCulture); static JsonNode TaskIdArray(string value) { if(!System.Text.RegularExpressions.Regex.IsMatch(value,@"\A[ \t\r\n]*\[[ \t\r\n]*(?:[1-9][0-9]*[ \t\r\n]*(?:,[ \t\r\n]*[1-9][0-9]*[ \t\r\n]*)*)?\][ \t\r\n]*\z"))throw new Exception("Use a JSON array of numeric positive Task IDs; no strings, fractions or exponents.");var body=value.Trim();body=body.Substring(1,body.Length-2).Trim();var result=new JsonArray();if(body.Length!=0)foreach(var item in body.Split(','))result.Add(PositiveId(item.Trim()));return result; } static string Text(object value) => value==null?"":value is JsonNode node?Text(node):Convert.ToString(value,CultureInfo.InvariantCulture); internal static async Task Run() { var import_source_id = PositiveId(Required("EXHIBITDAY_SOURCE_EVENT_ID")); var import_target_id = PositiveId(Required("EXHIBITDAY_EVENT_ID")); RequireCondition(NotValue(Equal(import_source_id, import_target_id)), "Choose different source and target Events."); var import_task_ids_json = Required("EXHIBITDAY_TASK_IDS"); var import_task_ids = TaskIdArray(import_task_ids_json); RequireCondition(NotValue(IsEmpty(import_task_ids)), "Choose a nonempty numeric Task ID array from the source Event."); var import_requested_ids = NewIdSet(); foreach (var import_selected_task in Items(import_task_ids)) { var import_selected_id = PositiveId(Text(import_selected_task)); RequireCondition(RememberId(import_requested_ids, import_selected_id), "Select distinct source Task IDs."); } var import_section_id = Optional("EXHIBITDAY_TASK_SECTION_ID", ""); if (IsPresent(import_section_id)) { import_section_id = PositiveId(import_section_id); } var import_keep_assignees = Optional("EXHIBITDAY_KEEP_ASSIGNEES", "false"); var import_keep_files = Optional("EXHIBITDAY_KEEP_ATTACHMENTS", "false"); var import_due_mode = Optional("EXHIBITDAY_DUE_DATE_MODE", "none"); RequireCondition(Either(Equal(import_keep_assignees, "true"), Equal(import_keep_assignees, "false")), "Use literal true or false for the client Boolean options."); RequireCondition(Either(Equal(import_keep_files, "true"), Equal(import_keep_files, "false")), "Use literal true or false for the client Boolean options."); RequireCondition(Either(Equal(import_due_mode, "none"), Either(Equal(import_due_mode, "same_date"), Equal(import_due_mode, "same_offset"))), "Use none, same_date or same_offset for this client's due-date mode."); var import_journal_path = Required("EXHIBITDAY_JOURNAL"); var import_job_id = Required("EXHIBITDAY_JOB_ID"); var import_job_mode = Optional("EXHIBITDAY_JOB_MODE", "resume"); var import_workspace_response = await Call("workspace_binding", new JsonObject { }, null, null); RequireCondition(Equal(ResponseStatus(import_workspace_response), "200"), "Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome."); var import_workspace = import_workspace_response.Body; var import_workspace_id = PositiveId(Text(Field(import_workspace, "id"))); var import_source_response = await Call("source", new JsonObject { ["id"] = import_source_id }, null, null); RequireCondition(Equal(ResponseStatus(import_source_response), "200"), "Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome."); var import_source_event = import_source_response.Body; RequireCondition(Equal(Text(Field(import_source_event, "id")), import_source_id), "Read the exact source and target Events before copying Tasks."); var import_target_response = await Call("target", new JsonObject { ["id"] = import_target_id }, null, null); RequireCondition(Equal(ResponseStatus(import_target_response), "200"), "Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome."); var import_target_event = import_target_response.Body; RequireCondition(Equal(Text(Field(import_target_event, "id")), import_target_id), "Read the exact source and target Events before copying Tasks."); var import_input_fingerprint = JournalFingerprint(new JsonObject { ["workflow_contract_sha256"] = "093C5C392110864D42C6DAAC78ED03CD194F117A1DB3CA4815BDA003407D6B06", ["request"] = JournalFingerprint(new JsonObject { ["source_event_id"] = import_source_id, ["event_id"] = import_target_id, ["task_ids"] = import_task_ids_json, ["task_section_id"] = import_section_id, ["keep_assignees"] = import_keep_assignees, ["due_date_mode"] = import_due_mode, ["keep_attachments"] = import_keep_files }) }); using (var import_job = OpenJournal(import_journal_path, "https://api.exhibitday.com/v1", import_workspace_id, "reuse-event-plan", import_job_id, import_input_fingerprint, new JsonArray(new JsonArray("import_tasks", "POST", "/v1/tasks/import_from_event")), import_job_mode)) { var import_saved_pairs = ParseJson("[]"); if (JournalAcknowledged(import_job, "import_tasks")) { var import_saved = JournalSaved(import_job, "import_tasks"); RequireCondition(Both(Equal(Text(Field(import_saved, "source_event_id")), import_source_id), Equal(Text(Field(import_saved, "event_id")), import_target_id)), "Saved import state belongs to different Events; stop and reconcile."); import_saved_pairs = ParseJson(Text(Field(import_saved, "tasks"))); } else { var import_request_fingerprint = JournalFingerprint(new JsonObject { ["source_event_id"] = import_source_id, ["event_id"] = import_target_id, ["task_ids"] = import_task_ids_json, ["task_section_id"] = import_section_id, ["keep_assignees"] = import_keep_assignees, ["due_date_mode"] = import_due_mode, ["keep_attachments"] = import_keep_files }); var import_intent = JournalBegin(import_job, "import_tasks", "POST", "/v1/tasks/import_from_event", import_request_fingerprint); var import_response = await Call("import_tasks", new JsonObject { }, new JsonObject { ["source_event_id"] = import_source_id, ["event_id"] = import_target_id, ["task_ids"] = import_task_ids_json, ["task_section_id"] = import_section_id, ["keep_assignees"] = Equal(import_keep_assignees, "true"), ["due_date_mode"] = import_due_mode, ["keep_attachments"] = Equal(import_keep_files, "true") }, Text(Field(import_intent, "idempotency_key"))); RequireCondition(Equal(ResponseStatus(import_response), "200"), "Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome."); var import_receipt = import_response.Body; RequireCondition(Both(Equal(Text(Field(import_receipt, "source_event_id")), import_source_id), Equal(Text(Field(import_receipt, "event_id")), import_target_id)), "The import acknowledgement belongs to a different source or target Event."); import_saved_pairs = Field(import_receipt, "tasks"); RequireCondition(Equal(Text(Field(import_receipt, "tasks_copied")), Text(Count(import_task_ids))), "The acknowledged copied-task count differs from the selected Tasks."); var import_saved_pairs_receipt_rows = Items(import_saved_pairs); RequireCondition(Equal(Count(import_saved_pairs_receipt_rows), Count(import_task_ids)), "Some selected Tasks were not imported (the response warnings name them); review them before continuing."); var import_saved_pairs_receipt_seen_source = NewIdSet(); var import_saved_pairs_receipt_seen_new = NewIdSet(); foreach (var import_saved_pairs_receipt_row in Items(import_saved_pairs_receipt_rows)) { var import_saved_pairs_receipt_source_id = PositiveId(Text(Field(import_saved_pairs_receipt_row, "source_task_id"))); var import_saved_pairs_receipt_new_id = PositiveId(Text(Field(import_saved_pairs_receipt_row, "id"))); RequireCondition(NotValue(RememberId(import_requested_ids, import_saved_pairs_receipt_source_id)), "An import pair refers to a Task outside the explicit source selection."); RequireCondition(Both(RememberId(import_saved_pairs_receipt_seen_source, import_saved_pairs_receipt_source_id), RememberId(import_saved_pairs_receipt_seen_new, import_saved_pairs_receipt_new_id)), "Each selected source Task and each new Task ID must appear once in the import receipt."); } JournalAcknowledge(import_job, "import_tasks", new JsonObject { ["source_event_id"] = import_source_id, ["event_id"] = import_target_id, ["tasks"] = JsonString(import_saved_pairs), ["tasks_copied"] = Text(Field(import_receipt, "tasks_copied")) }); } var import_saved_pairs_verify_rows = Items(import_saved_pairs); RequireCondition(Equal(Count(import_saved_pairs_verify_rows), Count(import_task_ids)), "Some selected Tasks were not imported (the response warnings name them); review them before continuing."); var import_saved_pairs_verify_seen_source = NewIdSet(); var import_saved_pairs_verify_seen_new = NewIdSet(); foreach (var import_saved_pairs_verify_row in Items(import_saved_pairs_verify_rows)) { var import_saved_pairs_verify_source_id = PositiveId(Text(Field(import_saved_pairs_verify_row, "source_task_id"))); var import_saved_pairs_verify_new_id = PositiveId(Text(Field(import_saved_pairs_verify_row, "id"))); RequireCondition(NotValue(RememberId(import_requested_ids, import_saved_pairs_verify_source_id)), "An import pair refers to a Task outside the explicit source selection."); RequireCondition(Both(RememberId(import_saved_pairs_verify_seen_source, import_saved_pairs_verify_source_id), RememberId(import_saved_pairs_verify_seen_new, import_saved_pairs_verify_new_id)), "Each selected source Task and each new Task ID must appear once in the import receipt."); var import_saved_pairs_task_response = await Call("verify_task", new JsonObject { ["id"] = import_saved_pairs_verify_new_id }, null, null); RequireCondition(Equal(ResponseStatus(import_saved_pairs_task_response), "200"), "Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome."); var import_saved_pairs_task = import_saved_pairs_task_response.Body; RequireCondition(Equal(Text(Field(import_saved_pairs_task, "id")), import_saved_pairs_verify_new_id), "A captured imported Task is missing or replaced; stop rather than importing a replacement."); var import_saved_pairs_event = Field(import_saved_pairs_task, "event"); RequireCondition(Equal(Text(Field(import_saved_pairs_event, "id")), import_target_id), "A copied Task is no longer under the selected target Event; do not silently re-import it."); } PrintValue(new JsonObject { ["source_event_id"] = import_source_id, ["event_id"] = import_target_id, ["tasks_verified"] = Text(Count(import_task_ids)) }); } } static Task Main() => Run(); } ``` ```java // 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 SPEC = JSON.fromJson("{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"source\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"target\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"import_tasks\":{\"method\":\"POST\",\"path\":\"/tasks/import_from_event\"},\"verify_task\":{\"method\":\"GET\",\"path\":\"/tasks/info\"}}}", Map.class); static final String API_KEY = headerKey(required("EXHIBITDAY_API_KEY")); static String headerKey(String value){if(value.chars().anyMatch(c->c<32||c>126))throw new IllegalArgumentException("Use the API key as one ASCII header value without control characters");return value;} static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).followRedirects(HttpClient.Redirect.NEVER).build(); interface RequestSender { HttpResponse send(HttpRequest request)throws IOException,InterruptedException; } static RequestSender SEND=request->CLIENT.send(request,HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); static class Result { int status; Object body; Map headers; String raw; Result(int s, Object b, Map h,String r) {status=s;body=b;headers=h;raw=r;} } // 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 obj(Object value) {return value==null?new LinkedHashMap<>(): (Map)value;} @SuppressWarnings("unchecked") static List list(Object value) {return value==null?Collections.emptyList():(List)value;} static Map map(Object... pairs) {Map result=new LinkedHashMap<>();for(int i=0;i query,Object body,String key) { Map route=obj(obj(SPEC.get("requests")).get(name));String method=text(route.get("method")); Map headers=map("Authorization","Bearer " + API_KEY,"Accept","application/json"); if(method.equals("POST")){if(key==null||key.isEmpty())throw new IllegalArgumentException("Persist a logical create key before sending POST");headers.put("Idempotency-Key",key);} 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); // 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. boolean resend=method.equals("GET"); 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 response; try {response=SEND.send(request.build());} 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();Object parsed=null; if(status!=304&&!response.body().isEmpty()) { try {parsed=JSON.fromJson(response.body(),Object.class);} catch(RuntimeException error){if(status<400)throw new IllegalStateException("Expected a JSON success response",error);} } Map 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=resend&&(status==429||status>=500); 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,response.body()); } throw new IllegalStateException("Retry limit reached"); } static boolean both(boolean left,boolean right){return left&&right;} static List items(Object value){if(!(value instanceof List))throw new IllegalStateException("Expected a JSON array");return list(value);} static long count(Object value){return items(value).size();} static boolean either(boolean left,boolean right){return left||right;} static boolean equal(Object left,Object right){return Objects.equals(left,right);} static Object field(Object value,String name){if(!(value instanceof Map)||!obj(value).containsKey(name))throw new IllegalStateException("Missing response field: "+name);return obj(value).get(name);} static boolean is_empty(Object value){return count(value)==0;} static boolean is_present(String value){return value!=null&&!value.isEmpty();} // Private client restart state only. No transport, application or JSON interpreter. static final class Journal implements AutoCloseable { public static final class Refusal extends IllegalStateException { Refusal(String message){super(message);} } public static final byte[] PREAMBLE="EXHIBITDAY-GUIDE-JOURNAL 1\n".getBytes(StandardCharsets.US_ASCII); static boolean valid(String value,String pattern){return value!=null&&value.matches(pattern);} static byte[] utf8(String value)throws java.nio.charset.CharacterCodingException { if(value==null)throw new Refusal("Journal fields are exact strings"); java.nio.ByteBuffer encoded=StandardCharsets.UTF_8.newEncoder().onMalformedInput(java.nio.charset.CodingErrorAction.REPORT).onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT).encode(java.nio.CharBuffer.wrap(value));byte[] raw=new byte[encoded.remaining()];encoded.get(raw);return raw; } static String ascii(byte[] raw,int start,int count){for(int i=start;i127)throw new Refusal("Journal framing must be canonical ASCII");return new String(raw,start,count,StandardCharsets.US_ASCII);} public static byte[] strings(Collection values)throws IOException { ByteArrayOutputStream output=new ByteArrayOutputStream();for(String value:values){byte[] raw=utf8(value);output.write((raw.length+":").getBytes(StandardCharsets.US_ASCII));output.write(raw);}return output.toByteArray(); } static int find(byte[] raw,int offset,int value){for(int i=offset;i readStrings(byte[] raw)throws IOException { List values=new ArrayList<>();int offset=0; while(offset0)throw new Refusal("Incomplete journal string");int count=size.intValueExact(); values.add(StandardCharsets.UTF_8.newDecoder().onMalformedInput(java.nio.charset.CodingErrorAction.REPORT).onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT).decode(java.nio.ByteBuffer.wrap(raw,offset,count)).toString());offset+=count;} return values; } public static String digest(byte[] raw){try{byte[] hash=java.security.MessageDigest.getInstance("SHA-256").digest(raw);StringBuilder text=new StringBuilder();for(byte item:hash)text.append(String.format(Locale.ROOT,"%02X",item&255));return text.toString();}catch(java.security.NoSuchAlgorithmException error){throw new IllegalStateException(error);}} public static String fingerprint(Map pairs)throws IOException { List values=new ArrayList<>();for(String name:new TreeSet<>(pairs.keySet())){if(!valid(name,"[A-Za-z0-9_.-]+")||Arrays.asList("api_key","exhibitday_api_key").contains(name.toLowerCase(Locale.ROOT)))throw new Refusal("Use explicit secret-free fingerprint names");values.add(name);values.add(pairs.get(name));}return digest(strings(values)); } public static byte[] frame(Collection values)throws IOException {byte[] payload=strings(values);ByteArrayOutputStream output=new ByteArrayOutputStream();output.write((payload.length+" "+digest(payload)+"\n").getBytes(StandardCharsets.US_ASCII));output.write(payload);output.write(10);return output.toByteArray();} public static List> decode(byte[] raw)throws IOException { if(raw.length> records=new ArrayList<>(); while(offset=0)throw new Refusal("Incomplete frame; reconcile before retry");int count=size.intValueExact();byte[] payload=Arrays.copyOfRange(raw,offset,offset+count);offset+=count; if(raw[offset]!=10||!digest(payload).equals(fields[1]))throw new Refusal("Journal integrity failed; reconcile before retry");records.add(readStrings(payload));offset++;}return records; } static void writeAll(java.nio.channels.FileChannel target,byte[] raw)throws IOException {java.nio.ByteBuffer data=java.nio.ByteBuffer.wrap(raw);while(data.hasRemaining())if(target.write(data)<=0)throw new IOException("Journal write did not advance");} static java.nio.channels.FileChannel createPrivate(Path path,OpenOption... options)throws IOException { java.nio.file.attribute.FileAttribute[] attributes=FileSystems.getDefault().supportedFileAttributeViews().contains("posix")?new java.nio.file.attribute.FileAttribute[]{java.nio.file.attribute.PosixFilePermissions.asFileAttribute(java.nio.file.attribute.PosixFilePermissions.fromString("rw-------"))}:new java.nio.file.attribute.FileAttribute[0]; return java.nio.channels.FileChannel.open(path,new HashSet<>(Arrays.asList(options)),attributes); } final Path path,lockPath;final String owner;final List header; final Map> allowed=new LinkedHashMap<>();Map> intents=new LinkedHashMap<>(),savedValues=new LinkedHashMap<>(); java.nio.channels.FileChannel lock;boolean owned,tainted;Object fileKey;java.nio.file.attribute.FileTime creation; public Journal(Path path,String apiBase,String workspace,String slug,String job,String inputFingerprint,List> writes)throws IOException {this(path,apiBase,workspace,slug,job,inputFingerprint,writes,"resume");} public Journal(Path path,String apiBase,String workspace,String slug,String job,String inputFingerprint,List> writes,String mode)throws IOException { this.path=path;lockPath=Path.of(path.toString()+".lock");byte[] random=new byte[16];new java.security.SecureRandom().nextBytes(random);StringBuilder token=new StringBuilder();for(byte item:random)token.append(String.format(Locale.ROOT,"%02x",item&255));owner=token.toString(); URI address=URI.create(apiBase);if(!Arrays.asList("https","http").contains(address.getScheme())||address.getHost()==null||address.getUserInfo()!=null||address.getRawQuery()!=null||address.getRawFragment()!=null||!valid(slug,"[a-z][a-z0-9-]*"))throw new Refusal("Use actual API base and closed guide slug"); if(job==null||job.trim().isEmpty()||!valid(workspace,"[1-9][0-9]*")||!valid(inputFingerprint,"[0-9A-F]{64}"))throw new Refusal("Use actual workspace, stable explicit job ID and exact fingerprint"); if(!Arrays.asList("new","resume").contains(mode))throw new Refusal("Choose new or resume for this local job"); List manifest=new ArrayList<>();for(List item:writes){if(item.size()!=3)throw new Refusal("Invalid write manifest shape");String step=item.get(0),method=item.get(1),route=item.get(2); if(!valid(step,"[a-z][a-z0-9_-]*")||allowed.containsKey(step)||!Arrays.asList("POST","PATCH","DELETE").contains(method)||!valid(route,"/v1/[A-Za-z0-9_/-]+")||route.contains("//"))throw new Refusal("Use a closed unique write manifest");allowed.put(step,List.of(method,route));manifest.addAll(item);} if(allowed.isEmpty())throw new Refusal("Only write workflows need a restart journal");header=List.of("H","1",apiBase,workspace,slug,job,inputFingerprint,digest(strings(manifest)));strings(header); try{lock=createPrivate(lockPath,StandardOpenOption.CREATE_NEW,StandardOpenOption.READ,StandardOpenOption.WRITE);owned=true;}catch(FileAlreadyExistsException error){throw new Refusal("This journal is locked; do not overlap jobs or steal a stale lock");} try{writeAll(lock,owner.getBytes(StandardCharsets.US_ASCII));lock.force(true);java.nio.file.attribute.BasicFileAttributes identity=Files.readAttributes(lockPath,java.nio.file.attribute.BasicFileAttributes.class,LinkOption.NOFOLLOW_LINKS);fileKey=identity.fileKey();creation=identity.creationTime(); if(Files.isSymbolicLink(path))throw new Refusal("Choose a private regular journal file"); if(mode.equals("resume")&&!Files.exists(path))throw new Refusal("Journal missing: stop and reconcile lost state before starting a new logical job"); if(mode.equals("new")&&Files.exists(path))throw new Refusal("Journal exists; use resume for the same logical job"); if(mode.equals("new")){try(java.nio.channels.FileChannel target=createPrivate(path,StandardOpenOption.CREATE_NEW,StandardOpenOption.WRITE)){writeAll(target,PREAMBLE);writeAll(target,frame(header));target.force(true);}} List> records=decode(Files.readAllBytes(path));if(records.isEmpty()||!records.get(0).equals(header))throw new Refusal("Journal workspace/base/guide/job/input binding differs");for(List record:records.subList(1,records.size()))apply(record); if(intents.keySet().stream().anyMatch(step->!savedValues.containsKey(step)))throw new Refusal("Saved intent lacks ACK; stop and reconcile before retry"); }catch(IOException|RuntimeException error){close();throw error;} } void apply(List record){ if(record.isEmpty())throw new Refusal("Empty journal record"); if(record.get(0).equals("I")){ if(record.size()!=6)throw new Refusal("Invalid intent shape");String step=record.get(1),method=record.get(2),route=record.get(3),fingerprint=record.get(4),key=record.get(5); if(!valid(step,"[a-z][a-z0-9_-]*")||intents.containsKey(step)||!List.of(method,route).equals(allowed.get(step))||!valid(fingerprint,"[0-9A-F]{64}")||intents.keySet().stream().anyMatch(name->!savedValues.containsKey(name)))throw new Refusal("Invalid, future or repeated intent"); if(method.equals("POST")&&!valid(key,"[0-9a-f]{32}")||!method.equals("POST")&&!key.isEmpty())throw new Refusal("Invalid persisted action key");intents.put(step,new LinkedHashMap<>(Map.of("method",method,"path",route,"request_fingerprint",fingerprint,"idempotency_key",key))); }else if(record.get(0).equals("A")){ if(record.size()<3||!valid(record.get(2),"0|[1-9][0-9]*")||!new java.math.BigInteger(record.get(2)).multiply(java.math.BigInteger.TWO).equals(java.math.BigInteger.valueOf(record.size()-3))||!intents.containsKey(record.get(1))||savedValues.containsKey(record.get(1)))throw new Refusal("ACK without exactly one prior intent"); List names=new ArrayList<>();for(int i=3;i(new TreeSet<>(names)))||names.stream().anyMatch(name->!valid(name,"[a-z][a-z0-9_]*")||name.equals("api_key")||name.equals("exhibitday_api_key")))throw new Refusal("ACK fields must be unique sorted secret-free identifiers"); Map saved=new LinkedHashMap<>();for(int i=0;i record)throws IOException {requireActive();byte[] raw=frame(record);try(java.nio.channels.FileChannel target=java.nio.channels.FileChannel.open(path,StandardOpenOption.WRITE,StandardOpenOption.APPEND)){writeAll(target,raw);target.force(true);}catch(IOException|RuntimeException error){tainted=true;throw error;}} public boolean acknowledged(String step)throws IOException{requireActive();return savedValues.containsKey(step);} public Map saved(String step)throws IOException{requireActive();if(!savedValues.containsKey(step))throw new Refusal("No acknowledged state exists");return new LinkedHashMap<>(savedValues.get(step));} public Map begin(String step,String method,String route,String requestFingerprint)throws IOException { requireActive();if(intents.containsKey(step))throw new Refusal("Never blindly repeat an existing action");String key="";if(method.equals("POST")){byte[] bytes=new byte[16];new java.security.SecureRandom().nextBytes(bytes);StringBuilder text=new StringBuilder();for(byte item:bytes)text.append(String.format(Locale.ROOT,"%02x",item&255));key=text.toString();} List record=List.of("I",step,method,route,requestFingerprint,key);Map> previous=new LinkedHashMap<>(intents);try{apply(record);}finally{intents=previous;}append(record);apply(record);return new LinkedHashMap<>(intents.get(step)); } public void acknowledge(String step,Map saved)throws IOException { requireActive();List record=new ArrayList<>(List.of("A",step,Integer.toString(saved.size())));for(String name:new TreeSet<>(saved.keySet())){record.add(name);record.add(saved.get(name));} Map> previous=new LinkedHashMap<>(savedValues);try{apply(record);strings(record);}finally{savedValues=previous;}append(record);apply(record); } public void close()throws IOException { if(!owned)return;if(tainted){lock.close();lock=null;owned=false;return;} try{requireActive();}catch(IOException|RuntimeException error){lock.close();lock=null;owned=false;throw error;}lock.close();lock=null;owned=false;Files.delete(lockPath); } } static Map journal_values(Object value){if(!(value instanceof Map))throw new Journal.Refusal("Saved/fingerprint values need an explicit object");Map result=new LinkedHashMap<>();for(Map.Entry field:((Map)value).entrySet()){if(!(field.getKey() instanceof String)||!(field.getValue() instanceof String))throw new Journal.Refusal("Saved/fingerprint values must be exact strings");result.put((String)field.getKey(),(String)field.getValue());}return result;} static void journal_acknowledge(Journal job,String step,Object saved)throws IOException{job.acknowledge(step,journal_values(saved));} static boolean journal_acknowledged(Journal job,String step)throws IOException{return job.acknowledged(step);} static Object journal_begin(Journal job,String step,String method,String path,String requestFingerprint)throws IOException{return new LinkedHashMap(job.begin(step,method,path,requestFingerprint));} static String journal_fingerprint(Object value)throws IOException{return Journal.fingerprint(journal_values(value));} static Object journal_saved(Journal job,String step)throws IOException{return new LinkedHashMap(job.saved(step));} static String json_string(Object value){return new GsonBuilder().serializeNulls().create().toJson(value);} static Set new_id_set(){return new HashSet<>();} static boolean not_value(boolean value){return !value;} static Journal open_journal(String path,String base,String workspace,String slug,String job,String inputFingerprint,Object manifest,String mode)throws IOException { if(!(manifest instanceof List))throw new Journal.Refusal("A closed write manifest is required");List> writes=new ArrayList<>();for(Object row:(List)manifest){if(!(row instanceof List)||((List)row).size()!=3)throw new Journal.Refusal("Each write must bind step/method/path");List fields=new ArrayList<>();for(Object value:(List)row){if(!(value instanceof String))throw new Journal.Refusal("Manifest values are exact strings");fields.add((String)value);}writes.add(fields);}return new Journal(Path.of(path),base,workspace,slug,job,inputFingerprint,writes,mode); } static String optional(String name,String fallback){String value=System.getenv(name);return value==null||value.isEmpty()?fallback:value;} static Object parse_json(String value){return JSON.fromJson(value,Object.class);} static String positive_id(String value){try{if(value==null||!value.matches("[1-9][0-9]*")||Long.parseLong(value)<=0)throw new IllegalArgumentException();return value;}catch(RuntimeException error){throw new IllegalArgumentException("Use a positive record ID");}} static void print_value(Object value){try{String text=value instanceof String?(String)value:JSON.toJson(value);System.out.write((text+"\n").getBytes(StandardCharsets.UTF_8));}catch(IOException error){throw new UncheckedIOException(error);}} static boolean remember_id(Set seen,String value){return seen.add(value);} static void require_condition(boolean value,String message){if(!value)throw new IllegalStateException(message);} static String response_status(Result value){return Integer.toString(value.status);} static List task_id_array(String value) { if(!value.matches("[ \\t\\r\\n]*\\[[ \\t\\r\\n]*(?:[1-9][0-9]*[ \\t\\r\\n]*(?:,[ \\t\\r\\n]*[1-9][0-9]*[ \\t\\r\\n]*)*)?\\][ \\t\\r\\n]*"))throw new IllegalArgumentException("Use a JSON array of numeric positive Task IDs; no strings, fractions or exponents.");String body=value.trim();body=body.substring(1,body.length()-1).trim();List result=new ArrayList<>();if(!body.isEmpty())for(String item:body.split(","))result.add(positive_id(item.trim()));return result; } static void run()throws Exception { String import_source_id = positive_id(required("EXHIBITDAY_SOURCE_EVENT_ID")); String import_target_id = positive_id(required("EXHIBITDAY_EVENT_ID")); require_condition(not_value(equal(import_source_id, import_target_id)), "Choose different source and target Events."); String import_task_ids_json = required("EXHIBITDAY_TASK_IDS"); List import_task_ids = task_id_array(import_task_ids_json); require_condition(not_value(is_empty(import_task_ids)), "Choose a nonempty numeric Task ID array from the source Event."); Set import_requested_ids = new_id_set(); for (Object import_selected_task : items(import_task_ids)) { String import_selected_id = positive_id(text(import_selected_task)); require_condition(remember_id(import_requested_ids, import_selected_id), "Select distinct source Task IDs."); } String import_section_id = optional("EXHIBITDAY_TASK_SECTION_ID", ""); if (is_present(import_section_id)) { import_section_id = positive_id(import_section_id); } String import_keep_assignees = optional("EXHIBITDAY_KEEP_ASSIGNEES", "false"); String import_keep_files = optional("EXHIBITDAY_KEEP_ATTACHMENTS", "false"); String import_due_mode = optional("EXHIBITDAY_DUE_DATE_MODE", "none"); require_condition(either(equal(import_keep_assignees, "true"), equal(import_keep_assignees, "false")), "Use literal true or false for the client Boolean options."); require_condition(either(equal(import_keep_files, "true"), equal(import_keep_files, "false")), "Use literal true or false for the client Boolean options."); require_condition(either(equal(import_due_mode, "none"), either(equal(import_due_mode, "same_date"), equal(import_due_mode, "same_offset"))), "Use none, same_date or same_offset for this client's due-date mode."); String import_journal_path = required("EXHIBITDAY_JOURNAL"); String import_job_id = required("EXHIBITDAY_JOB_ID"); String import_job_mode = optional("EXHIBITDAY_JOB_MODE", "resume"); Result import_workspace_response = call("workspace_binding", map(), null, null); require_condition(equal(response_status(import_workspace_response), "200"), "Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome."); Object import_workspace = import_workspace_response.body; String import_workspace_id = positive_id(text(field(import_workspace, "id"))); Result import_source_response = call("source", map("id", import_source_id), null, null); require_condition(equal(response_status(import_source_response), "200"), "Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome."); Object import_source_event = import_source_response.body; require_condition(equal(text(field(import_source_event, "id")), import_source_id), "Read the exact source and target Events before copying Tasks."); Result import_target_response = call("target", map("id", import_target_id), null, null); require_condition(equal(response_status(import_target_response), "200"), "Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome."); Object import_target_event = import_target_response.body; require_condition(equal(text(field(import_target_event, "id")), import_target_id), "Read the exact source and target Events before copying Tasks."); String import_input_fingerprint = journal_fingerprint(map("workflow_contract_sha256", "093C5C392110864D42C6DAAC78ED03CD194F117A1DB3CA4815BDA003407D6B06", "request", journal_fingerprint(map("source_event_id", import_source_id, "event_id", import_target_id, "task_ids", import_task_ids_json, "task_section_id", import_section_id, "keep_assignees", import_keep_assignees, "due_date_mode", import_due_mode, "keep_attachments", import_keep_files)))); try (Journal import_job = open_journal(import_journal_path, "https://api.exhibitday.com/v1", import_workspace_id, "reuse-event-plan", import_job_id, import_input_fingerprint, Arrays.asList(Arrays.asList("import_tasks", "POST", "/v1/tasks/import_from_event")), import_job_mode)) { Object import_saved_pairs = parse_json("[]"); if (journal_acknowledged(import_job, "import_tasks")) { Object import_saved = journal_saved(import_job, "import_tasks"); require_condition(both(equal(text(field(import_saved, "source_event_id")), import_source_id), equal(text(field(import_saved, "event_id")), import_target_id)), "Saved import state belongs to different Events; stop and reconcile."); import_saved_pairs = parse_json(text(field(import_saved, "tasks"))); } else { String import_request_fingerprint = journal_fingerprint(map("source_event_id", import_source_id, "event_id", import_target_id, "task_ids", import_task_ids_json, "task_section_id", import_section_id, "keep_assignees", import_keep_assignees, "due_date_mode", import_due_mode, "keep_attachments", import_keep_files)); Object import_intent = journal_begin(import_job, "import_tasks", "POST", "/v1/tasks/import_from_event", import_request_fingerprint); Result import_response = call("import_tasks", map(), map("source_event_id", import_source_id, "event_id", import_target_id, "task_ids", import_task_ids_json, "task_section_id", import_section_id, "keep_assignees", equal(import_keep_assignees, "true"), "due_date_mode", import_due_mode, "keep_attachments", equal(import_keep_files, "true")), text(field(import_intent, "idempotency_key"))); require_condition(equal(response_status(import_response), "200"), "Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome."); Object import_receipt = import_response.body; require_condition(both(equal(text(field(import_receipt, "source_event_id")), import_source_id), equal(text(field(import_receipt, "event_id")), import_target_id)), "The import acknowledgement belongs to a different source or target Event."); import_saved_pairs = field(import_receipt, "tasks"); require_condition(equal(text(field(import_receipt, "tasks_copied")), text(count(import_task_ids))), "The acknowledged copied-task count differs from the selected Tasks."); List import_saved_pairs_receipt_rows = items(import_saved_pairs); require_condition(equal(count(import_saved_pairs_receipt_rows), count(import_task_ids)), "Some selected Tasks were not imported (the response warnings name them); review them before continuing."); Set import_saved_pairs_receipt_seen_source = new_id_set(); Set import_saved_pairs_receipt_seen_new = new_id_set(); for (Object import_saved_pairs_receipt_row : items(import_saved_pairs_receipt_rows)) { String import_saved_pairs_receipt_source_id = positive_id(text(field(import_saved_pairs_receipt_row, "source_task_id"))); String import_saved_pairs_receipt_new_id = positive_id(text(field(import_saved_pairs_receipt_row, "id"))); require_condition(not_value(remember_id(import_requested_ids, import_saved_pairs_receipt_source_id)), "An import pair refers to a Task outside the explicit source selection."); require_condition(both(remember_id(import_saved_pairs_receipt_seen_source, import_saved_pairs_receipt_source_id), remember_id(import_saved_pairs_receipt_seen_new, import_saved_pairs_receipt_new_id)), "Each selected source Task and each new Task ID must appear once in the import receipt."); } journal_acknowledge(import_job, "import_tasks", map("source_event_id", import_source_id, "event_id", import_target_id, "tasks", json_string(import_saved_pairs), "tasks_copied", text(field(import_receipt, "tasks_copied")))); } List import_saved_pairs_verify_rows = items(import_saved_pairs); require_condition(equal(count(import_saved_pairs_verify_rows), count(import_task_ids)), "Some selected Tasks were not imported (the response warnings name them); review them before continuing."); Set import_saved_pairs_verify_seen_source = new_id_set(); Set import_saved_pairs_verify_seen_new = new_id_set(); for (Object import_saved_pairs_verify_row : items(import_saved_pairs_verify_rows)) { String import_saved_pairs_verify_source_id = positive_id(text(field(import_saved_pairs_verify_row, "source_task_id"))); String import_saved_pairs_verify_new_id = positive_id(text(field(import_saved_pairs_verify_row, "id"))); require_condition(not_value(remember_id(import_requested_ids, import_saved_pairs_verify_source_id)), "An import pair refers to a Task outside the explicit source selection."); require_condition(both(remember_id(import_saved_pairs_verify_seen_source, import_saved_pairs_verify_source_id), remember_id(import_saved_pairs_verify_seen_new, import_saved_pairs_verify_new_id)), "Each selected source Task and each new Task ID must appear once in the import receipt."); Result import_saved_pairs_task_response = call("verify_task", map("id", import_saved_pairs_verify_new_id), null, null); require_condition(equal(response_status(import_saved_pairs_task_response), "200"), "Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome."); Object import_saved_pairs_task = import_saved_pairs_task_response.body; require_condition(equal(text(field(import_saved_pairs_task, "id")), import_saved_pairs_verify_new_id), "A captured imported Task is missing or replaced; stop rather than importing a replacement."); Object import_saved_pairs_event = field(import_saved_pairs_task, "event"); require_condition(equal(text(field(import_saved_pairs_event, "id")), import_target_id), "A copied Task is no longer under the selected target Event; do not silently re-import it."); } print_value(map("source_event_id", import_source_id, "event_id", import_target_id, "tasks_verified", text(count(import_task_ids)))); } } public static void main(String[] args)throws Exception {run();} } ``` ```php $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, ?string $key = null): array { global $spec, $apiKey, $transport; $route = $spec['requests'][$name]; $headers = ['Authorization' => 'Bearer ' . $apiKey, 'Accept' => 'application/json']; if ($route['method'] === 'POST') { if ($key === null || $key === '') throw new RuntimeException('Persist a logical create key before sending POST'); $headers['Idempotency-Key'] = $key; // 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); // 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 = 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 = $resend && ($status === 429 || $status >= 500); 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, 'raw' => $raw]; } throw new RuntimeException('Retry limit reached'); } $transport = Closure::fromCallable('nativeTransport'); function both(bool $left,bool $right):bool{return $left&&$right;} function either(bool $left,bool $right):bool{return $left||$right;} function equal(mixed $left,mixed $right):bool{return $left===$right;} function field(mixed $value,string $name):mixed{if(!is_array($value)||!array_key_exists($name,$value))throw new RuntimeException("Missing response field: ".$name);return $value[$name];} function items(mixed $value):array{if(!is_array($value)||!array_is_list($value))throw new RuntimeException("Expected a JSON array");return $value;} function is_empty(mixed $value):bool{return count(items($value))===0;} function is_present(?string $value):bool{return $value!==null&&$value!=="";} final class JournalRefusal extends RuntimeException {} final class JournalProtocol { public const PREAMBLE="EXHIBITDAY-GUIDE-JOURNAL 1\n"; public static function utf8(mixed $value):string {if(!is_string($value)||preg_match('//u',$value)!==1)throw new JournalRefusal('Journal fields must be exact valid UTF8 strings');return$value;} public static function strings(array $values):string {$raw='';foreach($values as$value){$item=self::utf8($value);$raw.=strlen($item).':'.$item;}return$raw;} private static function length(string $text,int $remaining):int {if(!preg_match('/\A(?:0|[1-9][0-9]*)\z/',$text))throw new JournalRefusal('Noncanonical string length');$maximum=(string)$remaining;if(strlen($text)>strlen($maximum)||(strlen($text)===strlen($maximum)&&strcmp($text,$maximum)>0))throw new JournalRefusal('Incomplete journal string/frame');return(int)$text;} public static function readStrings(string $raw):array {$values=[];$offset=0;while($offset=strlen($raw)-$offset)throw new JournalRefusal('Incomplete frame; reconcile before retry');$payload=substr($raw,$offset,$size);$offset+=$size;if($raw[$offset]!=="\n"||self::digest($payload)!==$match[2])throw new JournalRefusal('Journal integrity failed; reconcile before retry');$records[]=self::readStrings($payload);$offset++;}return$records;} public static function writeAll($file,string $raw):void {$offset=0;while($offsetpath=$path;$this->lockPath=$path.'.lock';$this->owner=bin2hex(random_bytes(16));$address=parse_url($base); if($address===false||!in_array($address['scheme']??null,['https','http'],true)||!isset($address['host'])||isset($address['user'])||isset($address['pass'])||isset($address['query'])||isset($address['fragment'])||!preg_match('/\A[a-z][a-z0-9-]*\z/',$slug))throw new JournalRefusal('Use actual API base and closed guide slug'); if(trim($job)===''||!preg_match('/\A[1-9][0-9]*\z/',$workspace)||!preg_match('/\A[0-9A-F]{64}\z/',$inputFingerprint))throw new JournalRefusal('Use actual workspace, stable explicit job ID and exact fingerprint'); if(!in_array($mode,['new','resume'],true))throw new JournalRefusal('Choose new or resume for this local job'); $manifest=[];foreach($writes as$write){if(!is_array($write)||!array_is_list($write)||count($write)!==3)throw new JournalRefusal('Invalid write manifest');[$step,$method,$route]=$write; if(!is_string($step)||!preg_match('/\A[a-z][a-z0-9_-]*\z/',$step)||isset($this->allowed[$step])||!in_array($method,['POST','PATCH','DELETE'],true)||!is_string($route)||!preg_match('~\A/v1/[A-Za-z0-9_/-]+\z~',$route)||str_contains($route,'//'))throw new JournalRefusal('Use a closed unique write manifest');$this->allowed[$step]=[$method,$route];array_push($manifest,$step,$method,$route);} if($this->allowed===[])throw new JournalRefusal('Only write workflows need restart journal');$this->header=['H','1',$base,$workspace,$slug,$job,$inputFingerprint,JournalProtocol::digest(JournalProtocol::strings($manifest))];JournalProtocol::strings($this->header); $this->file=JournalProtocol::createPrivate($this->lockPath);$this->owned=true; try{ JournalProtocol::writeAll($this->file,$this->owner);$identity=fstat($this->file);if($identity===false)throw new JournalRefusal('Cannot bind acquired lock identity');$this->identity=$identity; clearstatcache(true,$path);if(is_link($path))throw new JournalRefusal('Choose private regular journal file'); $exists=file_exists($path);if($mode==='resume'&&!$exists)throw new JournalRefusal('Journal missing: stop and reconcile lost state before starting a new logical job');if($mode==='new'&&$exists)throw new JournalRefusal('Journal exists; use resume for the same logical job'); if($mode==='new'){$target=JournalProtocol::createPrivate($path);try{JournalProtocol::writeAll($target,JournalProtocol::PREAMBLE.JournalProtocol::frame($this->header));}finally{fclose($target);}} $raw=file_get_contents($path);if($raw===false)throw new JournalRefusal('Cannot read journal');$records=JournalProtocol::decode($raw);if($records===[]||$records[0]!==$this->header)throw new JournalRefusal('Journal workspace/base/guide/job/input binding differs');foreach(array_slice($records,1)as$record)$this->apply($record); if(array_diff(array_keys($this->intents),array_keys($this->savedValues))!==[])throw new JournalRefusal('Saved intent lacks ACK; stop and reconcile before retry'); }catch(Throwable $error){$this->close();throw$error;} } private function apply(array $record):void { if(($record[0]??null)==='I'){ if(count($record)!==6)throw new JournalRefusal('Invalid intent shape');[,$step,$method,$route,$fingerprint,$key]=$record; if(!preg_match('/\A[a-z][a-z0-9_-]*\z/',$step)||isset($this->intents[$step])||($this->allowed[$step]??null)!==[$method,$route]||!preg_match('/\A[0-9A-F]{64}\z/',$fingerprint)||array_diff(array_keys($this->intents),array_keys($this->savedValues))!==[])throw new JournalRefusal('Invalid, future or repeated intent'); if(($method==='POST'&&!preg_match('/\A[0-9a-f]{32}\z/',$key))||($method!=='POST'&&$key!==''))throw new JournalRefusal('Invalid persisted action key');$this->intents[$step]=['method'=>$method,'path'=>$route,'request_fingerprint'=>$fingerprint,'idempotency_key'=>$key]; }elseif(($record[0]??null)==='A'){ if(count($record)<3)throw new JournalRefusal('Invalid ACK shape');[,$step,$count]=$record;$pairs=array_slice($record,3); if(!preg_match('/\A(?:0|[1-9][0-9]*)\z/',$count)||(string)intdiv(count($pairs),2)!==$count||count($pairs)%2!==0||!isset($this->intents[$step])||isset($this->savedValues[$step]))throw new JournalRefusal('ACK without exactly one prior intent'); $names=[];for($i=0;$i$name){if(!preg_match('/\A[a-z][a-z0-9_]*\z/',$name)||in_array($name,['api_key','exhibitday_api_key'],true))throw new JournalRefusal('Use secret-free ACK field names');$saved[$name]=$pairs[$i*2+1];}$this->savedValues[$step]=$saved; }else throw new JournalRefusal('Unknown journal transition'); } private function requireActive():void { if(!$this->owned||$this->file===null||$this->tainted)throw new JournalRefusal('Journal closed or IO outcome needs reconciliation');clearstatcache(true,$this->lockPath);$current=@lstat($this->lockPath);$token=@file_get_contents($this->lockPath); if($current===false||($current['dev']??null)!==($this->identity['dev']??null)||($current['ino']??null)!==($this->identity['ino']??null)||$token!==$this->owner)throw new JournalRefusal('Journal lock replaced; stop without deleting it'); } private function append(array $record):void { $this->requireActive();$raw=JournalProtocol::frame($record);$target=null; try{$target=@fopen($this->path,'ab');if($target===false)throw new JournalRefusal('Cannot append journal; stop and reconcile');JournalProtocol::writeAll($target,$raw);}catch(Throwable $error){$this->tainted=true;throw$error;}finally{if(is_resource($target))fclose($target);} } public function acknowledged(string $step):bool{$this->requireActive();return isset($this->savedValues[$step]);} public function saved(string $step):array{$this->requireActive();if(!isset($this->savedValues[$step]))throw new JournalRefusal('No acknowledged state exists');return$this->savedValues[$step];} public function beginAction(string $step,string $method,string $route,string $requestFingerprint):array { $this->requireActive();if(isset($this->intents[$step]))throw new JournalRefusal('Never blindly repeat an existing action');$key=$method==='POST'?bin2hex(random_bytes(16)):'';$record=['I',$step,$method,$route,$requestFingerprint,$key];$previous=$this->intents;try{$this->apply($record);}finally{$this->intents=$previous;}$this->append($record);$this->apply($record);return$this->intents[$step]; } public function acknowledge(string $step,array $saved):void { $this->requireActive();$record=['A',$step,(string)count($saved)];$names=array_keys($saved);sort($names,SORT_STRING);foreach($names as$name){$record[]=$name;$record[]=$saved[$name];}$previous=$this->savedValues;try{$this->apply($record);JournalProtocol::strings($record);}finally{$this->savedValues=$previous;}$this->append($record);$this->apply($record); } public function close():void { if(!$this->owned)return;if($this->tainted){fclose($this->file);$this->file=null;$this->owned=false;return;} try{$this->requireActive();}catch(Throwable $error){fclose($this->file);$this->file=null;$this->owned=false;throw$error;}fclose($this->file);$this->file=null;$this->owned=false;if(!unlink($this->lockPath))throw new JournalRefusal('Could not release owned journal lock'); } } function journal_values(mixed $value):array{if(!is_object($value))throw new JournalRefusal('Saved/fingerprint values need an explicit object');$result=get_object_vars($value);foreach($result as$name=>$item)if(!is_string($name)||!is_string($item))throw new JournalRefusal('Saved/fingerprint values must be exact strings');return$result;} function journal_acknowledge(GuideJournal $job,string $step,mixed $saved):void{$job->acknowledge($step,journal_values($saved));} function journal_acknowledged(GuideJournal $job,string $step):bool{return $job->acknowledged($step);} function journal_begin(GuideJournal $job,string $step,string $method,string $path,string $requestFingerprint):array{return $job->beginAction($step,$method,$path,$requestFingerprint);} function journal_fingerprint(mixed $value):string{return JournalProtocol::fingerprint(journal_values($value));} function journal_saved(GuideJournal $job,string $step):array{return $job->saved($step);} function json_string(mixed $value):string{return json_encode($value,JSON_THROW_ON_ERROR|JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);} function new_id_set():array{return [];} function not_value(bool $value):bool{return !$value;} function open_journal(string $path,string $base,string $workspace,string $slug,string $job,string $inputFingerprint,array $writes,string $mode):GuideJournal{return new GuideJournal($path,$base,$workspace,$slug,$job,$inputFingerprint,$writes,$mode);} function parse_json(string $value):mixed{return json_decode($value,true,512,JSON_THROW_ON_ERROR);} function positive_id(string $value):string{if(!preg_match("/^[1-9][0-9]*$/D",$value)||strlen($value)>19||(strlen($value)===19&&strcmp($value,"9223372036854775807")>0))throw new RuntimeException("Use a positive record ID");return $value;} function print_value(mixed $value):void{echo (is_string($value)?$value:json_encode($value,JSON_THROW_ON_ERROR))."\n";} function remember_id(array &$seen,string $value):bool{if(array_key_exists($value,$seen))return false;$seen[$value]=true;return true;} function require_condition(bool $value,string $message):void{if(!$value)throw new RuntimeException($message);} function response_status(array $value):string{return(string)$value["status"];} function task_id_array(string $value):array { if(preg_match('/\A[ \t\r\n]*\[[ \t\r\n]*(?:[1-9][0-9]*[ \t\r\n]*(?:,[ \t\r\n]*[1-9][0-9]*[ \t\r\n]*)*)?\][ \t\r\n]*\z/',$value)!==1)throw new RuntimeException('Use a JSON array of numeric positive Task IDs; no strings, fractions or exponents.');$body=trim($value);$body=trim(substr($body,1,-1));return $body===''?[]:array_map(fn($id)=>positive_id(trim($id)),explode(',',$body)); } function text(mixed $value):string{if($value===null)return "";if(is_string($value))return $value;if(is_bool($value))return $value?"true":"false";if(is_int($value))return (string)$value;throw new RuntimeException("Expected a scalar response value");} function main():void { $import_source_id = positive_id(required('EXHIBITDAY_SOURCE_EVENT_ID')); $import_target_id = positive_id(required('EXHIBITDAY_EVENT_ID')); require_condition(not_value(equal($import_source_id, $import_target_id)), 'Choose different source and target Events.'); $import_task_ids_json = required('EXHIBITDAY_TASK_IDS'); $import_task_ids = task_id_array($import_task_ids_json); require_condition(not_value(is_empty($import_task_ids)), 'Choose a nonempty numeric Task ID array from the source Event.'); $import_requested_ids = new_id_set(); foreach (items($import_task_ids) as $import_selected_task) { $import_selected_id = positive_id(text($import_selected_task)); require_condition(remember_id($import_requested_ids, $import_selected_id), 'Select distinct source Task IDs.'); } $import_section_id = optional('EXHIBITDAY_TASK_SECTION_ID', ''); if (is_present($import_section_id)) { $import_section_id = positive_id($import_section_id); } $import_keep_assignees = optional('EXHIBITDAY_KEEP_ASSIGNEES', 'false'); $import_keep_files = optional('EXHIBITDAY_KEEP_ATTACHMENTS', 'false'); $import_due_mode = optional('EXHIBITDAY_DUE_DATE_MODE', 'none'); require_condition(either(equal($import_keep_assignees, 'true'), equal($import_keep_assignees, 'false')), 'Use literal true or false for the client Boolean options.'); require_condition(either(equal($import_keep_files, 'true'), equal($import_keep_files, 'false')), 'Use literal true or false for the client Boolean options.'); require_condition(either(equal($import_due_mode, 'none'), either(equal($import_due_mode, 'same_date'), equal($import_due_mode, 'same_offset'))), 'Use none, same_date or same_offset for this client\'s due-date mode.'); $import_journal_path = required('EXHIBITDAY_JOURNAL'); $import_job_id = required('EXHIBITDAY_JOB_ID'); $import_job_mode = optional('EXHIBITDAY_JOB_MODE', 'resume'); $import_workspace_response = call('workspace_binding', [], null, null); require_condition(equal(response_status($import_workspace_response), '200'), 'Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome.'); $import_workspace = $import_workspace_response["body"]; $import_workspace_id = positive_id(text(field($import_workspace, 'id'))); $import_source_response = call('source', ['id' => $import_source_id], null, null); require_condition(equal(response_status($import_source_response), '200'), 'Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome.'); $import_source_event = $import_source_response["body"]; require_condition(equal(text(field($import_source_event, 'id')), $import_source_id), 'Read the exact source and target Events before copying Tasks.'); $import_target_response = call('target', ['id' => $import_target_id], null, null); require_condition(equal(response_status($import_target_response), '200'), 'Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome.'); $import_target_event = $import_target_response["body"]; require_condition(equal(text(field($import_target_event, 'id')), $import_target_id), 'Read the exact source and target Events before copying Tasks.'); $import_input_fingerprint = journal_fingerprint((object)['workflow_contract_sha256' => '093C5C392110864D42C6DAAC78ED03CD194F117A1DB3CA4815BDA003407D6B06', 'request' => journal_fingerprint((object)['source_event_id' => $import_source_id, 'event_id' => $import_target_id, 'task_ids' => $import_task_ids_json, 'task_section_id' => $import_section_id, 'keep_assignees' => $import_keep_assignees, 'due_date_mode' => $import_due_mode, 'keep_attachments' => $import_keep_files])]); $import_job = open_journal($import_journal_path, 'https://api.exhibitday.com/v1', $import_workspace_id, 'reuse-event-plan', $import_job_id, $import_input_fingerprint, [['import_tasks', 'POST', '/v1/tasks/import_from_event']], $import_job_mode); try { $import_saved_pairs = parse_json('[]'); if (journal_acknowledged($import_job, 'import_tasks')) { $import_saved = journal_saved($import_job, 'import_tasks'); require_condition(both(equal(text(field($import_saved, 'source_event_id')), $import_source_id), equal(text(field($import_saved, 'event_id')), $import_target_id)), 'Saved import state belongs to different Events; stop and reconcile.'); $import_saved_pairs = parse_json(text(field($import_saved, 'tasks'))); } else { $import_request_fingerprint = journal_fingerprint((object)['source_event_id' => $import_source_id, 'event_id' => $import_target_id, 'task_ids' => $import_task_ids_json, 'task_section_id' => $import_section_id, 'keep_assignees' => $import_keep_assignees, 'due_date_mode' => $import_due_mode, 'keep_attachments' => $import_keep_files]); $import_intent = journal_begin($import_job, 'import_tasks', 'POST', '/v1/tasks/import_from_event', $import_request_fingerprint); $import_response = call('import_tasks', [], (object)['source_event_id' => $import_source_id, 'event_id' => $import_target_id, 'task_ids' => $import_task_ids_json, 'task_section_id' => $import_section_id, 'keep_assignees' => equal($import_keep_assignees, 'true'), 'due_date_mode' => $import_due_mode, 'keep_attachments' => equal($import_keep_files, 'true')], text(field($import_intent, 'idempotency_key'))); require_condition(equal(response_status($import_response), '200'), 'Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome.'); $import_receipt = $import_response["body"]; require_condition(both(equal(text(field($import_receipt, 'source_event_id')), $import_source_id), equal(text(field($import_receipt, 'event_id')), $import_target_id)), 'The import acknowledgement belongs to a different source or target Event.'); $import_saved_pairs = field($import_receipt, 'tasks'); require_condition(equal(text(field($import_receipt, 'tasks_copied')), text(count($import_task_ids))), 'The acknowledged copied-task count differs from the selected Tasks.'); $import_saved_pairs_receipt_rows = items($import_saved_pairs); require_condition(equal(count($import_saved_pairs_receipt_rows), count($import_task_ids)), 'Some selected Tasks were not imported (the response warnings name them); review them before continuing.'); $import_saved_pairs_receipt_seen_source = new_id_set(); $import_saved_pairs_receipt_seen_new = new_id_set(); foreach (items($import_saved_pairs_receipt_rows) as $import_saved_pairs_receipt_row) { $import_saved_pairs_receipt_source_id = positive_id(text(field($import_saved_pairs_receipt_row, 'source_task_id'))); $import_saved_pairs_receipt_new_id = positive_id(text(field($import_saved_pairs_receipt_row, 'id'))); require_condition(not_value(remember_id($import_requested_ids, $import_saved_pairs_receipt_source_id)), 'An import pair refers to a Task outside the explicit source selection.'); require_condition(both(remember_id($import_saved_pairs_receipt_seen_source, $import_saved_pairs_receipt_source_id), remember_id($import_saved_pairs_receipt_seen_new, $import_saved_pairs_receipt_new_id)), 'Each selected source Task and each new Task ID must appear once in the import receipt.'); } journal_acknowledge($import_job, 'import_tasks', (object)['source_event_id' => $import_source_id, 'event_id' => $import_target_id, 'tasks' => json_string($import_saved_pairs), 'tasks_copied' => text(field($import_receipt, 'tasks_copied'))]); } $import_saved_pairs_verify_rows = items($import_saved_pairs); require_condition(equal(count($import_saved_pairs_verify_rows), count($import_task_ids)), 'Some selected Tasks were not imported (the response warnings name them); review them before continuing.'); $import_saved_pairs_verify_seen_source = new_id_set(); $import_saved_pairs_verify_seen_new = new_id_set(); foreach (items($import_saved_pairs_verify_rows) as $import_saved_pairs_verify_row) { $import_saved_pairs_verify_source_id = positive_id(text(field($import_saved_pairs_verify_row, 'source_task_id'))); $import_saved_pairs_verify_new_id = positive_id(text(field($import_saved_pairs_verify_row, 'id'))); require_condition(not_value(remember_id($import_requested_ids, $import_saved_pairs_verify_source_id)), 'An import pair refers to a Task outside the explicit source selection.'); require_condition(both(remember_id($import_saved_pairs_verify_seen_source, $import_saved_pairs_verify_source_id), remember_id($import_saved_pairs_verify_seen_new, $import_saved_pairs_verify_new_id)), 'Each selected source Task and each new Task ID must appear once in the import receipt.'); $import_saved_pairs_task_response = call('verify_task', ['id' => $import_saved_pairs_verify_new_id], null, null); require_condition(equal(response_status($import_saved_pairs_task_response), '200'), 'Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome.'); $import_saved_pairs_task = $import_saved_pairs_task_response["body"]; require_condition(equal(text(field($import_saved_pairs_task, 'id')), $import_saved_pairs_verify_new_id), 'A captured imported Task is missing or replaced; stop rather than importing a replacement.'); $import_saved_pairs_event = field($import_saved_pairs_task, 'event'); require_condition(equal(text(field($import_saved_pairs_event, 'id')), $import_target_id), 'A copied Task is no longer under the selected target Event; do not silently re-import it.'); } print_value((object)['source_event_id' => $import_source_id, 'event_id' => $import_target_id, 'tasks_verified' => text(count($import_task_ids))]); } finally { $import_job->close(); } } if (realpath($_SERVER['SCRIPT_FILENAME'] ?? '') === __FILE__) main(); ``` ```ruby # 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":true,"requests":{"workspace_binding":{"method":"GET","path":"/references/workspace_info"},"source":{"method":"GET","path":"/events/info"},"target":{"method":"GET","path":"/events/info"},"import_tasks":{"method":"POST","path":"/tasks/import_from_event"},"verify_task":{"method":"GET","path":"/tasks/info"}}}') API_KEY = ENV.fetch('EXHIBITDAY_API_KEY') raise 'Use the API key as one ASCII header value without control characters' if API_KEY.each_codepoint.any?{|point|point<32||point>126} 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, 'DELETE' => Net::HTTP::Delete }.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, key = nil) route = SPEC.fetch('requests').fetch(name) headers = { 'Authorization' => 'Bearer ' + API_KEY, 'Accept' => 'application/json' } if route.fetch('method') == 'POST' headers['Idempotency-Key'] = key || raise('Persist a logical create key before sending POST') # 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) # 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.fetch('method') == 'GET' 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 = resend && (status == 429 || (500..599).cover?(status)) 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, raw: raw } end raise 'Retry limit reached' end def both(left,right);left&&right;end def items(value) raise "Expected a JSON array" unless value.is_a?(Array) value end def count(value) items(value).length end def either(left,right) raise "Expected Boolean criteria" unless [true,false].include?(left) && [true,false].include?(right) left || right end def equal(left,right) left.class==right.class && left==right end def field(value,name) raise "Missing response field: #{name}" unless value.is_a?(Hash) && value.key?(name) value.fetch(name) end def is_empty(value) count(value)==0 end def is_present(value) !value.nil? && value!="" end require 'digest' require 'securerandom' require 'uri' # Private client restart state, with no transport or application dependency. module GuideJournalProtocol PREAMBLE="EXHIBITDAY-GUIDE-JOURNAL 1\n".b.freeze class Refusal < StandardError; end def self.utf8(value) raise Refusal,'Journal fields are exact strings' unless value.is_a?(String)&&value.valid_encoding? raw=value.encode(Encoding::UTF_8) raise Refusal,'Invalid UTF8 journal field' unless raw.valid_encoding? raw.b end def self.strings(values) values.map{|value|raw=utf8(value);raw.bytesize.to_s.b+':'.b+raw}.join.b end def self.read_strings(raw) values=[];offset=0 while offsetraw.bytesize-offset value=raw.byteslice(offset,size).dup.force_encoding(Encoding::UTF_8);raise Refusal,'Invalid UTF8 string' unless value.valid_encoding? values<=raw.bytesize-offset payload=raw.byteslice(offset,size);offset+=size raise Refusal,'Journal integrity failed; reconcile before retry' unless raw.getbyte(offset)==10&&digest(payload)==match[2] records<0 offset+=written end file.flush;file.fsync end end class GuideJournal P=GuideJournalProtocol def initialize(path,base,workspace,slug,job,input_fingerprint,writes,mode='resume') @path=path.dup;@lock_path=path+'.lock';@file=nil;@owned=false;@tainted=false;@intents={};@saved={};@allowed={} address=URI(base) raise P::Refusal,'Use actual API base and closed guide slug' unless ['https','http'].include?(address.scheme)&&address.host&&address.userinfo.nil?&&address.query.nil?&&address.fragment.nil?&&slug.match?(/\A[a-z][a-z0-9-]*\z/) raise P::Refusal,'Use actual workspace, stable explicit job ID and exact fingerprint' unless !job.strip.empty?&&workspace.match?(/\A[1-9][0-9]*\z/)&&input_fingerprint.match?(/\A[0-9A-F]{64}\z/) raise P::Refusal,'Choose new or resume for this local job' unless ['new','resume'].include?(mode) manifest=[] writes.each do|step,method,route| raise P::Refusal,'Use closed unique write manifest' unless step.match?(/\A[a-z][a-z0-9_-]*\z/)&&!@allowed.key?(step)&&['POST','PATCH','DELETE'].include?(method)&&route.match?(/\A\/v1\/[A-Za-z0-9_\/-]+\z/)&&!route.include?('//') @allowed[step.dup.freeze]=[method.dup.freeze,route.dup.freeze].freeze;manifest.concat([step,method,route]) end raise P::Refusal,'Only write workflows need a restart journal' if @allowed.empty? @header=['H','1',base,workspace,slug,job,input_fingerprint,P.digest(P.strings(manifest))].map{|value|value.dup.freeze}.freeze;P.strings(@header) begin @file=File.open(@lock_path,File::RDWR|File::CREAT|File::EXCL,0o600);@file.binmode;@owned=true rescue Errno::EEXIST raise P::Refusal,'This journal is locked; do not overlap jobs or steal a stale lock' end begin @owner=SecureRandom.hex(16).freeze;P.write_all(@file,@owner.b);@identity=@file.stat # Ruby's Windows fstat reports dev=0 while lstat reports the drive number. # Both expose the same exact inode. Retain it plus the initial path device; # compare like-for-like instead of treating the differing dev APIs as equal. named_identity=File.lstat(@lock_path);raise P::Refusal,'Lock identity did not bind' unless named_identity.ino==@identity.ino @path_device=named_identity.dev raise P::Refusal,'Choose a private regular journal file' if File.symlink?(@path) raise P::Refusal,'Journal missing: stop and reconcile lost state before starting a new logical job' if mode=='resume'&&!File.exist?(@path) raise P::Refusal,'Journal exists; use resume for the same logical job' if mode=='new'&&File.exist?(@path) if mode=='new' File.open(@path,File::WRONLY|File::CREAT|File::EXCL,0o600){|target|target.binmode;P.write_all(target,P::PREAMBLE+P.frame(@header))} end records=P.decode(File.binread(@path));raise P::Refusal,'Journal workspace/base/guide/job/input binding differs' if records.empty?||records[0]!=@header records.drop(1).each{|record|apply(record)} raise P::Refusal,'Saved intent lacks ACK; stop and reconcile before retry' if @intents.keys.any?{|step|!@saved.key?(step)} rescue Exception close;raise end end def apply(record) case record[0] when 'I' raise P::Refusal,'Invalid intent shape' unless record.length==6 _,step,method,route,fingerprint,key=record raise P::Refusal,'Invalid, future or repeated intent' unless step.match?(/\A[a-z][a-z0-9_-]*\z/)&&!@intents.key?(step)&&@allowed[step]==[method,route]&&fingerprint.match?(/\A[0-9A-F]{64}\z/)&&!@intents.keys.any?{|name|!@saved.key?(name)} raise P::Refusal,'Invalid persisted action key' unless (method=='POST'&&key.match?(/\A[0-9a-f]{32}\z/))||(method!='POST'&&key=='') @intents[step.dup.freeze]={'method'=>method.dup.freeze,'path'=>route.dup.freeze,'request_fingerprint'=>fingerprint.dup.freeze,'idempotency_key'=>key.dup.freeze}.freeze when 'A' raise P::Refusal,'Invalid ACK shape' unless record.length>=3 _,step,count,*pairs=record raise P::Refusal,'ACK without exactly one prior intent' unless count.match?(/\A(?:0|[1-9][0-9]*)\z/)&&pairs.length==2*count.to_i&&@intents.key?(step)&&!@saved.key?(step) names=pairs.each_slice(2).map(&:first) raise P::Refusal,'ACK fields must be unique sorted secret-free identifiers' unless names==names.uniq.sort&&names.all?{|name|name.match?(/\A[a-z][a-z0-9_]*\z/)&&!['api_key','exhibitday_api_key'].include?(name)} @saved[step.dup.freeze]=pairs.each_slice(2).to_h.transform_values{|value|value.dup.freeze}.freeze else raise P::Refusal,'Unknown journal transition' end end def require_active raise P::Refusal,'Journal is closed or IO outcome needs reconciliation' unless @owned&&@file&&!@tainted current=File.lstat(@lock_path) raise P::Refusal,'Journal lock replaced; stop without deleting it' unless current.dev==@path_device&¤t.ino==@identity.ino&&File.binread(@lock_path)==@owner.b end def append(record) require_active;raw=P.frame(record) begin File.open(@path,'ab'){|target|P.write_all(target,raw)} rescue Exception @tainted=true;raise end end def acknowledged(step);require_active;@saved.key?(step);end def saved(step) require_active;raise P::Refusal,'No acknowledged state exists' unless @saved.key?(step) @saved.fetch(step).transform_values(&:dup) end def begin_action(step,method,route,request_fingerprint) require_active;raise P::Refusal,'Never blindly repeat an action' if @intents.key?(step) record=['I',step,method,route,request_fingerprint,method=='POST'?SecureRandom.hex(16):''] previous=@intents.dup;begin;apply(record);ensure;@intents=previous;end append(record);apply(record);@intents.fetch(step).transform_values(&:dup) end def acknowledge(step,saved) require_active;record=['A',step,saved.length.to_s];saved.keys.sort.each{|name|record.concat([name,saved.fetch(name)])} previous=@saved.dup;begin;apply(record);P.strings(record);ensure;@saved=previous;end append(record);apply(record) end def close return unless @owned if @tainted;@file.close;@file=nil;@owned=false;return;end begin;require_active;rescue Exception;@file.close;@file=nil;@owned=false;raise;end @file.close;@file=nil;@owned=false;File.unlink(@lock_path) end end def journal_values(value) raise GuideJournalProtocol::Refusal,'Saved/fingerprint values must be exact strings' unless value.is_a?(Hash)&&value.all?{|name,item|name.is_a?(String)&&item.is_a?(String)} value.transform_values(&:dup) end def journal_acknowledge(job,step,saved);job.acknowledge(step,journal_values(saved));end def journal_acknowledged(job,step);job.acknowledged(step);end def journal_begin(job,step,method,path,request_fingerprint);job.begin_action(step,method,path,request_fingerprint);end def journal_fingerprint(value);GuideJournalProtocol.fingerprint(journal_values(value));end def journal_saved(job,step);job.saved(step);end def json_string(value) JSON.generate(value) end def new_id_set {} end def not_value(value) raise "Expected a Boolean" unless value==true || value==false !value end def open_journal(path,base,workspace,slug,job,input_fingerprint,writes,mode);GuideJournal.new(path,base,workspace,slug,job,input_fingerprint,writes,mode);end def optional(name,fallback) value=ENV[name] value.nil? || value.empty? ? fallback : value end def parse_json(value) JSON.parse(value) end def positive_id(value) raise "Use a positive record ID" unless /\A[1-9][0-9]*\z/.match?(value) && Integer(value)<=9223372036854775807 value end def print_value(value) STDOUT.binmode.write((value.is_a?(String)?value:JSON.generate(value))+"\n") end def remember_id(seen,value) return false if seen.key?(value) seen[value]=true true end def require_condition(value,message) raise message unless value==true end def required(name) value=ENV[name] raise "Set #{name}" if value.nil? || value.strip.empty? value end def response_status(value);value.fetch(:status).to_s;end def task_id_array(value) raise 'Use a JSON array of numeric positive Task IDs; no strings, fractions or exponents.' unless /\A[ \t\r\n]*\[[ \t\r\n]*(?:[1-9][0-9]*[ \t\r\n]*(?:,[ \t\r\n]*[1-9][0-9]*[ \t\r\n]*)*)?\][ \t\r\n]*\z/.match?(value) body = value.strip[1...-1].strip body.empty? ? [] : body.split(',').map { |id| positive_id(id.strip) } end def text(value) return "" if value.nil? return value.to_s if value.is_a?(String)||value.is_a?(Integer)||value==true||value==false raise "Expected a scalar response value" end def main import_source_id = positive_id(required('EXHIBITDAY_SOURCE_EVENT_ID')) import_target_id = positive_id(required('EXHIBITDAY_EVENT_ID')) require_condition(not_value(equal(import_source_id, import_target_id)), 'Choose different source and target Events.') import_task_ids_json = required('EXHIBITDAY_TASK_IDS') import_task_ids = task_id_array(import_task_ids_json) require_condition(not_value(is_empty(import_task_ids)), 'Choose a nonempty numeric Task ID array from the source Event.') import_requested_ids = new_id_set() items(import_task_ids).each do |import_selected_task| import_selected_id = positive_id(text(import_selected_task)) require_condition(remember_id(import_requested_ids, import_selected_id), 'Select distinct source Task IDs.') end import_section_id = optional('EXHIBITDAY_TASK_SECTION_ID', '') if is_present(import_section_id) import_section_id = positive_id(import_section_id) end import_keep_assignees = optional('EXHIBITDAY_KEEP_ASSIGNEES', 'false') import_keep_files = optional('EXHIBITDAY_KEEP_ATTACHMENTS', 'false') import_due_mode = optional('EXHIBITDAY_DUE_DATE_MODE', 'none') require_condition(either(equal(import_keep_assignees, 'true'), equal(import_keep_assignees, 'false')), 'Use literal true or false for the client Boolean options.') require_condition(either(equal(import_keep_files, 'true'), equal(import_keep_files, 'false')), 'Use literal true or false for the client Boolean options.') require_condition(either(equal(import_due_mode, 'none'), either(equal(import_due_mode, 'same_date'), equal(import_due_mode, 'same_offset'))), 'Use none, same_date or same_offset for this client\'s due-date mode.') import_journal_path = required('EXHIBITDAY_JOURNAL') import_job_id = required('EXHIBITDAY_JOB_ID') import_job_mode = optional('EXHIBITDAY_JOB_MODE', 'resume') import_workspace_response = call('workspace_binding', {}, nil, nil) require_condition(equal(response_status(import_workspace_response), '200'), 'Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome.') import_workspace = import_workspace_response.fetch(:body) import_workspace_id = positive_id(text(field(import_workspace, 'id'))) import_source_response = call('source', {'id' => import_source_id}, nil, nil) require_condition(equal(response_status(import_source_response), '200'), 'Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome.') import_source_event = import_source_response.fetch(:body) require_condition(equal(text(field(import_source_event, 'id')), import_source_id), 'Read the exact source and target Events before copying Tasks.') import_target_response = call('target', {'id' => import_target_id}, nil, nil) require_condition(equal(response_status(import_target_response), '200'), 'Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome.') import_target_event = import_target_response.fetch(:body) require_condition(equal(text(field(import_target_event, 'id')), import_target_id), 'Read the exact source and target Events before copying Tasks.') import_input_fingerprint = journal_fingerprint({'workflow_contract_sha256' => '093C5C392110864D42C6DAAC78ED03CD194F117A1DB3CA4815BDA003407D6B06', 'request' => journal_fingerprint({'source_event_id' => import_source_id, 'event_id' => import_target_id, 'task_ids' => import_task_ids_json, 'task_section_id' => import_section_id, 'keep_assignees' => import_keep_assignees, 'due_date_mode' => import_due_mode, 'keep_attachments' => import_keep_files})}) import_job = open_journal(import_journal_path, 'https://api.exhibitday.com/v1', import_workspace_id, 'reuse-event-plan', import_job_id, import_input_fingerprint, [['import_tasks', 'POST', '/v1/tasks/import_from_event']], import_job_mode) begin import_saved_pairs = parse_json('[]') if journal_acknowledged(import_job, 'import_tasks') import_saved = journal_saved(import_job, 'import_tasks') require_condition(both(equal(text(field(import_saved, 'source_event_id')), import_source_id), equal(text(field(import_saved, 'event_id')), import_target_id)), 'Saved import state belongs to different Events; stop and reconcile.') import_saved_pairs = parse_json(text(field(import_saved, 'tasks'))) else import_request_fingerprint = journal_fingerprint({'source_event_id' => import_source_id, 'event_id' => import_target_id, 'task_ids' => import_task_ids_json, 'task_section_id' => import_section_id, 'keep_assignees' => import_keep_assignees, 'due_date_mode' => import_due_mode, 'keep_attachments' => import_keep_files}) import_intent = journal_begin(import_job, 'import_tasks', 'POST', '/v1/tasks/import_from_event', import_request_fingerprint) import_response = call('import_tasks', {}, {'source_event_id' => import_source_id, 'event_id' => import_target_id, 'task_ids' => import_task_ids_json, 'task_section_id' => import_section_id, 'keep_assignees' => equal(import_keep_assignees, 'true'), 'due_date_mode' => import_due_mode, 'keep_attachments' => equal(import_keep_files, 'true')}, text(field(import_intent, 'idempotency_key'))) require_condition(equal(response_status(import_response), '200'), 'Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome.') import_receipt = import_response.fetch(:body) require_condition(both(equal(text(field(import_receipt, 'source_event_id')), import_source_id), equal(text(field(import_receipt, 'event_id')), import_target_id)), 'The import acknowledgement belongs to a different source or target Event.') import_saved_pairs = field(import_receipt, 'tasks') require_condition(equal(text(field(import_receipt, 'tasks_copied')), text(count(import_task_ids))), 'The acknowledged copied-task count differs from the selected Tasks.') import_saved_pairs_receipt_rows = items(import_saved_pairs) require_condition(equal(count(import_saved_pairs_receipt_rows), count(import_task_ids)), 'Some selected Tasks were not imported (the response warnings name them); review them before continuing.') import_saved_pairs_receipt_seen_source = new_id_set() import_saved_pairs_receipt_seen_new = new_id_set() items(import_saved_pairs_receipt_rows).each do |import_saved_pairs_receipt_row| import_saved_pairs_receipt_source_id = positive_id(text(field(import_saved_pairs_receipt_row, 'source_task_id'))) import_saved_pairs_receipt_new_id = positive_id(text(field(import_saved_pairs_receipt_row, 'id'))) require_condition(not_value(remember_id(import_requested_ids, import_saved_pairs_receipt_source_id)), 'An import pair refers to a Task outside the explicit source selection.') require_condition(both(remember_id(import_saved_pairs_receipt_seen_source, import_saved_pairs_receipt_source_id), remember_id(import_saved_pairs_receipt_seen_new, import_saved_pairs_receipt_new_id)), 'Each selected source Task and each new Task ID must appear once in the import receipt.') end journal_acknowledge(import_job, 'import_tasks', {'source_event_id' => import_source_id, 'event_id' => import_target_id, 'tasks' => json_string(import_saved_pairs), 'tasks_copied' => text(field(import_receipt, 'tasks_copied'))}) end import_saved_pairs_verify_rows = items(import_saved_pairs) require_condition(equal(count(import_saved_pairs_verify_rows), count(import_task_ids)), 'Some selected Tasks were not imported (the response warnings name them); review them before continuing.') import_saved_pairs_verify_seen_source = new_id_set() import_saved_pairs_verify_seen_new = new_id_set() items(import_saved_pairs_verify_rows).each do |import_saved_pairs_verify_row| import_saved_pairs_verify_source_id = positive_id(text(field(import_saved_pairs_verify_row, 'source_task_id'))) import_saved_pairs_verify_new_id = positive_id(text(field(import_saved_pairs_verify_row, 'id'))) require_condition(not_value(remember_id(import_requested_ids, import_saved_pairs_verify_source_id)), 'An import pair refers to a Task outside the explicit source selection.') require_condition(both(remember_id(import_saved_pairs_verify_seen_source, import_saved_pairs_verify_source_id), remember_id(import_saved_pairs_verify_seen_new, import_saved_pairs_verify_new_id)), 'Each selected source Task and each new Task ID must appear once in the import receipt.') import_saved_pairs_task_response = call('verify_task', {'id' => import_saved_pairs_verify_new_id}, nil, nil) require_condition(equal(response_status(import_saved_pairs_task_response), '200'), 'Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome.') import_saved_pairs_task = import_saved_pairs_task_response.fetch(:body) require_condition(equal(text(field(import_saved_pairs_task, 'id')), import_saved_pairs_verify_new_id), 'A captured imported Task is missing or replaced; stop rather than importing a replacement.') import_saved_pairs_event = field(import_saved_pairs_task, 'event') require_condition(equal(text(field(import_saved_pairs_event, 'id')), import_target_id), 'A copied Task is no longer under the selected target Event; do not silently re-import it.') end print_value({'source_event_id' => import_source_id, 'event_id' => import_target_id, 'tasks_verified' => text(count(import_task_ids))}) ensure import_job.close() end end main if $PROGRAM_NAME == __FILE__ ``` ```go // Go 1.18+; standard library only. Set EXHIBITDAY_API_KEY. package main import ( "bytes" "crypto/rand" "crypto/sha256" "encoding/hex" "regexp" "sort" "unicode/utf8" "encoding/json" "fmt" "io" "net/http" "net/url" "os" "strconv" "strings" "time" ) const base = "https://api.exhibitday.com/v1" const specification = "{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"source\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"target\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"import_tasks\":{\"method\":\"POST\",\"path\":\"/tasks/import_from_event\"},\"verify_task\":{\"method\":\"GET\",\"path\":\"/tasks/info\"}}}" 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 }} var send = client.Do type result struct { status int; body any; headers http.Header; raw []byte } // 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 call(name string, query map[string]string, body any, key string) result { route := object(object(spec["requests"])[name]); method := text(route["method"]) headers := map[string]string{"Authorization": "Bearer " + apiKey, "Accept": "application/json"} if method == "POST" { if key == "" { panic("Persist a logical create key before sending POST") }; 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() } // 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 := method == "GET" 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 := send(request) if err != nil { if !resend { panic(apiError{0, "", "No response", true}) }; if attempt == 4 { panic(err) }; time.Sleep(time.Second*time.Duration(1<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 := resend && (response.StatusCode == 429 || response.StatusCode >= 500) if retry { if attempt == 4 { panic("Retry limit reached; check the outcome before starting a new create") } seconds := float64(int64(1)<= 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, raw} } panic("Retry limit reached") } func both(left,right bool)bool{return left&&right} func items(value any)[]any{result,ok:=value.([]any);if !ok{panic("Expected a JSON array")};return result} func count(value any)int64{return int64(len(items(value)))} func either(left,right bool)bool{return left||right} func equal(left,right any)bool{switch a:=left.(type){case string:b,ok:=right.(string);return ok&&a==b;case bool:b,ok:=right.(bool);return ok&&a==b;case int64:b,ok:=right.(int64);return ok&&a==b};return left==nil&&right==nil} func field(value any,name string)any{obj,ok:=value.(map[string]any);if !ok{panic("Missing response object")};item,found:=obj[name];if !found{panic("Missing response field: "+name)};return item} func is_empty(value any)bool{return count(value)==0} func is_present(value string)bool{return value!=""} // Private client restart state only; no API transport or workflow interpreter. const journalPreamble = "EXHIBITDAY-GUIDE-JOURNAL 1\n" type journalRefusal struct{ message string } func (e journalRefusal) Error() string { return e.message } func journalNeed(ok bool, message string) { if !ok { panic(journalRefusal{message}) } } func journalMatch(value, pattern string) bool { return regexp.MustCompile("\\A(?:"+pattern+")\\z").MatchString(value) } func journalStrings(values []string) []byte { var output bytes.Buffer for _,value:=range values { journalNeed(utf8.ValidString(value),"Journal fields must be valid UTF8 strings"); output.WriteString(strconv.Itoa(len(value))+":");output.WriteString(value) } return output.Bytes() } func journalReadStrings(raw []byte) []string { values:=[]string{};offset:=0 for offset=0,"Incomplete journal string length");end:=offset+relative;text:=string(raw[offset:end]);journalNeed(journalMatch(text,"0|[1-9][0-9]*"),"Noncanonical journal string length");size,err:=strconv.ParseUint(text,10,64);offset=end+1;journalNeed(err==nil&&size<=uint64(len(raw)-offset),"Incomplete journal string");count:=int(size);value:=string(raw[offset:offset+count]);journalNeed(utf8.ValidString(value),"Invalid UTF8 journal field");values=append(values,value);offset+=count } return values } func journalDigest(raw []byte) string { hash:=sha256.Sum256(raw);return strings.ToUpper(hex.EncodeToString(hash[:])) } func journalFingerprint(pairs map[string]string) string { names:=make([]string,0,len(pairs));for name:=range pairs { names=append(names,name) };sort.Strings(names);values:=[]string{} for _,name:=range names { lower:=strings.ToLower(name);journalNeed(journalMatch(name,"[A-Za-z0-9_.-]+")&&lower!="api_key"&&lower!="exhibitday_api_key","Use explicit secret-free fingerprint names");values=append(values,name,pairs[name]) } return journalDigest(journalStrings(values)) } func journalFrame(values []string) []byte { raw:=journalStrings(values);header:=[]byte(strconv.Itoa(len(raw))+" "+journalDigest(raw)+"\n");result:=append(header,raw...);return append(result,'\n') } func journalDecode(raw []byte) [][]string { journalNeed(bytes.HasPrefix(raw,[]byte(journalPreamble)),"Unknown or incomplete journal version");offset:=len(journalPreamble);records:=[][]string{} for offset=0,"Incomplete frame header; reconcile before retry");end:=offset+relative;header:=string(raw[offset:end]);journalNeed(journalMatch(header,"(0|[1-9][0-9]*) [0-9A-F]{64}"),"Invalid frame header");fields:=strings.Split(header," ");size,err:=strconv.ParseUint(fields[0],10,64);offset=end+1;journalNeed(err==nil&&size0 { count,err:=file.Write(raw);if err!=nil{return err};if count<=0{return io.ErrShortWrite};raw=raw[count:] } return file.Sync() } func journalWriteFile(path string,flags int,raw []byte) (err error) { file,err:=os.OpenFile(path,flags,0600);if err!=nil{return err};defer func(){closed:=file.Close();if err==nil{err=closed}}();return journalWriteAll(file,raw) } func journalCopy(source map[string]string) map[string]string { copy:=map[string]string{};for name,value:=range source{copy[name]=value};return copy } func journalCopyStates(source map[string]map[string]string) map[string]map[string]string { copy:=map[string]map[string]string{};for name,value:=range source{copy[name]=journalCopy(value)};return copy } type guideJournal struct { path,lockPath,owner string header []string allowed map[string][2]string intents,savedValues map[string]map[string]string file *os.File identity os.FileInfo owned,tainted bool } func openGuideJournal(path,base,workspace,slug,job,inputFingerprint string,writes [][3]string,modes ...string) (result *guideJournal) { mode:="resume";journalNeed(len(modes)<=1,"Choose one local job mode");if len(modes)==1{mode=modes[0]};journalNeed(mode=="new"||mode=="resume","Choose new or resume for this local job") address,err:=url.Parse(base);journalNeed(err==nil&&address.Hostname()!=""&&(address.Scheme=="https"||address.Scheme=="http")&&address.User==nil&&address.RawQuery==""&&address.Fragment==""&&journalMatch(slug,"[a-z][a-z0-9-]*"),"Use actual API base and closed guide slug") journalNeed(strings.TrimSpace(job)!=""&&journalMatch(workspace,"[1-9][0-9]*")&&journalMatch(inputFingerprint,"[0-9A-F]{64}"),"Use actual workspace, stable explicit job ID and exact fingerprint") j:=&guideJournal{path:path,lockPath:path+".lock",allowed:map[string][2]string{},intents:map[string]map[string]string{},savedValues:map[string]map[string]string{}} manifest:=[]string{};for _,write:=range writes { step,method,route:=write[0],write[1],write[2];_,exists:=j.allowed[step];journalNeed(journalMatch(step,"[a-z][a-z0-9_-]*")&&!exists&&(method=="POST"||method=="PATCH"||method=="DELETE")&&journalMatch(route,"/v1/[A-Za-z0-9_/-]+")&&!strings.Contains(route,"//"),"Use a closed unique write manifest");j.allowed[step]=[2]string{method,route};manifest=append(manifest,step,method,route) } journalNeed(len(j.allowed)>0,"Only write workflows need a restart journal");j.header=[]string{"H","1",base,workspace,slug,job,inputFingerprint,journalDigest(journalStrings(manifest))};journalStrings(j.header) j.file,err=os.OpenFile(j.lockPath,os.O_RDWR|os.O_CREATE|os.O_EXCL,0600);if err!=nil { if os.IsExist(err){panic(journalRefusal{"This journal is locked; do not overlap jobs or steal a stale lock"})};panic(err) };j.owned=true defer func(){ if observed:=recover();observed!=nil { j.Close();panic(observed) } }() random:=make([]byte,16);if _,err=io.ReadFull(rand.Reader,random);err!=nil{panic(err)};j.owner=hex.EncodeToString(random);if err=journalWriteAll(j.file,[]byte(j.owner));err!=nil{panic(err)};j.identity,err=j.file.Stat();if err!=nil{panic(err)} info,err:=os.Lstat(path);if err!=nil&&!os.IsNotExist(err){panic(err)};exists:=err==nil;if exists{journalNeed(info.Mode()&os.ModeSymlink==0,"Choose a private regular journal file")};journalNeed(mode!="resume"||exists,"Journal missing: stop and reconcile lost state before starting a new logical job");journalNeed(mode!="new"||!exists,"Journal exists; use resume for the same logical job");if mode=="new"{raw:=append([]byte(journalPreamble),journalFrame(j.header)...);if err=journalWriteFile(path,os.O_WRONLY|os.O_CREATE|os.O_EXCL,raw);err!=nil{panic(err)}} raw,err:=os.ReadFile(path);if err!=nil{panic(err)};records:=journalDecode(raw);journalNeed(len(records)>0&&stringsEqual(records[0],j.header),"Journal workspace/base/guide/job/input binding differs");for _,record:=range records[1:]{j.apply(record)};for step:=range j.intents{_,ok:=j.savedValues[step];journalNeed(ok,"Saved intent lacks ACK; stop and reconcile before retry")};return j } func stringsEqual(left,right []string) bool { if len(left)!=len(right){return false};for i,value:=range left{if value!=right[i]{return false}};return true } func (j *guideJournal) apply(record []string) { journalNeed(len(record)>0,"Empty journal record") if record[0]=="I" { journalNeed(len(record)==6,"Invalid intent shape");step,method,route,fingerprint,key:=record[1],record[2],record[3],record[4],record[5];_,exists:=j.intents[step];expected,allowed:=j.allowed[step];pending:=false;for name:=range j.intents{if _,ok:=j.savedValues[name];!ok{pending=true}} journalNeed(journalMatch(step,"[a-z][a-z0-9_-]*")&&!exists&&allowed&&expected==[2]string{method,route}&&journalMatch(fingerprint,"[0-9A-F]{64}")&&!pending,"Invalid, future or repeated intent");journalNeed(method=="POST"&&journalMatch(key,"[0-9a-f]{32}")||method!="POST"&&key=="","Invalid persisted action key");j.intents[step]=map[string]string{"method":method,"path":route,"request_fingerprint":fingerprint,"idempotency_key":key} }else if record[0]=="A" { journalNeed(len(record)>=3,"Invalid ACK shape");step,text:=record[1],record[2];count,err:=strconv.ParseUint(text,10,64);_,prior:=j.intents[step];_,done:=j.savedValues[step];journalNeed(journalMatch(text,"0|[1-9][0-9]*")&&err==nil&&len(record)%2==1&&count==uint64((len(record)-3)/2)&&prior&&!done,"ACK without exactly one prior intent");names:=[]string{};for i:=3;i0&&value[0]!='0';for _,ch:=range value{valid=valid&&ch>='0'&&ch<='9'};id,err:=strconv.ParseInt(value,10,64);if !valid||err!=nil||id<=0{panic("Use a positive record ID")};return value} func print_value(value any){if result,ok:=value.(string);ok{fmt.Println(result);return};raw,err:=json.Marshal(value);if err!=nil{panic(err)};fmt.Println(string(raw))} func remember_id(seen map[string]bool,value string)bool{if seen[value]{return false};seen[value]=true;return true} func require_condition(value bool,message string){if !value{panic(message)}} func response_status(value result)string{return strconv.Itoa(value.status)} func task_id_array(value string)[]any{if !regexp.MustCompile("^[ \\t\\r\\n]*\\[[ \\t\\r\\n]*(?:[1-9][0-9]*[ \\t\\r\\n]*(?:,[ \\t\\r\\n]*[1-9][0-9]*[ \\t\\r\\n]*)*)?\\][ \\t\\r\\n]*$").MatchString(value){panic("Use a JSON array of numeric positive Task IDs; no strings, fractions or exponents.")} ;body:=strings.TrimSpace(value);body=strings.TrimSpace(body[1:len(body)-1]);result:=[]any{};if body!=""{for _,id:=range strings.Split(body,","){result=append(result,positive_id(strings.TrimSpace(id)))}};return result} func workflow() { import_source_id := positive_id(required("EXHIBITDAY_SOURCE_EVENT_ID")) import_target_id := positive_id(required("EXHIBITDAY_EVENT_ID")) require_condition(not_value(equal(import_source_id, import_target_id)), "Choose different source and target Events.") import_task_ids_json := required("EXHIBITDAY_TASK_IDS") import_task_ids := task_id_array(import_task_ids_json) require_condition(not_value(is_empty(import_task_ids)), "Choose a nonempty numeric Task ID array from the source Event.") import_requested_ids := new_id_set() for _, import_selected_task := range items(import_task_ids) { import_selected_id := positive_id(text(import_selected_task)) require_condition(remember_id(import_requested_ids, import_selected_id), "Select distinct source Task IDs.") } import_section_id := optional("EXHIBITDAY_TASK_SECTION_ID", "") if is_present(import_section_id) { import_section_id = positive_id(import_section_id) } import_keep_assignees := optional("EXHIBITDAY_KEEP_ASSIGNEES", "false") import_keep_files := optional("EXHIBITDAY_KEEP_ATTACHMENTS", "false") import_due_mode := optional("EXHIBITDAY_DUE_DATE_MODE", "none") require_condition(either(equal(import_keep_assignees, "true"), equal(import_keep_assignees, "false")), "Use literal true or false for the client Boolean options.") require_condition(either(equal(import_keep_files, "true"), equal(import_keep_files, "false")), "Use literal true or false for the client Boolean options.") require_condition(either(equal(import_due_mode, "none"), either(equal(import_due_mode, "same_date"), equal(import_due_mode, "same_offset"))), "Use none, same_date or same_offset for this client's due-date mode.") import_journal_path := required("EXHIBITDAY_JOURNAL") import_job_id := required("EXHIBITDAY_JOB_ID") import_job_mode := optional("EXHIBITDAY_JOB_MODE", "resume") import_workspace_response := call("workspace_binding", map[string]string{}, nil, "") require_condition(equal(response_status(import_workspace_response), "200"), "Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome.") import_workspace := import_workspace_response.body import_workspace_id := positive_id(text(field(import_workspace, "id"))) import_source_response := call("source", map[string]string{"id": import_source_id}, nil, "") require_condition(equal(response_status(import_source_response), "200"), "Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome.") import_source_event := import_source_response.body require_condition(equal(text(field(import_source_event, "id")), import_source_id), "Read the exact source and target Events before copying Tasks.") import_target_response := call("target", map[string]string{"id": import_target_id}, nil, "") require_condition(equal(response_status(import_target_response), "200"), "Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome.") import_target_event := import_target_response.body require_condition(equal(text(field(import_target_event, "id")), import_target_id), "Read the exact source and target Events before copying Tasks.") import_input_fingerprint := journal_fingerprint(map[string]any{"workflow_contract_sha256": "093C5C392110864D42C6DAAC78ED03CD194F117A1DB3CA4815BDA003407D6B06", "request": journal_fingerprint(map[string]any{"source_event_id": import_source_id, "event_id": import_target_id, "task_ids": import_task_ids_json, "task_section_id": import_section_id, "keep_assignees": import_keep_assignees, "due_date_mode": import_due_mode, "keep_attachments": import_keep_files})}) func() { import_job := open_journal(import_journal_path, "https://api.exhibitday.com/v1", import_workspace_id, "reuse-event-plan", import_job_id, import_input_fingerprint, []any{[]any{"import_tasks", "POST", "/v1/tasks/import_from_event"}}, import_job_mode) defer import_job.Close() import_saved_pairs := parse_json("[]") if journal_acknowledged(import_job, "import_tasks") { import_saved := journal_saved(import_job, "import_tasks") require_condition(both(equal(text(field(import_saved, "source_event_id")), import_source_id), equal(text(field(import_saved, "event_id")), import_target_id)), "Saved import state belongs to different Events; stop and reconcile.") import_saved_pairs = parse_json(text(field(import_saved, "tasks"))) } else { import_request_fingerprint := journal_fingerprint(map[string]any{"source_event_id": import_source_id, "event_id": import_target_id, "task_ids": import_task_ids_json, "task_section_id": import_section_id, "keep_assignees": import_keep_assignees, "due_date_mode": import_due_mode, "keep_attachments": import_keep_files}) import_intent := journal_begin(import_job, "import_tasks", "POST", "/v1/tasks/import_from_event", import_request_fingerprint) import_response := call("import_tasks", map[string]string{}, map[string]any{"source_event_id": import_source_id, "event_id": import_target_id, "task_ids": import_task_ids_json, "task_section_id": import_section_id, "keep_assignees": equal(import_keep_assignees, "true"), "due_date_mode": import_due_mode, "keep_attachments": equal(import_keep_files, "true")}, text(field(import_intent, "idempotency_key"))) require_condition(equal(response_status(import_response), "200"), "Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome.") import_receipt := import_response.body require_condition(both(equal(text(field(import_receipt, "source_event_id")), import_source_id), equal(text(field(import_receipt, "event_id")), import_target_id)), "The import acknowledgement belongs to a different source or target Event.") import_saved_pairs = field(import_receipt, "tasks") require_condition(equal(text(field(import_receipt, "tasks_copied")), text(count(import_task_ids))), "The acknowledged copied-task count differs from the selected Tasks.") import_saved_pairs_receipt_rows := items(import_saved_pairs) require_condition(equal(count(import_saved_pairs_receipt_rows), count(import_task_ids)), "Some selected Tasks were not imported (the response warnings name them); review them before continuing.") import_saved_pairs_receipt_seen_source := new_id_set() import_saved_pairs_receipt_seen_new := new_id_set() for _, import_saved_pairs_receipt_row := range items(import_saved_pairs_receipt_rows) { import_saved_pairs_receipt_source_id := positive_id(text(field(import_saved_pairs_receipt_row, "source_task_id"))) import_saved_pairs_receipt_new_id := positive_id(text(field(import_saved_pairs_receipt_row, "id"))) require_condition(not_value(remember_id(import_requested_ids, import_saved_pairs_receipt_source_id)), "An import pair refers to a Task outside the explicit source selection.") require_condition(both(remember_id(import_saved_pairs_receipt_seen_source, import_saved_pairs_receipt_source_id), remember_id(import_saved_pairs_receipt_seen_new, import_saved_pairs_receipt_new_id)), "Each selected source Task and each new Task ID must appear once in the import receipt.") } journal_acknowledge(import_job, "import_tasks", map[string]any{"source_event_id": import_source_id, "event_id": import_target_id, "tasks": json_string(import_saved_pairs), "tasks_copied": text(field(import_receipt, "tasks_copied"))}) } import_saved_pairs_verify_rows := items(import_saved_pairs) require_condition(equal(count(import_saved_pairs_verify_rows), count(import_task_ids)), "Some selected Tasks were not imported (the response warnings name them); review them before continuing.") import_saved_pairs_verify_seen_source := new_id_set() import_saved_pairs_verify_seen_new := new_id_set() for _, import_saved_pairs_verify_row := range items(import_saved_pairs_verify_rows) { import_saved_pairs_verify_source_id := positive_id(text(field(import_saved_pairs_verify_row, "source_task_id"))) import_saved_pairs_verify_new_id := positive_id(text(field(import_saved_pairs_verify_row, "id"))) require_condition(not_value(remember_id(import_requested_ids, import_saved_pairs_verify_source_id)), "An import pair refers to a Task outside the explicit source selection.") require_condition(both(remember_id(import_saved_pairs_verify_seen_source, import_saved_pairs_verify_source_id), remember_id(import_saved_pairs_verify_seen_new, import_saved_pairs_verify_new_id)), "Each selected source Task and each new Task ID must appear once in the import receipt.") import_saved_pairs_task_response := call("verify_task", map[string]string{"id": import_saved_pairs_verify_new_id}, nil, "") require_condition(equal(response_status(import_saved_pairs_task_response), "200"), "Expected the documented HTTP200 response; preserve pending import state and reconcile another outcome.") import_saved_pairs_task := import_saved_pairs_task_response.body require_condition(equal(text(field(import_saved_pairs_task, "id")), import_saved_pairs_verify_new_id), "A captured imported Task is missing or replaced; stop rather than importing a replacement.") import_saved_pairs_event := field(import_saved_pairs_task, "event") require_condition(equal(text(field(import_saved_pairs_event, "id")), import_target_id), "A copied Task is no longer under the selected target Event; do not silently re-import it.") } print_value(map[string]any{"source_event_id": import_source_id, "event_id": import_target_id, "tasks_verified": text(count(import_task_ids))}) }() } func header_key(value string)string{for _,ch:=range value{if ch<32||ch>126{panic("Use the API key as one ASCII header value without control characters")}};return value} func main(){apiKey=header_key(required("EXHIBITDAY_API_KEY"));if err:=json.Unmarshal([]byte(specification),&spec);err!=nil{panic(err)};workflow()} ``` #### Example response Response 200 — OK 400 — Bad Request 401 — Unauthorized 404 — Not Found 409 — Conflict 429 — Too Many Requests 500 — Internal Server Error Example Successful request ```json { "source_event_id": 12345, "event_id": 23456, "tasks_copied": 1, "tasks": [ { "source_task_id": 34567, "id": 45678 } ] } ``` Note: Confirmed Task import. One selected source Task was copied into the target Event. The following read checks the returned new Task ID under that target. ```json { "status_code": 400, "status": "Bad Request", "message": "HTTP method override is not supported.", "error_code": "invalid_request", "errors": [ "Send the documented HTTP method directly. X-HTTP-Method-Override cannot change a request's HTTP method." ], "error_params": [ "X-HTTP-Method-Override" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 400, "status": "Bad Request", "message": "This Idempotency-Key was already used with a different request. Use a new key for a new request.", "error_code": "idempotency_key_reused", "errors": [ "This Idempotency-Key was already used with a different request. Use a new key for a new request." ], "error_params": [ "Idempotency-Key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "No API key was provided. Send your key in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "missing_api_key", "errors": [ "Copy the key from Workspace Settings > API & Integrations > API Access in ExhibitDay." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "The API key is not valid. Check that you copied the whole key from Workspace Settings > API & Integrations > API Access, then send it in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "invalid_api_key", "errors": [ "Check that you sent the whole key. If it was regenerated, use the current key from Workspace Settings > API & Integrations > API Access." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "Access to the ExhibitDay API is not enabled for your workspace. Please contact support@exhibitday.com to enable API Access. Once access is enabled, send your key in the Authorization header as 'Bearer YOUR_API_KEY'.", "error_code": "api_access_disabled", "errors": [ "Nothing was read or changed." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 404, "status": "Not Found", "message": "Event not found. Check source_event_id: use an Event ID from GET /v1/events.", "error_code": "not_found", "errors": [ "Event not found. Check source_event_id: use an Event ID from GET /v1/events." ], "error_params": [ "source_event_id" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 404, "status": "Not Found", "message": "Task not found. None of the task_ids are Tasks of the source Event. Use Task IDs from GET /v1/tasks for that Event.", "error_code": "not_found", "errors": [ "Task not found. None of the task_ids are Tasks of the source Event. Use Task IDs from GET /v1/tasks for that Event." ], "error_params": [ "task_ids" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 404, "status": "Not Found", "message": "Task Section not found. Invalid Task Section ID: 12345.", "error_code": "not_found", "errors": [ "Task Section not found. Invalid Task Section ID: 12345." ], "error_params": [ "task_section_id" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "A request with this Idempotency-Key is still being processed. Retry after a moment.", "error_code": "idempotency_key_in_use", "errors": [ "A request with this Idempotency-Key is still being processed. Retry after a moment." ], "error_params": [ "Idempotency-Key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "A previous request with this Idempotency-Key did not finish and its outcome is unknown, so this retry was not run to avoid creating a duplicate. Check whether the earlier request succeeded; to try again, use a new Idempotency-Key.", "error_code": "idempotency_key_indeterminate", "errors": [ "A previous request with this Idempotency-Key did not finish and its outcome is unknown, so this retry was not run to avoid creating a duplicate. Check whether the earlier request succeeded; to try again, use a new Idempotency-Key." ], "error_params": [ "Idempotency-Key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "The saved response cannot be replayed safely.", "error_code": "idempotency_key_indeterminate", "errors": [ "The earlier request with this Idempotency-Key completed, but its saved response cannot be returned safely. This retry was not run and its key was not released. Look for the existing record with a GET; use a new Idempotency-Key only after checking whether another create is needed." ], "error_params": [ "Idempotency-Key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "The source or target Tasks are busy or changed. Retrieve current Tasks before retrying.", "error_code": "record_changed", "errors": [ "The source or target Tasks are busy or changed. Retrieve current Tasks before retrying." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "The source or target Tasks changed. Retrieve their current state before retrying.", "error_code": "record_changed", "errors": [ "The source or target Tasks changed. Retrieve their current state before retrying." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "Current Task assignee membership or permission information changed. Retrieve current values before retrying.", "error_code": "record_changed", "errors": [ "Current Task assignee membership or permission information changed. Retrieve current values before retrying." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 429, "status": "Too Many Requests", "message": "Error 429 - Too Many Requests", "error_code": "rate_limited", "errors": [ "Error 429 - Too Many Requests" ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "The import outcome could not be confirmed. Retrieve the target Event's current Tasks before deciding whether to retry; this request was not automatically repeated." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "The import response could not be completed safely. Retrieve the target Event's current Tasks before deciding whether to retry." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "An unexpected error occurred. Please try again later." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` Note: Use the request_id from your own response when contacting support. ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "Check whether your change was saved before trying again." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` #### Things to keep in mind - Choose distinct Task IDs from the source Event. If your own request leaves out `task_ids`, the API copies every Task from the source Event. - The program sends the selected IDs as JSON text so large IDs stay exact. The source Tasks stay in place. #### If a run stops - Keep the journal private. It records what the program tried to save and which save it confirmed. - To continue a run with no unresolved save, use `EXHIBITDAY_JOB_MODE=resume` with the same job ID, journal path and inputs. - A resumed run skips an import the journal already checked. The program reads each saved copy before printing the number verified. - If the import response is lost or a copy has changed, check the target Event before running the program again. - If you still need a change after checking the old run, use `EXHIBITDAY_JOB_MODE=new` with a new job ID and journal path. - Run only one copy per journal. - If a crash leaves a `.lock` file, make sure no copy using that journal is running or can start. Then remove the lock file and keep the journal. #### Related guides - [Get a Complete List of Attendees, Travel and More](https://api.exhibitday.com/Help/V1?guide=find-filter-page) - [Handle Errors and Retry Failed Requests](https://api.exhibitday.com/Help/V1?guide=errors-and-retries) ### Search Activity Audit Logs to See Who Changed What, and When Guide page: https://api.exhibitday.com/Help/V1?guide=workspace-activity See who changed what and when, for audits, investigations or monitoring. Example use case You want to see who completed a Task during a show or who last updated a Storage Location. What you'll end up with Matching activity entries with their log ID, timestamp and activity text. The API also returns saved actor information and record associations where available. Before you start Have a workspace API key and choose a time window. If you want to narrow the program's search, have the ID of the Event, Asset, Storage Location or Task. Good to know Activity entries describe recorded actions. Use the record APIs to check the current values. #### At a glance Time to try About 5 minutes Effect on your data Read-only Endpoints 1 The program reads and prints matching Workspace Activity entries. - [`GET /v1/workspace_settings/logs`](https://api.exhibitday.com/Help/V1?epf=6&topic=logs#get-v1-workspace_settings-logs) #### How it works 1. Choose a time window for the activity you want to review. Optional record IDs narrow the results. 2. The program reads the oldest activity first and fetches each next page using the same filters. 3. It prints each log entry once during the run, using its log ID to skip repeats. #### Read the activity The example below reads the first page of activity. The program reads another page when the response says there are more entries. #### Step 1: Read the activity in your time window Start at offset zero and sort oldest first to follow the activity in order. ```bash curl -X GET "https://api.exhibitday.com/v1/workspace_settings/logs?filter_by_create_timestamp_greater_than_or_equal_to=2030-01-02T00%3A00%3A00Z&filter_by_create_timestamp_smaller_than_or_equal_to=2030-01-02T23%3A59%3A59Z&%24result_sort=create_timestamp_asc&%24offset=0&%24limit=2" -H "Authorization: Bearer YOUR_API_KEY" ``` Example response (shortened) ```json { "list_data": [ { "id": 67890, "log_entry_created_timestamp": "2030-01-02T17:04:05Z", "actor_display_name": "Alex Morgan", "log_entry": "Alex Morgan completed the Task: Confirm booth artwork." }, { "id": 67891, "log_entry_created_timestamp": "2030-01-02T17:04:06Z", "actor_display_name": "Jordan Lee", "log_entry": "Jordan Lee updated the Storage Location notes." } ], "records_found": 2, "total_records": 3, "has_more": true } ``` **Check:** `records_found` is the number of entries on this page. Here `has_more` is true, so keep the same filters and sort, add 2 to the offset and fetch the next page. Keep adding each page's `records_found` until `has_more` is false. #### Try it #### Before running the example | Variable | What to put in it | Required? | | --- | --- | --- | | `EXHIBITDAY_API_KEY` | Your workspace API key. | Yes | | `EXHIBITDAY_LOG_FROM` | Inclusive start, for example `2030-01-02T00:00:00Z`. | Yes | | `EXHIBITDAY_LOG_UNTIL` | Inclusive end, for example `2030-01-02T23:59:59Z`. | Yes | | `EXHIBITDAY_EVENT_ID` | The Event ID. | No | | `EXHIBITDAY_ASSET_ID` | The Asset ID. | No | | `EXHIBITDAY_STORAGE_LOCATION_ID` | The Storage Location ID. | No | | `EXHIBITDAY_TASK_ID` | The Task ID. | No | | `EXHIBITDAY_PAGE_SIZE` | A positive page size. The default is 100. | No | **Note.** This example only reads data. An entry must match every record filter you set. #### Bash ``` export EXHIBITDAY_API_KEY='YOUR_API_KEY' export EXHIBITDAY_LOG_FROM='2030-01-02T00:00:00Z' export EXHIBITDAY_LOG_UNTIL='2030-01-02T23:59:59Z' ``` #### PowerShell ``` $env:EXHIBITDAY_API_KEY = 'YOUR_API_KEY' $env:EXHIBITDAY_LOG_FROM = '2030-01-02T00:00:00Z' $env:EXHIBITDAY_LOG_UNTIL = '2030-01-02T23:59:59Z' ``` Then copy the complete example program below in your language and run it. The program prints one JSON object per distinct log ID and preserves each ID as decimal text in its output. #### Complete example program Code Samples ```bash #!/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\":{\"page\":{\"method\":\"GET\",\"path\":\"/workspace_settings/logs\"}}}") API_KEY = os.environ["EXHIBITDAY_API_KEY"] if any(ord(char) < 32 or ord(char) > 126 for char in API_KEY): raise RuntimeError("Use the API key as one ASCII header value without control characters") if not API_KEY.strip(): raise RuntimeError("Set EXHIBITDAY_API_KEY") def decode_json(text): if SPEC["preserveNumbers"]: # Quote JSON NUMBER tokens, never text inside a JSON string, to keep CSV decimals exact. text = re.sub(r'"(?:\\.|[^"\\])*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?', lambda m: m[0] if m[0].startswith('"') else json.dumps(m[0]), text) return json.loads(text) from pathlib import Path # This terminal version uses curl for HTTP and Python's standard library for JSON/CSV. import subprocess import tempfile def transport(method, url, headers, data): with tempfile.TemporaryDirectory(prefix="exhibitday-guide-") as directory: folder = Path(directory) # curl may leave no output file for a valid bodyless304 response. (folder / "body").write_bytes(b"") command = ["curl", "--disable", "--silent", "--show-error", "--request", method, "--url", url, "--max-time", "30", "--dump-header", str(folder / "headers"), "--output", str(folder / "body"), "--write-out", "%{http_code}"] for name, value in headers.items(): command += ["--header", name + ": " + value] if data is not None: (folder / "request").write_bytes(data) command += ["--data-binary", "@" + str(folder / "request")] result = subprocess.run(command, capture_output=True, text=True) if result.returncode: raise urllib.error.URLError(result.stderr.strip()) response_headers = {} blocks = (folder / "headers").read_text(encoding="iso-8859-1").replace("\r\n", "\n").strip().split("\n\n") for line in blocks[-1].splitlines()[1:]: name, separator, value = line.partition(":") if separator: response_headers[name] = value.strip() return int(result.stdout), (folder / "body").read_bytes(), response_headers class ApiError(RuntimeError): """An API error response. Branch on error_code (and status), never on the message text. uncertain is True when a PATCH or DELETE got no response or a server error: it may or may not have been applied.""" def __init__(self, status, body, uncertain=False): self.status = status self.uncertain = uncertain self.error_code = body.get("error_code") if isinstance(body, dict) else None super().__init__(f"{body.get('error_code')} {body.get('error_params')}: {body.get('errors')} (request {body.get('request_id')})" if isinstance(body, dict) else "HTTP " + str(status) if status else "No response") def call(name, params=None, body=None, key=None): route = SPEC["requests"][name] headers = {"Authorization": "Bearer " + API_KEY, "Accept": "application/json"} if route["method"] == "POST": if not key: raise RuntimeError("Persist a logical create key before sending POST") headers["Idempotency-Key"] = key data = None if body is None else json.dumps(body).encode("utf-8") if data is not None: headers["Content-Type"] = "application/json" query = urllib.parse.urlencode(params or {}) url = BASE + route["path"] + ("?" + query if query else "") # Only GET has automatic retries in this workflow. A PATCH or DELETE that got no response or a # server error is never resent blindly: it may already have been applied, so the caller reads the record first. resend = route["method"] == "GET" for attempt in range(5): try: status, raw, response_headers = transport(route["method"], url, headers, data) except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException): if not resend: raise ApiError(0, None, uncertain=True) if attempt == 4: raise time.sleep(2 ** attempt) continue response_headers = {k.lower(): v for k, v in response_headers.items()} result = None if status != 304 and raw: try: result = decode_json(raw.decode("utf-8")) except (ValueError, UnicodeError): if status < 400: raise RuntimeError("Expected a JSON success response") if status >= 500 and not resend: raise ApiError(status, result, uncertain=True) retry = resend and (status == 429 or status >= 500) if retry: if attempt == 4: raise RuntimeError("Retry limit reached; check the request outcome before starting a new create") delay = response_headers.get("retry-after", str(2 ** attempt)) time.sleep(max(0, float(delay))) continue if status >= 400: raise ApiError(status, result) return {"status": status, "body": result, "headers": response_headers, "raw": raw} raise RuntimeError("Retry limit reached") def 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 items(value): if not isinstance(value, list): raise RuntimeError("Expected a JSON array") return value def count(value): return len(items(value)) 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] def is_empty(value): return count(value) == 0 def is_present(value): return value is not None and value != "" def new_id_set(): return set() def not_value(value): if not isinstance(value, bool): raise RuntimeError("Expected a Boolean") return not value def optional(name, fallback): value = os.environ.get(name) return fallback if value is None or value == "" else value def page_size(value): if not re.fullmatch(r"[1-9][0-9]*", value) or int(value) > 2147483647: raise RuntimeError("Page size must be a positive int32") return 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 remember_id(seen, value): if value in seen: return False seen.add(value) return True 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 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(): activity_page_size = page_size(optional("EXHIBITDAY_PAGE_SIZE", "100")) activity_from = required("EXHIBITDAY_LOG_FROM") activity_until = required("EXHIBITDAY_LOG_UNTIL") activity_query = {"filter_by_create_timestamp_greater_than_or_equal_to": activity_from, "filter_by_create_timestamp_smaller_than_or_equal_to": activity_until, "$result_sort": "create_timestamp_asc", "$limit": activity_page_size} activity_event_id = optional("EXHIBITDAY_EVENT_ID", "") if is_present(activity_event_id): activity_query["filter_by_event_id"] = positive_id(activity_event_id) activity_asset_id = optional("EXHIBITDAY_ASSET_ID", "") if is_present(activity_asset_id): activity_query["filter_by_asset_id"] = positive_id(activity_asset_id) activity_storage_location_id = optional("EXHIBITDAY_STORAGE_LOCATION_ID", "") if is_present(activity_storage_location_id): activity_query["filter_by_storage_location_id"] = positive_id(activity_storage_location_id) activity_task_id = optional("EXHIBITDAY_TASK_ID", "") if is_present(activity_task_id): activity_query["filter_by_task_id"] = positive_id(activity_task_id) activity_offset = "0" activity_seen_ids = new_id_set() while True: activity_query["$offset"] = activity_offset activity_response = call("page", activity_query, None, None) activity_page = activity_response["body"] activity_rows = items(field(activity_page, "list_data")) require_condition(equal(text(field(activity_page, "records_found")), text(count(activity_rows))), "records_found does not match this page's rows.") require_condition(is_present(text(field(activity_page, "total_records"))), "The collection wrapper needs total_records.") require_condition(either(equal(field(activity_page, "has_more"), True), equal(field(activity_page, "has_more"), False)), "Expected a Boolean has_more value.") for activity_entry in items(activity_rows): activity_entry_id = positive_id(text(field(activity_entry, "id"))) require_condition(is_present(text(field(activity_entry, "log_entry_created_timestamp"))), "A log entry needs its timestamp.") if remember_id(activity_seen_ids, activity_entry_id): print_value({"id": activity_entry_id, "log_entry_created_timestamp": field(activity_entry, "log_entry_created_timestamp"), "log_entry": field(activity_entry, "log_entry")}) if equal(field(activity_page, "has_more"), False): break require_condition(not_value(is_empty(activity_rows)), "An empty page has has_more=true; stop and reconcile the query.") activity_offset = add_offset(activity_offset, count(activity_rows)) if __name__ == "__main__": main() EXHIBITDAY_PY ``` ```javascript // Server-side Node.js with fetch; built-in modules only. Set EXHIBITDAY_API_KEY. const BASE = "https://api.exhibitday.com/v1"; const SPEC = JSON.parse("{\"preserveNumbers\":true,\"requests\":{\"page\":{\"method\":\"GET\",\"path\":\"/workspace_settings/logs\"}}}"); const API_KEY = process.env.EXHIBITDAY_API_KEY; if (!API_KEY || !API_KEY.trim()) throw new Error("Set EXHIBITDAY_API_KEY"); if (/[^\x20-\x7e]/.test(API_KEY)) throw new Error("Use the API key as one ASCII header value without control characters"); 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, errors: result.errors, error_params: result.error_params, 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, key = null) { const route = SPEC.requests[name]; const headers = { Authorization: "Bearer " + API_KEY, Accept: "application/json" }; if (route.method === "POST") { if (!key) throw new Error("Persist a logical create key before sending POST"); headers["Idempotency-Key"] = key; } 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 : ""); // 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. const resend = route.method === "GET"; 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 = resend && (response.status === 429 || response.status >= 500); 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, raw }; } throw new Error("Retry limit reached"); } function add_offset(offset, received) { const result = BigInt(offset) + received; if (received <= 0n || result > 2147483647n) throw new Error("Cannot advance this int32 offset; reconcile the query"); return result.toString(); } function items(value) { if (!Array.isArray(value)) throw new Error("Expected a JSON array"); return value; } function count(value) { return BigInt(items(value).length); } function either(left, right) { if (typeof left !== "boolean" || typeof right !== "boolean") throw new Error("Expected Boolean criteria"); return left || right; } function equal(left, right) { return typeof left === typeof right && left === right; } function field(value, name) { if (!value || Array.isArray(value) || typeof value !== "object" || !Object.hasOwn(value, name)) throw new Error("Missing response field: " + name); return value[name]; } function is_empty(value) { return count(value) === 0n; } function is_present(value) { return value !== null && value !== undefined && value !== ""; } function new_id_set() { return new Set(); } function not_value(value) { if (typeof value !== "boolean") throw new Error("Expected a Boolean"); return !value; } function optional(name, fallback) { const value = process.env[name]; return value === undefined || value === "" ? fallback : value; } function page_size(value) { if (!/^[1-9][0-9]*$/.test(value) || BigInt(value) > 2147483647n) throw new Error("Page size must be a positive int32"); return value; } function positive_id(value) { if (!/^[1-9][0-9]*$/.test(value) || BigInt(value) > 9223372036854775807n) throw new Error("Use a positive record ID"); return value; } function print_value(value) { console.log(typeof value === "string" ? value : JSON.stringify(value)); } function remember_id(seen, value) { if (seen.has(value)) return false; seen.add(value); return true; } function require_condition(value, message) { if (value !== true) throw new Error(message); } function required(name) { const value = process.env[name]; if (value === undefined || !value.trim()) throw new Error("Set " + name); return value; } function text(value) { if (value === null || value === undefined) return ""; if (["string", "boolean", "bigint"].includes(typeof value)) return String(value); throw new Error("Expected a scalar response value"); } async function main() { let activity_page_size = page_size(optional("EXHIBITDAY_PAGE_SIZE", "100")); let activity_from = required("EXHIBITDAY_LOG_FROM"); let activity_until = required("EXHIBITDAY_LOG_UNTIL"); let activity_query = {"filter_by_create_timestamp_greater_than_or_equal_to": activity_from, "filter_by_create_timestamp_smaller_than_or_equal_to": activity_until, "$result_sort": "create_timestamp_asc", "$limit": activity_page_size}; let activity_event_id = optional("EXHIBITDAY_EVENT_ID", ""); if (is_present(activity_event_id)) { activity_query["filter_by_event_id"] = positive_id(activity_event_id); } let activity_asset_id = optional("EXHIBITDAY_ASSET_ID", ""); if (is_present(activity_asset_id)) { activity_query["filter_by_asset_id"] = positive_id(activity_asset_id); } let activity_storage_location_id = optional("EXHIBITDAY_STORAGE_LOCATION_ID", ""); if (is_present(activity_storage_location_id)) { activity_query["filter_by_storage_location_id"] = positive_id(activity_storage_location_id); } let activity_task_id = optional("EXHIBITDAY_TASK_ID", ""); if (is_present(activity_task_id)) { activity_query["filter_by_task_id"] = positive_id(activity_task_id); } let activity_offset = "0"; let activity_seen_ids = new_id_set(); while (true) { activity_query["$offset"] = activity_offset; let activity_response = await call("page", activity_query, null, null); let activity_page = activity_response.body; let activity_rows = items(field(activity_page, "list_data")); require_condition(equal(text(field(activity_page, "records_found")), text(count(activity_rows))), "records_found does not match this page's rows."); require_condition(is_present(text(field(activity_page, "total_records"))), "The collection wrapper needs total_records."); require_condition(either(equal(field(activity_page, "has_more"), true), equal(field(activity_page, "has_more"), false)), "Expected a Boolean has_more value."); for (const activity_entry of items(activity_rows)) { let activity_entry_id = positive_id(text(field(activity_entry, "id"))); require_condition(is_present(text(field(activity_entry, "log_entry_created_timestamp"))), "A log entry needs its timestamp."); if (remember_id(activity_seen_ids, activity_entry_id)) { print_value({"id": activity_entry_id, "log_entry_created_timestamp": field(activity_entry, "log_entry_created_timestamp"), "log_entry": field(activity_entry, "log_entry")}); } } if (equal(field(activity_page, "has_more"), false)) { break; } require_condition(not_value(is_empty(activity_rows)), "An empty page has has_more=true; stop and reconcile the query."); activity_offset = add_offset(activity_offset, count(activity_rows)); } } if (require.main === module) main().catch(error => { console.error(error.message); process.exitCode = 1; }); module.exports = { main }; ``` ```python # 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\":{\"page\":{\"method\":\"GET\",\"path\":\"/workspace_settings/logs\"}}}") 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) 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, key=None): route = SPEC["requests"][name] headers = {"Authorization": "Bearer " + API_KEY, "Accept": "application/json"} if route["method"] == "POST": if not key: raise RuntimeError("Persist a logical create key before sending POST") headers["Idempotency-Key"] = key data = None if body is None else json.dumps(body).encode("utf-8") if data is not None: headers["Content-Type"] = "application/json" query = urllib.parse.urlencode(params or {}) url = BASE + route["path"] + ("?" + query if query else "") # Only GET has automatic retries in this workflow. A PATCH or DELETE that got no response or a # server error is never resent blindly: it may already have been applied, so the caller reads the record first. resend = route["method"] == "GET" for attempt in range(5): try: status, raw, response_headers = transport(route["method"], url, headers, data) except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException): if not resend: raise ApiError(0, None, uncertain=True) if attempt == 4: raise time.sleep(2 ** attempt) continue response_headers = {k.lower(): v for k, v in response_headers.items()} result = None if status != 304 and raw: try: result = decode_json(raw.decode("utf-8")) except (ValueError, UnicodeError): if status < 400: raise RuntimeError("Expected a JSON success response") if status >= 500 and not resend: raise ApiError(status, result, uncertain=True) retry = resend and (status == 429 or status >= 500) if retry: if attempt == 4: raise RuntimeError("Retry limit reached; check the request outcome before starting a new create") delay = response_headers.get("retry-after", str(2 ** attempt)) time.sleep(max(0, float(delay))) continue if status >= 400: raise ApiError(status, result) return {"status": status, "body": result, "headers": response_headers, "raw": raw} raise RuntimeError("Retry limit reached") def 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 items(value): if not isinstance(value, list): raise RuntimeError("Expected a JSON array") return value def count(value): return len(items(value)) 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] def is_empty(value): return count(value) == 0 def is_present(value): return value is not None and value != "" def new_id_set(): return set() def not_value(value): if not isinstance(value, bool): raise RuntimeError("Expected a Boolean") return not value def optional(name, fallback): value = os.environ.get(name) return fallback if value is None or value == "" else value def page_size(value): if not re.fullmatch(r"[1-9][0-9]*", value) or int(value) > 2147483647: raise RuntimeError("Page size must be a positive int32") return 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 remember_id(seen, value): if value in seen: return False seen.add(value) return True 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 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(): activity_page_size = page_size(optional("EXHIBITDAY_PAGE_SIZE", "100")) activity_from = required("EXHIBITDAY_LOG_FROM") activity_until = required("EXHIBITDAY_LOG_UNTIL") activity_query = {"filter_by_create_timestamp_greater_than_or_equal_to": activity_from, "filter_by_create_timestamp_smaller_than_or_equal_to": activity_until, "$result_sort": "create_timestamp_asc", "$limit": activity_page_size} activity_event_id = optional("EXHIBITDAY_EVENT_ID", "") if is_present(activity_event_id): activity_query["filter_by_event_id"] = positive_id(activity_event_id) activity_asset_id = optional("EXHIBITDAY_ASSET_ID", "") if is_present(activity_asset_id): activity_query["filter_by_asset_id"] = positive_id(activity_asset_id) activity_storage_location_id = optional("EXHIBITDAY_STORAGE_LOCATION_ID", "") if is_present(activity_storage_location_id): activity_query["filter_by_storage_location_id"] = positive_id(activity_storage_location_id) activity_task_id = optional("EXHIBITDAY_TASK_ID", "") if is_present(activity_task_id): activity_query["filter_by_task_id"] = positive_id(activity_task_id) activity_offset = "0" activity_seen_ids = new_id_set() while True: activity_query["$offset"] = activity_offset activity_response = call("page", activity_query, None, None) activity_page = activity_response["body"] activity_rows = items(field(activity_page, "list_data")) require_condition(equal(text(field(activity_page, "records_found")), text(count(activity_rows))), "records_found does not match this page's rows.") require_condition(is_present(text(field(activity_page, "total_records"))), "The collection wrapper needs total_records.") require_condition(either(equal(field(activity_page, "has_more"), True), equal(field(activity_page, "has_more"), False)), "Expected a Boolean has_more value.") for activity_entry in items(activity_rows): activity_entry_id = positive_id(text(field(activity_entry, "id"))) require_condition(is_present(text(field(activity_entry, "log_entry_created_timestamp"))), "A log entry needs its timestamp.") if remember_id(activity_seen_ids, activity_entry_id): print_value({"id": activity_entry_id, "log_entry_created_timestamp": field(activity_entry, "log_entry_created_timestamp"), "log_entry": field(activity_entry, "log_entry")}) if equal(field(activity_page, "has_more"), False): break require_condition(not_value(is_empty(activity_rows)), "An empty page has has_more=true; stop and reconcile the query.") activity_offset = add_offset(activity_offset, count(activity_rows)) if __name__ == "__main__": main() ``` ```csharp // .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\":true,\"requests\":{\"page\":{\"method\":\"GET\",\"path\":\"/workspace_settings/logs\"}}}"); static readonly string ApiKey = HeaderKey(Required("EXHIBITDAY_API_KEY")); static string HeaderKey(string value) { if(value.Any(c=>c<32||c>126))throw new Exception("Use the API key as one ASCII header value without control characters");return value; } static readonly HttpClient Client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false }) { Timeout = TimeSpan.FromSeconds(30) }; internal static Func> Send = request => Client.SendAsync(request); sealed class Result { public int Status; public JsonNode Body; public Dictionary Headers; public string Raw; } // 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(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 Call(string name, JsonObject query = null, JsonNode body = null, string key = null) { var route = Spec["requests"][name]; var method = Text(route["method"]); var headers = new Dictionary(StringComparer.OrdinalIgnoreCase) { ["Authorization"] = "Bearer " + ApiKey, ["Accept"] = "application/json" }; if (method == "POST") { if (string.IsNullOrEmpty(key)) throw new Exception("Persist a logical create key before sending POST"); headers["Idempotency-Key"] = key; } 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); // 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. var resend = method == "GET"; 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 Send(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 = resend && (status == 429 || status >= 500); 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, Raw = raw }; } } throw new Exception("Retry limit reached"); } static string AddOffset(string offset,long received) { var result=checked(long.Parse(offset,CultureInfo.InvariantCulture)+received);if(received<=0||result>int.MaxValue)throw new Exception("Cannot advance this int32 offset; reconcile the query");return result.ToString(CultureInfo.InvariantCulture); } static JsonNode CopyNode(JsonNode value) => value?.DeepClone(); static JsonArray Items(JsonNode value) => value as JsonArray ?? throw new Exception("Expected a JSON array"); static long Count(JsonNode value) => Items(value).Count; static bool Either(bool left,bool right) => left || right; static object Scalar(object value) { if(value is JsonValue json){if(json.TryGetValue(out var boolean))return boolean;if(json.TryGetValue(out var text))return text;return json.ToJsonString();}return value; } static bool Equal(object left,object right) => object.Equals(Scalar(left),Scalar(right)); static JsonNode Field(JsonNode value,string name) { if(value is not JsonObject obj || !obj.TryGetPropertyValue(name,out var item))throw new Exception("Missing response field: "+name);return item; } static bool IsEmpty(JsonNode value) => Count(value)==0; static bool IsPresent(string value) => value!=null && value!=""; static HashSet NewIdSet() => new HashSet(StringComparer.Ordinal); static bool NotValue(bool value) => !value; static string Optional(string name,string fallback) { var value=Environment.GetEnvironmentVariable(name);return value==null||value==""?fallback:value; } static string PageSize(string value) { if(string.IsNullOrEmpty(value)||value[0]=='0'||!value.All(c=>c>='0'&&c<='9')||!int.TryParse(value,NumberStyles.None,CultureInfo.InvariantCulture,out var limit)||limit<=0)throw new Exception("Page size must be a positive int32");return value; } static string PositiveId(string value) { if(string.IsNullOrEmpty(value)||value[0]=='0'||!value.All(c=>c>='0'&&c<='9')||!long.TryParse(value,NumberStyles.None,CultureInfo.InvariantCulture,out var id)||id<=0)throw new Exception("Use a positive record ID");return value; } static void PrintValue(object value) => Console.WriteLine(value is string text ? text : JsonSerializer.Serialize(value)); static bool RememberId(HashSet seen,string value) => seen.Add(value); static void RequireCondition(bool value,string message) { if(!value)throw new Exception(message); } static string Text(object value) => value==null?"":value is JsonNode node?Text(node):Convert.ToString(value,CultureInfo.InvariantCulture); internal static async Task Run() { var activity_page_size = PageSize(Optional("EXHIBITDAY_PAGE_SIZE", "100")); var activity_from = Required("EXHIBITDAY_LOG_FROM"); var activity_until = Required("EXHIBITDAY_LOG_UNTIL"); var activity_query = new JsonObject { ["filter_by_create_timestamp_greater_than_or_equal_to"] = activity_from, ["filter_by_create_timestamp_smaller_than_or_equal_to"] = activity_until, ["$result_sort"] = "create_timestamp_asc", ["$limit"] = activity_page_size }; var activity_event_id = Optional("EXHIBITDAY_EVENT_ID", ""); if (IsPresent(activity_event_id)) { activity_query["filter_by_event_id"] = PositiveId(activity_event_id); } var activity_asset_id = Optional("EXHIBITDAY_ASSET_ID", ""); if (IsPresent(activity_asset_id)) { activity_query["filter_by_asset_id"] = PositiveId(activity_asset_id); } var activity_storage_location_id = Optional("EXHIBITDAY_STORAGE_LOCATION_ID", ""); if (IsPresent(activity_storage_location_id)) { activity_query["filter_by_storage_location_id"] = PositiveId(activity_storage_location_id); } var activity_task_id = Optional("EXHIBITDAY_TASK_ID", ""); if (IsPresent(activity_task_id)) { activity_query["filter_by_task_id"] = PositiveId(activity_task_id); } var activity_offset = "0"; var activity_seen_ids = NewIdSet(); while (true) { activity_query["$offset"] = activity_offset; var activity_response = await Call("page", activity_query, null, null); var activity_page = activity_response.Body; var activity_rows = Items(Field(activity_page, "list_data")); RequireCondition(Equal(Text(Field(activity_page, "records_found")), Text(Count(activity_rows))), "records_found does not match this page's rows."); RequireCondition(IsPresent(Text(Field(activity_page, "total_records"))), "The collection wrapper needs total_records."); RequireCondition(Either(Equal(Field(activity_page, "has_more"), true), Equal(Field(activity_page, "has_more"), false)), "Expected a Boolean has_more value."); foreach (var activity_entry in Items(activity_rows)) { var activity_entry_id = PositiveId(Text(Field(activity_entry, "id"))); RequireCondition(IsPresent(Text(Field(activity_entry, "log_entry_created_timestamp"))), "A log entry needs its timestamp."); if (RememberId(activity_seen_ids, activity_entry_id)) { PrintValue(new JsonObject { ["id"] = activity_entry_id, ["log_entry_created_timestamp"] = CopyNode(Field(activity_entry, "log_entry_created_timestamp")), ["log_entry"] = CopyNode(Field(activity_entry, "log_entry")) }); } } if (Equal(Field(activity_page, "has_more"), false)) { break; } RequireCondition(NotValue(IsEmpty(activity_rows)), "An empty page has has_more=true; stop and reconcile the query."); activity_offset = AddOffset(activity_offset, Count(activity_rows)); } } static Task Main() => Run(); } ``` ```java // 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 SPEC = JSON.fromJson("{\"preserveNumbers\":true,\"requests\":{\"page\":{\"method\":\"GET\",\"path\":\"/workspace_settings/logs\"}}}", Map.class); static final String API_KEY = headerKey(required("EXHIBITDAY_API_KEY")); static String headerKey(String value){if(value.chars().anyMatch(c->c<32||c>126))throw new IllegalArgumentException("Use the API key as one ASCII header value without control characters");return value;} static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).followRedirects(HttpClient.Redirect.NEVER).build(); interface RequestSender { HttpResponse send(HttpRequest request)throws IOException,InterruptedException; } static RequestSender SEND=request->CLIENT.send(request,HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); static class Result { int status; Object body; Map headers; String raw; Result(int s, Object b, Map h,String r) {status=s;body=b;headers=h;raw=r;} } // 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 obj(Object value) {return value==null?new LinkedHashMap<>(): (Map)value;} @SuppressWarnings("unchecked") static List list(Object value) {return value==null?Collections.emptyList():(List)value;} static Map map(Object... pairs) {Map result=new LinkedHashMap<>();for(int i=0;i query,Object body,String key) { Map route=obj(obj(SPEC.get("requests")).get(name));String method=text(route.get("method")); Map headers=map("Authorization","Bearer " + API_KEY,"Accept","application/json"); if(method.equals("POST")){if(key==null||key.isEmpty())throw new IllegalArgumentException("Persist a logical create key before sending POST");headers.put("Idempotency-Key",key);} 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); // 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. boolean resend=method.equals("GET"); 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 response; try {response=SEND.send(request.build());} 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();Object parsed=null; if(status!=304&&!response.body().isEmpty()) { try {parsed=JSON.fromJson(response.body(),Object.class);} catch(RuntimeException error){if(status<400)throw new IllegalStateException("Expected a JSON success response",error);} } Map 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=resend&&(status==429||status>=500); 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,response.body()); } throw new IllegalStateException("Retry limit reached"); } static String add_offset(String offset,long received){long result=Math.addExact(Long.parseLong(offset),received);if(received<=0||result>Integer.MAX_VALUE)throw new IllegalStateException("Cannot advance this int32 offset; reconcile the query");return Long.toString(result);} static List items(Object value){if(!(value instanceof List))throw new IllegalStateException("Expected a JSON array");return list(value);} static long count(Object value){return items(value).size();} static boolean either(boolean left,boolean right){return left||right;} static boolean equal(Object left,Object right){return Objects.equals(left,right);} static Object field(Object value,String name){if(!(value instanceof Map)||!obj(value).containsKey(name))throw new IllegalStateException("Missing response field: "+name);return obj(value).get(name);} static boolean is_empty(Object value){return count(value)==0;} static boolean is_present(String value){return value!=null&&!value.isEmpty();} static Set new_id_set(){return new HashSet<>();} static boolean not_value(boolean value){return !value;} static String optional(String name,String fallback){String value=System.getenv(name);return value==null||value.isEmpty()?fallback:value;} static String page_size(String value){try{if(value==null||!value.matches("[1-9][0-9]*")||Integer.parseInt(value)<=0)throw new IllegalArgumentException();return value;}catch(RuntimeException error){throw new IllegalArgumentException("Page size must be a positive int32");}} static String positive_id(String value){try{if(value==null||!value.matches("[1-9][0-9]*")||Long.parseLong(value)<=0)throw new IllegalArgumentException();return value;}catch(RuntimeException error){throw new IllegalArgumentException("Use a positive record ID");}} static void print_value(Object value){try{String text=value instanceof String?(String)value:JSON.toJson(value);System.out.write((text+"\n").getBytes(StandardCharsets.UTF_8));}catch(IOException error){throw new UncheckedIOException(error);}} static boolean remember_id(Set seen,String value){return seen.add(value);} static void require_condition(boolean value,String message){if(!value)throw new IllegalStateException(message);} static void run()throws Exception { String activity_page_size = page_size(optional("EXHIBITDAY_PAGE_SIZE", "100")); String activity_from = required("EXHIBITDAY_LOG_FROM"); String activity_until = required("EXHIBITDAY_LOG_UNTIL"); Map activity_query = map("filter_by_create_timestamp_greater_than_or_equal_to", activity_from, "filter_by_create_timestamp_smaller_than_or_equal_to", activity_until, "$result_sort", "create_timestamp_asc", "$limit", activity_page_size); String activity_event_id = optional("EXHIBITDAY_EVENT_ID", ""); if (is_present(activity_event_id)) { activity_query.put("filter_by_event_id", positive_id(activity_event_id)); } String activity_asset_id = optional("EXHIBITDAY_ASSET_ID", ""); if (is_present(activity_asset_id)) { activity_query.put("filter_by_asset_id", positive_id(activity_asset_id)); } String activity_storage_location_id = optional("EXHIBITDAY_STORAGE_LOCATION_ID", ""); if (is_present(activity_storage_location_id)) { activity_query.put("filter_by_storage_location_id", positive_id(activity_storage_location_id)); } String activity_task_id = optional("EXHIBITDAY_TASK_ID", ""); if (is_present(activity_task_id)) { activity_query.put("filter_by_task_id", positive_id(activity_task_id)); } String activity_offset = "0"; Set activity_seen_ids = new_id_set(); while (true) { activity_query.put("$offset", activity_offset); Result activity_response = call("page", activity_query, null, null); Object activity_page = activity_response.body; List activity_rows = items(field(activity_page, "list_data")); require_condition(equal(text(field(activity_page, "records_found")), text(count(activity_rows))), "records_found does not match this page's rows."); require_condition(is_present(text(field(activity_page, "total_records"))), "The collection wrapper needs total_records."); require_condition(either(equal(field(activity_page, "has_more"), true), equal(field(activity_page, "has_more"), false)), "Expected a Boolean has_more value."); for (Object activity_entry : items(activity_rows)) { String activity_entry_id = positive_id(text(field(activity_entry, "id"))); require_condition(is_present(text(field(activity_entry, "log_entry_created_timestamp"))), "A log entry needs its timestamp."); if (remember_id(activity_seen_ids, activity_entry_id)) { print_value(map("id", activity_entry_id, "log_entry_created_timestamp", field(activity_entry, "log_entry_created_timestamp"), "log_entry", field(activity_entry, "log_entry"))); } } if (equal(field(activity_page, "has_more"), false)) { break; } require_condition(not_value(is_empty(activity_rows)), "An empty page has has_more=true; stop and reconcile the query."); activity_offset = add_offset(activity_offset, count(activity_rows)); } } public static void main(String[] args)throws Exception {run();} } ``` ```php $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, ?string $key = null): array { global $spec, $apiKey, $transport; $route = $spec['requests'][$name]; $headers = ['Authorization' => 'Bearer ' . $apiKey, 'Accept' => 'application/json']; if ($route['method'] === 'POST') { if ($key === null || $key === '') throw new RuntimeException('Persist a logical create key before sending POST'); $headers['Idempotency-Key'] = $key; // 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); // 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 = 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 = $resend && ($status === 429 || $status >= 500); 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, 'raw' => $raw]; } throw new RuntimeException('Retry limit reached'); } $transport = Closure::fromCallable('nativeTransport'); function add_offset(string $offset,int $received):string{$result=(int)$offset+$received;if($received<=0||$result>2147483647)throw new RuntimeException("Cannot advance this int32 offset; reconcile the query");return (string)$result;} function either(bool $left,bool $right):bool{return $left||$right;} function equal(mixed $left,mixed $right):bool{return $left===$right;} function field(mixed $value,string $name):mixed{if(!is_array($value)||!array_key_exists($name,$value))throw new RuntimeException("Missing response field: ".$name);return $value[$name];} function items(mixed $value):array{if(!is_array($value)||!array_is_list($value))throw new RuntimeException("Expected a JSON array");return $value;} function is_empty(mixed $value):bool{return count(items($value))===0;} function is_present(?string $value):bool{return $value!==null&&$value!=="";} function new_id_set():array{return [];} function not_value(bool $value):bool{return !$value;} function page_size(string $value):string{if(!preg_match("/^[1-9][0-9]*$/D",$value)||strlen($value)>10||(strlen($value)===10&&strcmp($value,"2147483647")>0))throw new RuntimeException("Page size must be a positive int32");return $value;} function positive_id(string $value):string{if(!preg_match("/^[1-9][0-9]*$/D",$value)||strlen($value)>19||(strlen($value)===19&&strcmp($value,"9223372036854775807")>0))throw new RuntimeException("Use a positive record ID");return $value;} function print_value(mixed $value):void{echo (is_string($value)?$value:json_encode($value,JSON_THROW_ON_ERROR))."\n";} function remember_id(array &$seen,string $value):bool{if(array_key_exists($value,$seen))return false;$seen[$value]=true;return true;} function require_condition(bool $value,string $message):void{if(!$value)throw new RuntimeException($message);} function text(mixed $value):string{if($value===null)return "";if(is_string($value))return $value;if(is_bool($value))return $value?"true":"false";if(is_int($value))return (string)$value;throw new RuntimeException("Expected a scalar response value");} function main():void { $activity_page_size = page_size(optional('EXHIBITDAY_PAGE_SIZE', '100')); $activity_from = required('EXHIBITDAY_LOG_FROM'); $activity_until = required('EXHIBITDAY_LOG_UNTIL'); $activity_query = ['filter_by_create_timestamp_greater_than_or_equal_to' => $activity_from, 'filter_by_create_timestamp_smaller_than_or_equal_to' => $activity_until, '$result_sort' => 'create_timestamp_asc', '$limit' => $activity_page_size]; $activity_event_id = optional('EXHIBITDAY_EVENT_ID', ''); if (is_present($activity_event_id)) { $activity_query['filter_by_event_id'] = positive_id($activity_event_id); } $activity_asset_id = optional('EXHIBITDAY_ASSET_ID', ''); if (is_present($activity_asset_id)) { $activity_query['filter_by_asset_id'] = positive_id($activity_asset_id); } $activity_storage_location_id = optional('EXHIBITDAY_STORAGE_LOCATION_ID', ''); if (is_present($activity_storage_location_id)) { $activity_query['filter_by_storage_location_id'] = positive_id($activity_storage_location_id); } $activity_task_id = optional('EXHIBITDAY_TASK_ID', ''); if (is_present($activity_task_id)) { $activity_query['filter_by_task_id'] = positive_id($activity_task_id); } $activity_offset = '0'; $activity_seen_ids = new_id_set(); while (true) { $activity_query['$offset'] = $activity_offset; $activity_response = call('page', $activity_query, null, null); $activity_page = $activity_response["body"]; $activity_rows = items(field($activity_page, 'list_data')); require_condition(equal(text(field($activity_page, 'records_found')), text(count($activity_rows))), 'records_found does not match this page\'s rows.'); require_condition(is_present(text(field($activity_page, 'total_records'))), 'The collection wrapper needs total_records.'); require_condition(either(equal(field($activity_page, 'has_more'), true), equal(field($activity_page, 'has_more'), false)), 'Expected a Boolean has_more value.'); foreach (items($activity_rows) as $activity_entry) { $activity_entry_id = positive_id(text(field($activity_entry, 'id'))); require_condition(is_present(text(field($activity_entry, 'log_entry_created_timestamp'))), 'A log entry needs its timestamp.'); if (remember_id($activity_seen_ids, $activity_entry_id)) { print_value((object)['id' => $activity_entry_id, 'log_entry_created_timestamp' => field($activity_entry, 'log_entry_created_timestamp'), 'log_entry' => field($activity_entry, 'log_entry')]); } } if (equal(field($activity_page, 'has_more'), false)) { break; } require_condition(not_value(is_empty($activity_rows)), 'An empty page has has_more=true; stop and reconcile the query.'); $activity_offset = add_offset($activity_offset, count($activity_rows)); } } if (realpath($_SERVER['SCRIPT_FILENAME'] ?? '') === __FILE__) main(); ``` ```ruby # 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":true,"requests":{"page":{"method":"GET","path":"/workspace_settings/logs"}}}') API_KEY = ENV.fetch('EXHIBITDAY_API_KEY') raise 'Use the API key as one ASCII header value without control characters' if API_KEY.each_codepoint.any?{|point|point<32||point>126} 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, 'DELETE' => Net::HTTP::Delete }.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, key = nil) route = SPEC.fetch('requests').fetch(name) headers = { 'Authorization' => 'Bearer ' + API_KEY, 'Accept' => 'application/json' } if route.fetch('method') == 'POST' headers['Idempotency-Key'] = key || raise('Persist a logical create key before sending POST') # 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) # 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.fetch('method') == 'GET' 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 = resend && (status == 429 || (500..599).cover?(status)) 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, raw: raw } end raise 'Retry limit reached' end def add_offset(offset,received) result=Integer(offset)+received raise "Cannot advance this int32 offset; reconcile the query" if received<=0 || result>2147483647 result.to_s end def items(value) raise "Expected a JSON array" unless value.is_a?(Array) value end def count(value) items(value).length end def either(left,right) raise "Expected Boolean criteria" unless [true,false].include?(left) && [true,false].include?(right) left || right end def equal(left,right) left.class==right.class && left==right end def field(value,name) raise "Missing response field: #{name}" unless value.is_a?(Hash) && value.key?(name) value.fetch(name) end def is_empty(value) count(value)==0 end def is_present(value) !value.nil? && value!="" end def new_id_set {} end def not_value(value) raise "Expected a Boolean" unless value==true || value==false !value end def optional(name,fallback) value=ENV[name] value.nil? || value.empty? ? fallback : value end def page_size(value) raise "Page size must be a positive int32" unless /\A[1-9][0-9]*\z/.match?(value) && Integer(value)<=2147483647 value end def positive_id(value) raise "Use a positive record ID" unless /\A[1-9][0-9]*\z/.match?(value) && Integer(value)<=9223372036854775807 value end def print_value(value) STDOUT.binmode.write((value.is_a?(String)?value:JSON.generate(value))+"\n") end def remember_id(seen,value) return false if seen.key?(value) seen[value]=true true end def require_condition(value,message) raise message unless value==true end def required(name) value=ENV[name] raise "Set #{name}" if value.nil? || value.strip.empty? value end def text(value) return "" if value.nil? return value.to_s if value.is_a?(String)||value.is_a?(Integer)||value==true||value==false raise "Expected a scalar response value" end def main activity_page_size = page_size(optional('EXHIBITDAY_PAGE_SIZE', '100')) activity_from = required('EXHIBITDAY_LOG_FROM') activity_until = required('EXHIBITDAY_LOG_UNTIL') activity_query = {'filter_by_create_timestamp_greater_than_or_equal_to' => activity_from, 'filter_by_create_timestamp_smaller_than_or_equal_to' => activity_until, '$result_sort' => 'create_timestamp_asc', '$limit' => activity_page_size} activity_event_id = optional('EXHIBITDAY_EVENT_ID', '') if is_present(activity_event_id) activity_query['filter_by_event_id'] = positive_id(activity_event_id) end activity_asset_id = optional('EXHIBITDAY_ASSET_ID', '') if is_present(activity_asset_id) activity_query['filter_by_asset_id'] = positive_id(activity_asset_id) end activity_storage_location_id = optional('EXHIBITDAY_STORAGE_LOCATION_ID', '') if is_present(activity_storage_location_id) activity_query['filter_by_storage_location_id'] = positive_id(activity_storage_location_id) end activity_task_id = optional('EXHIBITDAY_TASK_ID', '') if is_present(activity_task_id) activity_query['filter_by_task_id'] = positive_id(activity_task_id) end activity_offset = '0' activity_seen_ids = new_id_set() while true activity_query['$offset'] = activity_offset activity_response = call('page', activity_query, nil, nil) activity_page = activity_response.fetch(:body) activity_rows = items(field(activity_page, 'list_data')) require_condition(equal(text(field(activity_page, 'records_found')), text(count(activity_rows))), 'records_found does not match this page\'s rows.') require_condition(is_present(text(field(activity_page, 'total_records'))), 'The collection wrapper needs total_records.') require_condition(either(equal(field(activity_page, 'has_more'), true), equal(field(activity_page, 'has_more'), false)), 'Expected a Boolean has_more value.') items(activity_rows).each do |activity_entry| activity_entry_id = positive_id(text(field(activity_entry, 'id'))) require_condition(is_present(text(field(activity_entry, 'log_entry_created_timestamp'))), 'A log entry needs its timestamp.') if remember_id(activity_seen_ids, activity_entry_id) print_value({'id' => activity_entry_id, 'log_entry_created_timestamp' => field(activity_entry, 'log_entry_created_timestamp'), 'log_entry' => field(activity_entry, 'log_entry')}) end end if equal(field(activity_page, 'has_more'), false) break end require_condition(not_value(is_empty(activity_rows)), 'An empty page has has_more=true; stop and reconcile the query.') activity_offset = add_offset(activity_offset, count(activity_rows)) end end main if $PROGRAM_NAME == __FILE__ ``` ```go // Go 1.18+; standard library only. Set EXHIBITDAY_API_KEY. package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "net/url" "os" "strconv" "strings" "time" ) const base = "https://api.exhibitday.com/v1" const specification = "{\"preserveNumbers\":true,\"requests\":{\"page\":{\"method\":\"GET\",\"path\":\"/workspace_settings/logs\"}}}" 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 }} var send = client.Do type result struct { status int; body any; headers http.Header; raw []byte } // 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 call(name string, query map[string]string, body any, key string) result { route := object(object(spec["requests"])[name]); method := text(route["method"]) headers := map[string]string{"Authorization": "Bearer " + apiKey, "Accept": "application/json"} if method == "POST" { if key == "" { panic("Persist a logical create key before sending POST") }; 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() } // 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 := method == "GET" 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 := send(request) if err != nil { if !resend { panic(apiError{0, "", "No response", true}) }; if attempt == 4 { panic(err) }; time.Sleep(time.Second*time.Duration(1<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 := resend && (response.StatusCode == 429 || response.StatusCode >= 500) if retry { if attempt == 4 { panic("Retry limit reached; check the outcome before starting a new create") } seconds := float64(int64(1)<= 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, raw} } panic("Retry limit reached") } func add_offset(offset string,received int64)string{previous,err:=strconv.ParseInt(offset,10,32);if err!=nil||received<=0||received>2147483647-previous{panic("Cannot advance this int32 offset; reconcile the query")};return strconv.FormatInt(previous+received,10)} func items(value any)[]any{result,ok:=value.([]any);if !ok{panic("Expected a JSON array")};return result} func count(value any)int64{return int64(len(items(value)))} func either(left,right bool)bool{return left||right} func equal(left,right any)bool{switch a:=left.(type){case string:b,ok:=right.(string);return ok&&a==b;case bool:b,ok:=right.(bool);return ok&&a==b;case int64:b,ok:=right.(int64);return ok&&a==b};return left==nil&&right==nil} func field(value any,name string)any{obj,ok:=value.(map[string]any);if !ok{panic("Missing response object")};item,found:=obj[name];if !found{panic("Missing response field: "+name)};return item} func is_empty(value any)bool{return count(value)==0} func is_present(value string)bool{return value!=""} func new_id_set()map[string]bool{return map[string]bool{}} func not_value(value bool)bool{return !value} func optional(name,fallback string)string{value:=os.Getenv(name);if value==""{return fallback};return value} func page_size(value string)string{valid:=len(value)>0&&value[0]!='0';for _,ch:=range value{valid=valid&&ch>='0'&&ch<='9'};size,err:=strconv.ParseInt(value,10,32);if !valid||err!=nil||size<=0{panic("Page size must be a positive int32")};return value} func positive_id(value string)string{valid:=len(value)>0&&value[0]!='0';for _,ch:=range value{valid=valid&&ch>='0'&&ch<='9'};id,err:=strconv.ParseInt(value,10,64);if !valid||err!=nil||id<=0{panic("Use a positive record ID")};return value} func print_value(value any){if result,ok:=value.(string);ok{fmt.Println(result);return};raw,err:=json.Marshal(value);if err!=nil{panic(err)};fmt.Println(string(raw))} func remember_id(seen map[string]bool,value string)bool{if seen[value]{return false};seen[value]=true;return true} func require_condition(value bool,message string){if !value{panic(message)}} func workflow() { activity_page_size := page_size(optional("EXHIBITDAY_PAGE_SIZE", "100")) activity_from := required("EXHIBITDAY_LOG_FROM") activity_until := required("EXHIBITDAY_LOG_UNTIL") activity_query := map[string]string{"filter_by_create_timestamp_greater_than_or_equal_to": activity_from, "filter_by_create_timestamp_smaller_than_or_equal_to": activity_until, "$result_sort": "create_timestamp_asc", "$limit": activity_page_size} activity_event_id := optional("EXHIBITDAY_EVENT_ID", "") if is_present(activity_event_id) { activity_query["filter_by_event_id"] = positive_id(activity_event_id) } activity_asset_id := optional("EXHIBITDAY_ASSET_ID", "") if is_present(activity_asset_id) { activity_query["filter_by_asset_id"] = positive_id(activity_asset_id) } activity_storage_location_id := optional("EXHIBITDAY_STORAGE_LOCATION_ID", "") if is_present(activity_storage_location_id) { activity_query["filter_by_storage_location_id"] = positive_id(activity_storage_location_id) } activity_task_id := optional("EXHIBITDAY_TASK_ID", "") if is_present(activity_task_id) { activity_query["filter_by_task_id"] = positive_id(activity_task_id) } activity_offset := "0" activity_seen_ids := new_id_set() for true { activity_query["$offset"] = activity_offset activity_response := call("page", activity_query, nil, "") activity_page := activity_response.body activity_rows := items(field(activity_page, "list_data")) require_condition(equal(text(field(activity_page, "records_found")), text(count(activity_rows))), "records_found does not match this page's rows.") require_condition(is_present(text(field(activity_page, "total_records"))), "The collection wrapper needs total_records.") require_condition(either(equal(field(activity_page, "has_more"), true), equal(field(activity_page, "has_more"), false)), "Expected a Boolean has_more value.") for _, activity_entry := range items(activity_rows) { activity_entry_id := positive_id(text(field(activity_entry, "id"))) require_condition(is_present(text(field(activity_entry, "log_entry_created_timestamp"))), "A log entry needs its timestamp.") if remember_id(activity_seen_ids, activity_entry_id) { print_value(map[string]any{"id": activity_entry_id, "log_entry_created_timestamp": field(activity_entry, "log_entry_created_timestamp"), "log_entry": field(activity_entry, "log_entry")}) } } if equal(field(activity_page, "has_more"), false) { break } require_condition(not_value(is_empty(activity_rows)), "An empty page has has_more=true; stop and reconcile the query.") activity_offset = add_offset(activity_offset, count(activity_rows)) } } func header_key(value string)string{for _,ch:=range value{if ch<32||ch>126{panic("Use the API key as one ASCII header value without control characters")}};return value} func main(){apiKey=header_key(required("EXHIBITDAY_API_KEY"));if err:=json.Unmarshal([]byte(specification),&spec);err!=nil{panic(err)};workflow()} ``` #### Example response Response 200 — OK 304 — Not Modified 400 — Bad Request 401 — Unauthorized 429 — Too Many Requests 500 — Internal Server Error Example Successful request ```json { "records_found": 2, "total_records": 3, "has_more": true, "list_type": "workspace_log", "list_data": [ { "id": 67890, "log_entry_created_timestamp": "2030-01-02T17:04:05Z", "actor_user_id": "11111111-2222-4333-8444-555555555555", "actor_display_name": "Alex Morgan", "log_entry": "Alex Morgan completed the Task: Confirm booth artwork.", "event_id": 5001, "event_name": "Spring Expo 2030", "event_tab_id": 8, "task_id": 701, "task_name": "Confirm booth artwork", "asset_id": null, "asset_name": null, "storage_location_id": null, "storage_location_name": null }, { "id": 67891, "log_entry_created_timestamp": "2030-01-02T17:04:06Z", "actor_user_id": "66666666-7777-4888-8999-000000000000", "actor_display_name": "Jordan Lee", "log_entry": "Jordan Lee updated the Storage Location notes.", "event_id": null, "event_name": null, "event_tab_id": 0, "task_id": null, "task_name": null, "asset_id": 801, "asset_name": "Event display kit", "storage_location_id": 901, "storage_location_name": "Main warehouse" } ] } ``` Note: First activity page. Two illustrative entries from a time-window search. A third matching entry remains on the next page. Note: There is no response body. Keep using your cached response. ```json { "status_code": 400, "status": "Bad Request", "message": "HTTP method override is not supported.", "error_code": "invalid_request", "errors": [ "Send the documented HTTP method directly. X-HTTP-Method-Override cannot change a request's HTTP method." ], "error_params": [ "X-HTTP-Method-Override" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "No API key was provided. Send your key in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "missing_api_key", "errors": [ "Copy the key from Workspace Settings > API & Integrations > API Access in ExhibitDay." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "The API key is not valid. Check that you copied the whole key from Workspace Settings > API & Integrations > API Access, then send it in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "invalid_api_key", "errors": [ "Check that you sent the whole key. If it was regenerated, use the current key from Workspace Settings > API & Integrations > API Access." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "Access to the ExhibitDay API is not enabled for your workspace. Please contact support@exhibitday.com to enable API Access. Once access is enabled, send your key in the Authorization header as 'Bearer YOUR_API_KEY'.", "error_code": "api_access_disabled", "errors": [ "Nothing was read or changed." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 429, "status": "Too Many Requests", "message": "Error 429 - Too Many Requests", "error_code": "rate_limited", "errors": [ "Error 429 - Too Many Requests" ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "An unexpected error occurred. Please try again later." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` Note: Use the request_id from your own response when contacting support. ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "Check whether your change was saved before trying again." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` #### Things to keep in mind - **Manual example:** To look for a particular actor, add `filter_by_actor_user_id` with the actor's user ID as text. The complete program does not send this filter. Entries recorded by the API have a `null` `actor_user_id`, so this filter can't select them; identify them by `actor_display_name`. See the linked endpoint for other filters and sort choices. - Use an explicit time-zone offset in each time filter. Responses show whole seconds. The upper time bound includes the displayed second. A fractional lower bound starts at the next whole second. - Offset pages are separate reads. Changes during a run can move page boundaries. The program remembers IDs during the current run to skip duplicates. Keep the IDs in your own records if you need to reconcile multiple runs. - The log records activity text and available associations. It may omit some changes and does not provide complete before-and-after values. #### Related guides - [Get a Complete List of Attendees, Travel and More](https://api.exhibitday.com/Help/V1?guide=find-filter-page) - [Keep Another System Updated with Event and Task Changes](https://api.exhibitday.com/Help/V1?guide=sync-changes) ### Keep Another System Updated with Event and Task Changes Guide page: https://api.exhibitday.com/Help/V1?guide=sync-changes Keep a copy of your Events and Tasks in another system, refreshed with only what changed. Example use case Another system needs a local copy of your ExhibitDay Events and Tasks. What you'll end up with A JSON mirror for each record type and separate checkpoints for the next run. Before you start Have a workspace API key and choose a local directory. Keep the same workspace API key, filters and access scope throughout a sync. Good to know A checkpoint includes records updated at that exact time. Save each returned record by ID so processing it again replaces the previous entry. #### At a glance Time to try About 10 minutes Effect on your data Read-only Endpoints 2 Reads Events and Tasks. The program writes local mirror and checkpoint files. A small workspace takes about 10 minutes. - [`GET /v1/events`](https://api.exhibitday.com/Help/V1?epf=1#get-v1-events) - [`GET /v1/tasks`](https://api.exhibitday.com/Help/V1?epf=2#get-v1-tasks) #### How it works 1. Read every page of Events and Tasks on the first run. 2. Save each record by ID and keep a separate checkpoint for Events and for Tasks. 3. On later runs, read records updated at or after each checkpoint and replace their saved entries. 4. Save each local copy before moving its checkpoint forward. #### Read, save and refresh Steps 1 and 2 are for your first run. Steps 3 and 4 use the saved checkpoints on later runs. Each response below shows only the fields needed for paging and checkpoints. #### Step 1: Read all matching Events Start at offset zero and read every page to build your first Event mirror. ```bash curl -X GET "https://api.exhibitday.com/v1/events?%24limit=100&%24offset=0" -H "Authorization: Bearer YOUR_API_KEY" ``` **Example response (shortened)** ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_data": [ { "id": 12345, "event_last_update_timestamp": "2026-11-21T17:00:00Z" } ] } ``` **Check:** Use records_found to advance the offset and stop when has_more is false. total_records counts all matching Events before paging. #### Step 2: Read all matching Tasks Page through Tasks separately so the Task mirror can keep its own checkpoint. ```bash curl -X GET "https://api.exhibitday.com/v1/tasks?%24limit=100&%24offset=0" -H "Authorization: Bearer YOUR_API_KEY" ``` **Example response (shortened)** ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_data": [ { "id": 12345, "task_last_update_timestamp": "2026-11-21T17:00:00Z" } ] } ``` **Check:** Save or replace each Task by id. Finish and save the Task mirror before storing the latest task_last_update_timestamp. #### Step 3: Refresh Events on the next run Send the saved Event checkpoint to read Events updated at or after that time. ```bash curl -X GET "https://api.exhibitday.com/v1/events?%24limit=100&%24offset=0&filter_by_last_update_timestamp_greater_than_or_equal_to=2026-11-21T17%3A00%3A00Z" -H "Authorization: Bearer YOUR_API_KEY" ``` **Example response (shortened)** ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_data": [ { "id": 12345, "event_last_update_timestamp": "2026-11-21T17:00:00Z" } ] } ``` **Check:** Upsert every returned id, even at the exact boundary. Finish and save the Event mirror before advancing the Event checkpoint. #### Step 4: Refresh Tasks on the next run Use the separate Task checkpoint to refresh the Task mirror. ```bash curl -X GET "https://api.exhibitday.com/v1/tasks?%24limit=100&%24offset=0&filter_by_last_update_timestamp_greater_than_or_equal_to=2026-11-21T17%3A00%3A00Z" -H "Authorization: Bearer YOUR_API_KEY" ``` **Example response (shortened)** ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_data": [ { "id": 12345, "task_last_update_timestamp": "2026-11-21T17:00:00Z" } ] } ``` **Check:** Treat the timestamp as inclusive and save the Task mirror before advancing its checkpoint. #### Try it #### Before running the example | Variable | What to put in it | Required? | | --- | --- | --- | | `EXHIBITDAY_API_KEY` | Your workspace API key. | Yes | | `EXHIBITDAY_SYNC_DIR` | A directory for the mirrors and checkpoints. Defaults to the current directory. | No | **Note.** This example only reads data. It writes the two local mirrors and the checkpoint file. #### Bash ``` export EXHIBITDAY_API_KEY='YOUR_API_KEY' export EXHIBITDAY_SYNC_DIR='./exhibitday-sync' ``` #### PowerShell ``` $env:EXHIBITDAY_API_KEY = 'YOUR_API_KEY' $env:EXHIBITDAY_SYNC_DIR = './exhibitday-sync' ``` Then copy the complete example program below in your language and run it. #### Complete example program Code Samples ```bash #!/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 http.client 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\":{\"events\":{\"method\":\"GET\",\"path\":\"/events\"},\"tasks\":{\"method\":\"GET\",\"path\":\"/tasks\"}}}") 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) # curl may leave no output file for a valid bodyless304 response. (folder / "body").write_bytes(b"") 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 = {"Authorization": "Bearer " + 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, 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 = 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) directory = Path(os.environ.get("EXHIBITDAY_SYNC_DIR", ".")) directory.mkdir(parents=True, exist_ok=True) state_path = directory / "exhibitday-sync-state.json" state = load_json(state_path, {}) for entity, timestamp in [("events", "event_last_update_timestamp"), ("tasks", "task_last_update_timestamp")]: since = state.get(entity) params = {"filter_by_last_update_timestamp_greater_than_or_equal_to": since} if since else {} mirror_path = directory / ("exhibitday-" + entity + ".json") mirror = load_json(mirror_path, {}) latest, processed = since, 0 for record in pages(entity, params): # Always upsert inclusive-boundary rows: the same id/time can contain a later edit. mirror[str(record["id"])] = record stamp = record[timestamp] if latest is None or stamp > latest: latest = stamp processed += 1 save_json(mirror_path, mirror) # persist data BEFORE moving this entity's checkpoint if latest: state[entity] = latest save_json(state_path, state) print(entity, processed, "rows processed; cursor", latest) # Incremental lists do not report deletions. Reconcile full current IDs separately. EXHIBITDAY_PY ``` ```javascript // 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\":{\"events\":{\"method\":\"GET\",\"path\":\"/events\"},\"tasks\":{\"method\":\"GET\",\"path\":\"/tasks\"}}}"); 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 = { Authorization: "Bearer " + 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 directory = process.env.EXHIBITDAY_SYNC_DIR || "."; fs.mkdirSync(directory, { recursive: true }); const stateFile = path.join(directory, "exhibitday-sync-state.json"); const state = loadJson(stateFile, {}); for (const [entity, timestamp] of [["events", "event_last_update_timestamp"], ["tasks", "task_last_update_timestamp"]]) { const since = state[entity]; const params = since ? { filter_by_last_update_timestamp_greater_than_or_equal_to: since } : {}; const file = path.join(directory, "exhibitday-" + entity + ".json"); const mirror = loadJson(file, {}); let latest = since || null, processed = 0; for await (const record of pages(entity, params)) { // Reprocess inclusive-boundary rows; stable-id upsert cannot create duplicates. mirror[String(record.id)] = record; if (latest === null || record[timestamp] > latest) latest = record[timestamp]; processed++; } saveJson(file, mirror); // data first, checkpoint second if (latest) state[entity] = latest; saveJson(stateFile, state); console.log(entity, processed, "rows processed; cursor", latest); } // Incremental responses do not contain deletions; reconcile full current IDs separately. } const completion = main(); completion.catch(error => { console.error(error.message); process.exitCode = 1; }); ``` ```python # Python 3; standard library only. Set EXHIBITDAY_API_KEY before running. import csv import datetime import http.client 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\":{\"events\":{\"method\":\"GET\",\"path\":\"/events\"},\"tasks\":{\"method\":\"GET\",\"path\":\"/tasks\"}}}") 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 = {"Authorization": "Bearer " + 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, 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 = 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) directory = Path(os.environ.get("EXHIBITDAY_SYNC_DIR", ".")) directory.mkdir(parents=True, exist_ok=True) state_path = directory / "exhibitday-sync-state.json" state = load_json(state_path, {}) for entity, timestamp in [("events", "event_last_update_timestamp"), ("tasks", "task_last_update_timestamp")]: since = state.get(entity) params = {"filter_by_last_update_timestamp_greater_than_or_equal_to": since} if since else {} mirror_path = directory / ("exhibitday-" + entity + ".json") mirror = load_json(mirror_path, {}) latest, processed = since, 0 for record in pages(entity, params): # Always upsert inclusive-boundary rows: the same id/time can contain a later edit. mirror[str(record["id"])] = record stamp = record[timestamp] if latest is None or stamp > latest: latest = stamp processed += 1 save_json(mirror_path, mirror) # persist data BEFORE moving this entity's checkpoint if latest: state[entity] = latest save_json(state_path, state) print(entity, processed, "rows processed; cursor", latest) # Incremental lists do not report deletions. Reconcile full current IDs separately. ``` ```csharp // .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\":{\"events\":{\"method\":\"GET\",\"path\":\"/events\"},\"tasks\":{\"method\":\"GET\",\"path\":\"/tasks\"}}}"); 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 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(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 Call(string name, JsonObject query = null, JsonNode body = null, Dictionary extraHeaders = null, string key = null) { var route = Spec["requests"][name]; var method = Text(route["method"]); var headers = new Dictionary(extraHeaders ?? new Dictionary(), StringComparer.OrdinalIgnoreCase) { ["Authorization"] = "Bearer " + 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 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()) 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 directory = Environment.GetEnvironmentVariable("EXHIBITDAY_SYNC_DIR") ?? "."; Directory.CreateDirectory(directory); var stateFile = Path.Combine(directory, "exhibitday-sync-state.json"); var state = Load(stateFile); foreach (var entry in new[] { ("events", "event_last_update_timestamp"), ("tasks", "task_last_update_timestamp") }) { var since = Text(state[entry.Item1]); var query = since.Length == 0 ? new JsonObject() : Query(("filter_by_last_update_timestamp_greater_than_or_equal_to", since)); var file = Path.Combine(directory, "exhibitday-" + entry.Item1 + ".json"); var mirror = Load(file); var latest = since; var count = 0; await foreach (var row in Pages(entry.Item1, query)) { mirror[Text(row["id"])] = row.DeepClone(); // inclusive-boundary upsert, never skip a newer same-id payload var stamp = Text(row[entry.Item2]); if (string.CompareOrdinal(stamp, latest) > 0) latest = stamp; count++; } Save(file, mirror); // data first, checkpoint second if (latest.Length > 0) state[entry.Item1] = latest; Save(stateFile, state); Console.WriteLine($"{entry.Item1}: {count} rows processed; cursor {latest}"); } // Incremental lists omit deletions; reconcile full current IDs separately. } } ``` ```java // 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 SPEC = JSON.fromJson("{\"preserveNumbers\":false,\"requests\":{\"events\":{\"method\":\"GET\",\"path\":\"/events\"},\"tasks\":{\"method\":\"GET\",\"path\":\"/tasks\"}}}", 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 body; Map headers; Result(int s, Map b, Map 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 obj(Object value) {return value==null?new LinkedHashMap<>(): (Map)value;} @SuppressWarnings("unchecked") static List list(Object value) {return value==null?Collections.emptyList():(List)value;} static Map map(Object... pairs) {Map result=new LinkedHashMap<>();for(int i=0;i query,Object body,Map extra,String key) { Map route=obj(obj(SPEC.get("requests")).get(name));String method=text(route.get("method")); Map headers=map("Authorization","Bearer " + 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 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 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 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> pages(String name,Map parameters) { return ()->new Iterator>() { int offset=0;boolean more=true;Iterator rows=Collections.emptyIterator(); public boolean hasNext() { while(!rows.hasNext()&&more) { Map query=new LinkedHashMap<>();if(parameters!=null)query.putAll(parameters); query.put("$limit",100);query.put("$offset",offset); Map 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 next(){if(!hasNext())throw new NoSuchElementException();return obj(rows.next());} }; } static Map 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 { Path directory=Paths.get(env("EXHIBITDAY_SYNC_DIR","."));Files.createDirectories(directory); Path stateFile=directory.resolve("exhibitday-sync-state.json");Map state=load(stateFile); for(String[] entity:new String[][]{{"events","event_last_update_timestamp"},{"tasks","task_last_update_timestamp"}}) { String since=text(state.get(entity[0]));Map query=new LinkedHashMap<>(); if(!since.isEmpty())query.put("filter_by_last_update_timestamp_greater_than_or_equal_to",since); Path file=directory.resolve("exhibitday-"+entity[0]+".json");Map mirror=load(file); String latest=since;int count=0; for(Map row:pages(entity[0],query)) { mirror.put(text(row.get("id")),row); // inclusive-boundary upsert, not a discard by id/time String stamp=text(row.get(entity[1]));if(stamp.compareTo(latest)>0)latest=stamp;count++; } save(file,mirror); // data first, checkpoint second if(!latest.isEmpty())state.put(entity[0],latest);save(stateFile,state); System.out.println(entity[0]+": "+count+" rows processed; cursor "+latest); } // Incremental lists omit deletions; reconcile full current IDs separately. } } ``` ```php $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(['Authorization' => 'Bearer ' . $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); } } $directory = optional('EXHIBITDAY_SYNC_DIR', '.'); if (!is_dir($directory) && !mkdir($directory, 0777, true) && !is_dir($directory)) { throw new RuntimeException('Unable to create sync directory'); } $statePath = $directory . DIRECTORY_SEPARATOR . 'exhibitday-sync-state.json'; $state = loadJson($statePath, []); foreach (['events' => 'event_last_update_timestamp', 'tasks' => 'task_last_update_timestamp'] as $entity => $timestamp) { $since = $state[$entity] ?? null; $params = $since === null ? [] : ['filter_by_last_update_timestamp_greater_than_or_equal_to' => $since]; $mirrorPath = $directory . DIRECTORY_SEPARATOR . 'exhibitday-' . $entity . '.json'; $mirror = loadJson($mirrorPath, []); $latest = $since; $processed = 0; foreach (pages($entity, $params) as $record) { // Always upsert inclusive-boundary rows: the same id/time may contain a later edit. $mirror[(string)$record['id']] = $record; $stamp = $record[$timestamp]; if ($latest === null || strcmp($stamp, $latest) > 0) $latest = $stamp; $processed++; } saveJson($mirrorPath, (object)$mirror); // Data is durable BEFORE this entity's checkpoint moves. if ($latest !== null && $latest !== '') $state[$entity] = $latest; saveJson($statePath, (object)$state); echo $entity, ': ', $processed, ' rows processed; cursor ', $latest ?? '(none)', PHP_EOL; } // Incremental lists do not report deletions. Reconcile full current IDs separately. ``` ```ruby # 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":{"events":{"method":"GET","path":"/events"},"tasks":{"method":"GET","path":"/tasks"}}}') 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 = { 'Authorization' => 'Bearer ' + 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 directory = ENV.fetch('EXHIBITDAY_SYNC_DIR', '.') FileUtils.mkdir_p(directory) state_path = File.join(directory, 'exhibitday-sync-state.json') state = load_json(state_path, {}) [['events', 'event_last_update_timestamp'], ['tasks', 'task_last_update_timestamp']].each do |entity, timestamp| since = state[entity] params = since.nil? ? {} : { 'filter_by_last_update_timestamp_greater_than_or_equal_to' => since } mirror_path = File.join(directory, "exhibitday-#{entity}.json") mirror = load_json(mirror_path, {}) latest, processed = since, 0 pages(entity, params).each do |record| # Re-upsert inclusive-boundary rows: the same ID/time can contain a later edit. mirror[record.fetch('id').to_s] = record stamp = record.fetch(timestamp) latest = stamp if latest.nil? || stamp > latest processed += 1 end save_json(mirror_path, mirror) # Persist rows BEFORE advancing this entity's checkpoint. state[entity] = latest unless latest.nil? save_json(state_path, state) puts "#{entity}: #{processed} rows processed; cursor #{latest}" end # Incremental lists do not report deletions. Reconcile full current IDs separately. ``` ```go // Go 1.18+; standard library only. Set EXHIBITDAY_API_KEY. package main import ( "bytes" "path/filepath" "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\":{\"events\":{\"method\":\"GET\",\"path\":\"/events\"},\"tasks\":{\"method\":\"GET\",\"path\":\"/tasks\"}}}" 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{"Authorization": "Bearer " + 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<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)<= 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)} directory:=os.Getenv("EXHIBITDAY_SYNC_DIR");if directory=="" {directory="."} if err:=os.MkdirAll(directory,0700);err!=nil {panic(err)} stateFile:=filepath.Join(directory,"exhibitday-sync-state.json");state:=load(stateFile) for _,entity:=range []struct{name,stamp string}{{"events","event_last_update_timestamp"},{"tasks","task_last_update_timestamp"}} { since:=text(state[entity.name]);query:=map[string]string{} if since!="" {query["filter_by_last_update_timestamp_greater_than_or_equal_to"]=since} file:=filepath.Join(directory,"exhibitday-"+entity.name+".json");mirror:=load(file);latest:=since;count:=0 pages(entity.name,query,func(row map[string]any){ mirror[text(row["id"])]=row // inclusive-boundary upsert, never discard a newer same-id payload if stamp:=text(row[entity.stamp]);stamp>latest {latest=stamp};count++ }) save(file,mirror) // data first, checkpoint second if latest!="" {state[entity.name]=latest};save(stateFile,state) fmt.Println(entity.name,count,"rows processed; cursor",latest) } // Incremental lists omit deletions; reconcile full current IDs separately. } ``` #### Example response Response 200 — OK 304 — Not Modified 400 — Bad Request 401 — Unauthorized 409 — Conflict 429 — Too Many Requests 500 — Internal Server Error Example Successful request ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "event", "list_data": [ { "id": 12345, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=12345", "name": "Sample Event", "start_date": "2026-12-21", "end_date": "2026-12-23", "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, "booth_reservation_cost": { "amount": 125.50, "cost_center_breakdown": [ { "cost_center_id": 34567, "cost_center": "Marketing", "charge": 75.50 }, { "cost_center_id": 34568, "cost_center": "Operations", "charge": 50.00 } ] }, "cost_booth_reservation": 125.50, "booth_reservation_payment_status_id": 0, "booth_reservation_payment_status": "", "booth_reservation_payment_due_date": null, "booth_reservation_next_payment_due_date": null, "booth_reservation_payment_notes": null, "booth_reservation_invoice_attachment": { "id": 182345, "filename": "booth-reservation-invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" }, "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": 125.50, "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, "roo_score": null, "event_created_timestamp": "2026-11-21T17:00:00Z", "event_last_update_timestamp": "2026-11-21T17:00:00Z", "event_created_by": { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, "custom_fields": null, "task_sections": null, "tasks": null, "misc_expenses_credits": null, "integration_metadata_field_1": "", "integration_metadata_field_2": "", "integration_metadata_field_3": "", "integration_metadata_field_4": "", "integration_metadata_field_5": "" } ] } ``` Note: This is the first Event page on a first run. The program saves the records in a local mirror. It reads Task pages separately. Note: There is no response body. Keep using your cached response. ```json { "status_code": 400, "status": "Bad Request", "message": "HTTP method override is not supported.", "error_code": "invalid_request", "errors": [ "Send the documented HTTP method directly. X-HTTP-Method-Override cannot change a request's HTTP method." ], "error_params": [ "X-HTTP-Method-Override" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "No API key was provided. Send your key in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "missing_api_key", "errors": [ "Copy the key from Workspace Settings > API & Integrations > API Access in ExhibitDay." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "The API key is not valid. Check that you copied the whole key from Workspace Settings > API & Integrations > API Access, then send it in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "invalid_api_key", "errors": [ "Check that you sent the whole key. If it was regenerated, use the current key from Workspace Settings > API & Integrations > API Access." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "Access to the ExhibitDay API is not enabled for your workspace. Please contact support@exhibitday.com to enable API Access. Once access is enabled, send your key in the Authorization header as 'Bearer YOUR_API_KEY'.", "error_code": "api_access_disabled", "errors": [ "Nothing was read or changed." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "The invoice attachment or its owning record changed or has conflicting saved information. Retrieve the current record before retrying.", "error_code": "record_changed", "errors": [ "The invoice attachment or its owning record changed or has conflicting saved information. Retrieve the current record before retrying." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "The Booth Reservation payment information changed or has an unsupported saved status. Retrieve the current Event before retrying.", "error_code": "record_changed", "errors": [ "The Booth Reservation payment information changed or has an unsupported saved status. Retrieve the current Event before retrying." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "The Event objective score changed or could not be read consistently. Retrieve the Event before retrying.", "error_code": "record_changed", "errors": [ "The Event objective score changed or could not be read consistently. Retrieve the Event before retrying." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 429, "status": "Too Many Requests", "message": "Error 429 - Too Many Requests", "error_code": "rate_limited", "errors": [ "Error 429 - Too Many Requests" ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "An unexpected error occurred. Please try again later." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` Note: Use the request_id from your own response when contacting support. ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "Check whether your change was saved before trying again." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` The output reports how many rows were processed and the checkpoint for each record type. The curl workflow uses Bash, curl and Python 3. Use Node.js 18 or later with a .cjs file, a .NET 8 console project for C#, or Java 11 or later with Gson 2.14.0 on both classpaths. PHP needs 8.1 or later with cURL. Ruby 3.1 or later and Go 1.18 or later use their standard libraries. #### Things to keep in mind - Each page is a separate read. Updates during the run can move records between pages. Periodically compare your copy with a complete list of current IDs using the same filters and access. - A record missing from a changes-only run may still exist. Before removing it from your copy, confirm it is missing from a complete scan using the same filters and access. Use `$return_event_lites=true` for a smaller Event response during that scan. - Let your HTTP library encode query parameters. Encode `$` as `%24` in hand-written URLs. - The same inclusive timestamp pattern applies to Task comments and Event miscellaneous expenses and credits. Each has its own last-update field and checkpoint. - If you copy people from Events or Tasks, such as `task_created_by`, match them by `id`. Changes made through the API or Zapier show a person with an `id` of `null`. Identify these by `display_name`: `"ExhibitDay API"` or `"ExhibitDay API (Zapier)"`. #### If a run stops - Keep the latest timestamp for each record type exactly as returned. - If the program stops before saving a checkpoint, run it again with the same local directory. It can read those changes again and replace records by ID. #### Related guides - [Get a Complete List of Attendees, Travel and More](https://api.exhibitday.com/Help/V1?guide=find-filter-page) - [Handle Errors and Retry Failed Requests](https://api.exhibitday.com/Help/V1?guide=errors-and-retries) ### Record Costs and Split Them Across Cost Centers Guide page: https://api.exhibitday.com/Help/V1?guide=entering-costs Record a cost on a record, and optionally split it across cost centers. Example use case You receive a bill for a Booth Service and want to record the total or divide it between cost centers. What you'll end up with A saved cost on the Booth Service, with an allocation if you choose to send one. Before you start Have a workspace API key and identify a Booth Service you can edit. If you want to split the cost, confirm the cost centers in that workspace. Good to know Amounts are in the workspace currency. Enter numbers without currency symbols. #### At a glance Time to try About 10 minutes Effect on your data Updates records Endpoints 2 The runnable request immediately replaces the Booth Service's saved cost and allocation. - [`GET /v1/references/cost_centers`](https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-cost_centers) - [`PATCH /v1/events/booth_services`](https://api.exhibitday.com/Help/V1?epf=1&topic=booth-services#patch-v1-events-booth_services) #### How it works 1. Choose an existing Booth Service and an amount in your workspace currency. 2. Send the amount to replace the saved total and allocation. 3. To split the total, look up a cost center and send the complete breakdown instead. #### Record the amount and allocation The runnable example saves a single total in Step 2. Steps 1 and 3 show how to split the total if you need an allocation. #### Step 1: Find the cost center for a split Read the workspace's cost centers and choose the one that should receive part of the cost. **Manual example.** This request is separate from the runnable example below. ```bash curl -X GET "https://api.exhibitday.com/v1/references/cost_centers" -H "Authorization: Bearer YOUR_API_KEY" ``` **Example response** ```json [ { "id": 12345, "name": "Marketing" } ] ``` **Check:** Use the selected cost center's id from your workspace. Use null for any share marked Not Specified. #### Step 2: Record a single amount Send cost with an amount to set the Booth Service total in your workspace currency. ```bash curl -X PATCH "https://api.exhibitday.com/v1/events/booth_services" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" --data-binary "{\"id\":12345,\"cost\":{\"amount\":125.50}}" ``` **Example response** ```json { "status_code": 200, "status": "OK", "message": "Booth Service updated.", "errors": [] } ``` **Check:** A successful update confirms the request was saved. A single total goes under Not Specified where cost centers are supported. #### Step 3: Replace the amount with a split Send the complete breakdown so ExhibitDay records the amount assigned to each cost center. **Manual example.** This request is separate from the runnable example below. ```bash curl -X PATCH "https://api.exhibitday.com/v1/events/booth_services" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" --data-binary "{\"id\":12345,\"cost\":{\"amount\":1000,\"cost_center_breakdown\":[{\"cost_center_id\":12345,\"charge\":600},{\"cost_center_id\":null,\"charge\":400}]}}" ``` **Example response** ```json { "status_code": 200, "status": "OK", "message": "Booth Service updated.", "errors": [] } ``` **Check:** The charges add to 1,000. If you supply amount, it must equal the sum after rounding to cents. **Careful.** Sending a cost replaces the saved total and allocation. Read the current record before trying again after a timeout or an uncertain response. #### Choose how to send the cost | To do this | What to send | | --- | --- | | Set only the total | Send `cost` as a number or as an object with `amount`. Both put the total under Not Specified where cost centers are supported. | | Split the total | Send the complete `cost_center_breakdown`. The API adds the charges. If you also send `amount`, it must match the sum after rounding to cents. Charges must be nonnegative, except on a Misc. credit (see below), and stay within the endpoint's limits. | | Keep the saved cost | Omit `cost` on PATCH. | | Clear the saved cost | Use `0` or an empty breakdown. JSON `null` clears the cost unless `$ignore_params_with_empty_values=true` tells the update to ignore it. Blank input follows the endpoint's empty-value rules. | #### Try it #### Before running the example | Variable | What to put in it | Required? | | --- | --- | --- | | `YOUR_API_KEY` | Replace this placeholder in the example with your workspace API key. | Yes | | `id` | Replace 12345 in the request with the corresponding ID you can edit. | Yes | | `cost` | The sample uses 125.50. Replace it with the amount you want to save. | Yes | **Careful.** This example changes data in your workspace. Use a test Booth Service. Running it replaces the saved cost and allocation. Then copy the complete request example below in your language and run it when you are ready to save the cost. #### Complete request examples Code Samples ```bash curl -X PATCH "https://api.exhibitday.com/v1/events/booth_services" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"id\":12345,\"cost\":{\"amount\":125.50}}" ``` ```javascript const response = await fetch("https://api.exhibitday.com/v1/events/booth_services", { method: "PATCH", headers: { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, body: JSON.stringify({ "id": 12345, "cost": {"amount":125.50} }) }); const data = await response.json(); console.log(response.status, data); ``` ```python import requests import json response = requests.patch( "https://api.exhibitday.com/v1/events/booth_services", headers={"Authorization": "Bearer YOUR_API_KEY"}, json={"id": 12345, "cost": json.loads("{\"amount\":125.50}")}, ) print(response.status_code, response.json()) ``` ```csharp using System; using System.Text.Json; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); var response = await client.PatchAsync("https://api.exhibitday.com/v1/events/booth_services", JsonContent.Create(new { id = 12345, cost = JsonDocument.Parse("{\"amount\":125.50}").RootElement.Clone() })); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); ``` ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class ExhibitDayExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.exhibitday.com/v1/events/booth_services")) .header("Authorization", "Bearer YOUR_API_KEY") .header("Content-Type", "application/json") .method("PATCH", HttpRequest.BodyPublishers.ofString("{\"id\":12345,\"cost\":{\"amount\":125.50}}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); } } ``` ```php 'PATCH', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_API_KEY', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => '{"id":12345,"cost":{"amount":125.50}}', ]); $response = curl_exec($curl); if ($response === false) { throw new RuntimeException(curl_error($curl)); } echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . PHP_EOL . $response; curl_close($curl); ``` ```ruby require 'net/http' require 'uri' uri = URI('https://api.exhibitday.com/v1/events/booth_services') request = Net::HTTP::Patch.new(uri) request['Authorization'] = 'Bearer YOUR_API_KEY' request['Content-Type'] = 'application/json' request.body = '{"id":12345,"cost":{"amount":125.50}}' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts "#{response.code} #{response.body}" ``` ```go package main import ( "fmt" "io" "log" "net/http" "strings" ) func main() { request, err := http.NewRequest("PATCH", "https://api.exhibitday.com/v1/events/booth_services", strings.NewReader("{\"id\":12345,\"cost\":{\"amount\":125.50}}")) if err != nil { log.Fatal(err) } request.Header.Set("Authorization", "Bearer YOUR_API_KEY") request.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(request) if err != nil { log.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("%d %s\n", response.StatusCode, body) } ``` #### Example response Response 200 — OK 400 — Bad Request 401 — Unauthorized 404 — Not Found 409 — Conflict 429 — Too Many Requests 500 — Internal Server Error Example Successful request ```json { "status_code": 200, "status": "OK", "message": "Booth Service updated.", "errors": [] } ``` Note: This is the response after saving 125.50 in the workspace currency. Use your own Booth Service ID and amount when you run the request. ```json { "status_code": 400, "status": "Bad Request", "message": "X-HTTP-Method-Override: hTTP method override is not supported.", "error_code": "invalid_request", "errors": [ "Send the documented HTTP method directly. X-HTTP-Method-Override cannot change a request's HTTP method." ], "error_params": [ "X-HTTP-Method-Override" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 400, "status": "Bad Request", "message": "The Booth tab is hidden on this Event, so its records can't be added, changed or deleted. Show the tab in ExhibitDay before trying again.", "error_code": "not_allowed", "errors": [ "The Booth tab is hidden on this Event, so its records can't be added, changed or deleted. Show the tab in ExhibitDay before trying again." ], "error_params": [ "event_id" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "No API key was provided. Send your key in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "missing_api_key", "errors": [ "Copy the key from Workspace Settings > API & Integrations > API Access in ExhibitDay." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "The API key is not valid. Check that you copied the whole key from Workspace Settings > API & Integrations > API Access, then send it in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "invalid_api_key", "errors": [ "Check that you sent the whole key. If it was regenerated, use the current key from Workspace Settings > API & Integrations > API Access." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "Access to the ExhibitDay API is not enabled for your workspace. Please contact support@exhibitday.com to enable API Access. Once access is enabled, send your key in the Authorization header as 'Bearer YOUR_API_KEY'.", "error_code": "api_access_disabled", "errors": [ "Nothing was read or changed." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 404, "status": "Not Found", "message": "Booth Service not found. Invalid Booth Service ID: 12345.", "error_code": "not_found", "errors": [ "Booth Service not found. Invalid Booth Service ID: 12345." ], "error_params": [ "id" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 404, "status": "Not Found", "message": "Booth Service not found. Invalid Booth Service ID: 12345.", "error_code": "not_found", "errors": [ "Booth Service not found. Invalid Booth Service ID: 12345." ], "error_params": [ "id" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "This Booth Service changed since you read it; nothing was changed.", "error_code": "record_changed", "errors": [ "This Booth Service changed since you read it; nothing was changed." ], "error_params": [ "expected_revision" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "The Booth Service or its related scope changed. Read its current state and decide whether to retry; this request was rolled back.", "error_code": "record_changed", "errors": [ "The Booth Service or its related scope changed. Read its current state and decide whether to retry; this request was rolled back." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 429, "status": "Too Many Requests", "message": "Error 429 - Too Many Requests", "error_code": "rate_limited", "errors": [ "Error 429 - Too Many Requests" ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "An unexpected error occurred. Please try again later." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` Note: Use the request_id from your own response when contacting support. ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "Check whether your change was saved before trying again." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` #### Things to keep in mind - Use `cost` on records that support it. For an Event's Booth Reservation, use `booth_reservation_cost` on the Event update. The older `cost_booth_reservation` is a read-only summary. - A readable zero returns a cost object with amount 0. Check the record when the API returns null before treating the amount as zero. - For Annual Miscellaneous Expenses, the breakdown applies to actual costs. The `planned_amount` is a separate budget estimate. - For Assets, send only an amount. - A Misc. Expense or Credit marked as a credit reads back with a negative amount and negative charges. Send either the positive values or the same negative values: both record the same credit. An expense refuses negative values. - You can send a cost back exactly as you read it. Each breakdown line's `cost_center` name is read-only: the API accepts it, ignores it and saves the line by its `cost_center_id`. If the name you send doesn't match that cost center's current name, the response carries a warning that explains what was saved. - If a breakdown names the same cost center more than once, its charges are combined into one share. - If you send older fields with `cost`, make sure both describe the same amount and allocation. - Update payment fields separately where supported. Adding an Invoice Attachment leaves the saved cost and payment status as they were. #### Related guides - [Export Event Costs to Excel or a Reporting Tool](https://api.exhibitday.com/Help/V1?guide=export-event-costs) - [Handle Errors and Retry Failed Requests](https://api.exhibitday.com/Help/V1?guide=errors-and-retries) ### Export Event Costs to Excel or a Reporting Tool Guide page: https://api.exhibitday.com/Help/V1?guide=export-event-costs Save your Event costs to a CSV for Excel, Google Sheets, Power BI or another reporting tool. Example use case Your finance team wants a CSV of the year's Event costs for a report. What you'll end up with A local CSV with one row per returned cost record, including Event, amount and payment information. Before you start Have a workspace API key with access to the Events and their financial data. Good to know Amounts are in your workspace's currency. The API also returns cost-center allocations if your report needs them. #### At a glance Time to try About 10 minutes Effect on your data Read-only Endpoints 1 Read-only in ExhibitDay. The program creates or replaces a local CSV. - [`GET /v1/financials/event_costs`](https://api.exhibitday.com/Help/V1?epf=4&topic=event-costs#get-v1-financials-event_costs) #### How it works 1. Choose the year the Events start. The program uses the current year by default. 2. Read every page of Event costs for that year. 3. Write one row per cost record to a local CSV. #### Read each page of costs Start with the first page. Use Step 2 only when the response says more pages are available. #### Step 1: Read the first page of costs Filter by the year the Events start, with an offset of zero, to begin the export. ```bash curl -X GET "https://api.exhibitday.com/v1/financials/event_costs?filter_by_event_start_date_category=2026&%24limit=100&%24offset=0" -H "Authorization: Bearer YOUR_API_KEY" ``` **Example response (shortened)** ```json { "list_data": [ { "event": { "id": 12345, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=12345", "name": "Sample Event", "start_date": "2026-11-20", "end_date": "2026-11-22", "participation_type_id": 1, "participation_type": "Committed", "format_id": 1, "format": "In-Person", "event_created_timestamp": "2026-11-21T17:00:00Z", "event_last_update_timestamp": "2026-11-21T17:00:00Z" }, "cost_type": "Miscellaneous Expense/Credit", "cost_subtype": null, "amount": 125.5, "payment_status": { "id": 0, "name": "Not Specified" } } ], "records_found": 1, "has_more": false } ``` **Check:** The response has `list_data`, the number of records in this page in `records_found` and the `has_more` flag. The excerpt shows which nested values supply Event and payment columns. #### Step 2: Read the remaining pages If `has_more` is true, add `records_found` to your current offset so the next request starts after the records you just received. For example, if a larger export returned 100 records in its first page, its next request would look like this. ```bash curl -X GET "https://api.exhibitday.com/v1/financials/event_costs?filter_by_event_start_date_category=2026&%24limit=100&%24offset=100" -H "Authorization: Bearer YOUR_API_KEY" ``` **Example response (shortened)** ```json { "records_found": 1, "has_more": false } ``` **Check:** Save the rows from every page, including the last one. Stop when `has_more` is false. #### Try it #### Before running the example | Variable | What to put in it | Required? | | --- | --- | --- | | `EXHIBITDAY_API_KEY` | Your workspace API key. | Yes | | `EXHIBITDAY_YEAR` | The Event start year. The default is the current year. | No | | `EXHIBITDAY_CSV` | The local output path. The default is `event-costs-YEAR.csv`, where YEAR is the selected year. | No | **Note.** This example only reads data. It creates or replaces a local CSV, so choose a new output path to keep an existing file. If the run stops before it reports completion, the CSV may be incomplete. #### Bash ``` export EXHIBITDAY_API_KEY='YOUR_API_KEY' ``` #### PowerShell ``` $env:EXHIBITDAY_API_KEY = 'YOUR_API_KEY' ``` Then copy the complete example program below in your language and run it. #### Complete example program Code Samples ```bash #!/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 http.client 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\":true,\"requests\":{\"costs\":{\"method\":\"GET\",\"path\":\"/financials/event_costs\"}}}") 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) # curl may leave no output file for a valid bodyless304 response. (folder / "body").write_bytes(b"") 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 = {"Authorization": "Bearer " + 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, 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 = 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) year = os.environ.get("EXHIBITDAY_YEAR", str(datetime.date.today().year)) path = Path(os.environ.get("EXHIBITDAY_CSV", "event-costs-" + year + ".csv")) columns = ["event_id", "event_name", "event_start_date", "cost_type", "cost_subtype", "details", "amount", "payment_status", "payment_due_date"] count = 0 with path.open("w", newline="", encoding="utf-8-sig") as file: writer = csv.writer(file) writer.writerow(columns) for cost in pages("costs", {"filter_by_event_start_date_category": year}): event = cost["event"] writer.writerow([event["id"], event["name"], event.get("start_date"), cost.get("cost_type"), cost.get("cost_subtype"), cost.get("details"), cost.get("amount"), (cost.get("payment_status") or {}).get("name", ""), cost.get("payment_due_date")]) count += 1 print("Saved", count, "cost lines to", path) # Numeric response tokens remain strings in this guide: signed decimal values are not rounded through float. EXHIBITDAY_PY ``` ```javascript // 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\":true,\"requests\":{\"costs\":{\"method\":\"GET\",\"path\":\"/financials/event_costs\"}}}"); 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 = { Authorization: "Bearer " + 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 year = process.env.EXHIBITDAY_YEAR || String(new Date().getFullYear()); const file = process.env.EXHIBITDAY_CSV || "event-costs-" + year + ".csv"; const columns = ["event_id", "event_name", "event_start_date", "cost_type", "cost_subtype", "details", "amount", "payment_status", "payment_due_date"]; fs.writeFileSync(file, "\uFEFF" + columns.map(csvCell).join(",") + "\r\n", "utf8"); let count = 0; for await (const cost of pages("costs", { filter_by_event_start_date_category: year })) { const row = [cost.event.id, cost.event.name, cost.event.start_date, cost.cost_type, cost.cost_subtype, cost.details, cost.amount, cost.payment_status?.name, cost.payment_due_date]; fs.appendFileSync(file, row.map(csvCell).join(",") + "\r\n", "utf8"); count++; } console.log("Saved", count, "cost lines to", file); // The cost specification preserves JSON number tokens as strings: no float rounding of signed amounts. } const completion = main(); completion.catch(error => { console.error(error.message); process.exitCode = 1; }); ``` ```python # Python 3; standard library only. Set EXHIBITDAY_API_KEY before running. import csv import datetime import http.client 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\":true,\"requests\":{\"costs\":{\"method\":\"GET\",\"path\":\"/financials/event_costs\"}}}") 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 = {"Authorization": "Bearer " + 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, 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 = 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) year = os.environ.get("EXHIBITDAY_YEAR", str(datetime.date.today().year)) path = Path(os.environ.get("EXHIBITDAY_CSV", "event-costs-" + year + ".csv")) columns = ["event_id", "event_name", "event_start_date", "cost_type", "cost_subtype", "details", "amount", "payment_status", "payment_due_date"] count = 0 with path.open("w", newline="", encoding="utf-8-sig") as file: writer = csv.writer(file) writer.writerow(columns) for cost in pages("costs", {"filter_by_event_start_date_category": year}): event = cost["event"] writer.writerow([event["id"], event["name"], event.get("start_date"), cost.get("cost_type"), cost.get("cost_subtype"), cost.get("details"), cost.get("amount"), (cost.get("payment_status") or {}).get("name", ""), cost.get("payment_due_date")]) count += 1 print("Saved", count, "cost lines to", path) # Numeric response tokens remain strings in this guide: signed decimal values are not rounded through float. ``` ```csharp // .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\":true,\"requests\":{\"costs\":{\"method\":\"GET\",\"path\":\"/financials/event_costs\"}}}"); 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 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(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 Call(string name, JsonObject query = null, JsonNode body = null, Dictionary extraHeaders = null, string key = null) { var route = Spec["requests"][name]; var method = Text(route["method"]); var headers = new Dictionary(extraHeaders ?? new Dictionary(), StringComparer.OrdinalIgnoreCase) { ["Authorization"] = "Bearer " + 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 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()) 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 year = Environment.GetEnvironmentVariable("EXHIBITDAY_YEAR") ?? DateTime.Today.Year.ToString(CultureInfo.InvariantCulture); var file = Environment.GetEnvironmentVariable("EXHIBITDAY_CSV") ?? "event-costs-" + year + ".csv"; using var writer = new StreamWriter(file, false, new UTF8Encoding(true)); writer.WriteLine(string.Join(",", new[] { "event_id", "event_name", "event_start_date", "cost_type", "cost_subtype", "details", "amount", "payment_status", "payment_due_date" }.Select(Csv))); var count = 0; await foreach (var cost in Pages("costs", Query(("filter_by_event_start_date_category", year)))) { var ev = cost["event"]; // JsonNode keeps the original numeric token; do not convert signed amounts through double. var row = new[] { Text(ev["id"]), Text(ev["name"]), Text(ev["start_date"]), Text(cost["cost_type"]), Text(cost["cost_subtype"]), Text(cost["details"]), Text(cost["amount"]), Text(cost["payment_status"]?["name"]), Text(cost["payment_due_date"]) }; writer.WriteLine(string.Join(",", row.Select(Csv))); count++; } Console.WriteLine($"Saved {count} cost lines to {file}"); } } ``` ```java // 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 SPEC = JSON.fromJson("{\"preserveNumbers\":true,\"requests\":{\"costs\":{\"method\":\"GET\",\"path\":\"/financials/event_costs\"}}}", 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 body; Map headers; Result(int s, Map b, Map 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 obj(Object value) {return value==null?new LinkedHashMap<>(): (Map)value;} @SuppressWarnings("unchecked") static List list(Object value) {return value==null?Collections.emptyList():(List)value;} static Map map(Object... pairs) {Map result=new LinkedHashMap<>();for(int i=0;i query,Object body,Map extra,String key) { Map route=obj(obj(SPEC.get("requests")).get(name));String method=text(route.get("method")); Map headers=map("Authorization","Bearer " + 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 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 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 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> pages(String name,Map parameters) { return ()->new Iterator>() { int offset=0;boolean more=true;Iterator rows=Collections.emptyIterator(); public boolean hasNext() { while(!rows.hasNext()&&more) { Map query=new LinkedHashMap<>();if(parameters!=null)query.putAll(parameters); query.put("$limit",100);query.put("$offset",offset); Map 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 next(){if(!hasNext())throw new NoSuchElementException();return obj(rows.next());} }; } static Map 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 year=env("EXHIBITDAY_YEAR",Integer.toString(LocalDate.now().getYear())); Path file=Paths.get(env("EXHIBITDAY_CSV","event-costs-"+year+".csv"));int count=0; try(BufferedWriter writer=Files.newBufferedWriter(file,StandardCharsets.UTF_8)) { writer.write("\uFEFF");writer.write(csvRow("event_id","event_name","event_start_date","cost_type","cost_subtype","details","amount","payment_status","payment_due_date")); for(Map cost:pages("costs",map("filter_by_event_start_date_category",year))) { Map event=obj(cost.get("event")),payment=obj(cost.get("payment_status")); // Gson's LazilyParsedNumber retains the original signed decimal token; no double conversion. writer.write(csvRow(event.get("id"),event.get("name"),event.get("start_date"),cost.get("cost_type"),cost.get("cost_subtype"), cost.get("details"),cost.get("amount"),payment.get("name"),cost.get("payment_due_date")));count++; } } System.out.println("Saved "+count+" cost lines to "+file); } } ``` ```php $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(['Authorization' => 'Bearer ' . $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); } } $year = optional('EXHIBITDAY_YEAR', date('Y')); $path = optional('EXHIBITDAY_CSV', 'event-costs-' . $year . '.csv'); $columns = ['event_id', 'event_name', 'event_start_date', 'cost_type', 'cost_subtype', 'details', 'amount', 'payment_status', 'payment_due_date']; $file = fopen($path, 'wb'); if ($file === false) throw new RuntimeException('Unable to open CSV output'); $count = 0; try { fwrite($file, "\xEF\xBB\xBF"); // UTF-8 BOM for spreadsheet applications. if (fputcsv($file, $columns, ',', '"', '') === false) throw new RuntimeException('Unable to write CSV header'); foreach (pages('costs', ['filter_by_event_start_date_category' => $year]) as $cost) { $event = $cost['event']; $row = [$event['id'], $event['name'], $event['start_date'] ?? '', $cost['cost_type'] ?? '', $cost['cost_subtype'] ?? '', $cost['details'] ?? '', $cost['amount'] ?? '', $cost['payment_status']['name'] ?? '', $cost['payment_due_date'] ?? '']; if (fputcsv($file, $row, ',', '"', '') === false) throw new RuntimeException('Unable to write CSV row'); $count++; } } finally { fclose($file); } echo 'Saved ', $count, ' cost lines to ', $path, PHP_EOL; // Numeric response tokens remain strings; signed decimals never pass through binary float. ``` ```ruby # 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":true,"requests":{"costs":{"method":"GET","path":"/financials/event_costs"}}}') 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 = { 'Authorization' => 'Bearer ' + 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 year = ENV.fetch('EXHIBITDAY_YEAR', Date.today.year.to_s) path = ENV.fetch('EXHIBITDAY_CSV', "event-costs-#{year}.csv") columns = %w[event_id event_name event_start_date cost_type cost_subtype details amount payment_status payment_due_date] count = 0 File.open(path, 'wb') do |file| file.write("\uFEFF") # UTF-8 BOM helps Excel open names and notes correctly. writer = CSV.new(file, row_sep: "\r\n") writer << columns pages('costs', { 'filter_by_event_start_date_category' => year }).each do |cost| event = cost.fetch('event') writer << [event.fetch('id'), event.fetch('name'), event['start_date'], cost['cost_type'], cost['cost_subtype'], cost['details'], cost['amount'], (cost['payment_status'] || {})['name'], cost['payment_due_date']] count += 1 end writer.flush end puts "Saved #{count} cost lines to #{path}" # Numeric JSON tokens remain strings here; signed decimals never pass through float. ``` ```go // Go 1.18+; standard library only. Set EXHIBITDAY_API_KEY. package main import ( "bytes" "encoding/csv" "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\":true,\"requests\":{\"costs\":{\"method\":\"GET\",\"path\":\"/financials/event_costs\"}}}" 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{"Authorization": "Bearer " + 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<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)<= 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)} year:=os.Getenv("EXHIBITDAY_YEAR");if year=="" {year=strconv.Itoa(time.Now().Year())} file:=os.Getenv("EXHIBITDAY_CSV");if file=="" {file="event-costs-"+year+".csv"} output,err:=os.Create(file);if err!=nil {panic(err)};defer output.Close() if _,err=output.WriteString("\uFEFF");err!=nil {panic(err)} writer:=csv.NewWriter(output);writer.UseCRLF=true columns:=[]string{"event_id","event_name","event_start_date","cost_type","cost_subtype","details","amount","payment_status","payment_due_date"} if err=writer.Write(columns);err!=nil {panic(err)};count:=0 pages("costs",map[string]string{"filter_by_event_start_date_category":year},func(cost map[string]any){ event:=object(cost["event"]);payment:=object(cost["payment_status"]) row:=[]string{text(event["id"]),text(event["name"]),text(event["start_date"]),text(cost["cost_type"]),text(cost["cost_subtype"]), text(cost["details"]),text(cost["amount"]),text(payment["name"]),text(cost["payment_due_date"])} if err:=writer.Write(row);err!=nil {panic(err)};count++ }) writer.Flush();if err=writer.Error();err!=nil {panic(err)} fmt.Println("Saved",count,"cost lines to",file) // json.Number retains signed decimal tokens without float conversion. } ``` #### Example response Response 200 — OK 304 — Not Modified 400 — Bad Request 401 — Unauthorized 404 — Not Found 429 — Too Many Requests 500 — Internal Server Error Example Successful request ```json { "records_found": 1, "total_records": 1, "has_more": false, "list_type": "event_cost", "list_data": [ { "id": 12345, "cost_type_id": 6, "cost_type": "Miscellaneous Expense/Credit", "cost_subtype": null, "details": "Sample expense", "cost": { "amount": 125.50, "cost_center_breakdown": [ { "cost_center_id": null, "cost_center": "Not Specified", "charge": 125.50 } ] }, "amount": 125.50, "amount_cost_center_breakdown": [ { "cost_center_id": null, "cost_center": "Not Specified", "charge": 125.50 } ], "payment_due_date": "", "payment_status": { "id": 0, "name": "Not Specified" }, "next_payment_due_date": "", "payment_notes": "", "event": { "id": 12345, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=12345", "name": "Sample Event", "start_date": "2026-11-20", "end_date": "2026-11-22", "participation_type_id": 1, "participation_type": "Committed", "format_id": 1, "format": "In-Person", "event_created_timestamp": "2026-11-21T17:00:00Z", "event_last_update_timestamp": "2026-11-21T17:00:00Z" } } ] } ``` Note: This is the first page of costs for Events that start in the current year. The sample contains one expense. The program converts these records to CSV rows. Note: There is no response body. Keep using your cached response. ```json { "status_code": 400, "status": "Bad Request", "message": "HTTP method override is not supported.", "error_code": "invalid_request", "errors": [ "Send the documented HTTP method directly. X-HTTP-Method-Override cannot change a request's HTTP method." ], "error_params": [ "X-HTTP-Method-Override" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 400, "status": "Bad Request", "message": "Invalid value for parameter filter_by_budget_year. Use a whole budget year from 1754 through 9999.", "error_code": "invalid_request", "errors": [ "Invalid value for parameter filter_by_budget_year. Use a whole budget year from 1754 through 9999." ], "error_params": [ "filter_by_budget_year" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 400, "status": "Bad Request", "message": "Do not combine filter_by_budget_year with filter_by_event_start_date_category. Choose the fiscal budget year or the existing Event date category.", "error_code": "invalid_request", "errors": [ "Do not combine filter_by_budget_year with filter_by_event_start_date_category. Choose the fiscal budget year or the existing Event date category." ], "error_params": [ "filter_by_event_start_date_category", "filter_by_budget_year" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "No API key was provided. Send your key in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "missing_api_key", "errors": [ "Copy the key from Workspace Settings > API & Integrations > API Access in ExhibitDay." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "The API key is not valid. Check that you copied the whole key from Workspace Settings > API & Integrations > API Access, then send it in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "invalid_api_key", "errors": [ "Check that you sent the whole key. If it was regenerated, use the current key from Workspace Settings > API & Integrations > API Access." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "Access to the ExhibitDay API is not enabled for your workspace. Please contact support@exhibitday.com to enable API Access. Once access is enabled, send your key in the Authorization header as 'Bearer YOUR_API_KEY'.", "error_code": "api_access_disabled", "errors": [ "Nothing was read or changed." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 404, "status": "Not Found", "message": "Event not found. Invalid Event ID: 12345.", "error_code": "not_found", "errors": [ "Event not found. Invalid Event ID: 12345." ], "error_params": [ "filter_by_event_id" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 429, "status": "Too Many Requests", "message": "Error 429 - Too Many Requests", "error_code": "rate_limited", "errors": [ "Error 429 - Too Many Requests" ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "An unexpected error occurred. Please try again later." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` Note: Use the request_id from your own response when contacting support. ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "Check whether your change was saved before trying again." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` The program prints the number of cost rows saved and the output path. Import the completed CSV into your reporting tool. The CSV keeps the decimal amounts as returned by the API. The curl workflow uses Bash, curl and Python 3. Node.js needs version 18 or later (save as .cjs). Python uses its standard library. C# needs a .NET 8 console project (Program.cs). Java needs Java 11 or later and Gson 2.14.0 at compile time and runtime (Main.java). PHP needs PHP 8.1 or later with cURL. Ruby 3.1 or later and Go 1.18 or later use their standard libraries. #### Things to keep in mind - **Manual example:** To select one Event, use `filter_by_event_id`. To select a different period, use the endpoint's date filters. The full program uses the year filter. - Each page is a separate read. If records are added or removed during the export, page boundaries can shift. Export during a quiet period or compare the results again if records changed. - Use complete exports to track changes or detect costs that disappeared. Compare the new export with the previous one. - The program exports the total amount per cost record. Use `amount_cost_center_breakdown` from the API when the report needs the individual allocations. #### Related guides - [Get a Complete List of Attendees, Travel and More](https://api.exhibitday.com/Help/V1?guide=find-filter-page) - [Record Costs and Split Them Across Cost Centers](https://api.exhibitday.com/Help/V1?guide=entering-costs) ### Create Tasks from Forms, Tickets or Other Apps Guide page: https://api.exhibitday.com/Help/V1?guide=create-tasks Turn a form, ticket or plan item from another app (for example Google Forms, Zendesk or Jira) into an Event Task. Example use case Someone submits a booth request in another app. Your integration turns it into a Task for the right Event. What you'll end up with A new Event Task and its ID, with an optional Task Section and assignee. Before you start Have a workspace API key and the ID of an Event where you can add Tasks. Replace the example IDs with your own. Good to know Save one `Idempotency-Key` with the exact request for each Task you intend to create. #### At a glance Time to try About 10 minutes Effect on your data Creates records Endpoints 4 Each successful run creates an Event Task. Assigning a Task can queue a notification according to the user's settings. - [`GET /v1/events`](https://api.exhibitday.com/Help/V1?epf=1#get-v1-events) - [`GET /v1/events/info`](https://api.exhibitday.com/Help/V1?epf=1#get-v1-events-info) - [`GET /v1/references/users_and_resources`](https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-users_and_resources) - [`POST /v1/tasks`](https://api.exhibitday.com/Help/V1?epf=2#post-v1-tasks) #### How it works 1. Confirm the Event ID and read its Task Sections so you can check a section ID if you use one. 2. If you supply an assignee, confirm that the user can be assigned Tasks. 3. Create the Event Task and print its ID and name. Keep the ID with the original form or ticket. #### Check the details and create the Task These steps use an Event that already exists. Step 3 applies only if you supply an assignee. #### Step 1: Confirm the Event ID Filter the Events list by the ID you intend to use so the Task goes to the right Event. ```bash curl -X GET "https://api.exhibitday.com/v1/events?event_id=12345&%24return_event_lites=true" -H "Authorization: Bearer YOUR_API_KEY" ``` **Example response (shortened)** ```json { "list_data": [{ "id": 12345, "name": "Sample Event" }], "has_more": false } ``` **Check:** The intended ID appears in `list_data`. The complete program checks the supplied ID across returned pages. #### Step 2: Read the Event and its Task Sections Read the confirmed Event so you can choose a Task Section that belongs to it. ```bash curl -X GET "https://api.exhibitday.com/v1/events/info?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` **Example response (shortened)** ```json { "id": 12345, "task_sections": [{ "id": 67890, "name": "Booth setup" }] } ``` **Check:** The Event ID matches. If you set `EXHIBITDAY_TASK_SECTION_ID`, that ID must appear in `task_sections`. #### Step 3: Confirm the assignee, if supplied Filter the users list to people who can be assigned Tasks so you can confirm the optional assignee. ```bash curl -X GET "https://api.exhibitday.com/v1/references/users_and_resources?filter_by_can_have_tasks_assigned=true" -H "Authorization: Bearer YOUR_API_KEY" ``` **Example response (shortened)** ```json { "list_data": [{ "id": "4ee58d3b-ae3a-4b9b-a269-048dc191d2a9", "display_name": "Sam Rivera", "can_have_tasks_assigned": true }] } ``` **Check:** The assignee's ID appears in `list_data`. The filter excludes Resources. The complete program skips this request when `EXHIBITDAY_ASSIGNEE_ID` is unset. #### Step 4: Create the Task Send the Event ID and Task name with your unique key so a retry can reuse the original result. ```bash curl -X POST "https://api.exhibitday.com/v1/tasks" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -H "Idempotency-Key: YOUR_UNIQUE_KEY" -d "{\"event_id\":12345,\"name\":\"Order booth carpet\"}" ``` **Example response (shortened)** ```json { "id": 23456, "name": "Order booth carpet" } ``` **Check:** Save the returned `id` with the source form or ticket. The complete program prints the Task's ID and name. **Note.** The complete program also sets a due date 14 days from today and includes a short details value. It includes `task_section_id` and `assignee_user_id` when you supply the corresponding variables. #### Try it #### Before running the example | Variable | What to put in it | Required? | | --- | --- | --- | | `EXHIBITDAY_API_KEY` | Your workspace API key. | Yes | | `EXHIBITDAY_EVENT_ID` | The Event ID where you want to add a Task. | Yes | | `EXHIBITDAY_TASK_NAME` | Your Task name. Defaults to Order booth carpet. | No | | `EXHIBITDAY_TASK_SECTION_ID` | A Task Section ID from this Event. | No | | `EXHIBITDAY_ASSIGNEE_ID` | An eligible user's ID. Leave unset for an unassigned Task. | No | **Careful.** This example changes data in your workspace. Use a test Event. Each run uses a new key to create a Task. #### Bash ``` export EXHIBITDAY_API_KEY='YOUR_API_KEY' export EXHIBITDAY_EVENT_ID='12345' ``` #### PowerShell ``` $env:EXHIBITDAY_API_KEY = 'YOUR_API_KEY' $env:EXHIBITDAY_EVENT_ID = '12345' ``` Then copy the complete example program below in your language and run it. #### Complete example program Code Samples ```bash #!/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 http.client 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\":{\"events\":{\"method\":\"GET\",\"path\":\"/events\"},\"event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"assignees\":{\"method\":\"GET\",\"path\":\"/references/users_and_resources\"},\"createTask\":{\"method\":\"POST\",\"path\":\"/tasks\"}}}") 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) # curl may leave no output file for a valid bodyless304 response. (folder / "body").write_bytes(b"") 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 = {"Authorization": "Bearer " + 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, 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 = 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"] # choose your own event; no arbitrary first search result matches = list(pages("events", {"event_id": event_id, "$return_event_lites": "true"})) if not any(str(event["id"]) == event_id for event in matches): raise RuntimeError("The selected event was not found") event = call("event", {"id": event_id})["body"] task = {"event_id": event_id, "name": os.environ.get("EXHIBITDAY_TASK_NAME", "Order booth carpet"), "due_date": (datetime.date.today() + datetime.timedelta(days=14)).isoformat(), "details": "Requested from the integration guide"} section_id = os.environ.get("EXHIBITDAY_TASK_SECTION_ID") if section_id: if not any(str(section["id"]) == section_id for section in event.get("task_sections", [])): raise RuntimeError("Choose a task section from this event") task["task_section_id"] = section_id assignee_id = os.environ.get("EXHIBITDAY_ASSIGNEE_ID") if assignee_id: people = call("assignees", {"filter_by_can_have_tasks_assigned": "true"})["body"]["list_data"] if not any(str(person["id"]) == assignee_id for person in people): raise RuntimeError("Choose an assignable user/resource") task["assignee_user_id"] = assignee_id key = str(uuid.uuid4()) # keep this key with this logical task if your process must resume later created = call("createTask", body=task, key=key)["body"] print("Created task", created["id"], created["name"]) EXHIBITDAY_PY ``` ```javascript // 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\":{\"events\":{\"method\":\"GET\",\"path\":\"/events\"},\"event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"assignees\":{\"method\":\"GET\",\"path\":\"/references/users_and_resources\"},\"createTask\":{\"method\":\"POST\",\"path\":\"/tasks\"}}}"); 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 = { Authorization: "Bearer " + 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 matches = []; for await (const event of pages("events", { event_id: eventId, "$return_event_lites": "true" })) matches.push(event); if (!matches.some(event => String(event.id) === eventId)) throw new Error("The selected event was not found"); const event = (await call("event", { id: eventId })).body; const dueDate = new Date(); dueDate.setUTCDate(dueDate.getUTCDate() + 14); const task = { event_id: eventId, name: process.env.EXHIBITDAY_TASK_NAME || "Order booth carpet", due_date: dueDate.toISOString().slice(0, 10), details: "Requested from the integration guide" }; const section = process.env.EXHIBITDAY_TASK_SECTION_ID; if (section) { if (!(event.task_sections || []).some(item => String(item.id) === section)) throw new Error("Choose a task section from this event"); task.task_section_id = section; } const assignee = process.env.EXHIBITDAY_ASSIGNEE_ID; if (assignee) { const people = (await call("assignees", { filter_by_can_have_tasks_assigned: "true" })).body.list_data; if (!people.some(person => String(person.id) === assignee)) throw new Error("Choose an assignable user/resource"); task.assignee_user_id = assignee; } const key = randomUUID(); // persist this key with the logical task if resuming after process restart const created = (await call("createTask", {}, task, {}, key)).body; console.log("Created task", created.id, created.name); } const completion = main(); completion.catch(error => { console.error(error.message); process.exitCode = 1; }); ``` ```python # Python 3; standard library only. Set EXHIBITDAY_API_KEY before running. import csv import datetime import http.client 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\":{\"events\":{\"method\":\"GET\",\"path\":\"/events\"},\"event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"assignees\":{\"method\":\"GET\",\"path\":\"/references/users_and_resources\"},\"createTask\":{\"method\":\"POST\",\"path\":\"/tasks\"}}}") 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 = {"Authorization": "Bearer " + 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, 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 = 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"] # choose your own event; no arbitrary first search result matches = list(pages("events", {"event_id": event_id, "$return_event_lites": "true"})) if not any(str(event["id"]) == event_id for event in matches): raise RuntimeError("The selected event was not found") event = call("event", {"id": event_id})["body"] task = {"event_id": event_id, "name": os.environ.get("EXHIBITDAY_TASK_NAME", "Order booth carpet"), "due_date": (datetime.date.today() + datetime.timedelta(days=14)).isoformat(), "details": "Requested from the integration guide"} section_id = os.environ.get("EXHIBITDAY_TASK_SECTION_ID") if section_id: if not any(str(section["id"]) == section_id for section in event.get("task_sections", [])): raise RuntimeError("Choose a task section from this event") task["task_section_id"] = section_id assignee_id = os.environ.get("EXHIBITDAY_ASSIGNEE_ID") if assignee_id: people = call("assignees", {"filter_by_can_have_tasks_assigned": "true"})["body"]["list_data"] if not any(str(person["id"]) == assignee_id for person in people): raise RuntimeError("Choose an assignable user/resource") task["assignee_user_id"] = assignee_id key = str(uuid.uuid4()) # keep this key with this logical task if your process must resume later created = call("createTask", body=task, key=key)["body"] print("Created task", created["id"], created["name"]) ``` ```csharp // .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\":{\"events\":{\"method\":\"GET\",\"path\":\"/events\"},\"event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"assignees\":{\"method\":\"GET\",\"path\":\"/references/users_and_resources\"},\"createTask\":{\"method\":\"POST\",\"path\":\"/tasks\"}}}"); 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 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(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 Call(string name, JsonObject query = null, JsonNode body = null, Dictionary extraHeaders = null, string key = null) { var route = Spec["requests"][name]; var method = Text(route["method"]); var headers = new Dictionary(extraHeaders ?? new Dictionary(), StringComparer.OrdinalIgnoreCase) { ["Authorization"] = "Bearer " + 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 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()) 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 found = false; await foreach (var ev in Pages("events", Query(("event_id", eventId), ("$return_event_lites", "true")))) if (Text(ev["id"]) == eventId) found = true; if (!found) throw new Exception("The selected event was not found"); var selectedEvent = (await Call("event", Query(("id", eventId)))).Body; var task = new JsonObject { ["event_id"] = eventId, ["name"] = Environment.GetEnvironmentVariable("EXHIBITDAY_TASK_NAME") ?? "Order booth carpet", ["due_date"] = DateTime.UtcNow.AddDays(14).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), ["details"] = "Requested from the integration guide" }; var sectionId = Environment.GetEnvironmentVariable("EXHIBITDAY_TASK_SECTION_ID"); if (!string.IsNullOrEmpty(sectionId)) { if (!(selectedEvent["task_sections"]?.AsArray().Any(section => Text(section["id"]) == sectionId) ?? false)) throw new Exception("Choose a task section from this event"); task["task_section_id"] = sectionId; } var assigneeId = Environment.GetEnvironmentVariable("EXHIBITDAY_ASSIGNEE_ID"); if (!string.IsNullOrEmpty(assigneeId)) { var people = (await Call("assignees", Query(("filter_by_can_have_tasks_assigned", "true")))).Body["list_data"].AsArray(); if (!people.Any(person => Text(person["id"]) == assigneeId)) throw new Exception("Choose an assignable user/resource"); task["assignee_user_id"] = assigneeId; } var key = Guid.NewGuid().ToString(); // persist with this logical task if resuming after process restart var created = (await Call("createTask", body: task, key: key)).Body; Console.WriteLine($"Created task {Text(created["id"])}: {Text(created["name"])}"); } } ``` ```java // 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 SPEC = JSON.fromJson("{\"preserveNumbers\":false,\"requests\":{\"events\":{\"method\":\"GET\",\"path\":\"/events\"},\"event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"assignees\":{\"method\":\"GET\",\"path\":\"/references/users_and_resources\"},\"createTask\":{\"method\":\"POST\",\"path\":\"/tasks\"}}}", 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 body; Map headers; Result(int s, Map b, Map 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 obj(Object value) {return value==null?new LinkedHashMap<>(): (Map)value;} @SuppressWarnings("unchecked") static List list(Object value) {return value==null?Collections.emptyList():(List)value;} static Map map(Object... pairs) {Map result=new LinkedHashMap<>();for(int i=0;i query,Object body,Map extra,String key) { Map route=obj(obj(SPEC.get("requests")).get(name));String method=text(route.get("method")); Map headers=map("Authorization","Bearer " + 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 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 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 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> pages(String name,Map parameters) { return ()->new Iterator>() { int offset=0;boolean more=true;Iterator rows=Collections.emptyIterator(); public boolean hasNext() { while(!rows.hasNext()&&more) { Map query=new LinkedHashMap<>();if(parameters!=null)query.putAll(parameters); query.put("$limit",100);query.put("$offset",offset); Map 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 next(){if(!hasNext())throw new NoSuchElementException();return obj(rows.next());} }; } static Map 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");boolean found=false; for(Map row:pages("events",map("event_id",eventId,"$return_event_lites","true")))if(text(row.get("id")).equals(eventId))found=true; if(!found)throw new IllegalArgumentException("The selected event was not found"); Map event=call("event",map("id",eventId),null,null,null).body; Map task=map("event_id",eventId,"name",env("EXHIBITDAY_TASK_NAME","Order booth carpet"), "due_date",LocalDate.now(ZoneOffset.UTC).plusDays(14).toString(),"details","Requested from the integration guide"); String section=env("EXHIBITDAY_TASK_SECTION_ID",""); if(!section.isEmpty()) { boolean valid=false;for(Object row:list(event.get("task_sections")))if(text(obj(row).get("id")).equals(section))valid=true; if(!valid)throw new IllegalArgumentException("Choose a task section from this event");task.put("task_section_id",section); } String assignee=env("EXHIBITDAY_ASSIGNEE_ID",""); if(!assignee.isEmpty()) { Map people=call("assignees",map("filter_by_can_have_tasks_assigned","true"),null,null,null).body; boolean valid=false;for(Object row:list(people.get("list_data")))if(text(obj(row).get("id")).equals(assignee))valid=true; if(!valid)throw new IllegalArgumentException("Choose an assignable user/resource");task.put("assignee_user_id",assignee); } String key=UUID.randomUUID().toString(); // persist with this logical task if resuming later Map created=call("createTask",null,task,null,key).body; System.out.println("Created task "+created.get("id")+": "+created.get("name")); } } ``` ```php $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(['Authorization' => 'Bearer ' . $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'); // Select your own event, never an arbitrary first match. $found = false; foreach (pages('events', ['event_id' => $eventId, '$return_event_lites' => 'true']) as $candidate) { if ((string)$candidate['id'] === $eventId) $found = true; } if (!$found) throw new RuntimeException('The selected event was not found'); $event = call('event', ['id' => $eventId])['body']; $task = ['event_id' => $eventId, 'name' => optional('EXHIBITDAY_TASK_NAME', 'Order booth carpet'), 'due_date' => (new DateTimeImmutable('today'))->modify('+14 days')->format('Y-m-d'), 'details' => 'Requested from the integration guide']; $sectionId = getenv('EXHIBITDAY_TASK_SECTION_ID'); if ($sectionId !== false && $sectionId !== '') { $found = false; foreach ($event['task_sections'] ?? [] as $section) { if ((string)$section['id'] === $sectionId) $found = true; } if (!$found) throw new RuntimeException('Choose a task section from this event'); $task['task_section_id'] = $sectionId; } $assigneeId = getenv('EXHIBITDAY_ASSIGNEE_ID'); if ($assigneeId !== false && $assigneeId !== '') { $people = call('assignees', ['filter_by_can_have_tasks_assigned' => 'true'])['body']['list_data']; $found = false; foreach ($people as $person) { if ((string)$person['id'] === $assigneeId) $found = true; } if (!$found) throw new RuntimeException('Choose an assignable user/resource'); $task['assignee_user_id'] = $assigneeId; } $key = uuid4(); // Retain this key with this logical task if the process must resume. $created = call('createTask', [], $task, [], $key)['body']; echo 'Created task ', $created['id'], ': ', $created['name'], PHP_EOL; ``` ```ruby # 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":{"events":{"method":"GET","path":"/events"},"event":{"method":"GET","path":"/events/info"},"assignees":{"method":"GET","path":"/references/users_and_resources"},"createTask":{"method":"POST","path":"/tasks"}}}') 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 = { 'Authorization' => 'Bearer ' + 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') # Choose your own event, not an arbitrary search result. matches = pages('events', { 'event_id' => event_id, '$return_event_lites' => 'true' }).to_a raise 'The selected event was not found' unless matches.any? { |event| event.fetch('id').to_s == event_id } event = call('event', { 'id' => event_id }).fetch(:body) task = { 'event_id' => event_id, 'name' => ENV.fetch('EXHIBITDAY_TASK_NAME', 'Order booth carpet'), 'due_date' => (Date.today + 14).iso8601, 'details' => 'Requested from the integration guide' } section_id = ENV['EXHIBITDAY_TASK_SECTION_ID'] unless section_id.nil? || section_id.empty? sections = event.fetch('task_sections', []) raise 'Choose a task section from this event' unless sections.any? { |section| section.fetch('id').to_s == section_id } task['task_section_id'] = section_id end assignee_id = ENV['EXHIBITDAY_ASSIGNEE_ID'] unless assignee_id.nil? || assignee_id.empty? people = call('assignees', { 'filter_by_can_have_tasks_assigned' => 'true' }).fetch(:body).fetch('list_data') raise 'Choose an assignable user/resource' unless people.any? { |person| person.fetch('id').to_s == assignee_id } task['assignee_user_id'] = assignee_id end key = SecureRandom.uuid # Keep with this logical task if the process must resume later. created = call('createTask', {}, task, {}, key).fetch(:body) puts "Created task #{created.fetch('id')}: #{created.fetch('name')}" ``` ```go // 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\":{\"events\":{\"method\":\"GET\",\"path\":\"/events\"},\"event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"assignees\":{\"method\":\"GET\",\"path\":\"/references/users_and_resources\"},\"createTask\":{\"method\":\"POST\",\"path\":\"/tasks\"}}}" 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{"Authorization": "Bearer " + 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<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)<= 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");found:=false pages("events",map[string]string{"event_id":eventID,"$return_event_lites":"true"},func(row map[string]any){if text(row["id"])==eventID {found=true}}) if !found {panic("The selected event was not found")} event:=object(call("event",map[string]string{"id":eventID},nil,nil,"").body) name:=os.Getenv("EXHIBITDAY_TASK_NAME");if name=="" {name="Order booth carpet"} task:=map[string]any{"event_id":eventID,"name":name,"due_date":time.Now().UTC().AddDate(0,0,14).Format("2006-01-02"),"details":"Requested from the integration guide"} if section:=os.Getenv("EXHIBITDAY_TASK_SECTION_ID");section!="" { valid:=false;for _,row:=range array(event["task_sections"]) {if text(object(row)["id"])==section {valid=true}} if !valid {panic("Choose a task section from this event")};task["task_section_id"]=section } if assignee:=os.Getenv("EXHIBITDAY_ASSIGNEE_ID");assignee!="" { people:=object(call("assignees",map[string]string{"filter_by_can_have_tasks_assigned":"true"},nil,nil,"").body) valid:=false;for _,row:=range array(people["list_data"]) {if text(object(row)["id"])==assignee {valid=true}} if !valid {panic("Choose an assignable user/resource")};task["assignee_user_id"]=assignee } key:=uuid() // persist with this logical task if resuming after process restart created:=object(call("createTask",nil,task,nil,key).body) fmt.Println("Created task",created["id"],created["name"]) } ``` #### Example response Response 200 — OK 400 — Bad Request 401 — Unauthorized 409 — Conflict 429 — Too Many Requests 500 — Internal Server Error Example Successful request ```json { "id": 23456, "exhibitday_url": "https://www.exhibitday.com/Workspace/TaskView/98765?tid=23456", "event_task_section_id": null, "event_task_section": null, "display_rank": 0, "name": "Order booth carpet", "due_date": "2026-12-05", "assignee": null, "assigned_by": null, "contributors": [ { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, { "id": "66666666-7777-4888-8999-aaaaaaaaaaaa", "first_name": "Alex", "last_name": "Morgan", "display_name": "Alex Morgan", "email": "alex@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true } ], "is_completed": false, "task_completed_timestamp": null, "task_completed_by": null, "details": "Requested from the integration guide", "comments": [], "event": { "id": 12345, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=12345", "name": "Sample Event", "start_date": "2026-12-21", "end_date": "2026-12-23", "participation_type_id": 1, "participation_type": "Committed", "format_id": 1, "format": "In-Person", "event_created_timestamp": "2026-11-21T17:00:00Z", "event_last_update_timestamp": "2026-11-21T17: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": "2026-11-21T17:00:00Z", "task_last_update_timestamp": "2026-11-21T17:00:00Z", "integration_metadata_field_1": "", "integration_metadata_field_2": "", "integration_metadata_field_3": "", "integration_metadata_field_4": "", "integration_metadata_field_5": "" } ``` Note: This example uses Event 12345 and the default Task name. The Task Section and assignee were left blank. The Task ID is an example. The program prints the ID and name. ```json { "status_code": 400, "status": "Bad Request", "message": "HTTP method override is not supported.", "error_code": "invalid_request", "errors": [ "Send the documented HTTP method directly. X-HTTP-Method-Override cannot change a request's HTTP method." ], "error_params": [ "X-HTTP-Method-Override" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 400, "status": "Bad Request", "message": "This Idempotency-Key was already used with a different request. Use a new key for a new request.", "error_code": "idempotency_key_reused", "errors": [ "This Idempotency-Key was already used with a different request. Use a new key for a new request." ], "error_params": [ "Idempotency-Key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 400, "status": "Bad Request", "message": "Invalid value for the contributor_user_ids parameter. Each contributor must be a current workspace user who can be assigned tasks. You can get a list of users in your workspace from the /v1/references/users_and_resources endpoint.", "error_code": "invalid_request", "errors": [ "Invalid value for the contributor_user_ids parameter. Each contributor must be a current workspace user who can be assigned tasks. You can get a list of users in your workspace from the /v1/references/users_and_resources endpoint." ], "error_params": [ "contributor_user_ids" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 400, "status": "Bad Request", "message": "Invalid value for the contributor_user_ids parameter. Send a JSON array of unique user IDs, for example [\"user-id\",\"other-user-id\"], or one user ID. Send null or [] to remove all contributors.", "error_code": "invalid_request", "errors": [ "Invalid value for the contributor_user_ids parameter. Send a JSON array of unique user IDs, for example [\"user-id\",\"other-user-id\"], or one user ID. Send null or [] to remove all contributors." ], "error_params": [ "contributor_user_ids" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "No API key was provided. Send your key in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "missing_api_key", "errors": [ "Copy the key from Workspace Settings > API & Integrations > API Access in ExhibitDay." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "The API key is not valid. Check that you copied the whole key from Workspace Settings > API & Integrations > API Access, then send it in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "invalid_api_key", "errors": [ "Check that you sent the whole key. If it was regenerated, use the current key from Workspace Settings > API & Integrations > API Access." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "Access to the ExhibitDay API is not enabled for your workspace. Please contact support@exhibitday.com to enable API Access. Once access is enabled, send your key in the Authorization header as 'Bearer YOUR_API_KEY'.", "error_code": "api_access_disabled", "errors": [ "Nothing was read or changed." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "A request with this Idempotency-Key is still being processed. Retry after a moment.", "error_code": "idempotency_key_in_use", "errors": [ "A request with this Idempotency-Key is still being processed. Retry after a moment." ], "error_params": [ "Idempotency-Key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "A previous request with this Idempotency-Key did not finish and its outcome is unknown, so this retry was not run to avoid creating a duplicate. Check whether the earlier request succeeded; to try again, use a new Idempotency-Key.", "error_code": "idempotency_key_indeterminate", "errors": [ "A previous request with this Idempotency-Key did not finish and its outcome is unknown, so this retry was not run to avoid creating a duplicate. Check whether the earlier request succeeded; to try again, use a new Idempotency-Key." ], "error_params": [ "Idempotency-Key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "The saved response cannot be replayed safely.", "error_code": "idempotency_key_indeterminate", "errors": [ "The earlier request with this Idempotency-Key completed, but its saved response cannot be returned safely. This retry was not run and its key was not released. Look for the existing record with a GET; use a new Idempotency-Key only after checking whether another create is needed." ], "error_params": [ "Idempotency-Key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 429, "status": "Too Many Requests", "message": "Error 429 - Too Many Requests", "error_code": "rate_limited", "errors": [ "Error 429 - Too Many Requests" ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "We couldn't confirm whether the Task was saved. Before sending it again, look for it with GET /v1/tasks using filter_by_task_name_contains_text and, when applicable, filter_by_event_id. You can also filter by an integration metadata value you supplied. If you find it, do not send it again. If you need to retry, use the same Idempotency-Key if you supplied one. This request was not automatically retried." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "An unexpected error occurred. Please try again later." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` Note: Use the request_id from your own response when contacting support. ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "Check whether your change was saved before trying again." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` The curl workflow uses Bash, curl and Python 3. Node.js needs version 18 or later (save as .cjs). Python uses its standard library. C# needs a .NET 8 console project (Program.cs). Java needs Java 11 or later and Gson 2.14.0 at compile time and runtime (Main.java). PHP needs PHP 8.1 or later with cURL. Ruby 3.1 or later and Go 1.18 or later use their standard libraries. #### Things to keep in mind - If you lose the response, retry the exact request with the same key. For 24 hours, a completed request can return the saved response with `Idempotent-Replayed: true`. - If the key is in use, wait briefly and retry with the same key. - If the API returns `idempotency_key_indeterminate`, check whether the Task exists before deciding whether to create it. - Save the exact request and key if your integration must pick up after a restart. - If a locked Event Task list returns `not_allowed`, check the Event's Task settings before you retry. - **Manual example:** Omit `event_id` from `POST /v1/tasks` to create a general Task. The complete example always creates an Event Task. - **Manual example:** Add a comment with `POST /v1/tasks/comments`, supplying `task_id` and `comment`. #### Related guides - [Handle Errors and Retry Failed Requests](https://api.exhibitday.com/Help/V1?guide=errors-and-retries) - [Keep Another System Updated with Event and Task Changes](https://api.exhibitday.com/Help/V1?guide=sync-changes) ### Fill In Your Custom Event Fields from Another System Guide page: https://api.exhibitday.com/Help/V1?guide=custom-fields Fill in or read your workspace's own Event fields from another system. Example use case Another system tracks when an Event is ready. Copy that status into your workspace's custom Integration status field. What you'll end up with An updated Event field and a readback of the current value. Before you start Have a workspace API key and an editable Event with a visible custom text, dropdown or URL field. Good to know For a dropdown field, send one of the `options` listed for it in `GET /v1/references/event_custom_fields`. The same list gives you the field name. #### At a glance Time to try About 10 minutes Effect on your data Updates records Endpoints 4 A successful update sets or clears one custom field on the Event. - [`GET /v1/references/event_custom_fields`](https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-event_custom_fields) - [`GET /v1/events/info`](https://api.exhibitday.com/Help/V1?epf=1#get-v1-events-info) - [`PATCH /v1/events`](https://api.exhibitday.com/Help/V1?epf=1#patch-v1-events) - [`GET /v1/events`](https://api.exhibitday.com/Help/V1?epf=1#get-v1-events) #### How it works 1. Find the field name in the workspace list and read the Event's current value and revision. 2. Send the new value with that revision so the API can check for edits since your read. 3. Read the Event again to see the current value. 4. After a successful update to a text or dropdown field, the program can list Events that match the value you set. #### Set a field and read it back These examples use a text field called Integration status. Step 5 is optional and applies to text or dropdown fields. #### Step 1: Find the field name Read the workspace's Event Custom Fields so you can use the exact `field_name` in the update. ```bash curl -X GET "https://api.exhibitday.com/v1/references/event_custom_fields" -H "Authorization: Bearer YOUR_API_KEY" ``` **Example response (shortened)** ```json { "list_data": [{ "field_name": "custom_67890", "field_type": "Text (Single-line)", "is_hidden": false }] } ``` **Check:** The field appears in `list_data`, `is_hidden` is false, and `field_type` is text, dropdown or URL. #### Step 2: Read the current value and revision Read the Event with `$include_record_revision=true` so the update can check whether the Event changed after your read. ```bash curl -X GET "https://api.exhibitday.com/v1/events/info?id=12345&%24include_record_revision=true" -H "Authorization: Bearer YOUR_API_KEY" ``` **Example response (shortened)** ```json { "id": 12345, "record_revision": "REVISION_FROM_STEP_2", "custom_fields": [{ "field_name": "custom_67890", "value": "In progress" }] } ``` **Check:** Find your field in `custom_fields` and keep the full `record_revision` from the live response. #### Step 3: Update one field Send the Event ID, the exact field name and the revision from Step 2 so the API can reject a stale update. ```bash curl -X PATCH "https://api.exhibitday.com/v1/events" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"id\":12345,\"custom_67890\":\"Ready\",\"expected_revision\":\"REVISION_FROM_STEP_2\"}" ``` **Example response (shortened)** ```json { "status_code": 200 } ``` **Check:** A successful PATCH returns HTTP 200. HTTP 409 with `record_changed` means the request saved nothing. Read the current Event before deciding what to do next. #### Step 4: Read the Event again Read the Event to see the current value after the update attempt. ```bash curl -X GET "https://api.exhibitday.com/v1/events/info?id=12345" -H "Authorization: Bearer YOUR_API_KEY" ``` **Example response (shortened)** ```json { "id": 12345, "custom_fields": [ { "field_name": "custom_67890", "value": "Ready" } ] } ``` **Check:** Find `custom_67890` in `custom_fields` and check its `value`. After a lost response or uncertain server error, the program tries to read the current value and stops. Readback alone cannot tell you which request set it. #### Step 5: Find matching Events, if useful After a successful text or dropdown update, use the same field name in an Events list filter to find Events with that value. ```bash curl -X GET "https://api.exhibitday.com/v1/events?filter_by_custom_event_field__custom_67890=Ready" -H "Authorization: Bearer YOUR_API_KEY" ``` **Example response (shortened)** ```json { "list_data": [{ "id": 12345 }], "has_more": false } ``` **Check:** Read every page before using the complete list. Use one custom field per request. URL and File fields are outside this filter. #### Try it #### Before running the example | Variable | What to put in it | Required? | | --- | --- | --- | | `EXHIBITDAY_API_KEY` | Your workspace API key. | Yes | | `EXHIBITDAY_EVENT_ID` | The ID of an Event you can edit. | Yes | | `EXHIBITDAY_CUSTOM_FIELD` | The exact field name, such as custom_67890. | Yes | | `EXHIBITDAY_CUSTOM_VALUE` | Text, a configured dropdown choice or an HTTP or HTTPS URL. | Yes | **Careful.** This example changes data in your workspace. Use a test Event and field. Replace the example values with your own. #### Bash ``` export EXHIBITDAY_API_KEY='YOUR_API_KEY' export EXHIBITDAY_EVENT_ID='12345' export EXHIBITDAY_CUSTOM_FIELD='custom_67890' export EXHIBITDAY_CUSTOM_VALUE='Ready' ``` #### PowerShell ``` $env:EXHIBITDAY_API_KEY = 'YOUR_API_KEY' $env:EXHIBITDAY_EVENT_ID = '12345' $env:EXHIBITDAY_CUSTOM_FIELD = 'custom_67890' $env:EXHIBITDAY_CUSTOM_VALUE = 'Ready' ``` Then copy the complete example program below in your language and run it. #### Complete example program Code Samples ```bash #!/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 http.client 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) # curl may leave no output file for a valid bodyless304 response. (folder / "body").write_bytes(b"") 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 = {"Authorization": "Bearer " + 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, 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 = 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 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"]) saved = outcome == "saved" after = call("event", {"id": event_id})["body"] print({"saved": "After:", "changed": "The Event changed before the update. Current values:", "unknown": "Update outcome unknown. Current values:"}[outcome], 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 ``` ```javascript // 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 = { Authorization: "Bearer " + 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); // "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); const saved = outcome === "saved"; const after = (await call("event", { id: eventId })).body; console.log(saved ? "After:" : outcome === "changed" ? "The Event changed before the update. Current values:" : "Update outcome unknown. Current values:", 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 # Python 3; standard library only. Set EXHIBITDAY_API_KEY before running. import csv import datetime import http.client 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 = {"Authorization": "Bearer " + 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, 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 = 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 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"]) saved = outcome == "saved" after = call("event", {"id": event_id})["body"] print({"saved": "After:", "changed": "The Event changed before the update. Current values:", "unknown": "Update outcome unknown. Current values:"}[outcome], 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. ``` ```csharp // .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 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(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 Call(string name, JsonObject query = null, JsonNode body = null, Dictionary extraHeaders = null, string key = null) { var route = Spec["requests"][name]; var method = Text(route["method"]); var headers = new Dictionary(extraHeaders ?? new Dictionary(), StringComparer.OrdinalIgnoreCase) { ["Authorization"] = "Bearer " + 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 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()) 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() ?? 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"]); // "saved", "changed" (409 record_changed: nothing was saved) or "unknown". async Task 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"])); var saved = outcome == "saved"; var after = (await Call("event", Query(("id", eventId)))).Body; Console.WriteLine((saved ? "After: " : outcome == "changed" ? "The Event changed before the update. Current values: " : "Update outcome unknown. Current values: ") + 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 // 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 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 body; Map headers; Result(int s, Map b, Map 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 obj(Object value) {return value==null?new LinkedHashMap<>(): (Map)value;} @SuppressWarnings("unchecked") static List list(Object value) {return value==null?Collections.emptyList():(List)value;} static Map map(Object... pairs) {Map result=new LinkedHashMap<>();for(int i=0;i query,Object body,Map extra,String key) { Map route=obj(obj(SPEC.get("requests")).get(name));String method=text(route.get("method")); Map headers=map("Authorization","Bearer " + 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 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 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 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> pages(String name,Map parameters) { return ()->new Iterator>() { int offset=0;boolean more=true;Iterator rows=Collections.emptyIterator(); public boolean hasNext() { while(!rows.hasNext()&&more) { Map query=new LinkedHashMap<>();if(parameters!=null)query.putAll(parameters); query.put("$limit",100);query.put("$offset",offset); Map 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 next(){if(!hasNext())throw new NoSuchElementException();return obj(rows.next());} }; } static Map 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 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 before=call("event",map("id",eventId,"$include_record_revision","true"),null,null,null).body;System.out.println("Before: "+before.get("custom_fields")); // "saved", "changed" (409 record_changed: nothing was saved) or "unknown". java.util.function.Function 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")); boolean saved=outcome.equals("saved"); Map after=call("event",map("id",eventId),null,null,null).body;System.out.println((saved?"After: ":outcome.equals("changed")?"The Event changed before the update. Current values: ":"Update outcome unknown. Current values: ")+after.get("custom_fields")); if(saved&&(kind.startsWith("text")||kind.equals("dropdown"))&&!value.isEmpty()&&!value.equalsIgnoreCase("null")) { int count=0;for(Map 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 $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(['Authorization' => 'Bearer ' . $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; // '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); $saved = $outcome === 'saved'; $after = call('event', ['id' => $eventId])['body']; echo $saved ? 'After: ' : ($outcome === 'changed' ? 'The Event changed before the update. Current values: ' : 'Update outcome unknown. Current values: '), 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 # 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 = { 'Authorization' => 'Bearer ' + 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}" # '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']) saved = outcome == 'saved' after = call('event', { 'id' => event_id }).fetch(:body) puts "#{saved ? 'After' : (outcome == 'changed' ? 'The Event changed before the update. Current values' : 'Update outcome unknown. Current values')}: #{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 // 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{"Authorization": "Bearer " + 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<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)<= 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"]) // "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"]) saved:=outcome=="saved" after:=object(call("event",map[string]string{"id":eventID},nil,nil,"").body) label:="Update outcome unknown. Current values:" if saved {label="After:"} else if outcome=="changed" {label="The Event changed before the update. Current values:"} fmt.Println(label,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 response Response 200 — OK 304 — Not Modified 400 — Bad Request 401 — Unauthorized 404 — Not Found 409 — Conflict 429 — Too Many Requests 500 — Internal Server Error Example Successful request ```json { "id": 12345, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=12345", "name": "Sample Event", "start_date": "2026-12-21", "end_date": "2026-12-23", "participation_type_id": 1, "participation_type": "Committed", "format_id": 1, "format": "In-Person", "star_rating": 0, "tags": [ "International", "Field Marketing" ], "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, "booth_reservation_cost": { "amount": 125.50, "cost_center_breakdown": [ { "cost_center_id": 34567, "cost_center": "Marketing", "charge": 75.50 }, { "cost_center_id": 34568, "cost_center": "Operations", "charge": 50.00 } ] }, "cost_booth_reservation": 125.50, "booth_reservation_payment_status_id": 0, "booth_reservation_payment_status": "", "booth_reservation_payment_due_date": null, "booth_reservation_next_payment_due_date": null, "booth_reservation_payment_notes": null, "booth_reservation_invoice_attachment": { "id": 182345, "filename": "booth-reservation-invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" }, "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": 100.50, "cost_sponsorships": 0.00, "total_sum_event_costs": 226.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, "roo_score": null, "event_created_timestamp": "2026-11-21T17:00:00Z", "event_last_update_timestamp": "2026-11-21T17:00:00Z", "event_created_by": { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, "custom_fields": [ { "label": "Integration status", "value": "Ready", "notes": "", "field_name": "custom_67890", "field_type": "Text (Single-line)", "field_event_tab": "Info" }, { "label": "Setup instructions", "value": "Place the display beside the entrance.", "notes": "", "field_name": "custom_67891", "field_type": "Text (Single-line)", "field_event_tab": "Booth" } ], "task_sections": [ { "id": 13346, "name": "Planning", "display_rank": 1 }, { "id": 13347, "name": "At the Event", "display_rank": 2 } ], "tasks": [ { "id": 14346, "exhibitday_url": "https://www.exhibitday.com/Workspace/TaskView/98765?tid=14346", "event_task_section_id": 13346, "event_task_section": "Planning", "display_rank": 1, "name": "Confirm booth setup", "due_date": "2026-12-12", "assignee": { "id": "11111111-2222-4333-8444-555555555555", "first_name": "Jane", "last_name": "Smith", "display_name": "Jane Smith", "email": "jane@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, "is_completed": false, "task_completed_timestamp": null, "task_created_timestamp": "2026-11-21T17:01:00Z", "task_last_update_timestamp": "2026-11-21T17:01:00Z" }, { "id": 14347, "exhibitday_url": "https://www.exhibitday.com/Workspace/TaskView/98765?tid=14347", "event_task_section_id": 13347, "event_task_section": "At the Event", "display_rank": 2, "name": "Prepare the staff schedule", "due_date": "2026-12-13", "assignee": { "id": "66666666-7777-4888-8999-aaaaaaaaaaaa", "first_name": "Alex", "last_name": "Jordan", "display_name": "Alex Jordan", "email": "alex@example.invalid", "type": "user", "workspace_role": "team_member", "is_active": true }, "is_completed": false, "task_completed_timestamp": null, "task_created_timestamp": "2026-11-21T17:02:00Z", "task_last_update_timestamp": "2026-11-21T17:02:00Z" } ], "misc_expenses_credits": [ { "id": 15346, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=12345&riType=8&riSub=0&riId=15346", "description": "Conference meals", "is_credit": false, "cost": { "amount": 125.50, "cost_center_breakdown": [ { "cost_center_id": 34567, "cost_center": "Marketing", "charge": 75.50 }, { "cost_center_id": 34568, "cost_center": "Operations", "charge": 50.00 } ] }, "notes": "", "payment_due_date": null, "payment_status": { "id": 0, "name": "Not Specified" }, "next_payment_due_date": null, "payment_notes": null, "invoice_attachment": { "id": 685346, "filename": "expense-invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" }, "event_misc_expense_credit_created_timestamp": "2026-11-21T17:00:00Z", "event_misc_expense_credit_last_update_timestamp": "2026-11-21T17:00:00Z" }, { "id": 15347, "exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=12345&riType=8&riSub=0&riId=15347", "description": "Supplier refund", "is_credit": true, "cost": { "amount": -25.00, "cost_center_breakdown": [ { "cost_center_id": 34567, "cost_center": "Marketing", "charge": -15.00 }, { "cost_center_id": 34568, "cost_center": "Operations", "charge": -10.00 } ] }, "notes": "", "payment_due_date": null, "payment_status": { "id": 0, "name": "Not Specified" }, "next_payment_due_date": null, "payment_notes": null, "invoice_attachment": { "id": 685347, "filename": "expense-invoice.pdf", "attachment_created_timestamp": "2027-01-30T12:00:00Z" }, "event_misc_expense_credit_created_timestamp": "2026-11-21T17:00:00Z", "event_misc_expense_credit_last_update_timestamp": "2026-11-21T17:00:00Z" } ], "integration_metadata_field_1": "", "integration_metadata_field_2": "", "integration_metadata_field_3": "", "integration_metadata_field_4": "", "integration_metadata_field_5": "" } ``` Note: This example reads Event 12345 after the update. Its visible text field custom_67890 is called Integration status and now holds Ready. Use a valid value for the field type you select. Note: There is no response body. Keep using your cached response. ```json { "status_code": 400, "status": "Bad Request", "message": "HTTP method override is not supported.", "error_code": "invalid_request", "errors": [ "Send the documented HTTP method directly. X-HTTP-Method-Override cannot change a request's HTTP method." ], "error_params": [ "X-HTTP-Method-Override" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "No API key was provided. Send your key in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "missing_api_key", "errors": [ "Copy the key from Workspace Settings > API & Integrations > API Access in ExhibitDay." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "The API key is not valid. Check that you copied the whole key from Workspace Settings > API & Integrations > API Access, then send it in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "invalid_api_key", "errors": [ "Check that you sent the whole key. If it was regenerated, use the current key from Workspace Settings > API & Integrations > API Access." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "Access to the ExhibitDay API is not enabled for your workspace. Please contact support@exhibitday.com to enable API Access. Once access is enabled, send your key in the Authorization header as 'Bearer YOUR_API_KEY'.", "error_code": "api_access_disabled", "errors": [ "Nothing was read or changed." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 404, "status": "Not Found", "message": "Event not found. Invalid Event ID: 12345.", "error_code": "not_found", "errors": [ "Event not found. Invalid Event ID: 12345." ], "error_params": [ "id" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "The invoice attachment or its owning record changed or has conflicting saved information. Retrieve the current record before retrying.", "error_code": "record_changed", "errors": [ "The invoice attachment or its owning record changed or has conflicting saved information. Retrieve the current record before retrying." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "The Booth Reservation payment information changed or has an unsupported saved status. Retrieve the current Event before retrying.", "error_code": "record_changed", "errors": [ "The Booth Reservation payment information changed or has an unsupported saved status. Retrieve the current Event before retrying." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "The Event objective score changed or could not be read consistently. Retrieve the Event before retrying.", "error_code": "record_changed", "errors": [ "The Event objective score changed or could not be read consistently. Retrieve the Event before retrying." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 409, "status": "Conflict", "message": "The record was being changed while it was read, so no record_revision could be issued. Read it again.", "error_code": "record_changed", "errors": [ "The record was being changed while it was read, so no record_revision could be issued. Read it again." ], "error_params": [ "$include_record_revision" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 429, "status": "Too Many Requests", "message": "Error 429 - Too Many Requests", "error_code": "rate_limited", "errors": [ "Error 429 - Too Many Requests" ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "An unexpected error occurred. Please try again later." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` Note: Use the request_id from your own response when contacting support. ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "Check whether your change was saved before trying again." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` The curl workflow uses Bash, curl and Python 3. Node.js needs version 18 or later (save as .cjs). Python uses its standard library. C# needs a .NET 8 console project (Program.cs). Java needs Java 11 or later and Gson 2.14.0 at compile time and runtime (Main.java). PHP needs PHP 8.1 or later with cURL. Ruby 3.1 or later and Go 1.18 or later use their standard libraries. #### Things to keep in mind - Omit the field or send a blank string to keep its value. - To clear a supported field, send JSON `null` or the string `"null"`. When `$ignore_params_with_empty_values=true`, use the string `"null"` to clear a visible field. - Send plain text for multi-line fields. The API returns the stored HTML, including encoded characters and line breaks. Decode it to plain text before resubmitting. - For dropdowns, the API ignores case and surrounding spaces when matching your input. It saves the configured option. - Use the File Attachment endpoints for File fields. - If a field is hidden, the API returns HTTP 400 and names the field in `error_params`. - Send the full revision from the Event read. The API refuses a blank, null or malformed `expected_revision`. #### Related guides - [Avoid Overwriting Someone Else's Changes](https://api.exhibitday.com/Help/V1?guide=update-records-safely) - [Get a Complete List of Attendees, Travel and More](https://api.exhibitday.com/Help/V1?guide=find-filter-page) ### Handle Errors and Retry Failed Requests Guide page: https://api.exhibitday.com/Help/V1?guide=errors-and-retries Know what to do when a request fails: fix it, wait and retry, or check whether it already worked. Example use case Your integration needs to handle failed requests, rate limits and timeouts. What you'll end up with A rule for each kind of failure. Fix the request, wait and retry, or check whether the change already happened. Before you start Have a workspace API key. Good to know Branch on `error_code`. Message text can change. #### At a glance Time to try About 10 minutes Effect on your data Read-only Endpoints 1 The program reads payment statuses and shows how to interpret an example error locally. - [`GET /v1/references/payment_statuses`](https://api.exhibitday.com/Help/V1?epf=3#get-v1-references-payment_statuses) #### How it works 1. Read the payment statuses and keep the ETag returned with the list. 2. Send that ETag with the next read. Keep the earlier list if it is unchanged. 3. Read a sample error on your computer and use its code to decide how to respond. #### Read a list and check for changes #### Step 1: Read a list and note its ETag Read the payment statuses so you have the current list and its ETag. ```bash curl -i -X GET "https://api.exhibitday.com/v1/references/payment_statuses" -H "Authorization: Bearer YOUR_API_KEY" ``` The example response includes `records_found` and the list in `list_data`. **Example response** ```json { "records_found": 4, "list_type": "payment_status", "list_data": [ { "id": 0, "name": "Not Specified" }, { "id": 1, "name": "Paid in Full" }, { "id": 2, "name": "Partially Paid" }, { "id": 3, "name": "Not Paid Yet" } ] } ``` **Check:** The read returns HTTP 200 and an `ETag` header. #### Step 2: Check whether the list changed Repeat the GET with the ETag so the API can tell you whether your saved response is still current. In Bash, put the full `ETag` header value, including its quotes, in the `ETAG` variable. Repeat the GET with `If-None-Match`. ```bash curl -i -X GET "https://api.exhibitday.com/v1/references/payment_statuses" -H "Authorization: Bearer YOUR_API_KEY" -H "If-None-Match: $ETAG" ``` **Check:** If the list is unchanged, the API returns HTTP 304 with no body. Keep the first response. A changed list returns HTTP 200 with the current data. **Careful.** If you receive HTTP 429, wait the number of seconds in `Retry-After` before retrying. #### Try it #### Before running the example | Variable | What to put in it | Required? | | --- | --- | --- | | `EXHIBITDAY_API_KEY` | Your workspace API key. | Yes | **Note.** This example only reads data. It parses an illustrative error locally without sending an invalid request. #### Bash ``` export EXHIBITDAY_API_KEY='YOUR_API_KEY' ``` #### PowerShell ``` $env:EXHIBITDAY_API_KEY = 'YOUR_API_KEY' ``` Then copy the complete example program below in your language and run it. #### Complete example program Code Samples ```bash #!/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 http.client 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\":{\"statuses\":{\"method\":\"GET\",\"path\":\"/references/payment_statuses\"}}}") 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) # curl may leave no output file for a valid bodyless304 response. (folder / "body").write_bytes(b"") 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 = {"Authorization": "Bearer " + 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, 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 = 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) first = call("statuses") print("Payment statuses:", first["body"]["records_found"]) etag = first["headers"].get("etag") if etag: cached = call("statuses", extra_headers={"If-None-Match": etag}) print("Unchanged" if cached["status"] == 304 else "Reference data changed") # FORMAT-ONLY example, constructed locally. It is never sent as an API request. example = json.loads("{\r\n \"status_code\": 400,\r\n \"status\": \"Bad Request\",\r\n \"message\": \"HTTP method override is not supported.\",\r\n \"error_code\": \"invalid_request\",\r\n \"errors\": [\r\n \"Send the documented HTTP method directly. X-HTTP-Method-Override cannot change a request's HTTP method.\"\r\n ],\r\n \"error_params\": [\r\n \"X-HTTP-Method-Override\"\r\n ],\r\n \"request_id\": \"0123456789abcdef0123456789abcdef\"\r\n}") print(example["error_code"], example["error_params"], example["errors"], example["request_id"]) # call() retries only transient statuses/network errors; request errors stop immediately. EXHIBITDAY_PY ``` ```javascript // 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\":{\"statuses\":{\"method\":\"GET\",\"path\":\"/references/payment_statuses\"}}}"); 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 = { Authorization: "Bearer " + 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 first = await call("statuses"); console.log("Payment statuses:", first.body.records_found); if (first.headers.etag) { const cached = await call("statuses", {}, null, { "If-None-Match": first.headers.etag }); console.log(cached.status === 304 ? "Unchanged" : "Reference data changed"); } // FORMAT ONLY: this local object is NEVER sent as an API request. const example = JSON.parse("{\r\n \"status_code\": 400,\r\n \"status\": \"Bad Request\",\r\n \"message\": \"HTTP method override is not supported.\",\r\n \"error_code\": \"invalid_request\",\r\n \"errors\": [\r\n \"Send the documented HTTP method directly. X-HTTP-Method-Override cannot change a request's HTTP method.\"\r\n ],\r\n \"error_params\": [\r\n \"X-HTTP-Method-Override\"\r\n ],\r\n \"request_id\": \"0123456789abcdef0123456789abcdef\"\r\n}"); console.log(example.error_code, example.error_params, example.errors, example.request_id); } const completion = main(); completion.catch(error => { console.error(error.message); process.exitCode = 1; }); ``` ```python # Python 3; standard library only. Set EXHIBITDAY_API_KEY before running. import csv import datetime import http.client 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\":{\"statuses\":{\"method\":\"GET\",\"path\":\"/references/payment_statuses\"}}}") 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 = {"Authorization": "Bearer " + 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, 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 = 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) first = call("statuses") print("Payment statuses:", first["body"]["records_found"]) etag = first["headers"].get("etag") if etag: cached = call("statuses", extra_headers={"If-None-Match": etag}) print("Unchanged" if cached["status"] == 304 else "Reference data changed") # FORMAT-ONLY example, constructed locally. It is never sent as an API request. example = json.loads("{\r\n \"status_code\": 400,\r\n \"status\": \"Bad Request\",\r\n \"message\": \"HTTP method override is not supported.\",\r\n \"error_code\": \"invalid_request\",\r\n \"errors\": [\r\n \"Send the documented HTTP method directly. X-HTTP-Method-Override cannot change a request's HTTP method.\"\r\n ],\r\n \"error_params\": [\r\n \"X-HTTP-Method-Override\"\r\n ],\r\n \"request_id\": \"0123456789abcdef0123456789abcdef\"\r\n}") print(example["error_code"], example["error_params"], example["errors"], example["request_id"]) # call() retries only transient statuses/network errors; request errors stop immediately. ``` ```csharp // .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\":{\"statuses\":{\"method\":\"GET\",\"path\":\"/references/payment_statuses\"}}}"); 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 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(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 Call(string name, JsonObject query = null, JsonNode body = null, Dictionary extraHeaders = null, string key = null) { var route = Spec["requests"][name]; var method = Text(route["method"]); var headers = new Dictionary(extraHeaders ?? new Dictionary(), StringComparer.OrdinalIgnoreCase) { ["Authorization"] = "Bearer " + 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 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()) 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 first = await Call("statuses"); Console.WriteLine("Payment statuses: " + Text(first.Body["records_found"])); if (first.Headers.TryGetValue("etag", out var etag)) { var cached = await Call("statuses", extraHeaders: new Dictionary { ["If-None-Match"] = etag }); Console.WriteLine(cached.Status == 304 ? "Unchanged" : "Reference data changed"); } // FORMAT ONLY: this local object is NEVER sent as an API request. var example = JsonNode.Parse("{\r\n \"status_code\": 400,\r\n \"status\": \"Bad Request\",\r\n \"message\": \"HTTP method override is not supported.\",\r\n \"error_code\": \"invalid_request\",\r\n \"errors\": [\r\n \"Send the documented HTTP method directly. X-HTTP-Method-Override cannot change a request's HTTP method.\"\r\n ],\r\n \"error_params\": [\r\n \"X-HTTP-Method-Override\"\r\n ],\r\n \"request_id\": \"0123456789abcdef0123456789abcdef\"\r\n}"); Console.WriteLine(example.ToJsonString()); } } ``` ```java // 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 SPEC = JSON.fromJson("{\"preserveNumbers\":false,\"requests\":{\"statuses\":{\"method\":\"GET\",\"path\":\"/references/payment_statuses\"}}}", 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 body; Map headers; Result(int s, Map b, Map 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 obj(Object value) {return value==null?new LinkedHashMap<>(): (Map)value;} @SuppressWarnings("unchecked") static List list(Object value) {return value==null?Collections.emptyList():(List)value;} static Map map(Object... pairs) {Map result=new LinkedHashMap<>();for(int i=0;i query,Object body,Map extra,String key) { Map route=obj(obj(SPEC.get("requests")).get(name));String method=text(route.get("method")); Map headers=map("Authorization","Bearer " + 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 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 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 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> pages(String name,Map parameters) { return ()->new Iterator>() { int offset=0;boolean more=true;Iterator rows=Collections.emptyIterator(); public boolean hasNext() { while(!rows.hasNext()&&more) { Map query=new LinkedHashMap<>();if(parameters!=null)query.putAll(parameters); query.put("$limit",100);query.put("$offset",offset); Map 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 next(){if(!hasNext())throw new NoSuchElementException();return obj(rows.next());} }; } static Map 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 { Result first=call("statuses",null,null,null,null);System.out.println("Payment statuses: "+first.body.get("records_found")); String etag=first.headers.get("etag"); if(etag!=null) { Result cached=call("statuses",null,null,map("If-None-Match",etag),null); System.out.println(cached.status==304?"Unchanged":"Reference data changed"); } // FORMAT ONLY: this local object is NEVER sent as an API request. Map example=JSON.fromJson("{\r\n \"status_code\": 400,\r\n \"status\": \"Bad Request\",\r\n \"message\": \"HTTP method override is not supported.\",\r\n \"error_code\": \"invalid_request\",\r\n \"errors\": [\r\n \"Send the documented HTTP method directly. X-HTTP-Method-Override cannot change a request's HTTP method.\"\r\n ],\r\n \"error_params\": [\r\n \"X-HTTP-Method-Override\"\r\n ],\r\n \"request_id\": \"0123456789abcdef0123456789abcdef\"\r\n}",Map.class); System.out.println(JSON.toJson(example)); } } ``` ```php $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(['Authorization' => 'Bearer ' . $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); } } $first = call('statuses'); echo 'Payment statuses: ', $first['body']['records_found'], PHP_EOL; $etag = $first['headers']['etag'] ?? null; if ($etag !== null && $etag !== '') { $cached = call('statuses', [], null, ['If-None-Match' => $etag]); echo $cached['status'] === 304 ? 'Unchanged' : 'Reference data changed', PHP_EOL; } // FORMAT-ONLY example, built locally. It is never sent as an API request. $example = json_decode('{ "status_code": 400, "status": "Bad Request", "message": "HTTP method override is not supported.", "error_code": "invalid_request", "errors": [ "Send the documented HTTP method directly. X-HTTP-Method-Override cannot change a request\'s HTTP method." ], "error_params": [ "X-HTTP-Method-Override" ], "request_id": "0123456789abcdef0123456789abcdef" }', true, 512, JSON_THROW_ON_ERROR); echo json_encode($example, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR), PHP_EOL; // call() retries transient statuses/network errors only; request errors stop immediately. ``` ```ruby # 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":{"statuses":{"method":"GET","path":"/references/payment_statuses"}}}') 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 = { 'Authorization' => 'Bearer ' + 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 first = call('statuses') puts "Payment statuses: #{first.fetch(:body).fetch('records_found')}" etag = first.fetch(:headers)['etag'] if etag cached = call('statuses', {}, nil, { 'If-None-Match' => etag }) puts(cached.fetch(:status) == 304 ? 'Unchanged' : 'Reference data changed') end # FORMAT-ONLY example constructed locally; never sent as an API request. example = JSON.parse('{ "status_code": 400, "status": "Bad Request", "message": "HTTP method override is not supported.", "error_code": "invalid_request", "errors": [ "Send the documented HTTP method directly. X-HTTP-Method-Override cannot change a request\'s HTTP method." ], "error_params": [ "X-HTTP-Method-Override" ], "request_id": "0123456789abcdef0123456789abcdef" }') puts "#{example['error_code']} #{example['error_params'].inspect}: #{example['errors'].inspect} (request #{example['request_id']})" # call() retries transient statuses/network failures only; request errors stop immediately. ``` ```go // 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\":{\"statuses\":{\"method\":\"GET\",\"path\":\"/references/payment_statuses\"}}}" 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{"Authorization": "Bearer " + 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<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)<= 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)} first:=call("statuses",nil,nil,nil,"");fmt.Println("Payment statuses:",object(first.body)["records_found"]) if etag:=first.headers.Get("ETag");etag!="" { cached:=call("statuses",nil,nil,map[string]string{"If-None-Match":etag},"") if cached.status==304 {fmt.Println("Unchanged")} else {fmt.Println("Reference data changed")} } // FORMAT ONLY: this local object is NEVER sent as an API request. var example map[string]any if err:=json.Unmarshal([]byte("{\r\n \"status_code\": 400,\r\n \"status\": \"Bad Request\",\r\n \"message\": \"HTTP method override is not supported.\",\r\n \"error_code\": \"invalid_request\",\r\n \"errors\": [\r\n \"Send the documented HTTP method directly. X-HTTP-Method-Override cannot change a request's HTTP method.\"\r\n ],\r\n \"error_params\": [\r\n \"X-HTTP-Method-Override\"\r\n ],\r\n \"request_id\": \"0123456789abcdef0123456789abcdef\"\r\n}"),&example);err!=nil {panic(err)} fmt.Println(example) } ``` Requirements: the curl workflow uses Bash, curl and Python 3; Node.js requires version 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. #### Things to keep in mind #### Read the error code and affected parameters For example, trying to override the HTTP method produces this error. This is sample data generated from the current response example; no invalid request is sent. ```json { "status_code": 400, "status": "Bad Request", "message": "HTTP method override is not supported.", "error_code": "invalid_request", "errors": [ "Send the documented HTTP method directly. X-HTTP-Method-Override cannot change a request's HTTP method." ], "error_params": [ "X-HTTP-Method-Override" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` - `status_code` matches the HTTP status. Branch on `error_code`, rather than parsing message text; use the HTTP status as a fallback for an unfamiliar code. - `errors` provides details. `error_params` names affected inputs when the API can identify them; otherwise it is empty. - Keep `request_id`, also returned in `X-Request-Id`, when contacting support@exhibitday.com. | error_code | HTTP status | What it means | What to do | | --- | --- | --- | --- | | `invalid_request` | 400 | A parameter is missing or has an invalid value (error_params names it when the API can tell). This includes any parameter sent more than once with different values (matching copies are accepted), and an expected_revision that is blank, null, malformed or sent to an operation that does not support it. | Correct or review the reported issue before retrying. | | `malformed_json` | 400 | The request body is not valid JSON. The error message says what the parser found and where (line and position), so you can correct the JSON and send it again. | Correct or review the reported issue before retrying. | | `not_allowed` | 400 | The change is not allowed for that record in ExhibitDay (e.g., the event's tasks or its deletion are locked, or its Misc. Expenses & Credits tab is hidden). | Correct or review the reported issue before retrying. | | `idempotency_key_reused` | 400 | The Idempotency-Key was already used with a different request. Use a new key for a new request. | Correct or review the reported issue before retrying. | | `missing_api_key` | 401 | No API key was provided. Send your key in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter. | Check your API key and the workspace's API access. The X-API-Key header also works. | | `invalid_api_key` | 401 | The API key is not valid. Check that you copied the whole key from Workspace Settings > API & Integrations > API Access, then send it in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter. | Check your API key and the workspace's API access. | | `api_access_disabled` | 401 | Access to the ExhibitDay API is not enabled for your workspace. Please contact support@exhibitday.com to enable API Access. Once access is enabled, send your key in the Authorization header as 'Bearer YOUR_API_KEY'. | Check your API key and the workspace's API access. | | `not_found` | 404 | No record with that id exists in your workspace. | Correct or review the reported issue before retrying. | | `unknown_endpoint` | 404 | The URL or HTTP method is not part of the API. | Correct or review the reported issue before retrying. | | `idempotency_key_in_use` | 409 | A request with the same Idempotency-Key is still being processed. Retry after a moment. | Wait briefly, then retry the identical create with the same key. | | `idempotency_key_indeterminate` | 409 | An earlier request did not finish with a confirmed outcome, or its saved response can no longer be returned safely. This retry was not run. Look for the existing record with a GET before deciding whether another create is needed; use a new Idempotency-Key only after checking. | Check the earlier create's outcome before deciding whether a new create is needed. | | `record_changed` | 409 | The record changed while it was being saved or read, or it changed since the read whose record_revision you sent as expected_revision. Nothing was changed by this request. Retrieve its current values, review them and retry only if your change still applies. | Read the current record and review it before deciding whether to send the change again. | | `file_copy_pending` | 409 | This file is still being copied. Try again in a few minutes. | Wait a few minutes, then retry the same Information document download. | | `inventory_busy` | 409 | Another inventory operation is still finishing. This request did not start its event changes; wait briefly, retrieve the event's current state and retry deletion if still needed. | Wait briefly, retrieve the Event and retry deletion only if still needed. | | `attachment_preservation_failed` | 409 | Required reservation attachment copies could not be created. The event and its inventory were not changed. Check the reservation attachments in ExhibitDay before retrying deletion. | Check the reservation File Attachments in ExhibitDay before retrying deletion. | | `rate_limited` | 429 | Too many requests. Wait the number of seconds in the Retry-After header, then retry. | Wait for Retry-After, then retry. | | `internal_error` | 500 | An unexpected error occurred. Please try again later. | A read can be retried after a wait. For a write, follow the outcome checks below; it may already have been saved. | #### Choose a retry based on the request - **GET:** Wait briefly before retrying a temporary server or network failure. Limit how many times you retry. - **POST that supports Idempotency-Key:** Retry with the same key, including its original capitalization, and the same body and parameters. Don't switch to a new key just because a response was lost. If the API cannot confirm the result, check the earlier create before starting a new one. - **POST without Idempotency-Key, or an action that does not support it:** If you get no response or a server error, check whether the record was created or the action took effect before trying again. Stop if you cannot confirm the result. Follow the endpoint's revision rules where supported. - **PATCH or DELETE:** If you get no response or a server error, read the current record. Check whether the change was saved before you send anything else. The create replay rule does not apply. - **record_changed:** This request made no change. Read the record again and check the current values. Use a fresh `record_revision` only if the same update still makes sense. Check any earlier request whose result is unclear separately. - **Validation or access errors:** Fix the request or resolve the access issue before sending it again. After an uncertain DELETE, `not_found` on a read means the record is unavailable at that URL. `unknown_endpoint` means the URL or HTTP method needs correction. Do not infer a successful delete from a routing error. #### Wait when the rate limit is reached The standard workspace allowance is 50 calls per second. When the request reaches the workspace rate check, `X-RateLimit-Limit`, `X-RateLimit-Remaining` and `X-RateLimit-Reset` describe its effective allowance. On HTTP 429, wait the number of seconds in `Retry-After` before retrying. #### Correct request conditions instead of retrying them When an operation supports `expected_revision`, send a valid token. Blank, null, malformed or conflicting repeated tokens return HTTP 400 `invalid_request`, with `expected_revision` in `error_params`. You can send a supported parameter more than once if every copy has the same value. If the copies differ, the API returns HTTP 400. The error identifies the parameter and where it was sent. Use the actual HTTP method: `X-HTTP-Method-Override` and form/query `_method` tunneling are refused. Responses can contain warnings for ignored, unknown, unsupported or defaulted inputs, including error responses, so a misspelled parameter behind an error is pointed out. Warnings can also report attachments that could not be copied to an inventory return. Check the `X-API-Warnings` header for ignored inputs. A response object can also include `warnings`. `X-API-Warnings-Count` reports the full count; `X-API-Warnings-Truncated` indicates that the 6,000-character header limit was reached. Use the default object response for the full warning list. #### Example response Response 200 — OK 304 — Not Modified 400 — Bad Request 401 — Unauthorized 429 — Too Many Requests 500 — Internal Server Error Example Successful request ```json { "records_found": 4, "list_type": "payment_status", "list_data": [ { "id": 0, "name": "Not Specified" }, { "id": 1, "name": "Paid in Full" }, { "id": 2, "name": "Partially Paid" }, { "id": 3, "name": "Not Paid Yet" } ] } ``` Note: The first payment status read. The repeat read with the ETag can return HTTP 304 with no body. The error example on this page is sample data. The program parses that sample locally. Note: There is no response body. Keep using your cached response. ```json { "status_code": 400, "status": "Bad Request", "message": "HTTP method override is not supported.", "error_code": "invalid_request", "errors": [ "Send the documented HTTP method directly. X-HTTP-Method-Override cannot change a request's HTTP method." ], "error_params": [ "X-HTTP-Method-Override" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "No API key was provided. Send your key in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "missing_api_key", "errors": [ "Copy the key from Workspace Settings > API & Integrations > API Access in ExhibitDay." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "The API key is not valid. Check that you copied the whole key from Workspace Settings > API & Integrations > API Access, then send it in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.", "error_code": "invalid_api_key", "errors": [ "Check that you sent the whole key. If it was regenerated, use the current key from Workspace Settings > API & Integrations > API Access." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 401, "status": "Unauthorized", "message": "Access to the ExhibitDay API is not enabled for your workspace. Please contact support@exhibitday.com to enable API Access. Once access is enabled, send your key in the Authorization header as 'Bearer YOUR_API_KEY'.", "error_code": "api_access_disabled", "errors": [ "Nothing was read or changed." ], "error_params": [ "api_key" ], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 429, "status": "Too Many Requests", "message": "Error 429 - Too Many Requests", "error_code": "rate_limited", "errors": [ "Error 429 - Too Many Requests" ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "An unexpected error occurred. Please try again later." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` Note: Use the request_id from your own response when contacting support. ```json { "status_code": 500, "status": "Unexpected Internal Error", "message": "An unexpected error occurred. Please try again later.", "error_code": "internal_error", "errors": [ "Check whether your change was saved before trying again." ], "error_params": [], "request_id": "0123456789abcdef0123456789abcdef" } ``` #### Related guides - [Avoid Overwriting Someone Else's Changes](https://api.exhibitday.com/Help/V1?guide=update-records-safely) - [Create Tasks from Forms, Tickets or Other Apps](https://api.exhibitday.com/Help/V1?guide=create-tasks) - [Keep Another System Updated with Event and Task Changes](https://api.exhibitday.com/Help/V1?guide=sync-changes)