Syncing an NZ Bank Account with Akahu
A free Akahu personal app gives you API access to your own NZ bank accounts. Here is the setup, the gotchas, and a safe pattern for syncing into a budgeting tool.
NZ banks don't give you a simple personal API. Akahu does the bank connection for you and exposes one consistent REST API across accounts. I used it to feed ASB transactions into a budgeting app, and this is the setup plus the parts that tripped me up. Everything below is a placeholder: never paste real keys, account numbers or balances into a script, a repo or a chat.
What you need
- An Akahu profile (free) and a bank login for the accounts you want to read.
- An Akahu personal app. Akahu's docs list personal apps as free, limited to your own Akahu account, so they are meant for exactly this kind of home project.
- Something to call a REST API:
curlto test, then a small script in whatever language you like. The examples here use Python 3 and nothing outside the standard library.
Create the developer account and generate your keys
- Go to my.akahu.nz and create a profile. Akahu asks you to connect your first bank account while you set it up (see the next section).
- Turn on multi-factor authentication for the profile. Akahu requires it before you can create an app.
- Open the Developers page in your Akahu profile and accept the Developer Terms.
- Create a personal app. Akahu then shows you two credentials:
- an App ID Token, sent as the
X-Akahu-Idheader, and - a User Access Token, sent as
Authorization: Bearer <token>.
- an App ID Token, sent as the
- Copy both somewhere private straight away, such as a password manager. If you regenerate a token the old one stops working and calls with it return
401 Unauthorized.
I wrote the steps above from Akahu's personal-apps documentation and my own setup. The exact button labels on the Developers page may differ, so follow what the page shows. Personal apps cannot use Akahu's OAuth flow; the two tokens are all you get.
Keep the tokens out of everything
- Read them from environment variables (
AKAHU_APP_TOKEN,AKAHU_USER_TOKEN) or from a file outside any git repo withchmod 600. - Never commit them, paste them into a chat with an AI assistant, or put them in a script's source.
- If one leaks, regenerate it on the Developers page. The old one is invalidated immediately.
Connect your bank and choose the accounts
Akahu connects to your bank for you, so you sign in to the bank through Akahu and agree to share specific accounts. I connected ASB. The API is the same for any bank Akahu supports, so another NZ bank works the same way; check Akahu's current list of supported banks, as I have not verified which ones are available.
- Share only the accounts you want in the bank consent step.
- In my case a newly shared account also had to be allowed for the app in the Akahu app access settings before it appeared in the API. If an account you just shared is missing from
GET /accounts, check both places. - Existing account IDs did not change when I added more accounts later.
Test it with curl
Every request goes to https://api.akahu.io/v1 with the two headers:
export AKAHU_APP_TOKEN='<your app id token>'
export AKAHU_USER_TOKEN='<your user access token>'
curl -s https://api.akahu.io/v1/me \
-H "Authorization: Bearer $AKAHU_USER_TOKEN" \
-H "X-Akahu-Id: $AKAHU_APP_TOKEN"
curl -s https://api.akahu.io/v1/accounts \
-H "Authorization: Bearer $AKAHU_USER_TOKEN" \
-H "X-Akahu-Id: $AKAHU_APP_TOKEN"
/accounts returns each account with an Akahu ID (acc_...), name, type, balance and a refreshed block with timestamps for balance and transactions. Note the IDs: you will map them to your destination accounts. Then try GET /transactions.
Gotchas I hit
- 403 Forbidden on every call. Akahu lets you restrict the app to IPv4 ranges on the Developers page (by default any IP is allowed). I had set an allow list and then ran the script from a different network, so every endpoint returned 403. Find your current address with
curl -4 https://api.ipify.organd add it as<ip>/32. The docs don't tie 403 to the allow list, so this is what I observed, not something I can quote. - Dates are a day early. Akahu stores a transaction's date as the UTC timestamp of NZ midnight, so the first 10 characters of the string are the previous day. Convert to
Pacific/Aucklandbefore taking the date. - No time of day. Every transaction lands at NZ midnight, so you cannot tell lunch from dinner. The raw data does carry a merchant name and a category you can use instead.
- Settled transactions only.
GET /transactionsreturns settled items. Pending ones are on a separate/transactions/pendingendpoint. - Data is not instant. Akahu refreshes from the bank on its own schedule (about daily for me).
POST /refreshasks for an immediate refresh, but personal apps are rate limited (Akahu documents an hour's rest between manual refreshes, and a 429 if you retry too soon). Wait untilrefreshed.transactionson/accountschanges before you read. - History is limited. Akahu returned about two years of history for me, counting back from the day I granted access. Anything older needs a bank export from your bank.
- Sign convention. Amounts are signed: negative is money out. That matched what my destination expected, but check yours.
Reading transactions with pagination
GET /transactions takes start (exclusive), end (inclusive) and cursor. Each response has items and cursor.next; keep requesting until next is empty or you only get the first page.
import json, os, urllib.parse, urllib.request
from datetime import datetime
from zoneinfo import ZoneInfo
NZ = ZoneInfo("Pacific/Auckland")
HEADERS = {
"Authorization": "Bearer " + os.environ["AKAHU_USER_TOKEN"],
"X-Akahu-Id": os.environ["AKAHU_APP_TOKEN"],
}
def get(url):
req = urllib.request.Request(url, headers=HEADERS)
with urllib.request.urlopen(req, timeout=30) as r:
return json.load(r)
def fetch_transactions(start, end=None):
params = {"start": start}
if end:
params["end"] = end
items, cursor = [], None
while True:
q = dict(params, **({"cursor": cursor} if cursor else {}))
page = get("https://api.akahu.io/v1/transactions?" + urllib.parse.urlencode(q))
items += page["items"]
cursor = (page.get("cursor") or {}).get("next")
if not cursor:
return items
def nz_date(iso):
# Akahu dates are UTC timestamps of NZ midnight; the first 10 chars are a day early.
return datetime.fromisoformat(iso.replace("Z", "+00:00")).astimezone(NZ).date().isoformat()
assert nz_date("2024-11-19T11:00:00.000Z") == "2024-11-20" # NZDT
assert nz_date("2026-06-30T12:00:00.000Z") == "2026-07-01" # NZST
Each item has _id, _account, date, amount, description and usually a running balance. Start with start=2000-01-01T00:00:00Z to get everything Akahu has.
Syncing into another tool without duplicates
I synced into PocketSmith through its REST API, but the same pattern works for a spreadsheet, a database or any other target. The goal is a script you can re-run at any time without worrying.
- Map accounts once. Keep a small table from each Akahu account ID to the destination account ID. Only mapped accounts are synced, so a new account does nothing until you add it.
- Stamp every record with its Akahu ID. I put
akahu:<_id>in the memo field of each transaction I create. - Read what already exists before writing. For each account, list the destination records for the date range (plus a week either side in case a date was edited) and skip any
_idalready stamped. The destination is the record of what was sent, so a lost local file or a crash halfway cannot cause duplicates. - Dry run by default. Print what would be sent and require a
--sendflag to write anything. Try one account and a short date range first. - Be careful retrying writes. Retry reads on 429 or 5xx. Retry a write only on 429, which means it was not processed. On a timeout or a 5xx after sending, stop: the record may exist. Re-running skips it if it did.
- Throttle. A short sleep between writes keeps you under the destination's rate limits.
Deleting the stamp from a record in the destination makes the next sync send it again, so leave it alone.
Example: syncing into PocketSmith
This is a trimmed-down version of the script I use. Everything personal is a placeholder: the account IDs, the keys and the user ID.
Get a PocketSmith developer key
- Create a developer key in PocketSmith's security settings. It is sent as the
X-Developer-Keyheader. - The key has full access to your PocketSmith account, so treat it like the Akahu tokens: environment variable only, never in a file you commit or a chat.
Find the account IDs
Transactions belong to a PocketSmith transaction account, which is not the same ID as the account shown in the web app's URL. List them and match each one to an Akahu account by name or number:
export POCKETSMITH_KEY='<your developer key>'
# your user ID
curl -s https://api.pocketsmith.com/v2/me -H "X-Developer-Key: $POCKETSMITH_KEY"
# transaction accounts: note each id, name and number
curl -s https://api.pocketsmith.com/v2/users/<user id>/transaction_accounts \
-H "X-Developer-Key: $POCKETSMITH_KEY"
If an account is missing, create it with POST /users/<user id>/accounts (institution_id, title, currency_code, type). The response's primary_transaction_account.id is the ID to sync into.
The script
Python 3.9 or later, standard library only. Fill in ACCOUNTS with your own IDs.
#!/usr/bin/env python3
"""Akahu -> PocketSmith sync. Dry run by default; --send to write.
Needs AKAHU_APP_TOKEN, AKAHU_USER_TOKEN and POCKETSMITH_KEY in the environment."""
import argparse, json, os, re, sys, time, urllib.parse, urllib.request
from datetime import date, datetime, timedelta
from zoneinfo import ZoneInfo
NZ = ZoneInfo("Pacific/Auckland")
PS = "https://api.pocketsmith.com/v2"
MARKER = re.compile(r"akahu:(\S+)")
PAD = timedelta(days=7)
# Akahu account ID -> PocketSmith transaction account ID (placeholders)
ACCOUNTS = {
"acc_xxxxxxxxxxxxxxxxxxxxxxxxx": 1111111, # everyday account
"acc_yyyyyyyyyyyyyyyyyyyyyyyyy": 2222222, # credit card
}
AKAHU = {"Authorization": "Bearer " + os.environ.get("AKAHU_USER_TOKEN", ""),
"X-Akahu-Id": os.environ.get("AKAHU_APP_TOKEN", "")}
POCKET = {"X-Developer-Key": os.environ.get("POCKETSMITH_KEY", ""),
"Content-Type": "application/json", "Accept": "application/json"}
def call(url, headers, body=None):
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(url, data=data, headers=headers)
with urllib.request.urlopen(req, timeout=30) as r:
return r.status, json.loads(r.read() or b"null"), r.headers
def fetch_transactions(start):
items, cursor = [], None
while True:
q = {"start": start, **({"cursor": cursor} if cursor else {})}
_, page, _ = call("https://api.akahu.io/v1/transactions?" + urllib.parse.urlencode(q), AKAHU)
items += page["items"]
cursor = (page.get("cursor") or {}).get("next")
if not cursor:
return items
def nz_date(iso):
return datetime.fromisoformat(iso.replace("Z", "+00:00")).astimezone(NZ).date()
def existing_ids(account, start, end):
"""Akahu IDs already stamped on PocketSmith transactions in this account."""
# PocketSmith returns 400 unless both start_date and end_date are given.
url = f"{PS}/transaction_accounts/{account}/transactions?" + urllib.parse.urlencode(
{"start_date": start.isoformat(), "end_date": end.isoformat(), "per_page": 1000})
found = set()
while url:
_, page, headers = call(url, POCKET)
found |= {m.group(1) for t in page if (m := MARKER.search(t.get("memo") or ""))}
nxt = re.search(r'<([^>]+)>;\s*rel="next"', headers.get("Link") or "")
url = nxt.group(1) if nxt else None
return found
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--start", default="2000-01-01T00:00:00Z")
ap.add_argument("--send", action="store_true")
args = ap.parse_args()
by_account = {}
for t in fetch_transactions(args.start):
if t["_account"] in ACCOUNTS:
by_account.setdefault(ACCOUNTS[t["_account"]], {})[t["_id"]] = t
for account, txns in by_account.items():
dates = [nz_date(t["date"]) for t in txns.values()]
have = existing_ids(account, min(dates) - PAD, max(dates) + PAD)
for t in sorted((t for i, t in txns.items() if i not in have), key=lambda t: t["date"]):
body = {"date": nz_date(t["date"]).isoformat(), "amount": t["amount"],
"payee": t["description"], "memo": f"akahu:{t['_id']}"}
print(("SEND" if args.send else "DRY "), account, body["date"], body["amount"], body["payee"])
if args.send:
# No automatic retry: a failed POST may still have landed. Re-run instead.
status, _, _ = call(f"{PS}/transaction_accounts/{account}/transactions", POCKET, body)
if status != 201:
sys.exit(f"unexpected {status} for {t['_id']}")
time.sleep(0.2)
if __name__ == "__main__":
assert nz_date("2024-11-19T11:00:00.000Z") == date(2024, 11, 20)
main()
Run it as a dry run first, check the list, then send:
python3 sync.py # dry run: lists what would be sent
python3 sync.py --start 2026-11-01T00:00:00Z # only recent transactions
python3 sync.py --send # write them
I've kept this version short. My own script also retries reads on 429 and 5xx errors and has offline tests for the duplicate check; add both before you rely on it.
PocketSmith gotchas
- 400 "Invalid start and end dates". Listing an account's transactions needs both
start_dateandend_date;start_datealone fails. - Paging is in the
Linkheader, not the response body. Followrel="next"until it disappears. - Category rules apply on creation. PocketSmith's own rules categorised most transactions as the script created them. A rule added later only catches new transactions; fix older ones with
PUT /transactions/<id>and acategory_id. - Rules can be created through the API but not edited or deleted. Use the web app for that.
- Balances lag. After you change a starting balance,
current_balancerecalculates a few seconds later, so wait before comparing it with the bank. - A starting balance includes its own day. Date it the day before the first synced transaction. For a loan, a starting balance of 0 the day before the advance worked for me.
- Loans show principal only. Akahu gives the advance and the principal part of each repayment; the interest is inside the repayment from your everyday account. Categorise principal and advances as transfers.
Check the result
- Compare each account's balance and transaction count with Akahu for the same date range.
- If the destination started with an opening balance, set it after the first sync so the current balance matches the bank. Recalculation can take a few seconds. If part of the history is missing, balances before that gap will be offset.
- Transfers between your own accounts arrive as a debit in one and a credit in the other. Decide how your destination should pair or categorise them.
Adding another account later
- Share the account in the bank consent and allow it in the Akahu app access settings.
- Create the matching account in your destination.
- Add its Akahu ID and the destination ID to your mapping.
- Run a dry run, then
--send, then fix the opening balance.
Credit cards, loans and savings accounts work the same way, but liabilities show negative balances, so check how your destination represents them.