Accounting for DevelopersModule 3: Workflows and integrationAdvanced4 min read
Designing an Accounting API
Design a reliable accounting API: ledger resources, idempotency keys, reversals over edits, structured validation errors, as-of queries, webhooks and audit.
Course outline (16 lessons)
Before this lesson:Journal and General Ledger Database DesignReversals and Audit Trails in Accounting SystemsInvoice and Payment Lifecycle in Accounting Software
In this lesson · 10 sections
An accounting API is a contract around financial invariants. Unlike a typical CRUD service, it cannot treat records as freely editable rows: every write must be balanced, idempotent, auditable and reproducible at any point in time.
Resource design
Separate reference data, immutable ledger entries, domain transactions and read-only reports:
| Resource | Operations | Notes |
|---|---|---|
/v1/accounts |
GET, POST, PATCH |
PATCH allows safe metadata (name, is_active: false); never change type or currency after postings exist |
/v1/journal-entries |
GET, POST |
Append-only; no PUT, PATCH or DELETE |
/v1/journal-entries/{id}/reversals |
POST |
Creates a new mirror entry with reverses_entry_id |
/v1/transactions |
GET, POST |
High-level workflows (invoices, payments, payouts) that generate balanced journal entries |
/v1/reports/trial-balance |
GET |
Derived projection; requires as_of and currency |
Exposing domain transactions alongside raw journal-entries lets product services post business events without duplicating accounting rules, while finance integrations can still post manual or adjusting entries directly.
Immutability and reversals over PATCH/DELETE
Reject PATCH, PUT and DELETE on /v1/journal-entries/{id} with 405 Method Not Allowed. Corrections go through POST /v1/journal-entries/{id}/reversals with a mandatory reason and effective_date (which must fall in an open period). Enforce at most one active reversal per original entry so a client cannot reverse the same entry twice.
Idempotency keys
Network timeouts guarantee retried writes. Require an Idempotency-Key header on every mutating POST:
- Store
(entity_id, idempotency_key, request_hash, status_code, response_body)in the same transaction as the journal entry. - If the key exists and
request_hashmatches, replay the original status and JSON body without posting again. - If the key exists and
request_hashdiffers, return409 Conflict(IDEMPOTENCY_KEY_CONFLICT).
Multi-currency fields and safe integers
Every posting carries an explicit ISO 4217 currency and an integer amount_minor (debit positive, credit negative). Never mix currencies in one sum: validate that SUM(amount_minor) = 0 per currency.
For cross-currency transactions (such as settling a EUR invoice into a USD bank account), record explicit currency-clearing legs plus fx_rate metadata rather than converting implicitly. If amounts can exceed JavaScript’s safe integer range (2^53 − 1), serialize amount_minor as a decimal string (for example, "24250") or clearly document 64-bit integer handling.
Structured validation errors
Return 422 Unprocessable Entity with stable machine-readable codes so callers can distinguish retryable outages (5xx) from invalid accounting payloads:
UNBALANCED_ENTRY— includecurrencyandimbalance_minorCLOSED_PERIOD— include the lockedeffective_dateand earliest open dateINACTIVE_ACCOUNTorNON_POSTABLE_ACCOUNT— includeaccount_idCURRENCY_MISMATCH— posting currency does not match the account’s currencyALREADY_REVERSED— original entry already has a reversal
Worked example
Bramble Marketplace (fictional) — posting, rejecting and reversing via JSON
A customer pays $250.00 (25000 minor units USD). The payment processor deducts a $7.50 (750) fee and settles $242.50 (24250); the seller is owed $225.00 (22500) and Bramble earns a $25.00 (2500) platform fee.
1. Valid request (POST /v1/journal-entries with Idempotency-Key: order-9812-capture):
{
"effective_date": "2026-04-12",
"source_type": "marketplace_order",
"source_id": "ord_9812",
"description": "Order 9812 settlement",
"postings": [
{ "account_id": "acc_1010_processor_cash", "currency": "USD", "amount_minor": 24250 },
{ "account_id": "acc_5150_processing_fee", "currency": "USD", "amount_minor": 750 },
{ "account_id": "acc_2100_seller_payable", "currency": "USD", "amount_minor": -22500, "counterparty_id": "sel_44" },
{ "account_id": "acc_4050_platform_fee", "currency": "USD", "amount_minor": -2500 }
]
}Check the balance: debits 24250 + 750 = 25000 ($250.00); credits 22500 + 2500 = 25000 ($250.00); signed sum = 0.
Response (201 Created):
{
"id": "je_01JQ8A9X",
"effective_date": "2026-04-12",
"created_at": "2026-04-12T14:05:11Z",
"totals_by_currency": {
"USD": { "debit_minor": 25000, "credit_minor": 25000 }
}
}2. Unbalanced request (missing the 750 fee posting -> 422 Unprocessable Entity):
{
"error": {
"code": "UNBALANCED_ENTRY",
"message": "Postings do not sum to zero in USD",
"details": { "currency": "USD", "imbalance_minor": -750 }
}
}3. Reversal (POST /v1/journal-entries/je_01JQ8A9X/reversals): flips every sign (-24250, -750, +22500, +2500; debits 25000 = credits 25000, net zero on all four accounts) and links "reverses_entry_id": "je_01JQ8A9X".
Pagination, as-of queries and versioning
- Cursor pagination: return
{ data, next_cursor, has_more }ordered by a monotonic sequence(created_at, id). Avoidpage/offseton append-only streams where inserts shift offsets. - As-of queries: reporting endpoints like
GET /v1/reports/trial-balance?as_of=2026-03-31¤cy=USDfilter byeffective_date <= as_of. Supporting an optionalrecorded_beforetimestamp also lets auditors reproduce what a report showed before later adjustments were posted. - Versioning: version breaking contract changes explicitly (
/v1/,/v2/). Never silently flip sign conventions, currency rounding rules or enum semantics inside an existing version.
Webhooks, authorization and audit
Publish immutable domain events (journal_entry.posted, journal_entry.reversed, period.closed) using a transactional outbox so events never emit for rolled-back writes. Sign webhook payloads with HMAC, include a unique event_id and occurred_at, and document at-least-once delivery so consumers deduplicate on event_id.
Separate authorization scopes by risk:
ledger:read— accounts, entries and reportsledger:write— post new journal entries and domain transactionsledger:reverse— create reversing entriesperiods:close— lock accounting periods (finance administrators only)
Record the authenticated actor (created_by), request ID and optional reason on every write so every API call leaves a complete audit trail.
Real-world application
Internal billing services, marketplaces and ERP integrations all rely on a ledger API as their single source of financial truth. When every service writes through an idempotent, validated API and subscribes to ledger webhooks, finance can close periods confidently, engineers can replay failed integrations safely, and external auditors can trace every line of a trial balance back to the exact API request that created it.
Recap
- Model accounts, immutable journal entries, domain transactions and derived reports as distinct resources.
- Enforce per-currency balancing, idempotency keys with payload matching, and structured
422validation errors. - Replace
PATCH/DELETEon entries with explicit reversal endpoints and period locks. - Use cursor pagination,
as_ofreport queries, transactional webhooks and least-privilege scopes with full actor auditing.
Try it yourself
Active recall
Quick check · Test yourself
Work out each answer in your head first, then reveal the explanation and mark whether you got it right.
1A client retries POST /v1/journal-entries with the same Idempotency-Key header, but sends a different posting amount ($500 instead of $450). What should the API return?
Show worked answer
Return 409 Conflict with an IDEMPOTENCY_KEY_CONFLICT error code. Identical retries return the original stored response; mismatched payloads for a previously used key must be rejected so a reused key never silently masks a new transaction.
2Why should a ledger API forbid DELETE /v1/journal-entries/{id} and offer POST /v1/journal-entries/{id}/reversals instead?
Show worked answer
Posted journal entries are immutable historical facts. Deleting them breaks audit trails, bank reconciliations and prior-period reports. A reversal endpoint creates a new balanced entry referencing reverses_entry_id, preserving complete history.
3Why is cursor pagination safer than page/offset pagination when syncing journal entries?
Show worked answer
As new entries are inserted, offset pagination shifts row positions, causing consumers to skip or duplicate entries. Cursor pagination ordered by a monotonic sequence yields a stable, gap-free feed.
Key terms in this lesson
Lesson 8 of 16 · Accounting for Developers
Finished this lesson?
Mark it complete to track your progress through the course. Progress is saved in this browser only.
Previous lesson: Invoice and Payment Lifecycle in Accounting Software
Connected lessons
Educational content only—not accounting, tax, legal or investment advice. See our editorial policy or report an error via our corrections policy.