The authenticated request helpers for the Xero Accounting API, plus HttpError with validation errors and rate limits, retry classification, paging, and Xero date parsing.

Tenant. Every call sends xero-tenant-id: opts.tenant-id, else the xero.tenant.id context variable (from ::xero::oauth/connections). Custom Connections reach one organisation and may omit it. Tenant ids must be GUIDs. A tenant-id in opts that is blank or null is an Err, so a tenant whose id is missing never runs on the configured organisation.

Per-call credentials. Every function that calls the API takes a trailing opts Map, resolved by resolve: opts first, then context, then defaults. Nothing from opts is written to ctx, and per-call credentials are masked in call records. A credential present in opts but blank or null is an Err naming the key, never a fallback to context. Requests only go to Xero's own hosts; there is no per-call URL.

Per-call options (besides credentials): tenant-id, if-modified-since (only records changed since; a timestamp such as 2026-10-01T00:00:00, UTC), idempotency-key (up to 128 characters; Xero returns the original result for a repeated key on a write, and the call becomes eligible for the one immediate retry), and retry: false.

Rate limits. Per organisation: 60 calls a minute and 5,000 a day (1,000 a day on the free Starter tier), 5 concurrent calls; 10,000 a minute across the app. Xero reports what is left in X-MinLimit-Remaining, X-DayLimit-Remaining and X-AppMinLimit-Remaining. rate-limits(headers) reads them; last-rate-limits(opts) returns the latest for a tenant in this run, and HttpError.rate-limits carries them. A 429 has Retry-After (seconds) and X-Rate-Limit-Problem (minute, day or appminute). This package never waits: check is-retryable and let a Hot retry policy back off; for a day problem, retry tomorrow.

Context Vars

Optional
  • xero.tenant.id

Values

GUID_PATTERN

GUID_PATTERN: Str "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"

MAX_PAGES

MAX_PAGES: Int 10000

RETRY_STATUSES

RETRY_STATUSES: Vec [
  408,
  429,
  500,
  502,
  503,
  504
]

Functions

api-url

fn (path: Str, params: Map): Str

The full Accounting API URL for path (starting with /) and params (pure).

Example

::xero::api/api-url("/Invoices", {page: 2})  // "https://api.xero.com/api.xro/2.0/Invoices?page=2"

build-headers

fn (token: Str, tenant: Str?, opts: Map, json-body: Bool, extra: Map): Map

Request headers (pure): Bearer auth, Accept (default application/json), xero-tenant-id when set, If-Modified-Since and Idempotency-Key from opts, Content-Type: application/json for a Map/Vec body. extra headers win.

Example

headers ::xero::api/build-headers("TOKEN", "c2cc9b6e-9458-4c7d-93cc-f02b81b0594f", {idempotency-key: "order-1"}, true, {})
headers.Authorization  // "Bearer TOKEN"
headers.xero-tenant-id  // "c2cc9b6e-9458-4c7d-93cc-f02b81b0594f"
headers.Idempotency-Key  // "order-1"
headers.Content-Type  // "application/json"

build-request

fn (method: Str, url: Str, token: Str, tenant: Str?, body: Any, opts: Map, extra: Map): ::hot::http/HttpRequest

Build the outgoing HttpRequest (pure). Map/Vec bodies are JSON; Str/Bytes bodies are sent verbatim (set Content-Type in extra); ""/null send none.

Example

req ::xero::api/build-request("PUT", "https://api.xero.com/api.xro/2.0/Contacts", "TOKEN", null, {Contacts: []}, {}, {})
req.method  // "PUT"
req.body  // "{\"Contacts\":[]}"

bytes

fn (path: Str, accept: Str, opts: Map): Bytes

GET path as binary with Accept: accept (e.g. a PDF or an attachment). Returns Bytes, or an Err carrying HttpError.

Example

pdf ::xero::api/bytes("/Invoices/243216c5-369e-4056-ac67-05388f86dc81", "application/pdf", {})
length(pdf)

connections

fn (): Vec
fn (opts: Map): Vec

GET /connections with the credentials from opts / context (see ::xero::oauth/connections for the fields). No tenant header is needed. opts.auth-event-id narrows the list.

Example

orgs ::xero::api/connections()
map(orgs, %.tenantName)

// With one user's credentials
::xero::api/connections({access-token: ::hot::ctx/get("acme.xero.access-token")})

delete-connection

fn (connection-id: Str): Bool
fn (connection-id: Str, opts: Map): Bool

DELETE /connections/{id} with the credentials from opts / context: disconnect one organisation (the connection id, not the tenant id). Returns true.

