Transport for the Middesk API: environment selection from the key prefix, Basic auth with the API key as the username, JSON bodies with unset fields dropped, page-number pagination (page, per_page, has_more), and errors parsed into HttpError with TINs, SSNs and birth dates redacted.

No retries. Nothing here retries or waits. Middesk allows about 20 requests per second per key (and 5 per 15 seconds for PATCH /businesses/{id}); a 429 comes back as err(HttpError). Check is-retryable and let a handler or schedule retry policy back off.

Per-call credentials. Every API-calling function takes an optional trailing options Map, resolved by resolve: options first, then the context variables, then the defaults. Nothing from options is written to ctx, so one run can serve many Middesk accounts, and per-call keys are masked in call records. An api-key present but blank or null is an error, never a fallback to context.

Context Vars

Optional
  • middesk.api.key
  • middesk.env

Values

MAX_PAGES

MAX_PAGES: Int 1000

RETRYABLE_STATUSES

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

SENSITIVE_KEYS

SENSITIVE_KEYS: Vec [
  "tin",
  "ssn",
  "dob",
  "socialsecuritynumber",
  "dateofbirth",
  "birthdate",
  "secret",
  "apikey",
  "authorization",
  "downloadurl"
]

USER_AGENT

USER_AGENT: Str "hot-dev-middesk/0.1.0"

Functions

auth-header

fn (api-key: Str): Str

Middesk Basic auth: the API key as the username and an empty password, Basic base64("{key}:"). Exposed for testing.

Example

::middesk::api/auth-header("mk_test_...")  // "Basic bWtfdGVzdF8uLi46"

base-url

fn (env: Str): Str

The base URL for an environment name (see ::middesk/ENVIRONMENTS).

Example

::middesk::api/base-url("sandbox")  // "https://api-sandbox.middesk.com/v1"

build-request

fn (method: Str, url: Str, body: Any, api-key: Str): ::hot::http/HttpRequest

Build (without sending) the HttpRequest for a Middesk call. A non-empty Map body is compacted and JSON-encoded; otherwise no body is sent. Exposed for testing.

Example

req ::middesk::api/build-request("get", "https://api-sandbox.middesk.com/v1/businesses", null, "mk_test_...")
req.method  // "GET"
req.headers.Authorization  // "Basic bWtfdGVzdF8uLi46"

call

fn (method: Str, path: Str): Any
fn (method: Str, path: Str, params: Map): Any
fn (method: Str, path: Str, params: Map, options: Map): Any

Call a Middesk endpoint by path (relative to /v1) and return the decoded JSON, or an Err carrying HttpError. params become the query string for GET and DELETE and the JSON body otherwise. The escape hatch for endpoints without a typed wrapper.

Example

::middesk::api/call("GET", "/tin_match/availability")
::middesk::api/call("POST", "/identities/autocomplete", {name: "Acme Robotics"})

collect

fn (path: Str, params: Map, limit: Int): Vec
fn (path: Str, params: Map, limit: Int, options: Map): Vec

Collect up to limit objects from a list endpoint, following has_more. params takes the endpoint's filters (and per_page).

Example

in-review ::middesk::api/collect("/businesses", {status: "in_review"}, 200)

collect-pages

fn (fetch: Fn, page-number: Int, limit: Int, acc: Vec): Vec

Follow page numbers, concatenating each page's data, until limit items, has_more: false, an empty page, or MAX_PAGES. fetch takes the page number and returns one list page; the first Err is returned. Exposed for testing; collect uses it.

Example

::middesk::api/collect-pages((n) { {data: [n], has_more: lt(n, 3)} }, 1, 10, [])  // [1, 2, 3]

compact

fn (value: Any): Any

Drop null values recursively through maps and the maps inside vectors. false, 0 and "" are kept. Exposed for testing.

Example

::middesk::api/compact({a: 1, b: null, c: [{d: null, e: false}]})
// {a: 1, c: [{e: false}]}

error-entries

fn (body: Any): Vec

