Yolk SDK
Connectors

Read and write Fortnox records

Read and write Fortnox records, prices, payments, offers, inbox, settings, and bookkeeping with host-owned OAuth.

Use @yolk-sdk/connectors/fortnox to read Fortnox records directly or expose them as agent tools. The connector exposes 102 actions: 51 read, 32 write, and 19 destructive. It sends GET, POST, PUT, and DELETE requests to https://api.fortnox.se/3.

destructive actions cannot be undone through the Fortnox API: deletes, payment bookkeeping, creating a voucher (Fortnox books it at once), offer conversion, cancellation, emailing, and marking an offer sent. Gate them with host approval. Customer invoices still have no send, book, cancel, or credit action; those remain host capabilities.

Host-only invoice and offer preview PDFs, archive and inbox downloads, archive and inbox uploads, and supplier-file discovery are described in Transfer connector files. Previews do not mark a document Sent. fortnox.get_sie_file is the one action that returns file bytes; see Bookkeeping.

Connect a host credential

Install matching canary versions:

pnpm add @yolk-sdk/connectors@canary @yolk-sdk/agent@canary effect@4.2.0

Wiring fragment (host layers and Effect execution omitted):

import { makeCredentialBinding, makeIntegration } from '@yolk-sdk/connectors'
import { FortnoxConnector, FortnoxOAuthCredentialSlot } from '@yolk-sdk/connectors/fortnox'

const integration = makeIntegration({
  connectorId: 'fortnox',
  credentialBindings: [
    makeCredentialBinding({
      slotId: FortnoxOAuthCredentialSlot.id,
      credentialRef: 'host-fortnox-credential'
    })
  ]
})

const program = FortnoxConnector.invoke({
  integration,
  action: 'fortnox.list_invoices',
  input: { filter: 'unpaid', limit: 25 }
})

Provide CredentialResolver and ConnectorHttpClient Effect layers. The resolver must return an OAuthCredential with provider: 'fortnox' and a current accessToken. Resolve or refresh the credential before returning it; the connector does not refresh tokens or enforce their expiry. Integration config needs no keys and must not contain tokens or client secrets.

The HTTP adapter must preserve Authorization: Bearer … and Accept: application/json. When a request carries a JSON body it must also preserve Content-Type: application/json and the body. Lifecycle PUTs (bookkeep, createorder, createinvoice, cancel, externalprint) and all DELETEs are body-less. fortnox.email_offer is a side-effecting GET: never retry it or follow its redirects. Never retry POSTs either: a retried fortnox.create_voucher books a second voucher. Hosts own network policy, response-size limits, redirect safety, and avoiding credential/body logs.

Fortnox has no read-only OAuth scopes. Each resource scope grants read and write access at the provider. Explain this distinction during consent and retain host authorization checks. Fortnox also requires a company license for each resource. Action access metadata (read, write, destructive) is what hosts gate on; it does not narrow the token.

All slots bind through fortnox.oauth:

SlotRequired scopeDeveloper Portal nameFortnox license
FortnoxCompanyInformationOAuthCredentialSlotcompanyinformationFöretagsinformationAny
FortnoxCustomerOAuthCredentialSlotcustomerKundKundfaktura or Order
FortnoxInvoiceOAuthCredentialSlotinvoiceFakturaOrder or Kundfaktura
FortnoxSupplierOAuthCredentialSlotsupplierLeverantörBokföring
FortnoxSupplierInvoiceOAuthCredentialSlotsupplierinvoiceLeverantörsfakturaBokföring
FortnoxConnectFileOAuthCredentialSlotconnectfileKoppla filerBokföring, Anläggning, Arkiv
FortnoxArchiveOAuthCredentialSlotarchiveArkivplatsAny
FortnoxArticleOAuthCredentialSlotarticleArtikelOrder or Kundfaktura
FortnoxPriceOAuthCredentialSlotpricePrisOrder or Kundfaktura
FortnoxCostCenterOAuthCredentialSlotcostcenterKostnadsställeBokföring, Order, Kundfaktura
FortnoxPaymentOAuthCredentialSlotpaymentBetalningarBokföring, Order, Kundfaktura
FortnoxOfferOAuthCredentialSlotofferOffertOrder
FortnoxPrintOAuthCredentialSlotprintUtskriftOrder or Kundfaktura
FortnoxInboxOAuthCredentialSlotinboxInboxAny
FortnoxSettingsOAuthCredentialSlotsettingsInställningarAny
FortnoxProfileOAuthCredentialSlotprofileProfilAny
FortnoxBookkeepingOAuthCredentialSlotbookkeepingBokföringBokföring or Kundfaktura