Example

orgs ::xero::api/connections()
::xero::api/delete-connection(first(orgs).id)

is-connection-failure

fn (message: Str): Bool

True when a transport error message is a connection or read failure, not a size-limit or URL error.

Example

::xero::api/is-connection-failure("request failed: connection reset")  // true
::xero::api/is-connection-failure("request failed: body exceeds 10 MB")  // false

is-retryable

fn (error: Result): Bool

True when a failed call is worth retrying later: an HttpError (or Err holding one) with status 408, 429 or 5xx, or a connection failure. False for successes and permanent errors (400 validation, 401, 403, 404). A 429 with rate-limits.problem: "day" is retryable only after the daily reset; schedule accordingly.

sync-xero
meta {schedule: "every 30 minutes", retry: {attempts: 5, delay: 5000, backoff: "exponential", max_delay: 120000}}
fn (event) {
  page ::xero::accounting/list-page("Invoices", {page: 1})
  cond {
    ::xero::api/is-retryable(page) => { fail(`xero: retrying later: ${err-message(page)}`) }
    is-err(page) => { println(`xero: giving up: ${err-message(page)}`) }
    => { length(page.items) }
  }
}

json

fn (method: Str, path: Str): Any
fn (method: Str, path: Str, params: Map, body: Any, opts: Map): Any
fn (method: Str, path: Str, params: Map, body: Any, extra-headers: Map, opts: Map): Any

Like request, but unwrapped (see unwrap). Use it for endpoints the typed modules do not cover.

currencies ::xero::api/json("GET", "/Currencies", {}, "", {})

last-rate-limits

fn (): Map?
fn (opts: Map): Map?

The rate limits from the most recent call in this run for the tenant in opts / context (see rate-limits), or null before any call.

Example

::xero::accounting/list-page("Contacts")
limits ::xero::api/last-rate-limits()
limits.minute-remaining

// For a call made with tenant-id in opts
::xero::api/last-rate-limits({tenant-id: "c2cc9b6e-9458-4c7d-93cc-f02b81b0594f"})

next-page

fn (page: Int, size: Int, count: Int, pagination: Any): Int?

The page number after page, or null when it was the last (pure). Uses the response's pagination.pageCount when Xero sends it (the endpoints that accept pageSize), else whether the page was full (count rows for page size size).

Example

::xero::api/next-page(1, 100, 100, null)  // 2
::xero::api/next-page(1, 100, 40, null)  // null
::xero::api/next-page(2, 500, 500, {pageCount: 2})  // null

parse-date

fn (value: Any): Int?

Xero's JSON date ("/Date(1761955200000+0000)/") as epoch milliseconds (Int), or null for anything else. Xero also sends ISO strings in fields such as DateString; read those directly.

Example

::xero::api/parse-date("/Date(1761955200000+0000)/")  // 1761955200000
::xero::api/parse-date("2026-11-01")  // null

query-string

fn (params: Map): Str

