The authenticated request helpers for the Accounting API, plus environment and realm handling, the pinned minorversion, Intuit Fault parsing and retry classification.

Environment. quickbooks.environment (or opts.environment) is sandbox or production; unset means production. Anything else is an Err, so a typo never sends sandbox credentials to production or the reverse. Sandbox and production companies have different realm ids and tokens, so a per-call environment that differs from quickbooks.environment needs a credential (access-token, refresh-token or token-store) in the same opts: context credentials never go to the other environment's host.

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, realm-id or environment present in opts but blank or null is an Err naming the key, never a fallback to context.

Company. Every call is scoped to /v3/company/{realmId}: the quickbooks.realm.id context variable or opts.realm-id. Realm ids must be digits.

Idempotent writes. Pass opts.request-id (at most 50 characters, unique per operation) on a create or update: Intuit sends it as requestid and returns the original result for a repeated id instead of writing twice. Such calls are then also eligible for the one immediate retry on a connection failure.

Retry. This package never waits. A connection failure on a GET (or a POST with request-id, or a query) is retried once, immediately (opts.retry: false turns that off). 429 throttling and 5xx come back as err(HttpError); check is-retryable and let a Hot retry policy back off (see https://hot.dev/docs/retries). Intuit allows about 500 requests a minute and 10 concurrent requests per company, and 40 batch requests a minute.

401. When a cached token is rejected, it is evicted and the call is retried once with a freshly refreshed token.

Context Vars

Optional
  • quickbooks.realm.id
  • quickbooks.environment
  • quickbooks.minorversion

Values

MAX_IMMEDIATE_RETRIES

MAX_IMMEDIATE_RETRIES: Int 1

RETRY_FAULT_CODES

RETRY_FAULT_CODES: Vec [
  "3001",
  "003001"
]

RETRY_STATUSES

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

Functions

base-url

fn (env: Str): Str

The API host for an environment: https://sandbox-quickbooks.api.intuit.com or https://quickbooks.api.intuit.com.

Example

::quickbooks::api/base-url("sandbox")  // "https://sandbox-quickbooks.api.intuit.com"
::quickbooks::api/base-url("production")  // "https://quickbooks.api.intuit.com"

body-excerpt

fn (body: Any): Str

A short (at most 300 characters) printable form of a body, for error messages.

Example

::quickbooks::api/body-excerpt("Service unavailable")  // "Service unavailable"
::quickbooks::api/body-excerpt(null)  // ""

build-request

fn (method: Str, url: Str, token: Str, body: Any, headers: Map): ::hot::http/HttpRequest

Build the outgoing HttpRequest (pure). Map/Vec bodies are sent as JSON; a Str body is sent verbatim (set its Content-Type in headers); "" or null sends no body. Accept defaults to application/json. Caller headers win.

Example

token ::hot::ctx/get("quickbooks.access.token")
url "https://sandbox-quickbooks.api.intuit.com/v3/company/9341453/customer?minorversion=75"
req ::quickbooks::api/build-request("POST", url, token, {DisplayName: "Acme Corp"}, {})
req.headers.Content-Type  // the Map body is sent as JSON

bytes

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

GET path as binary (e.g. /invoice/130/pdf) with Accept: accept. Returns the response Bytes, or an Err carrying HttpError.

Example

pdf ::quickbooks::api/bytes("/invoice/130/pdf", "application/pdf", {realm-id: "9341453"})
length(pdf)

call-environment

fn (opts: Map): Str

environment(opts), or an Err when environment in opts differs from quickbooks.environment and opts has no credential of its own (access-token, refresh-token or token-store): sandbox and production tokens differ, so context credentials never go to the other environment's host.

Example

// Sandbox calls from a production project bring their own credential
::quickbooks::api/call-environment({
  environment: "sandbox",
  access-token: ::hot::ctx/get("quickbooks.access.token")
})

company-url

fn (env: Str, realm: Str, minor: Str, path: Str, params: Map): Str

The full URL for a company-scoped path (pure): {host}/v3/company/{realm}{path} with minorversion and params in the query. path starts with /.

::quickbooks::api/company-url("sandbox", "9341453", "75", "/invoice/130/pdf", {})
// "https://sandbox-quickbooks.api.intuit.com/v3/company/9341453/invoice/130/pdf?minorversion=75"

environment

fn (opts: Map): Str

The environment for a call: opts.environment, else quickbooks.environment, else production. An environment in opts that is blank or null is an Err, so it never means production by accident.

Example

::quickbooks::api/environment({environment: "sandbox"})  // "sandbox"
is-err(::quickbooks::api/environment({environment: ""}))  // true

fault-details

fn (body: Any): Map

Parse an Intuit Fault ({Fault: {Error: [{Message, Detail, code, element}], type}}, or the lowercase shape of authentication failures) into {fault-type, errors}, where each error is {message, detail, code, element}. errors is empty when the body has no fault. Pure.

Example

body {Fault: {type: "ValidationFault", Error: [{Message: "Duplicate Name", code: "6240"}]}}
::quickbooks::api/fault-details(body)
// {fault-type: "ValidationFault", errors: [{message: "Duplicate Name", code: "6240"}]}

fault-of

fn (body: Any): Map?

The Fault object of a decoded body (either case), or null.

Example

::quickbooks::api/fault-of({Fault: {type: "ValidationFault"}})  // {type: "ValidationFault"}
::quickbooks::api/fault-of({Invoice: {Id: "130"}})  // null

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

::quickbooks::api/is-connection-failure("request failed: connection reset")  // true
::quickbooks::api/is-connection-failure("request failed: body exceeds limit")  // 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 Intuit's throttling fault code 3001; or a connection failure. False for successes and for permanent errors (400 validation, 401, 403, 404, stale SyncToken).

This package never waits and retries for you; give the handler or schedule a retry policy and fail the run when this is true.

sync-invoices
meta {schedule: "every 15 minutes", retry: {attempts: 5, delay: 2000, backoff: "exponential", max_delay: 60000}}
fn (event) {
  page ::quickbooks::query/query("select * from Invoice where Balance > '0'")
  cond {
    ::quickbooks::api/is-retryable(page) => { fail(`quickbooks: retrying later: ${err-message(page)}`) }
    is-err(page) => { println(`quickbooks: 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, headers: Map, opts: Map): Any

Like request, but unwrapped: the decoded JSON body, or an Err carrying HttpError (credential problems carry ::quickbooks::oauth/TokenError). Use it for any endpoint the typed modules do not cover.

prefs ::quickbooks::api/json("GET", "/preferences", {}, "", {})

minorversion

fn (opts: Map): Str

The minorversion for a call: opts.minorversion, else quickbooks.minorversion, else MINOR_VERSION.

Example

::quickbooks::api/minorversion({minorversion: 80})  // "80"

query-string

fn (params: Map): Str

Build a ?a=1&b=2 suffix from a Map: null values are dropped, Bools encode as true/false, Vecs are comma-joined (entities=Invoice,Bill), and keys and values are percent-encoded (spaces as %20). "" when nothing remains. Pure.

Example

::quickbooks::api/query-string({operation: "void", include: null})  // "?operation=void"
::quickbooks::api/query-string({entities: ["Invoice", "Bill"]})  // "?entities=Invoice,Bill"
::quickbooks::api/query-string({})  // ""

realm-id

fn (opts: Map): Str

The company for a call: opts.realm-id, else quickbooks.realm.id. A realm-id in opts that is blank or null is an Err, so a tenant whose id is missing never runs on the configured company.

Example

::quickbooks::api/realm-id({realm-id: "9341453"})  // "9341453"
is-err(::quickbooks::api/realm-id({realm-id: ""}))  // true

request

fn (method: Str, path: Str, params: Map, body: Any, opts: Map): ::hot::http/HttpResponse
fn (method: Str, path: Str, params: Map, body: Any, 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 /v3/company/{realm} (e.g. /invoice/130); params go in the query string with minorversion; body is a Map (JSON), a Str (verbatim, set Content-Type in headers) or "". opts carries per-call credentials, realm-id, environment, minorversion, request-id and retry.

Example

response ::quickbooks::api/request("GET", "/invoice/130", {}, "", {realm-id: "9341453"})
if(::hot::http/is-ok-response(response), response.body.Invoice.Balance, response.status)

// Six arguments add request headers
::quickbooks::api/request("POST", "/query", {}, "select * from Vendor", {Content-Type: "application/text"}, {idempotent: true})

resolve

fn (opts: Map): Map

The package's single resolver: everything a call needs from opts, then context, then defaults. Returns {credentials, environment, realm-id, minorversion, request-id} (credentials as ::quickbooks::auth/credentials-from describes), or the first Err (bad environment, a per-call environment without a per-call credential, missing or malformed realm, retired minorversion, a blank credential in opts, no credentials). It only reads context; per-call values are never written to it, so parallel flows for different companies stay apart, and per-call credentials are masked in call records.

tenant-refresh-token ::hot::ctx/get("quickbooks.refresh.token")
r ::quickbooks::api/resolve({realm-id: "9341453", refresh-token: tenant-refresh-token, environment: "sandbox"})
r.credentials.kind   // "refresh"

resolved-url

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

The full URL for path and params from a resolve result (pure).

Example

resolved {environment: "sandbox", realm-id: "9341453", minorversion: "75", request-id: null}
::quickbooks::api/resolved-url(resolved, "/invoice/130", {})
// "https://sandbox-quickbooks.api.intuit.com/v3/company/9341453/invoice/130?minorversion=75"

retry-after-seconds

fn (headers: Map?): Int?

A numeric Retry-After header as whole seconds, or null.

Example

::quickbooks::api/retry-after-seconds({retry-after: "30"})  // 30
::quickbooks::api/retry-after-seconds({})  // null

retry-budget

fn (opts: Map, idempotent: Bool): Int

How many immediate retries a call gets (0 or 1): none when opts.retry is false or 0, or when the call is not idempotent. Pure.

Example

::quickbooks::api/retry-budget({}, true)  // 1
::quickbooks::api/retry-budget({retry: false}, true)  // 0
::quickbooks::api/retry-budget({}, false)  // 0

segment

fn (value: Any): Str

Percent-encode one path segment (an entity id). Ints pass through as text.

Example

::quickbooks::api/segment("a b")  // "a%20b"
::quickbooks::api/segment(130)  // "130"

unwrap

fn (response: Result): Any

The decoded body of a successful response; an Err for transport failures; err(HttpError) for non-2xx responses and for 2xx bodies that carry a Fault.

Example

ok-response ::hot::http/HttpResponse({status: 200, body: {Invoice: {Id: "130"}}})
::quickbooks::api/unwrap(ok-response).Invoice.Id  // "130"

failed ::hot::http/HttpResponse({status: 404, body: ""})
is-err(::quickbooks::api/unwrap(failed))  // true

validate-environment

fn (value: Any): Str

"sandbox" or "production" (trimmed, lowercased) from a value; null means production. Anything else is an Err. Pure.

Example

::quickbooks::api/validate-environment(" Sandbox ")  // "sandbox"
::quickbooks::api/validate-environment(null)  // "production"
is-err(::quickbooks::api/validate-environment("staging"))  // true

validate-minorversion

fn (value: Any): Str

A minorversion as a digit Str: null means MINOR_VERSION; values below MIN_MINOR_VERSION (retired by Intuit) and non-numbers are Errs. Pure.

Example

::quickbooks::api/validate-minorversion(null)  // "75"
::quickbooks::api/validate-minorversion(80)  // "80"
is-err(::quickbooks::api/validate-minorversion(60))  // true

validate-realm-id

fn (value: Any): Str

A realm id (company id) as a digit Str, or an Err. Ints are accepted. Pure.

Example

::quickbooks::api/validate-realm-id(9341453)  // "9341453"
is-err(::quickbooks::api/validate-realm-id("acme"))  // true

validate-request-id

fn (value: Any): Str?

An opts.request-id (1-50 characters) or null; longer values are an Err. Pure.

Example

::quickbooks::api/validate-request-id("order-4411-invoice")  // "order-4411-invoice"
::quickbooks::api/validate-request-id(null)  // null

Types

HttpError

HttpError type {
    status: Int,
    headers: Map?,
    body: Any,
    message: Str,
    fault-type: Str?,
    code: Str?,
    detail: Str?,
    element: Str?,
    errors: Vec?,
    intuit-tid: Str?,
    retry-after: Int?
}

A failed Accounting API call: a non-2xx response, or a 2xx whose body is an Intuit Fault.

  • status, headers, body - the raw response
  • message - readable, e.g. "quickbooks: HTTP 400 ValidationFault 6240: Duplicate Name Exists Error: The name supplied already exists. (intuit_tid: 1-6730...)"
  • fault-type - ValidationFault, SystemFault, AuthenticationFault, AuthorizationFault, ...
  • code, detail, element - from the first Fault.Error[]
  • errors - every Fault.Error[] as {message, detail, code, element}
  • intuit-tid - the intuit_tid response header; quote it to Intuit support
  • retry-after - seconds from a numeric Retry-After header, else null