print covers only print templates; printing, previewing, or emailing a document uses the document's own scope (invoice, offer). Fortnox also lists Company Logo (Företagslogga) and a sales API (Försäljnings-API) as Developer Portal scopes, but documents no endpoints for them, so the connector has no actions for either.

FortnoxOAuthCredentialSlot is the generic binding without scope hints. FortnoxCombinedOAuthCredentialSlot declares the original five record scopes only (not the file, article, price, cost-center, payment, offer, print, inbox, settings, profile, or bookkeeping scopes); use it only when the host needs exactly those resources. Action-scoped slots supply consent hints to the resolver, not a token store or permission checker.

Host OAuth implementation:

  • Use fortnoxOAuthAuthorizeUrl (https://apps.fortnox.se/oauth-v1/auth) with response_type=code, a CSRF-protected state, the registered redirect URI, and space-delimited scopes. Request access_type=offline when refresh is needed. Service-account selection is host policy.
  • Exchange the code at fortnoxOAuthTokenUrl (https://apps.fortnox.se/oauth-v1/token) with HTTP Basic client authentication and a form-urlencoded body.
  • Store and refresh tokens server-side. Fortnox rotates refresh tokens; serialize refreshes and persist the replacement safely. Hosts own revocation, reauthorization, and credential identity.

fortnox.list_supplier_invoice_files takes { givenNumber, page?, limit? }, returns { files, pagination }, and uses connectfile consent. Its filter is internal GivenNumber, not supplier InvoiceNumber. The new file scopes grant both reads and writes like other Fortnox scopes.

Actions and outputs

ActionAccessInputSuccess value
fortnox.get_company_informationread{}FortnoxCompanyInformation
fortnox.list_customersreadFortnoxListCustomersInput{ customers, pagination }
fortnox.get_customerread{ customerNumber }FortnoxCustomer
fortnox.create_customerwriteFortnoxCreateCustomerInputFortnoxCustomer
fortnox.update_customerwriteFortnoxUpdateCustomerInputFortnoxCustomer
fortnox.list_invoicesreadFortnoxListInvoicesInput{ invoices, pagination }
fortnox.get_invoiceread{ documentNumber }FortnoxInvoice
fortnox.create_invoicewriteFortnoxCreateInvoiceInputFortnoxInvoice
fortnox.update_invoicewriteFortnoxUpdateInvoiceInputFortnoxInvoice
fortnox.list_suppliersreadFortnoxListSuppliersInput{ suppliers, pagination }
fortnox.get_supplierread{ supplierNumber }FortnoxSupplier
fortnox.list_supplier_invoicesreadFortnoxListSupplierInvoicesInput{ supplierInvoices, pagination }
fortnox.get_supplier_invoiceread{ givenNumber }FortnoxSupplierInvoice
fortnox.list_supplier_invoice_filesreadFortnoxListSupplierInvoiceFilesInput{ files, pagination }

Master data, payments, offers, inbox, settings, and profile

Get and delete inputs use camelCase identifiers ({ articleNumber }, { code }, { paymentNumber }, { documentNumber }, { itemId }, { labelId }). Create and update inputs use Fortnox field spelling, carry the identifier, and bind it into the URL instead of the body. Deletes return { <identifier>, deleted: true } without decoding Fortnox's empty answer.

Resource (scope)Actions
Articles (article)read: list_articles, get_article; write: create_article, update_article; destructive: delete_article
Price lists (price)read: list_price_lists, get_price_list; write: create_price_list, update_price_list
Prices (price)read: list_prices, get_price; write: create_price, update_price; destructive: delete_price
Cost centers (costcenter)read: list_cost_centers, get_cost_center; write: create_cost_center, update_cost_center; destructive: delete_cost_center
Invoice payments (payment)read: list_invoice_payments, get_invoice_payment; write: create_invoice_payment, update_invoice_payment; destructive: delete_invoice_payment, bookkeep_invoice_payment
Supplier invoice payments (payment)read: list_supplier_invoice_payments, get_supplier_invoice_payment; write: create_…, update_…; destructive: delete_supplier_invoice_payment, bookkeep_supplier_invoice_payment
Offers (offer)read: list_offers, get_offer; write: create_offer, update_offer; destructive: create_order_from_offer, create_invoice_from_offer, cancel_offer, email_offer, mark_offer_sent
Print templates (print)read: list_print_templates (type: invoice, offer, or order; not paginated)
Inbox (inbox)read: get_inbox_folder ({ folderId? }, root when omitted); destructive: delete_inbox_item
Company settings (settings)read: get_company_settings, get_locked_period
Predefined accounts (settings)read: list_predefined_accounts, get_predefined_account; write: update_predefined_account
Labels (settings)read: list_labels; write: create_label, update_label; destructive: delete_label
Modes of payment (settings)read: list_modes_of_payment, get_mode_of_payment; write: create_…, update_…; destructive: delete_mode_of_payment
Terms of payment (settings)read: list_terms_of_payment, get_terms_of_payment; write: create_…, update_…; destructive: delete_terms_of_payment
Terms of delivery (settings)read: list_terms_of_delivery, get_terms_of_delivery; write: create_…, update_… (Fortnox has no delete)
Ways of delivery (settings)read: list_ways_of_delivery, get_way_of_delivery; write: create_…, update_…; destructive: delete_way_of_delivery
Units (settings)read: list_units, get_unit; write: create_unit, update_unit; destructive: delete_unit
Profile (profile)read: get_profile (GET /3/me: the user behind the token)

All action IDs carry the fortnox. prefix. Notes per resource:

  • Articles. ArticleNumber is assigned by Fortnox when omitted and cannot change later. SalesPrice is read-only (it is the price in the default price list); set prices through the price actions. Update changes only the sent fields. Delete is permanent.
  • Prices. A price is identified by price list, article number, and FromQuantity (0 for the base price); all three form its URL path. The default price list is usually A. Fortnox documents no price-list delete. list_prices lists one article's prices in one price list.
  • Cost centers. Code is writable only on create. Prefer Active: false over deleting.
  • Payments. Created payments are normally unbooked; check Booked in the response. AmountCurrency is required when the invoice currency is not SEK. A supplier invoice payment's InvoiceNumber is the supplier invoice GivenNumber (FortnoxGivenNumber), not the supplier's own invoice number. Bookkeeping posts a voucher and has no API undo.
  • Offers. Row updates follow the invoice rules below (rows replace the list; RowId matches rows and is regenerated). create_order_from_offer needs the Order license; create_invoice_from_offer creates a customer invoice. Both return the offer number and the new order or invoice number (null if Fortnox does not report it), accepting either the documented { Offer } answer or the new document's own { Order }/{ Invoice } envelope; do not retry an ambiguous conversion, read the offer instead. email_offer sends to the offer's stored EmailInformation recipient through a GET (the only method Fortnox offers); host HTTP adapters must not retry it or follow redirects. mark_offer_sent sets Sent without producing a document. There is no print action: /print returns bytes and marks the offer Sent; use the host preview plus mark_offer_sent.
  • Inbox. Fortnox has nine static root folders (inbox_s supplier invoices, inbox_v vouchers, inbox_kf customer invoices, and others). get_inbox_folder returns folder metadata; a file id returns bytes, so use the host download helper. Deleting a subfolder deletes everything in it; delete_inbox_item refuses root and the static folders.
  • Settings. Company settings and the locked period are read-only through the API. update_predefined_account changes the account Fortnox books with by default. Deleting a label removes it from every document that uses it. Labels and predefined accounts are not paginated.
  • Not covered. Article URL connections, price-list deletion, ?path= inbox addressing, Email Senders, Predefined Voucher Series, Account Charts, voucher series writes, account writes, voucher external URL connections, Company Logo, and the sales API (scope or endpoint not confirmed, or not needed yet). Within the original scopes, customer-invoice send, book, cancel, and credit, customer deletion, supplier and supplier-invoice writes, and file-connection writes other than voucher file connections are also not connector actions yet.

These additions follow Fortnox's current API reference and archived resource pages; none has been observed against a live company yet. The Fortnox emulator serves their read endpoints (including the offer preview and inbox file bytes) with unverified, synthetic shapes named after the fields these actions read, which the read conformance cases cover; their writes, and side-effecting reads such as email_offer, are not emulated and fail closed with a 404.

Bookkeeping

Every bookkeeping action needs the bookkeeping scope, except the voucher file connections, which need connectfile, and uploads to the archive, which need archive (Fortnox scopes guide).

ActionAccessInputSuccess value
fortnox.list_financial_yearsread{ date?, page?, limit? }{ financialYears, pagination }
fortnox.get_financial_yearreadexactly one of { id } or { date }FortnoxFinancialYear
fortnox.list_accountsread{ financialYearId?, page?, limit?, lastModified? }{ accounts, pagination }
fortnox.get_accountread{ accountNumber, financialYearId? }FortnoxAccount
fortnox.list_voucher_seriesread{ financialYearId?, page?, limit?, lastModified? }{ voucherSeries, pagination }
fortnox.list_vouchersread{ financialYearId?, voucherSeries?, fromDate?, toDate?, costCenter?, page?, limit?, lastModified? }{ vouchers, pagination }
fortnox.get_voucherread{ voucherSeries, voucherNumber, financialYearId }FortnoxVoucher with VoucherRows
fortnox.create_voucherdestructiveFortnoxCreateVoucherInputFortnoxVoucher
fortnox.list_voucher_file_connectionsread{ voucherSeries, voucherNumber, financialYearId }{ connections }
fortnox.create_voucher_file_connectionwrite{ FileId, VoucherSeries, VoucherNumber, VoucherYear }FortnoxVoucherFileConnection
fortnox.get_sie_fileread{ sieType: 1 | 2 | 3 | 4, financialYearId }FortnoxGetSieFileOutput (file for agents)
  • Financial years. financialYearId is a financial year's Id; it is the financialyear query Fortnox uses to select the year (accounts, voucher series, and vouchers are per year). Omitted, Fortnox uses the current financial year. get_financial_year by date lists financialyears?date=… and answers fortnox_not_found when no year contains the date.
  • Accounts. BalanceBroughtForward is the opening balance (ingående balans) and BalanceCarriedForward the closing balance (utgående balans) in the selected year. The accounts endpoint has no per-period balances: SIE type 2 holds monthly balances, type 3 adds cost center and project balances.
  • Vouchers. A voucher is unique by VoucherSeries, VoucherNumber, and Year (the financial year Id): numbers restart every year. costCenter is Fortnox's substring search. List rows usually leave out VoucherRows; get_voucher returns them. A row's Description is the account name Fortnox sets; TransactionInformation is the row text. list_vouchers with voucherSeries uses /vouchers/sublist/{VoucherSeries}.
  • Creating a voucher books it. The Fortnox API documents no endpoint to delete or change a voucher (its licence table names a Delete Voucher right, with no documented endpoint), so create_voucher is destructive: a mistake needs a new correcting voucher. The input is closed (unknown keys fail at every depth) and is checked before any request: at least two rows, each with an Account, exactly one positive Debit or Credit that is exactly a two-decimal amount, optional TransactionInformation (at most 100 characters), CostCenter, and Project; total debit equals total credit, summed exactly in whole öre. An answer that names another series or financial year fails with fortnox_voucher_mismatch: that voucher is booked, so never create it again. The TransactionDate must lie in the financial year and after any locked period; Fortnox enforces that, and active accounts and existing cost centers and projects. The request is sent once and never retried: after a transport failure or an unreadable answer the voucher may exist, so list vouchers before trying again. Series codes compare case-insensitively.
  • Attaching files. A voucher file connection links an archive file to a voucher. Upload the file with the host-only uploadFortnoxArchiveFile (or take an inbox file's ArchiveFileId from get_inbox_folder), then call create_voucher_file_connection with its id. Which id forms Fortnox accepts is not verified against a live company. The create sends VoucherYear in the body (OpenAPI) and as the financialyear query (the archived page marks it read-only and selects the year in the URL with financialyeardate), and fails with fortnox_voucher_mismatch unless the answer names the same file, series, number, and year. The parameters guide allows one resource-specific filter at a time and matches substrings, so list_voucher_file_connections sends vouchernumber with the global financialyear, reads every page (at most ten of 500, MetaInformation required), and returns only the requested voucher's connections; a matching connection without VoucherYear fails closed. Neither request shape is verified live.
  • SIE files. get_sie_file downloads GET /3/sie/{type}?financialyear={id} through the host ConnectorBinaryHttpClient (the string HTTP port cannot carry the bytes) and fails with validation_failed when the host provides none. The file is IBM437 (code page 437) text, as the SIE format requires, and must start with #FLAGGA. As an agent tool it returns { value, files }: value is FortnoxSieFile (sieType, financialYearId, fileName, mimeType: 'text/plain', encoding: 'IBM437', byteLength) and the bytes become a file (file claim check); invoked directly it returns them as contentBase64. Files over fortnoxSieFileMaxBytes (50 MiB) fail with fortnox_response_too_large. The stored file is text/plain (file MIME types carry no charset): hosts and scripts that read it as text must decode IBM437, not UTF-8.
  • Wire forms. The archived examples send voucher and account Project as the number 0, financial year lists name the chart type accountCharts, and voucher file connections send VoucherNumber as a string. These decode to the public string and integer types.

None of the bookkeeping endpoints has been observed against a live company yet. The Fortnox emulator serves their reads with unverified, synthetic shapes, which the bookkeeping conformance cases cover; the voucher and voucher file connection creates and the archive upload are not emulated.

Create customer inputs require Name; Fortnox assigns CustomerNumber. Create invoice inputs require CustomerNumber; Fortnox assigns DocumentNumber. Update inputs carry the provider identifier (CustomerNumber or DocumentNumber) and omit it from the request body because it is bound into the URL. Invoice write inputs use InvoiceRows as JSON arrays; returned invoice rows are runtime Chunk values. Writes do not send or book invoices and are subject to host authorization. The connector forwards accepted write fields unchanged; it does not inject defaults or rewrite values. Invoice write inputs are not closed: when execute decodes input, unknown or provider-managed invoice keys (such as Booked or VoucherNumber) are dropped before the request. Agent tools from makeConnectorToolModule reject those keys instead, with a model-visible validation error, so a model never believes it booked or sent an invoice. executeTyped trusts an existing invoice input class instance and does not re-check its keys. InvoiceRows are closed when decoded or made, because dropping a row key (such as PriceExcludingVAT) would send a row without its price: execute and agent tools fail validation, and FortnoxCreateInvoiceInput.make / FortnoxUpdateInvoiceInput.make throw on an unknown row key. FortnoxInvoiceRowInput is a closed schema, not a class: build rows as plain objects.

Fortnox write semantics

These notes describe Fortnox behavior and connector validation. The action descriptions that agents see repeat the Fortnox behavior:

  • Customer contact fields. Customer write inputs omit Country and Phone. Fortnox derives the read-only Country from CountryCode, and the Customer resource has no Phone field; use Phone1/Phone2. Phone appears only in list rows. The fortnox.create_customer and fortnox.update_customer action inputs are closed: Country, Phone, or any other unknown key fails input validation before a request is sent, rather than being stripped. Decoding the exported input classes directly uses default Effect parsing, which strips unknown keys. FortnoxCustomer and FortnoxSupplier responses still include Country and Phone.
  • Customer updates. Only provided fields change; omitted fields keep their stored value. An empty string does not clear a stored value.
  • Invoice row inputs. Write rows are FortnoxInvoiceRowInput: the writable fields of Fortnox's row payload. Price is the unit price; Fortnox computes PriceExcludingVAT, Total, and TotalExcludingVAT, which are read-only (Fortnox rejects a written PriceExcludingVAT with code 2000321) and appear only on returned FortnoxInvoiceRow values.
  • Invoice rows on update. Sending InvoiceRows replaces the row list: existing rows that are not sent are deleted. If no sent row has RowId, rows are matched to existing rows by position, and fields omitted on a matched row keep their previous value (for example Discount/DiscountType). Send every row that should remain with all pricing fields, including Discount: 0 when no discount is intended. If any sent row has RowId, rows with a matching RowId are updated and rows without one are added. Fortnox regenerates RowIds on every update, so read the invoice again before reusing them.
  • Invoice text. Remarks is the invoice text (Fakturatext) printed on the invoice; Comments is an internal note that is not printed. Both are writable on create and update, and FortnoxInvoice returns both.
  • Referenced records. CostCenter, Project, ArticleNumber, AccountNumber, and a non-SEK Currency must already exist in the Fortnox company.

Pass identifier strings returned by the provider, preserving leading zeros. givenNumber is the numeric-string GivenNumber, not the supplier's InvoiceNumber. Identifiers are validated and encoded as path segments; returned provider URLs are never followed. Typed file-discovery inputs and outputs use FortnoxGivenNumber; downloadFortnoxInvoicePreview takes FortnoxDocumentNumber. Decode raw provider/request values with those exported schemas, or use .make for trusted constants. Dynamic FortnoxConnector.invoke still accepts plain JSON and decodes it at runtime.

Resource fields retain Fortnox spelling, including CustomerNumber, DocumentNumber, GivenNumber, CompanyName, and OrganisationNumber (company information uses OrganizationNumber). These are bounded read models: unknown provider fields are omitted, not a lossless accounting export. The exported schemas define the selected contact, status, reference, amount, and invoice-row fields. Supplier bank details and unmodeled provider fields are not exposed. List responses can contain fewer fields than detail responses; optional omission does not mean zero or false. Use a get action to retrieve available rows.

Collections are runtime Effect Chunk values, including InvoiceRows and SupplierInvoiceRows. Customer-invoice Total and Balance remain numbers; supplier-invoice Total and Balance remain strings, preserving their supplied decimal representation. Row amounts are numbers with nullable Total/CostCenter values; supplier invoice row amounts also accept numeric strings. The connector does not round or recompute response amounts; its only monetary arithmetic is the fortnox.create_voucher balance check (whole öre) before the request.

Supplier invoice read actions also accept JSON forms Fortnox's OpenAPI types do not list: GivenNumber, SupplierNumber, InvoiceNumber, OCR, CostCenter, Project and the row ArticleNumber, CostCenter and Project as strings or integers; VoucherNumber and row Account as integers or integer strings ("" is unset); the Booked, Cancelled, Credit and PaymentPending flags as booleans or "true"/"false" ("" is unset); row amounts as numbers or numeric strings; and invoice-level Total, Balance and CurrencyRate as strings or numbers (recorded as their string form). The public schemas do not change and stay strict when a host decodes raw provider JSON with them. A Fortnox amount sent as a JSON number past the double range (which parses to Infinity) fails the read with validation_failed. An identifier sent as a JSON number past Number.MAX_SAFE_INTEGER (a long OCR) still fails to decode: its digits are already lost.

Every list action fetches exactly one page, except fortnox.list_voucher_file_connections (see Bookkeeping). Record-list inputs support page (integer, at least 1), limit (integer, 1–500), and lastModified (provider timestamp string). Omitted values use Fortnox defaults (page 1, limit 100). Output pagination contains currentPage, totalPages, totalResources, and optional nextPage. Continue with page: nextPage, repeating the same limit and selection fields; stop when nextPage is absent. Missing or malformed pagination metadata is an error, not an assumed final page. The connector does not auto-paginate or promise snapshot consistency while records change.

Fortnox's OpenAPI invoice-list wrapper omits the generic MetaInformation field that this connector expects. Invoice pagination needs confirmation with a sanitized response from your account before production use; the connector does not infer completion when metadata is missing.

For resource-specific searches, supply one search: { field, value } pair:

ResourceSupported search.field values
Customerscustomernumber, name, organisationnumber, email, city, phone
Supplierssuppliernumber, name, organisationnumber, email, city, phone
Invoicescustomernumber, customername, documentnumber, ocr
Supplier invoicessuppliernumber, suppliername, invoicenumber, serialnumber, ocr
Articlesarticlenumber, description, ean, suppliernumber, manufacturer, manufacturerarticlenumber
Price listscode, comments
Invoice paymentsinvoicenumber (customer invoice DocumentNumber)
Supplier invoice paymentsinvoicenumber (supplier invoice GivenNumber)
Offerscustomername, customernumber, documentnumber, offerdate, ourreference, yourreference, costcenter, project

Fortnox supports only one resource-specific search field at a time; matching follows provider semantics, not guaranteed exact equality. Combine it with global lastModified, and for invoice lists, fromDate/toDate date strings. Dates are forwarded unchanged without timezone conversion.

Customers and articles additionally accept filter: 'active' | 'inactive'. Offers accept cancelled, expired, completed, notcompleted, ordercreated, or ordernotcreated, plus fromDate/toDate. Settings registers (modes of payment, terms, ways of delivery, units) take page and limit only. Print templates, labels, and predefined accounts are not paginated. Both invoice lists accept cancelled, fullypaid, unpaid, unpaidoverdue, or unbooked; supplier invoices also accept pendingpayment and authorizepending. Supplier lists do not expose a status filter. Unsupported sort/offset or arbitrary query parameters are not part of this connector.

Fortnox's API docs do not state how payment-status filters treat unbooked invoices. On a demo tenant, unpaid, unpaidoverdue, and fullypaid did not return unbooked customer invoices; use filter: 'unbooked' for those. An empty payment-status result does not prove nothing is outstanding.

Handle failures and rate limits

Non-2xx responses return ActionResult.failure, including fortnox_unauthorized (401), fortnox_forbidden (403), fortnox_not_found (404), fortnox_rate_limited (429), and fortnox_request_failed for other statuses. Fortnox ErrorInformation fields accept both documented casings (message/code and Message/Code). The message is retained; the code, when present, is available as error.underlying.providerCode. Raw error bodies are not returned. Missing/invalid credentials, input validation, malformed success bodies, and transport errors stay in the typed Effect error channel.

Hosts can classify failures from underlying.providerCode using Fortnox's documented error codes. The connector does not map these codes itself. Codes relevant to these actions include:

Code(s)Fortnox meaning
2000310, 2000311Access token (or client secret) missing or incorrect
2001101, 2001103, 2000663No license for the scope or API, or no access to scope
2001399Invalid field name
2000106, 2000108, 2000134Value must be alphanumeric, numeric, or boolean
2000359, 2000588Value contains invalid characters; invalid parameter
2001304Account not found
2001302, 2000428Article not found
2000204, 2000433Customer not found
2000637Customer number already used or reserved by a deleted one

Fortnox documents 25 requests per 5 seconds per access token. Hosts own throttling and retry policy; the connector never retries automatically. A valid delta-seconds Retry-After header is exposed as retryAfterMs; HTTP-date headers are not interpreted. A 403 may mean missing consent, license, or permissions rather than an expired token.

Expose agent tools

Wiring fragment; HostConnectorLayer is the host-provided layer described above:

import { makeConnectorToolModule } from '@yolk-sdk/connectors/agent'

const tools = makeConnectorToolModule(FortnoxConnector, {
  integration,
  layer: HostConnectorLayer
})

The adapter inherits each action's declared access metadata (read, write, or destructive); explicit host access overrides still win. Require manual approval for destructive tools such as fortnox.email_offer, fortnox.bookkeep_invoice_payment, and fortnox.create_voucher, or exclude them from the module. Customer-invoice sending and booking are still not connector actions, so any host-owned outbound action must keep its own approval gate. See Add connector tools for tool execution and authorization.

Conformance cases

Experimental. For tests and hand-run checks against a Fortnox developer test company.

@yolk-sdk/connectors/fortnox/conformance exports conformance cases for @yolk-sdk/conformance/runner. Each checks one claimed Fortnox behavior through the real connector actions. The claims are as currently understood; none is observed live yet. This table is the canonical list of cases:

Case idSafetySeedsClaim (as currently understood)
fortnox.invoice.list-populatedreadnoneInvoice lists carry MetaInformation; amounts decode to finite numbers or are unset, whether sent as numbers or as numeric strings (such as CurrencyRate: "1")
fortnox.invoice.preview-pdfreadpreviewInvoiceDocumentNumber/preview returns a complete PDF (%PDF- ... %%EOF) whatever content type it declares
fortnox.invoice.payment-filters-exclude-unbookedreadnoneunpaid leaves out an unbooked invoice with a positive balance; unpaidoverdue leaves out one whose DueDate is before today (Effect Clock). Aborts without such an invoice
fortnox.invoice.row-discount-stickywrite-reversiblediscountInvoiceDocumentNumberA positional row update without Discount keeps the previous discount; only Discount: 0 clears it. Every row needs an explicit Discount and DiscountType: PERCENT beforehand
fortnox.customer.empty-string-keeps-valuewrite-reversiblecustomerNumberUpdating Comments to "" keeps the stored value; how to clear a value is not established. The customer needs a non-empty Comments
fortnox.write.rejection-error-informationwrite-reversiblemissingCustomerNumberRejected writes return ErrorInformation with a code and message, surfaced as underlying.providerCode and the provider message
fortnox.invoice.send-emailwrite-irreversibleemailInvoiceDocumentNumber, emailRecipientGET /3/invoices/{DocumentNumber}/email answers 2xx with the invoice; whether a test company delivers the email is not established
fortnox.company.information-decodesreadnoneCompanyInformation decodes with a non-empty CompanyName
fortnox.customer.list-matches-getreadnoneCustomer lists carry MetaInformation; the first row reads back by CustomerNumber with the same Name (a mismatch never echoes either value)
fortnox.article.list-row-numeric-stringsreadnoneArticle list rows (numeric strings) and single reads (numbers) decode to the same VAT, SalesPrice, PurchasePrice, and QuantityInStock
fortnox.price.tier-matches-sublistreadnoneThe PreSelected price list and a price tier read back as listed; an article's SalesPrice is its base (FromQuantity 0) price in that list
fortnox.cost-center.list-matches-getreadnoneCost center lists carry MetaInformation; the first row reads back by Code as listed
fortnox.payment.invoice-payment-wire-numbersreadnoneInvoice payment voucher fields and ModeOfPaymentAccount decode (from numeric strings in the docs examples); the first row reads back as listed
fortnox.payment.supplier-payment-wire-numbersreadnoneSupplier invoice payment voucher fields decode (from numeric strings in the docs examples); the first row reads back as listed
fortnox.offer.rows-on-get-and-preview-pdfreadnoneOffer list rows carry no OfferRows (unverified: no live run confirms it); a single read has its rows; the offer preview is a complete PDF
fortnox.print-templates.unpaginatedreadnoneInvoice and offer print templates decode, and their raw answers carry no MetaInformation
fortnox.inbox.file-bytes-match-sizereadnoneThe inbox root lists its subfolders; a file found in the root or a direct subfolder downloads exactly its listed Size
fortnox.settings.company-and-locked-periodreadnoneCompanySettings has a non-empty Name; the locked period EndDate is a YYYY-MM-DD date, empty, or unset (unverified); a 404 aborts with a precondition
fortnox.settings.predefined-accounts-and-labelsreadnonePredefined accounts and labels decode, and their raw answers carry no MetaInformation; the first account reads back by Name; label ids are distinct
fortnox.settings.registers-list-matches-getreadnoneEach of the five settings registers lists with MetaInformation, and its first row reads back by Code as listed (a mode of payment AccountNumber decodes to the same integer whatever its wire type)
fortnox.profile.mereadnoneMe decodes with a non-empty Id
fortnox.bookkeeping.financial-year-id-and-datereadnoneFinancial year lists carry MetaInformation; the first year reads back with the same Id, dates, and AccountingMethod by id and by its FromDate (the chart type, accountCharts in list rows, is not compared)
fortnox.bookkeeping.account-balances-list-getreadnoneA populated account page of the first year is sorted by number and in that year; the first account reads back with the same balances in whole öre (unverified: OpenAPI types the list closing balance as a float)
fortnox.bookkeeping.voucher-list-get-balancedreadnoneA populated voucher page of the first year; its series and series sublist hold the first voucher, which reads back as listed with at least two rows that balance (unverified: removed rows); every raw file connection row carries VoucherYear (unverified)
fortnox.bookkeeping.sie-file-ibm437readnoneThe type 1 SIE file is exactly the bytes Fortnox answered and declares #FORMAT PC8 and #SIETYP 1 (unverified: whether Fortnox writes #FORMAT PC8)

The last eighteen cases cover company information, the customer list, the read-only resource modules, and bookkeeping: each only reads, needs no seed (it reads back the first row a list answers), and aborts with a precondition: mismatch when the practice company holds nothing to read. Their fixtures are shaped from the Fortnox API reference and the JSON examples of its archived resource pages.

The cases need FortnoxConformanceConfig seed identities (never hard-coded account data) and the connector ports; @yolk-sdk/connectors/conformance bridges an Effect HttpClient to those ports for tests only. A missing seed fails the case with a precondition: mismatch before any request.

What the write cases guarantee differs:

  • Row and customer cases read the original state first, always restore it afterwards (also after a failed assertion or an interruption), and verify the restore by reading back. The row case compares every written row field plus VATCode, and the invoice Total, TotalVAT, Net, and Gross, exactly. A failed restore fails the case with FortnoxConformanceRestoreFailed, which summarizes the original failure when the claim failed; check the account and restore it by hand if it still differs. A failed restore raised while the case is being interrupted is also handed, with its full message, to ConformanceCleanupReporter from @yolk-sdk/connectors/conformance (default: Effect.logWarning), since the interruption may replace it. The repository runner (pnpm conformance:fortnox) turns a first Ctrl-C into an interruption and prints these reports on stderr as WARN lines. Like the shared runners, it prints every line of a live run (the report, WARN lines, the run's own failure, staging output) with the live access token redacted, since Fortnox can echo it into a field a case reports. The rejection case and the email send do not report.
  • The rejection case does not restore anything. It first confirms that the customer is absent: a 404, or another 4xx with a customer-not-found ErrorInformation code (2000204, 2000433). 401, 403, and every other failure abort before the write. If Fortnox unexpectedly accepted the create, the case fails and names the invoice to cancel by hand.
  • The email case reads the invoice first and aborts unless EmailInformation.EmailAddressTo equals the emailRecipient seed exactly and no CC or BCC address is set. It sends with redirect: 'manual' and credentials: 'omit', and fails on any 3xx rather than treating it as sent. It is never automated.

The shipped fixtures are synthetic (evidence: 'unverified'). See Conformance APIs for the bridges.

For offline tests, the experimental Fortnox emulator (@yolk-sdk/emulators/fortnox) is a stateful stand-in that passes these cases and reproduces their quirks.

Official Fortnox references

On this page