Build a ?a=1&b=2 suffix (pure): nulls dropped, Bools as true/false, Vecs comma-joined (IDs, Statuses, ContactIDs), keys and values percent-encoded (spaces as %20, " as %22). "" when nothing remains.

Example

::xero::api/query-string({page: 2, Statuses: ["PAID", "VOIDED"], where: null})  // "?page=2&Statuses=PAID,VOIDED"
::xero::api/query-string({})  // ""

rate-limits

fn (headers: Map?): Map

Rate-limit state from response headers (pure): {minute-remaining, day-remaining, app-minute-remaining, retry-after, problem}, each null when absent. problem is Xero's X-Rate-Limit-Problem (minute, day, appminute) on a 429.

Example

limits ::xero::api/rate-limits({"x-minlimit-remaining": "58", "x-daylimit-remaining": "4990"})
limits.minute-remaining  // 58
limits.day-remaining  // 4990
limits.problem  // null

rate-limits-key

fn (tenant: Str?): Str

The context key the latest rate limits for a tenant are kept under: xero.rate-limits.{tenant-id} (.default without a tenant).

Example

::xero::api/rate-limits-key("acme")  // "xero.rate-limits.acme"
::xero::api/rate-limits-key(null)  // "xero.rate-limits.default"

request

fn (method: Str, path: Str, params: Map, body: Any, opts: Map): ::hot::http/HttpResponse
fn (method: Str, path: Str, params: Map, body: Any, extra-headers: Map, opts: Map): ::hot::http/HttpResponse

Make an authenticated Accounting API request and return the raw HttpResponse (non-2xx included), or an Err for credential, config and transport failures. path is relative to /api.xro/2.0 (e.g. /Invoices); params go in the query string; body is a Map/Vec (JSON), Str/Bytes (verbatim; set Content-Type in extra-headers) or "". See the namespace doc for opts.

Example

response ::xero::api/request("GET", "/Currencies", {}, "", {})
response.status

// Extra headers, and a tenant for this call
xml ::xero::api/request("GET", "/Currencies", {}, "", {Accept: "application/xml"}, {tenant-id: "c2cc9b6e-9458-4c7d-93cc-f02b81b0594f"})
xml.body

resolve

fn (opts: Map): Map

The package's single resolver: everything a call needs from opts, then context, then defaults. Returns {credentials, tenant-id, idempotency-key} (credentials as ::xero::auth/credentials-from describes), or the first Err (malformed tenant id, over-long idempotency key, a blank credential in opts, no credentials). It only reads context; per-call values are never written to it, so parallel flows for different users and organisations stay apart, and per-call credentials are masked in call records.

user-refresh-token ::hot::ctx/get("acme.xero.refresh-token")
r ::xero::api/resolve({tenant-id: "c2cc9b6e-9458-4c7d-93cc-f02b81b0594f", refresh-token: user-refresh-token})
r.credentials.kind   // "refresh"

retry-budget

fn (opts: Map, method: Str): Int

Immediate retries for a call (0 or 1): none when opts.retry is false/0 or the call is not idempotent (GET, or a write with idempotency-key). Pure.

Example

::xero::api/retry-budget({}, "GET")  // 1
::xero::api/retry-budget({}, "POST")  // 0
::xero::api/retry-budget({idempotency-key: "order-1"}, "POST")  // 1
::xero::api/retry-budget({retry: false}, "GET")  // 0

segment

fn (value: Any): Str

Percent-encode one path segment (an id or file name).

Example

::xero::api/segment("receipt 4411.pdf")  // "receipt%204411.pdf"

tenant-id

fn (opts: Map): Str?

The tenant for a call: opts.tenant-id, else xero.tenant.id; null when neither is set. A tenant-id in opts that is blank or null is an Err.

Example

::xero::api/tenant-id({tenant-id: "c2cc9b6e-9458-4c7d-93cc-f02b81b0594f"})  // "c2cc9b6e-9458-4c7d-93cc-f02b81b0594f"
is-err(::xero::api/tenant-id({tenant-id: ""}))  // true

unwrap

fn (response: Result): Any

The decoded body of a 2xx response (null for 204, {not-modified: true} for 304), the Err of a failed request, or err(HttpError).

Example

::http ::hot::http

::xero::api/unwrap(::http/HttpResponse({status: 200, body: {Id: "a1"}}))  // {Id: "a1"}
::xero::api/unwrap(::http/HttpResponse({status: 304, body: ""}))  // {not-modified: true}
is-err(::xero::api/unwrap(::http/HttpResponse({status: 400, body: ""})))  // true

validate-tenant-id

fn (value: Any): Str?

A tenant id (GUID) or null when blank; anything else is an Err. Pure.

Example

::xero::api/validate-tenant-id("c2cc9b6e-9458-4c7d-93cc-f02b81b0594f")  // "c2cc9b6e-9458-4c7d-93cc-f02b81b0594f"
::xero::api/validate-tenant-id("")  // null
is-err(::xero::api/validate-tenant-id("acme"))  // true

validation-messages

fn (body: Any): Vec

Every validation message in an error body (pure): top-level ValidationErrors and each Elements[].ValidationErrors, de-duplicated, in order.

Example

::xero::api/validation-messages({Elements: [{ValidationErrors: [{Message: "Email address must be valid."}]}]})  // ["Email address must be valid."]

Types

HttpError

HttpError type {
    status: Int,
    headers: Map?,
    body: Any,
    message: Str,
    error-type: Str?,
    error-number: Int?,
    validation-errors: Vec?,
    rate-limits: Map?,
    retry-after: Int?,
    correlation-id: Str?
}

A non-2xx Xero response.

  • status, headers, body - the raw response
  • message - readable, e.g. "xero: HTTP 400 ValidationException: A validation exception occurred: Email address must be valid."
  • error-type, error-number - Xero's Type / ErrorNumber (ValidationException, QueryParseException, ...)
  • validation-errors - every Elements[].ValidationErrors[].Message (and top-level ValidationErrors), de-duplicated
  • rate-limits - see rate-limits; retry-after - seconds on a 429
  • correlation-id - the xero-correlation-id header, for Xero support