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.0Wiring 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.
Choose consent scopes
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:
| Slot | Required scope | Developer Portal name | Fortnox license |
|---|---|---|---|
FortnoxCompanyInformationOAuthCredentialSlot | companyinformation | Företagsinformation | Any |
FortnoxCustomerOAuthCredentialSlot | customer | Kund | Kundfaktura or Order |
FortnoxInvoiceOAuthCredentialSlot | invoice | Faktura | Order or Kundfaktura |
FortnoxSupplierOAuthCredentialSlot | supplier | Leverantör | Bokföring |
FortnoxSupplierInvoiceOAuthCredentialSlot | supplierinvoice | Leverantörsfaktura | Bokföring |
FortnoxConnectFileOAuthCredentialSlot | connectfile | Koppla filer | Bokföring, Anläggning, Arkiv |
FortnoxArchiveOAuthCredentialSlot | archive | Arkivplats | Any |
FortnoxArticleOAuthCredentialSlot | article | Artikel | Order or Kundfaktura |
FortnoxPriceOAuthCredentialSlot | price | Pris | Order or Kundfaktura |
FortnoxCostCenterOAuthCredentialSlot | costcenter | Kostnadsställe | Bokföring, Order, Kundfaktura |
FortnoxPaymentOAuthCredentialSlot | payment | Betalningar | Bokföring, Order, Kundfaktura |
FortnoxOfferOAuthCredentialSlot | offer | Offert | Order |
FortnoxPrintOAuthCredentialSlot | print | Utskrift | Order or Kundfaktura |
FortnoxInboxOAuthCredentialSlot | inbox | Inbox | Any |
FortnoxSettingsOAuthCredentialSlot | settings | Inställningar | Any |
FortnoxProfileOAuthCredentialSlot | profile | Profil | Any |
FortnoxBookkeepingOAuthCredentialSlot | bookkeeping | Bokföring | Bokfö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) withresponse_type=code, a CSRF-protectedstate, the registered redirect URI, and space-delimited scopes. Requestaccess_type=offlinewhen 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
| Action | Access | Input | Success value |
|---|---|---|---|
fortnox.get_company_information | read | {} | FortnoxCompanyInformation |
fortnox.list_customers | read | FortnoxListCustomersInput | { customers, pagination } |
fortnox.get_customer | read | { customerNumber } | FortnoxCustomer |
fortnox.create_customer | write | FortnoxCreateCustomerInput | FortnoxCustomer |
fortnox.update_customer | write | FortnoxUpdateCustomerInput | FortnoxCustomer |
fortnox.list_invoices | read | FortnoxListInvoicesInput | { invoices, pagination } |
fortnox.get_invoice | read | { documentNumber } | FortnoxInvoice |
fortnox.create_invoice | write | FortnoxCreateInvoiceInput | FortnoxInvoice |
fortnox.update_invoice | write | FortnoxUpdateInvoiceInput | FortnoxInvoice |
fortnox.list_suppliers | read | FortnoxListSuppliersInput | { suppliers, pagination } |
fortnox.get_supplier | read | { supplierNumber } | FortnoxSupplier |
fortnox.list_supplier_invoices | read | FortnoxListSupplierInvoicesInput | { supplierInvoices, pagination } |
fortnox.get_supplier_invoice | read | { givenNumber } | FortnoxSupplierInvoice |
fortnox.list_supplier_invoice_files | read | FortnoxListSupplierInvoiceFilesInput | { 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.
ArticleNumberis assigned by Fortnox when omitted and cannot change later.SalesPriceis 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 usuallyA. Fortnox documents no price-list delete.list_priceslists one article's prices in one price list. - Cost centers.
Codeis writable only on create. PreferActive: falseover deleting. - Payments. Created payments are normally unbooked; check
Bookedin the response.AmountCurrencyis required when the invoice currency is not SEK. A supplier invoice payment'sInvoiceNumberis 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;
RowIdmatches rows and is regenerated).create_order_from_offerneeds the Order license;create_invoice_from_offercreates 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_offersends to the offer's storedEmailInformationrecipient through a GET (the only method Fortnox offers); host HTTP adapters must not retry it or follow redirects.mark_offer_sentsetsSentwithout producing a document. There is no print action:/printreturns bytes and marks the offer Sent; use the host preview plusmark_offer_sent. - Inbox. Fortnox has nine static root folders (
inbox_ssupplier invoices,inbox_vvouchers,inbox_kfcustomer invoices, and others).get_inbox_folderreturns folder metadata; a file id returns bytes, so use the host download helper. Deleting a subfolder deletes everything in it;delete_inbox_itemrefusesrootand the static folders. - Settings. Company settings and the locked period are read-only through the API.
update_predefined_accountchanges 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).
| Action | Access | Input | Success value |
|---|---|---|---|
fortnox.list_financial_years | read | { date?, page?, limit? } | { financialYears, pagination } |
fortnox.get_financial_year | read | exactly one of { id } or { date } | FortnoxFinancialYear |
fortnox.list_accounts | read | { financialYearId?, page?, limit?, lastModified? } | { accounts, pagination } |
fortnox.get_account | read | { accountNumber, financialYearId? } | FortnoxAccount |
fortnox.list_voucher_series | read | { financialYearId?, page?, limit?, lastModified? } | { voucherSeries, pagination } |
fortnox.list_vouchers | read | { financialYearId?, voucherSeries?, fromDate?, toDate?, costCenter?, page?, limit?, lastModified? } | { vouchers, pagination } |
fortnox.get_voucher | read | { voucherSeries, voucherNumber, financialYearId } | FortnoxVoucher with VoucherRows |
fortnox.create_voucher | destructive | FortnoxCreateVoucherInput | FortnoxVoucher |
fortnox.list_voucher_file_connections | read | { voucherSeries, voucherNumber, financialYearId } | { connections } |
fortnox.create_voucher_file_connection | write | { FileId, VoucherSeries, VoucherNumber, VoucherYear } | FortnoxVoucherFileConnection |
fortnox.get_sie_file | read | { sieType: 1 | 2 | 3 | 4, financialYearId } | FortnoxGetSieFileOutput (file for agents) |
- Financial years.
financialYearIdis a financial year'sId; it is thefinancialyearquery Fortnox uses to select the year (accounts, voucher series, and vouchers are per year). Omitted, Fortnox uses the current financial year.get_financial_yearbydatelistsfinancialyears?date=…and answersfortnox_not_foundwhen no year contains the date. - Accounts.
BalanceBroughtForwardis the opening balance (ingående balans) andBalanceCarriedForwardthe 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, andYear(the financial year Id): numbers restart every year.costCenteris Fortnox's substring search. List rows usually leave outVoucherRows;get_voucherreturns them. A row'sDescriptionis the account name Fortnox sets;TransactionInformationis the row text.list_voucherswithvoucherSeriesuses/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_voucherisdestructive: 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 anAccount, exactly one positiveDebitorCreditthat is exactly a two-decimal amount, optionalTransactionInformation(at most 100 characters),CostCenter, andProject; total debit equals total credit, summed exactly in whole öre. An answer that names another series or financial year fails withfortnox_voucher_mismatch: that voucher is booked, so never create it again. TheTransactionDatemust 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'sArchiveFileIdfromget_inbox_folder), then callcreate_voucher_file_connectionwith its id. Which id forms Fortnox accepts is not verified against a live company. The create sendsVoucherYearin the body (OpenAPI) and as thefinancialyearquery (the archived page marks it read-only and selects the year in the URL withfinancialyeardate), and fails withfortnox_voucher_mismatchunless the answer names the same file, series, number, and year. The parameters guide allows one resource-specific filter at a time and matches substrings, solist_voucher_file_connectionssendsvouchernumberwith the globalfinancialyear, reads every page (at most ten of 500,MetaInformationrequired), and returns only the requested voucher's connections; a matching connection withoutVoucherYearfails closed. Neither request shape is verified live. - SIE files.
get_sie_filedownloadsGET /3/sie/{type}?financialyear={id}through the hostConnectorBinaryHttpClient(the string HTTP port cannot carry the bytes) and fails withvalidation_failedwhen 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 }:valueisFortnoxSieFile(sieType,financialYearId,fileName,mimeType: 'text/plain',encoding: 'IBM437',byteLength) and the bytes become a file (file claim check); invoked directly it returns them ascontentBase64. Files overfortnoxSieFileMaxBytes(50 MiB) fail withfortnox_response_too_large. The stored file istext/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
Projectas the number0, financial year lists name the chart typeaccountCharts, and voucher file connections sendVoucherNumberas 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
CountryandPhone. Fortnox derives the read-onlyCountryfromCountryCode, and the Customer resource has noPhonefield; usePhone1/Phone2.Phoneappears only in list rows. Thefortnox.create_customerandfortnox.update_customeraction 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.FortnoxCustomerandFortnoxSupplierresponses still includeCountryandPhone. - 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.Priceis the unit price; Fortnox computesPriceExcludingVAT,Total, andTotalExcludingVAT, which are read-only (Fortnox rejects a writtenPriceExcludingVATwith code 2000321) and appear only on returnedFortnoxInvoiceRowvalues. - Invoice rows on update. Sending
InvoiceRowsreplaces the row list: existing rows that are not sent are deleted. If no sent row hasRowId, rows are matched to existing rows by position, and fields omitted on a matched row keep their previous value (for exampleDiscount/DiscountType). Send every row that should remain with all pricing fields, includingDiscount: 0when no discount is intended. If any sent row hasRowId, rows with a matchingRowIdare updated and rows without one are added. Fortnox regenerates RowIds on every update, so read the invoice again before reusing them. - Invoice text.
Remarksis the invoice text (Fakturatext) printed on the invoice;Commentsis an internal note that is not printed. Both are writable on create and update, andFortnoxInvoicereturns both. - Referenced records.
CostCenter,Project,ArticleNumber,AccountNumber, and a non-SEKCurrencymust 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.
Pagination and search
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:
| Resource | Supported search.field values |
|---|---|
| Customers | customernumber, name, organisationnumber, email, city, phone |
| Suppliers | suppliernumber, name, organisationnumber, email, city, phone |
| Invoices | customernumber, customername, documentnumber, ocr |
| Supplier invoices | suppliernumber, suppliername, invoicenumber, serialnumber, ocr |
| Articles | articlenumber, description, ean, suppliernumber, manufacturer, manufacturerarticlenumber |
| Price lists | code, comments |
| Invoice payments | invoicenumber (customer invoice DocumentNumber) |
| Supplier invoice payments | invoicenumber (supplier invoice GivenNumber) |
| Offers | customername, 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, 2000311 | Access token (or client secret) missing or incorrect |
2001101, 2001103, 2000663 | No license for the scope or API, or no access to scope |
2001399 | Invalid field name |
2000106, 2000108, 2000134 | Value must be alphanumeric, numeric, or boolean |
2000359, 2000588 | Value contains invalid characters; invalid parameter |
2001304 | Account not found |
2001302, 2000428 | Article not found |
2000204, 2000433 | Customer not found |
2000637 | Customer 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 id | Safety | Seeds | Claim (as currently understood) |
|---|---|---|---|
fortnox.invoice.list-populated | read | none | Invoice 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-pdf | read | previewInvoiceDocumentNumber | /preview returns a complete PDF (%PDF- ... %%EOF) whatever content type it declares |
fortnox.invoice.payment-filters-exclude-unbooked | read | none | unpaid 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-sticky | write-reversible | discountInvoiceDocumentNumber | A 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-value | write-reversible | customerNumber | Updating 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-information | write-reversible | missingCustomerNumber | Rejected writes return ErrorInformation with a code and message, surfaced as underlying.providerCode and the provider message |
fortnox.invoice.send-email | write-irreversible | emailInvoiceDocumentNumber, emailRecipient | GET /3/invoices/{DocumentNumber}/email answers 2xx with the invoice; whether a test company delivers the email is not established |
fortnox.company.information-decodes | read | none | CompanyInformation decodes with a non-empty CompanyName |
fortnox.customer.list-matches-get | read | none | Customer 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-strings | read | none | Article list rows (numeric strings) and single reads (numbers) decode to the same VAT, SalesPrice, PurchasePrice, and QuantityInStock |
fortnox.price.tier-matches-sublist | read | none | The 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-get | read | none | Cost center lists carry MetaInformation; the first row reads back by Code as listed |
fortnox.payment.invoice-payment-wire-numbers | read | none | Invoice 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-numbers | read | none | Supplier 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-pdf | read | none | Offer 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.unpaginated | read | none | Invoice and offer print templates decode, and their raw answers carry no MetaInformation |
fortnox.inbox.file-bytes-match-size | read | none | The 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-period | read | none | CompanySettings 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-labels | read | none | Predefined 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-get | read | none | Each 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.me | read | none | Me decodes with a non-empty Id |
fortnox.bookkeeping.financial-year-id-and-date | read | none | Financial 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-get | read | none | A 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-balanced | read | none | A 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-ibm437 | read | none | The 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 invoiceTotal,TotalVAT,Net, andGross, exactly. A failed restore fails the case withFortnoxConformanceRestoreFailed, 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, toConformanceCleanupReporterfrom@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 asWARNlines. Like the shared runners, it prints every line of a live run (the report,WARNlines, 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
ErrorInformationcode (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.EmailAddressToequals theemailRecipientseed exactly and no CC or BCC address is set. It sends withredirect: 'manual'andcredentials: '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
- API reference
- Scopes and required licenses
- Authorization code
- Access-token exchange
- Authorization and refresh lifecycle
- API request authentication
- Parameters and pagination
- Response and error envelopes
- Error codes
- SIE file format
- Voucher resource (archived)
- Customer resource (archived)
- Updating document rows with RowId (archived)