---
name: accountflow-api
description: Build and debug integrations against the Accountflow public API (Bridge) - OAuth2 client-credentials auth, reading general ledger, accounts, trial balances, VAT, bank, close status and documents, importing a company's books (API ledgers, accounts, dimensions, sub-ledgers, opening balances, general-ledger lines, open items, trial balances), correcting or deleting what was imported, company settings (modules, automation, account settings and reconciliation rules, routines, contacts, intercompany links, chart mapping, account templates), reconciliation runs, document links, the audit log and access reports, async jobs and webhooks. Use whenever code calls an api.*.accountflow.com host, or the user mentions Accountflow, Bridge, or the Accountflow API.
---

# Accountflow public API

You are helping someone build an integration against Accountflow's public API. This
skill was generated for the **prod** environment:

| | |
|---|---|
| API base | `https://api.prod.accountflow.com/v1` |
| Token endpoint | `https://auth.prod.accountflow.com/realms/accountflow/protocol/openid-connect/token` |
| Application (create API clients here) | `https://ajour.accountflow.com` |
| Developer portal and live spec | `https://developer.prod.accountflow.com` · `https://developer.prod.accountflow.com/openapi.yaml` |

Use exactly these hosts: `api.accountflow.com` and `auth.accountflow.com` do not resolve.
(A problem's `type`, `https://api.accountflow.com/errors/<slug>`, is a name, not a URL to call.)

## Work from the spec, never from memory

`references/openapi.yaml` is the released contract: every path, parameter, schema,
scope and status code. **Before writing a call, find its operation there** (search by
`operationId` or path) and take field names and types from the schema. Do not invent
endpoints, fields or query parameters: if the spec does not have it, the API does not
either. The other files in `references/` are the prose guides:

| Need | Read |
|---|---|
| first call, client setup, scopes | `references/quickstart.md` |
| pagination, enums, deletes, idempotency, reach, the `year` rules, reconciliation runs, rate limits | `references/conventions.md` |
| pushing a company's books, moving it from an ERP | `references/imports.md` |
| fixing or deleting pushed data, the 409 in-use rule | `references/corrections.md` |
| every error code and what to do about it | `references/errors.md` |
| webhook events, handshake, signature verification | `references/webhooks.md` |

## Rules that hold everywhere (the ones integrations get wrong)

1. **Auth is OAuth2 client credentials.** POST `grant_type=client_credentials`, `client_id`
   and `client_secret` (form-encoded) to the token endpoint, and **no `scope`**: the
   client's scopes are the ones granted to it in Accountflow. Cache the token until shortly before
   `expires_in`; never mint one per request. Token errors are OAuth-shaped
   (`{"error": "invalid_client"}`), not problem documents. Secrets come from the user's
   secret store or environment, never hard-coded, never logged.
2. **Outside your reach is `404`, never `403`.** A 404 (`resource_not_found`) means "does
   not exist for this client": wrong id, wrong organization, or deleted. Reach is checked
   before anything else in the request. Do not treat it as a permission error and do not
   retry it.
3. **Every `POST`, `PATCH` and `DELETE` needs an `Idempotency-Key` header** (a fresh UUID
   per logical action, reused on retries of that same action; missing is
   `400 idempotency_key_missing`). Same key + same body replays the stored response
   (`Idempotency-Replayed: true`); same key + different body is `422
   idempotency_key_reused`. Keys are scoped per API client and per operation, and a
   stored response is replayed for 24 hours - after that a retry executes again. This
   is what makes retrying after a timeout safe.
4. **Every list is a page**: `{ "data": [...], "pagination": { "nextCursor", "hasMore" } }`.
   Loop **while `hasMore` is true**, sending `nextCursor` back as `cursor`; never stop on a
   short or empty `data` (a page can be empty with `hasMore: true`), and loop on lists that
   are one page today too. Cursors are opaque and bound to the exact filters; never
   construct or modify one. `pageSize` is 1-200 (default 50); anything outside that range
   is `400 validation_failed`, not clamped. The trial balance pages its `accounts`, not
   `data`, with the year's `totals` on every page.
5. **One name per value, one casing rule.** JSON fields, query parameters and path
   parameters are `camelCase` (`pageSize`, `{companyId}`); `error` codes and `reason`
   values are `snake_case`; scopes are `resource:action`; headers are `Http-Case`. **Enum
   values are `UPPER_SNAKE_CASE`** (`RECONCILED`, `AWAITING_CONTROL`), in responses and in
   what you send (filters match any case). Send back exactly as read: aging buckets
   (`0-30`), the account rule language (`balanceRecon.method`, `matchRules` operators) and
   field-name lists (`reset`, a template diff's `field`). A query parameter under a retired
   name is refused, never ignored (`400`, `reason: parameter_renamed`, the replacement in
   `detail`), and many request bodies refuse unknown fields (`400`).
6. **Deletes take no body and answer one shape:** a company, document, reconciliation
   group or webhook endpoint answers `{id, status: "DELETED", deletedAt}`
   (`DELETE /companies/{companyId}?reason=` for the optional audit note). Deleting imported
   data answers `202` with an import. Actions are `POST …/actions/<verb>`.
7. **Money is decimal.** Parse amounts as decimals, never floats. When sending, use
   decimal strings (`"-1250.00"`, at most four decimals) - that is how the spec
   documents import amounts; numbers are accepted too.
8. **Errors are RFC 9457 problem documents** (`application/problem+json`). Branch on
   the machine-readable `error` code, and on `reason` when present; show `detail` to
   humans; log `requestId`. `parameter` names the parameter at fault; `errors[]` items are
   always `{field, message, index?, allowedValues?}`. Do not parse `title` or `detail`.
   `400 validation_failed` is a malformed request (fix the syntax); `422 unprocessable` is
   a well-formed request a rule refused (fix the data).
9. **Retry only what is retryable**: `429` and `503` (honour `Retry-After`), and `409
   idempotency_in_flight`. Network timeouts and a `500` on a mutation: retry with the
   **same** `Idempotency-Key`, and report a repeated `500`'s `requestId`. `409
   job_in_flight`: wait for the named `jobId`, then send. Every other 4xx is a bug in the
   request - fix it, do not retry it. `409` with `reason: company_read_only` means the organization was terminated:
   reads work, writes are refused for 90 days, then everything is `404`. Tell the user.
10. **Long work is `202` + poll.** The body is the resource to poll (for imports, the
   import at `GET /companies/{companyId}/imports/{importId}`); stop on a terminal
   status. Its `jobId` is also pollable at `GET /jobs/{jobId}`, `GET /jobs` lists the
   jobs this client submitted, and `job.succeeded` / `job.failed` webhooks announce
   the same thing.
11. **Every response carries `X-Request-Id`** (problem documents repeat it as
    `requestId`). Log it on every call, and send your own to correlate. Requests
    larger than 8 MiB are refused with `413`.
12. **Tolerate what is new.** `/v1` is additive-only: new fields, enum values, endpoints
    and event types may appear. Response enums are open (`x-extensible-enum`): treat an
    unknown value as "other" and an unknown field as absent; never fail on either.

## A client worth building

Whatever the language, give the integration one small client with: a token cache; a
single request function that sets `Authorization`, sets `Idempotency-Key` on
non-GET calls, parses problem documents into a typed error carrying `status`, `error`,
`reason`, `requestId` and the raw body; the retry policy from rule 9 with capped
exponential backoff; and a pagination helper that yields items across pages (following
`pagination.nextCursor` while `pagination.hasMore`). Then write the feature code on top
of that, not around it.

```python
# Shape, not a library - adapt to the project's HTTP client and conventions.
def request(method, path, *, params=None, json=None, idempotency_key=None):
    headers = {"Authorization": f"Bearer {tokens.get()}"}
    if method != "GET":
        headers["Idempotency-Key"] = idempotency_key or str(uuid.uuid4())
    for attempt in range(5):
        r = http.request(method, BASE + path, params=params, json=json, headers=headers, timeout=30)
        if r.status_code in (429, 500, 503) or (r.status_code == 409 and error_code(r) == "idempotency_in_flight"):
            time.sleep(float(r.headers.get("Retry-After", 2 ** attempt)))
            continue                      # same Idempotency-Key on every attempt
        if r.status_code >= 400:
            raise ApiError.from_problem(r)  # status, error, reason, requestId, body
        return r.json() if r.content else None
    raise ApiError.exhausted()

def items(path, params=None, rows="data"):  # rows="accounts" for the trial balance
    params = dict(params or {})
    while True:
        page = request("GET", path, params=params)
        yield from page[rows]               # may be empty while hasMore is true
        if not page["pagination"]["hasMore"]:
            return
        params["cursor"] = page["pagination"]["nextCursor"]
```

## Importing a company's books

Read `references/imports.md` first. The essentials:

- The company must be bound to the **Api** accounting system in Accountflow, and the
  client needs `imports:write`. `GET /companies/{companyId}/imports/readiness` tells you
  where the company stands (`blockers`, `nextStep`). `409 company_not_api_managed` means
  the binding is missing - that is a setup step for a human, not something to retry.
- **A company moving from an ERP** gets an Api ledger for the year it switches:
  `POST /companies/{companyId}/ledgers` with `{"year": 2026, "setCurrent": true}` (a
  backfill year without `setCurrent` stays beside the current one, `current: false`).
  `GET /companies/{companyId}/ledgers` lists them; both need `imports:write`.
- **Order: accounts → dimensions / sub-ledgers (optional) → opening balances →
  general-ledger lines → open items.** Lines naming an account code missing from that
  year's chart are refused (`422`, `reason: unknown_account_codes`).
- Each request holds **at most 10 000 lines** (`413` beyond). Batch larger data and
  send the batches **sequentially**: one import per kind and company runs at a time
  (`409`, `reason: job_in_flight`, with the `jobId` to wait for).
- Each request answers `202` with an import. **Poll `GET
  /companies/{companyId}/imports/{importId}`** until `SUCCEEDED` or `FAILED`. `SUCCEEDED`
  can still carry `rowsFailed > 0`: read `sampleErrors` (`line N: message`, N from 1), fix
  those lines and re-send them.
- **Lines carry the customer's own stable `id`** (no `:`, `/`, `{`, `}` or whitespace).
  Re-sending an `id` updates that line in place with history kept; a new `id` is a new
  line. Choose ids that are stable in the source system (document number + line number),
  never random per run. Reads return it as `sourceLineId`. A general-ledger line also
  requires `accountCode`, `amount`, `period`, `voucherKey` (your voucher key) and `voucherNo`.
- **`period` (1-12) and `year` are supplied explicitly**, never derived from dates.
- Open items: `subLedgerType` `CUSTOMER` or `SUPPLIER`, `mode` `INCREMENTAL` or a snapshot
  that retires what it leaves out (`BASELINE`, `FULL`, `FULL_REFRESH`), parties by `partyKey`.
- Structural validation failures are `422` with `errors: [{field, message, index}]`
  (index is 0-based into the request's array). Surface them to the user per line. A
  year whose ledger belongs to another accounting system is `409
  company_not_api_managed` even when the company is bound to Api. An import that
  ends `FAILED` with `failureReason` `internal_error` or `job_expired` is safe to
  re-send with a new key.
- `POST …/imports/trial-balance` (a monthly trial balance instead of vouchers) answers
  `409 trial_balance_import_unavailable` until it is switched on for the environment.
- General-ledger, opening-balance and trial-balance imports finish like an ERP fetch: what
  follows a fetch runs, and `erp_fetch.completed` is announced. Other kinds start nothing.

## Correcting and deleting

Read `references/corrections.md`. To change values, **re-send the same `id`**. To
remove, use the deletion endpoints (`…/imports/general-ledger-lines/deletions`,
`…/imports/opening-balances/deletions`, `DELETE …/accounts/{accountNumber}`,
`…/dimensions/{key}`, `…/sub-ledgers/{partyKey}`). Deletion is **all or nothing**, and
anything that work in Accountflow depends on is **never deleted**: the answer is `409`
with a `reason` (`lines_in_use`, `account_in_use`, …) and an `inUse` list of ids and
dependencies. Do not loop on that 409. Report the `inUse` list to the user; the ways
out are removing the dependent work in Accountflow, posting a reversing line, or (for
accounts) importing with `hidden: true`. Ids the ledger does not have come back under
`result.unknown` on the import - not an error, so deletions are safe to retry.

## Reading data

Reads need the matching read scope (`ledger:read`, `vat:read`, `bank:read`,
`documents:read`, `reconciliation:read`, …); each operation names its own. Start from
`GET /v1/whoami` and `GET /v1/companies` to discover what the client can reach.

- **Accounts are `accountNumber` + `year`.** `accountId` names one accounting year's
  account: sent with an explicit `year` of another year it is `400`,
  `reason: account_year_mismatch` (leave `year` out, or send the id's own). General-ledger
  lines are identified by `lineId` (Accountflow's) and, for imported lines, `sourceLineId`
  (yours).
- **An omitted `year`** is the company's current accounting year on most reads (the
  ledger's, not the calendar's), but every year on `GET …/vouchers`, a bank account's
  reconciliation groups, VAT terms and approvals, and required on the portfolio reads and
  the bank summaries. On writes, send it.
- The bank reconciliation summary's `approvalStatus` is `APPROVED`, `AWAITING_CONTROL`,
  `REVOKED` or null. A bank group is created with `POST …/bank/reconciliations`
  (`bankTransactionIds`, `lineIds`) and read at `…/reconciliations/{reconciliationGroupId}`.
- Comments, flags and pending accrual suggestions are read-only (`ledger:read`:
  `…/comments`, `…/flags`, `…/accrual-suggestions`); the API cannot write them. A comment
  or flag names its subject with the typed `subjectKey`.
- Access reads (`users:read`) include
  `GET /organizations/{organizationId}/users/{userId}/effective-access`. An access-policy
  rule grants a `role` on a `scopeType` (`COMPANY`, `PORTFOLIO` or `ORGANIZATION`, all
  writable) over a `resourceScope` (`ALL`, `TEMPLATES` with `templateTypes`, `ACCOUNTS`
  with `accountCodes`); `isDefault: true` is refused (`reason: default_policy_retired`).

## Runs, documents and the audit log

- **Reconciliation runs.** `POST /companies/{companyId}/reconciliation-runs`
  (`reconciliation:run`) orders runs for 1-50 accounts of one year:
  `{"year": 2026, "accounts": [{"accountId": "…"}, {"accountNumber": "1920"}]}`. The `202`
  has one entry per account: `ACCEPTED` with a `runId`, `NOT_ENABLED`, or `SKIPPED` with
  `reason: rate_limited` (one order per account per 15 minutes). Poll
  `GET …/reconciliation-runs/{runId}` (`reconciliation:read`) until `SUCCEEDED`, `FAILED`
  or `SKIPPED`; read deviations at `GET …/accounts/{accountNumber}/reconciliation`. A run
  applies the account's automation, so it may approve periods.
- **Document links.** Upload with `POST /companies/{companyId}/documents`, `PUT` the file to
  `upload.url` with every header in `upload.headers`, then
  `POST /documents/{documentId}/actions/complete`. `POST /documents/{documentId}/associations`
  links it to one target: `type` plus its field (`ACCOUNT` with `accountNumber` and `year`,
  `GL_LINE` `lineId`, `OPENING_BALANCE` `openingBalanceId`, `VOUCHER` `voucherKey`,
  `RECON_RUN` `runId`, `ERP_LEDGER` `ledgerId`). The answer's `connectionId` is the link;
  `DELETE …/associations/{connectionId}` detaches it and keeps it (`detachedAt`).
- **Audit log and access reports.** `GET /organizations/{organizationId}/audit-events`
  (`audit:read`) pages the audit trail; filter by `targetType`, `targetId`, `actorUserId`,
  `actionPrefix`, and give `dateFrom`/`dateTo`. A USER-mode client's person must be an
  organization admin, else `404`. `GET /organizations/{organizationId}/access-overview` and
  `GET /companies/{companyId}/access` (`access:manage`) say who reaches what, and why.

## Company settings

Settings are read with `settings:read` and changed with `settings:write`; neither is in
the default grant. An API client acts for its whole organization, so `settings:write`
lets it change any company's settings there — including `autoApprove` and
`autoPostOnHighConfidence`, which let Accountflow approve or post without a person.
Have a person confirm such a change before you make it.

- **Every change is a patch.** A field you leave out stays as it is. To clear a value or
  hand it back to the default, name it in `reset` (where the operation has one).
- **Name the version you read.** Settings reads return a `version` (company settings,
  the contact list, the template choice, an intercompany link or the groups, each
  routine source), `companyRoutineVersion` (an account's own routine) or
  `settingsRevision` (an account). Send it back as `expectedVersion` (optional) or
  `settingsRevision` (required). `409 conflict` with `currentVersion` or `currentRevision`
  means the settings changed since you read them: read again, re-apply your change to the
  fresh values, and send that. Never just retry with the new version.
- **The base currency is per accounting year and can be unset.** `currencyCode` is the
  current accounting year's, `null` while unknown: never assume NOK. `baseCurrencyYears`
  has the other years; a year without an entry takes the latest earlier year's, else the
  earliest later one's. A code you send (on create, or in the settings with an optional
  `currencyAccountingYear`) is recorded as set by your client, so send only a currency the
  company has confirmed. It reaches that year and later years without an entry of their
  own; years with a ledger, and the current year, keep the code they had. Only a direct ERP
  report for the same year refuses another code (`409`; that entry has `source: ERP`, the
  same `accountingYear` and no `inheritedFromYear`). Creating a company needs
  `currencyCode` when the country cannot supply one (`400` otherwise).
- **Deactivated, not deleted:** contacts and intercompany links. A deactivated link
  keeps its accounts, so those accounts cannot go on another link until they are taken
  off it; the `409` (`reason: intercompany_…`) names the link (`definitionId`, `active`).
- **Chart mapping** only to standard accounts of the company's own country
  (`GET …/standard-accounts`). `POST …/account-mappings` maps up to 500 rows in one
  call: a row that cannot be mapped comes back `FAILED` with a `message` and the rest
  are mapped, so read every row's `status`.
- **Applying an account template overwrites values the company changed itself.**
  `GET …/account-template/preview` first and show the user the changes and `warnings`;
  then `POST …/account-template/actions/apply` with the preview's `entryRevisions` and
  only the warnings the user confirmed (`confirmedWarnings`). `409` means the template
  changed since the preview (preview again); `422` with `reason: confirmation_required`
  lists the `warnings` still unconfirmed — ask the user, never confirm for them.

## Webhooks

Read `references/webhooks.md`. The essentials:

- Events are thin: `id`, `type`, `occurredAt` and `data` (`resourceType`, `resourceId`,
  `organizationId`, plus `companyId` when the resource belongs to a company). Fetch the
  resource for its state.
- Sources: writes through `/v1` (an API import ends as `job.succeeded` / `job.failed`),
  and facts Accountflow records: runs (`reconciliation_run.*`), ERP and bank fetches
  (`erp_fetch.*`, `bank_fetch.*`), app imports (`import.*`), approvals (`approval.*`),
  tasks (`task.changed`). Settings writes and matches made in the app raise nothing.
- Delivery is at-least-once and unordered: dedupe on `id`, answer 2xx within 10 seconds,
  work asynchronously.
- Verify `Webhook-Signature` over the **raw** body before parsing.
- Answer the handshake with the hex `HMAC-SHA256(secret, challenge)`; an echo of the
  challenge fails. The endpoint goes from `PENDING_VERIFICATION` to `ACTIVE`.
- A `DISABLED` endpoint comes back only through a `PATCH` that changes `url`, which re-runs
  the handshake. Deleting an endpoint cancels its queued deliveries.

## Before you call the integration done

- [ ] every endpoint, field and status code used exists in `references/openapi.yaml`
      under that name
- [ ] secrets from environment or secret store; tokens cached, requested without `scope`
- [ ] `Idempotency-Key` on every mutation, reused across retries of the same action
- [ ] retries only for 429 / 503 / `idempotency_in_flight` / timeouts / 500, with backoff
- [ ] pagination loops while `hasMore`, also past an empty page; `pageSize` within 1-200
- [ ] enums compared in upper case; unknown enum values and fields tolerated
- [ ] amounts handled as decimals end to end
- [ ] imports: batched to 10 000, sequential per kind, polled to a terminal status,
      `rowsFailed` and `sampleErrors` surfaced, stable ids
- [ ] deletions: `409 *_in_use` reported to the user with the `inUse` list, not retried
- [ ] settings writes are patches naming the read's `expectedVersion` / `settingsRevision`;
      a version `409` re-reads and re-applies, never blindly retries
- [ ] automatic approval or posting, and an account template apply, confirmed by a person
      first; `confirmedWarnings` holds only what they confirmed
- [ ] errors surfaced with `error`, `reason` and `requestId`; `X-Request-Id` logged
- [ ] tests cover a 404, a 409, a 422 with `errors[]`, a 429 with `Retry-After`, a
      replayed idempotent response and an empty page with `hasMore: true`
