Search API documentation

Type to search the API docs.

Handle Errors and Retry Failed Requests

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.

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.

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

{
  "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.

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.

Try it

Before running the example

VariableWhat to put in itRequired?
EXHIBITDAY_API_KEYYour workspace API key.Yes

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
#!/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
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.
{
  "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_codeHTTP statusWhat it meansWhat to do
invalid_request400A 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_json400The 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_allowed400The 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_reused400The 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_key401No 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_key401The 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_disabled401Access 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_found404No record with that id exists in your workspace.Correct or review the reported issue before retrying.
unknown_endpoint404The URL or HTTP method is not part of the API.Correct or review the reported issue before retrying.
idempotency_key_in_use409A 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_indeterminate409An 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_changed409The 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_pending409This file is still being copied. Try again in a few minutes.Wait a few minutes, then retry the same file download.
inventory_busy409Another 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_failed409Required 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_limited429Too many requests. Wait the number of seconds in the Retry-After header, then retry.Wait for Retry-After, then retry.
internal_error500An 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. Keep the same key when a response is 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.
Full payment statuses response examples

Example response

{
  "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.