Middesk's errors from a decoded error body as {message, parameter} entries (absent parts null). Exposed for testing.

Example

::middesk::api/error-entries({errors: [{message: "Name is required", parameter: "name"}]})
// [{message: "Name is required", parameter: "name"}]

error-message

fn (status: Int, body: Any): Str

The readable message for an error: middesk: HTTP {status}: {message} ({parameter}); ..., or a short excerpt of a text body (Middesk's 429 body is Retry later). Passed through redact-text. Exposed for testing.

Example

::middesk::api/error-message(422, {errors: [{message: "Name is required", parameter: "name"}]})
// "middesk: HTTP 422: Name is required (name)"

::middesk::api/error-message(429, "Retry later")  // "middesk: HTTP 429: Retry later"

error-status

fn (error: Result): Int?

The HTTP status of a failed call (an HttpError or a Result.Err holding one), or null for transport errors.

Example

::middesk::api/error-status(err({status: 422}))  // 422
::middesk::api/error-status(err("connection refused"))  // null

get-bytes

fn (path: Str, options: Map): Bytes

GET a binary endpoint (e.g. /businesses/{id}/pdf) and return the body as Bytes, or an Err carrying HttpError. The bytes are never put into errors or logs.

Example

pdf ::middesk::api/get-bytes("/businesses/biz_a1b2c3/pdf", {})
if(is-err(pdf), ::middesk::api/error-status(pdf), length(pdf))

is-retryable

fn (error: Result): Bool

True when a failed call is worth retrying later: HTTP 408, 429, 500, 502, 503 or 504.

Example

::middesk::api/is-retryable(err({status: 429}))  // true
::middesk::api/is-retryable(err({status: 422}))  // false

is-sensitive-key

fn (key: Any): Bool

True for an attribute name in SENSITIVE_KEYS in any casing (tin, ssn, dob, download_url, ...). Exposed for testing.

Example

::middesk::api/is-sensitive-key("Download-URL")  // true
::middesk::api/is-sensitive-key("name")  // false

key-env

fn (api-key: Str): Str?

The environment a key belongs to by prefix: mk_test_ is "sandbox", mk_live_ is "production", anything else null. Exposed for testing.

Example

::middesk::api/key-env("mk_test_...")  // "sandbox"
::middesk::api/key-env("mk_live_...")  // "production"
::middesk::api/key-env("other")  // null

list-page

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

GET one page of a list endpoint. params takes page (from 1) and per_page, plus the endpoint's filters. Returns {object: "list", data, has_more, total_count}; continue with next-page.

Example

page ::middesk::api/list-page("/businesses", {page: 1, per_page: 10, status: "in_review"})

next-page

fn (response: Any, current: Int): Int?

The page number after page when the list response says has_more: true, else null. current is the page that was requested (1 when unset).

Example

::middesk::api/next-page({has_more: true}, 1)  // 2
::middesk::api/next-page({has_more: false}, 3)  // null

parse-int

fn (value: Any): Int?

An Int from an Int or a decimal-digit Str; null for anything else. Never errs on bad input. Exposed for testing.

Example

::middesk::api/parse-int("42")  // 42
::middesk::api/parse-int("soon")  // null

query-string

fn (params: Map): Str

?a=1&b=2 from params, dropping nulls; Vec values are comma-joined (Middesk's tags=a,b style). "" when nothing remains. Exposed for testing.

Example

::middesk::api/query-string({page: 2, tags: ["a", "b"], status: null})
// "?page=2&tags=a%2Cb"

::middesk::api/query-string({})  // ""

redact

fn (value: Any): Any

Remove PII from a decoded body: values under sensitive keys become "[redacted]", other strings are masked by redact-text. Applied to every HttpError. Exposed for testing.

Example

::middesk::api/redact({name: "Acme", tin: "123410000", notes: ["call 512 555 0100"]})
// {name: "Acme", tin: "[redacted]", notes: ["call [redacted]"]}

redact-text

fn (text: Str): Str

Mask what could be PII in free text: runs of four or more digits (allowing spaces, dots, slashes and dashes inside, so TINs, SSNs and birth dates) become [redacted], and email addresses become [redacted-email]. Exposed for testing.

Example

::middesk::api/redact-text("TIN 12-3456789, jane@acme.com")
// "TIN [redacted], [redacted-email]"

resolve

fn (options: Any): Map

Credentials for one call: options (a Map, or a RequestOptions, with api-key, env) over the context variables (see resolve-from). An api-key from options is masked in call records and returned unchanged; nothing is written to ctx, so parallel flows and tenants never share credentials.

Example

// From the context variables
creds ::middesk::api/resolve({})
creds.env

// A second account for this call only
other ::middesk::api/resolve({api-key: ::hot::ctx/get("acme.middesk.api.key")})
other.env
Context Vars: middesk.api.key, middesk.env

resolve-env

fn (api-key: Str, configured: Str?): Str

The environment for a key and an optional configured name: the key's prefix decides; a configured "sandbox"/"production" must agree with it (Middesk rejects a key on the other host) and is used for keys without a known prefix; neither gives "sandbox". An unknown name or a mismatch is an Err. Exposed for testing.

Example

::middesk::api/resolve-env("mk_test_...", null)  // "sandbox"
::middesk::api/resolve-env("other", "production")  // "production"
is-err(::middesk::api/resolve-env("mk_live_...", "sandbox"))  // true

resolve-from

fn (options: Map, ctx-values: Map): Map

The one resolver, pure: {api-key, env} for a call from options first (api-key, env), then ctx-values (a Map of context variables), then defaults. An Err when no key is set, when api-key is in options but blank or null (that never falls back to context), or when the environment is invalid (see resolve-env). Nothing is written to ctx. Exposed for testing; resolve feeds it the context.

Example

::middesk::api/resolve-from({env: "sandbox"}, {"middesk.api.key": "mk_test_..."}).env  // "sandbox"
is-err(::middesk::api/resolve-from({}, {}))  // true

seg

fn (id: Any): Str

Percent-encode one path segment (an id).

Example

::middesk::api/seg("biz 1")  // "biz%201"

send

fn (method: Str, path: Str, query: Map, body: Any, options: Map): Any

Send one Middesk request: path is relative to /v1, query becomes the query string, a Map body the JSON body (null sends none). Returns the decoded body on 2xx, or an Err: HttpError for non-2xx, or the transport error.

Example

biz ::middesk::api/send("GET", "/businesses/biz_a1b2c3", {}, null, {})
if(is-err(biz), ::middesk::api/error-status(biz), biz.status)

// A POST body, with a key for this call only
::middesk::api/send("POST", "/businesses/biz_a1b2c3/orders", {}, {product: "liens"}, {
  api-key: ::hot::ctx/get("acme.middesk.api.key")
})

Types

HttpError

HttpError type {
    status: Int,
    headers: Map,
    body: Any,
    message: Str,
    errors: Vec,
    parameter: Str?,
    retry-after: Int?
}

A non-2xx Middesk response.

  • status: the HTTP status (422 for validation errors, 429 for rate limits)
  • errors: Middesk's errors array, each {message, parameter?} (redacted)
  • parameter: the first error's parameter, e.g. "name"
  • retry-after: the Retry-After header in seconds, else null (only the sandbox creation limit sends it)
  • message: one readable line, e.g. "middesk: HTTP 422: Name is required (name)"
  • headers, body: the response, with the body redacted

TINs, SSNs, birth dates and long digit runs are redacted from body, errors and message, so an HttpError is safe to log.

RequestOptions

RequestOptions type {
    api-key: Str?,
    env: Str?
}

Per-request options, the optional last argument of every function that calls the API. A plain Map with the same keys works too.

  • api-key: overrides middesk.api.key for this call. Masked in call records. Blank or null is an error, never a fallback to context.
  • env: overrides middesk.env for this call

Middesk has no idempotency keys. To make a create safe to retry, set unique_external_id on the business: Middesk refuses a second business with the same value.