ThoughtAPI

Docs FNB FNB bank APIs Transaction History

Sample code

Copy-ready examples in curl, Python and Rust for getting a token, fetching one page and reading every page of a date range from FNB's Transaction History API.

Base URL
https://api.i.fnb.co.za/apigateway
Version
OpenAPI 1.0.5
Auth
OAuth 2.0 bearer token
Status
Live

Please note: This page is our own understanding of an FNB API, written in our own words. It is not FNB's official documentation. See Copyright and disclaimer.

Before you start#

  • You need a client ID, client secret and an authorisation code from the Integration Channel subscription. See Authentication.
  • The token request below follows standard OAuth 2.0 with HTTP Basic client authentication. The bank's documents do not show the exact format, so confirm it during onboarding; only the token function changes if it differs.
  • Keep credentials in environment variables or a secret store, never in code.
  • How we tested these samples: against a small local stand-in server that imitates the documented behaviour (a 401 that needs a refresh, a 204 that needs a retry, two pages joined by lastItemKey, and a repeated entry across the page edge). They have not yet been run against FNB's own integration environment. We will note it here when they have.

curl#

Get a token#

curl -s -X POST "https://api.i.fnb.co.za/apigateway/oauth2/token/v2" \
  -u "$FNB_CLIENT_ID:$FNB_CLIENT_SECRET" \
  -d grant_type=authorization_code \
  -d code="$FNB_AUTH_CODE"

Refresh a token#

curl -s -X POST "https://api.i.fnb.co.za/apigateway/oauth2/token/v2" \
  -u "$FNB_CLIENT_ID:$FNB_CLIENT_SECRET" \
  -d grant_type=refresh_token \
  -d refresh_token="$FNB_REFRESH_TOKEN"

Fetch one page#

curl -s -i "https://api.i.fnb.co.za/apigateway/transaction-history/retrieve/v2/$FNB_ACCOUNT?fromDate=2026-11-01&toDate=2026-11-07" \
  -H "Authorization: Bearer $FNB_ACCESS_TOKEN" \
  -H "X-Request-ID: $(uuidgen)" \
  -H "X-Idempotency-ID: $(uuidgen)" \
  -H "Accept: application/json"

Fetch the next page#

Use the groupHeader.pagination.lastItemKey from the previous response, with the same dates:

curl -s "https://api.i.fnb.co.za/apigateway/transaction-history/retrieve/v2/$FNB_ACCOUNT?fromDate=2026-11-01&toDate=2026-11-07&lastItemKey=$LAST_ITEM_KEY" \
  -H "Authorization: Bearer $FNB_ACCESS_TOKEN" \
  -H "X-Request-ID: $(uuidgen)" \
  -H "X-Idempotency-ID: $(uuidgen)" \
  -H "Accept: application/json"

Python#

Needs requests. Handles token refresh on 401, bounded retries on 204, 423, 429 and 5xx with the same idempotency ID, and stops if pagination does not advance.

"""Read FNB Transaction History: get a token, fetch pages, follow lastItemKey.

pip install requests
Environment: FNB_BASE, FNB_TOKEN_URL, FNB_CLIENT_ID, FNB_CLIENT_SECRET, FNB_AUTH_CODE, FNB_ACCOUNT
"""
import os, random, time, uuid
import requests

BASE = os.environ.get("FNB_BASE", "https://api.i.fnb.co.za/apigateway")
TOKEN_URL = os.environ.get("FNB_TOKEN_URL", BASE + "/oauth2/token/v2")
CLIENT = (os.environ["FNB_CLIENT_ID"], os.environ["FNB_CLIENT_SECRET"])


def token_request(form):
    """Standard OAuth 2.0 token call (RFC 6749) with HTTP Basic client auth. Confirm the exact
    client authentication method with the bank; only this function changes if it differs."""
    r = requests.post(TOKEN_URL, data=form, auth=CLIENT, timeout=30)
    r.raise_for_status()
    return r.json()  # access_token, refresh_token, expires_in


class Tokens:
    def __init__(self, auth_code):
        self.t = token_request({"grant_type": "authorization_code", "code": auth_code})

    @property
    def access(self):
        return self.t["access_token"]

    def refresh(self):
        new = token_request({"grant_type": "refresh_token", "refresh_token": self.t["refresh_token"]})
        new.setdefault("refresh_token", self.t["refresh_token"])
        self.t = new  # persist this before using it in real code


RETRY = {204, 423, 429, 500, 502, 503, 504}


def fetch_page(tokens, account, from_date, to_date, last_item_key=None, attempts=6):
    """One page. Same X-Idempotency-ID on every retry of this page, new X-Request-ID per call."""
    idem = str(uuid.uuid4())
    params = {"fromDate": from_date, "toDate": to_date}
    if last_item_key:
        params["lastItemKey"] = last_item_key
    refreshed = False
    for attempt in range(attempts):
        r = requests.get(
            f"{BASE}/transaction-history/retrieve/v2/{account}",
            params=params,
            headers={"Authorization": f"Bearer {tokens.access}", "X-Request-ID": str(uuid.uuid4()),
                     "X-Idempotency-ID": idem, "Accept": "application/json"},
            timeout=60,
        )
        if r.status_code == 200:
            return r.json()
        if r.status_code == 401 and not refreshed:
            tokens.refresh()
            refreshed = True
            continue
        if r.status_code in RETRY:
            ra = r.headers.get("Retry-After", "")
            wait = float(ra) if ra.isdigit() else min(30, 2 ** (attempt + 1))  # Retry-After may also be a date
            time.sleep(wait * (0.5 + random.random() / 2))
            continue
        raise RuntimeError(f"FNB {r.status_code}: {r.text[:300]} (X-Request-ID {r.request.headers['X-Request-ID']})")
    raise RuntimeError("gave up after retries; try this window again on the next poll")


def fetch_all(tokens, account, from_date, to_date):
    """All entries in the range. Deduplicate downstream: entryId is not unique."""
    key, seen_keys = None, set()
    while True:
        page = fetch_page(tokens, account, from_date, to_date, key)
        yield from page.get("entry") or []
        p = (page.get("groupHeader") or {}).get("pagination") or {}
        if p.get("lastPageIndicator", True):
            return
        key = p.get("lastItemKey")
        if not key or key in seen_keys:
            raise RuntimeError("pagination did not advance; stopping")
        seen_keys.add(key)


if __name__ == "__main__":
    tokens = Tokens(os.environ["FNB_AUTH_CODE"])
    for e in fetch_all(tokens, os.environ["FNB_ACCOUNT"], "2026-11-01", "2026-11-07"):
        td = (e.get("entryDetails") or {}).get("transactionDetails") or {}
        print(e["bookingDate"]["Date"], e["creditDebitIndicator"], e["amount"]["amount"],
              (td.get("remittanceInfo") or {}).get("unstructured"))

Rust#

Blocking reqwest keeps the example short; the same logic works with async reqwest and tokio. In Cargo.toml:

[dependencies]
reqwest = { version = "0.12", default-features = false, features = ["blocking", "json", "rustls-tls"] }
serde_json = "1"
uuid = { version = "1", features = ["v4"] }
//! Read FNB Transaction History: token, one page, all pages.
//! Cargo deps: reqwest (blocking, json, rustls-tls), serde_json, uuid (v4).
//! Env: FNB_BASE, FNB_CLIENT_ID, FNB_CLIENT_SECRET, FNB_AUTH_CODE, FNB_ACCOUNT
use std::{collections::HashSet, env, thread, time::Duration};

use reqwest::blocking::Client;
use serde_json::Value;

type Res<T> = Result<T, Box<dyn std::error::Error>>;

struct Fnb {
    http: Client,
    base: String,
    client_id: String,
    client_secret: String,
    access: String,
    refresh: Option<String>,
}

impl Fnb {
    /// Standard OAuth 2.0 token call with HTTP Basic client auth (confirm the method with the bank).
    fn token(&mut self, form: &[(&str, &str)]) -> Res<()> {
        let v: Value = self
            .http
            .post(format!("{}/oauth2/token/v2", self.base))
            .basic_auth(&self.client_id, Some(&self.client_secret))
            .form(form)
            .send()?
            .error_for_status()?
            .json()?;
        self.access = v["access_token"].as_str().ok_or("no access_token")?.to_string();
        if let Some(r) = v["refresh_token"].as_str() {
            self.refresh = Some(r.to_string()); // persist before use in real code
        }
        Ok(())
    }

    fn refresh(&mut self) -> Res<()> {
        let rt = self.refresh.clone().ok_or("no refresh token: renew the subscription")?;
        self.token(&[("grant_type", "refresh_token"), ("refresh_token", &rt)])
    }

    /// One page. Same X-Idempotency-ID for every retry of this page.
    fn page(&mut self, account: &str, from: &str, to: &str, key: Option<&str>) -> Res<Value> {
        let idem = uuid::Uuid::new_v4().to_string();
        let mut q = vec![("fromDate", from), ("toDate", to)];
        if let Some(k) = key {
            q.push(("lastItemKey", k));
        }
        let mut refreshed = false;
        for attempt in 0..6u32 {
            let r = self
                .http
                .get(format!("{}/transaction-history/retrieve/v2/{account}", self.base))
                .query(&q)
                .bearer_auth(&self.access)
                .header("X-Request-ID", uuid::Uuid::new_v4().to_string())
                .header("X-Idempotency-ID", &idem)
                .header("Accept", "application/json")
                .send()?;
            match r.status().as_u16() {
                200 => return Ok(r.json()?),
                401 if !refreshed => {
                    self.refresh()?;
                    refreshed = true;
                }
                204 | 423 | 429 | 500 | 502 | 503 | 504 => {
                    let wait = r
                        .headers()
                        .get("Retry-After")
                        .and_then(|h| h.to_str().ok()?.parse().ok())
                        .unwrap_or_else(|| (2u64 << attempt).min(30));
                    thread::sleep(Duration::from_secs(wait));
                }
                s => return Err(format!("FNB {s}: {}", r.text().unwrap_or_default()).into()),
            }
        }
        Err("gave up after retries; try this window again on the next poll".into())
    }

    /// Every entry in the range. Deduplicate downstream: entryId is not unique.
    fn all(&mut self, account: &str, from: &str, to: &str) -> Res<Vec<Value>> {
        let (mut out, mut key, mut seen) = (Vec::new(), None::<String>, HashSet::new());
        loop {
            let p = self.page(account, from, to, key.as_deref())?;
            if let Some(e) = p["entry"].as_array() {
                out.extend(e.iter().cloned());
            }
            let pg = &p["groupHeader"]["pagination"];
            if pg["lastPageIndicator"].as_bool().unwrap_or(true) {
                return Ok(out);
            }
            let k = pg["lastItemKey"].as_str().ok_or("missing lastItemKey")?.to_string();
            if !seen.insert(k.clone()) {
                return Err("pagination did not advance; stopping".into());
            }
            key = Some(k);
        }
    }
}

fn main() -> Res<()> {
    let mut fnb = Fnb {
        http: Client::builder().timeout(Duration::from_secs(60)).build()?,
        base: env::var("FNB_BASE").unwrap_or_else(|_| "https://api.i.fnb.co.za/apigateway".into()),
        client_id: env::var("FNB_CLIENT_ID")?,
        client_secret: env::var("FNB_CLIENT_SECRET")?,
        access: String::new(),
        refresh: None,
    };
    let code = env::var("FNB_AUTH_CODE")?;
    fnb.token(&[("grant_type", "authorization_code"), ("code", &code)])?;
    for e in fnb.all(&env::var("FNB_ACCOUNT")?, "2026-11-01", "2026-11-07")? {
        println!(
            "{} {} {} {}",
            e["bookingDate"]["Date"], e["creditDebitIndicator"], e["amount"]["amount"],
            e["entryDetails"]["transactionDetails"]["remittanceInfo"]["unstructured"]
        );
    }
    Ok(())
}

After fetching: deduplicate and check the balance#

entryId is not unique and overlapping polls return entries again, so give each entry your own key. This Python sketch also checks the running balance between consecutive entries.

import hashlib
from collections import Counter
from decimal import Decimal


def cents(s):
    d = Decimal(s)
    if d != d.quantize(Decimal("0.01")):
        raise ValueError(f"more than 2 decimals: {s}")  # see known issue KI-02
    return int(d * 100)


def signed(amount_cents, indicator):
    return amount_cents if indicator == "CREDIT" else -amount_cents


def content_key(account, e):
    td = (e.get("entryDetails") or {}).get("transactionDetails") or {}
    parts = [
        account,
        e["bookingDate"]["Date"],
        e["valueDate"]["Date"],
        e["amount"]["amount"],
        e["amount"]["currency"],
        e["creditDebitIndicator"],
        (td.get("remittanceInfo") or {}).get("unstructured") or "",
        (td.get("reference") or {}).get("endToEndId") or "",
        e.get("entryId") or "",
        (e.get("availability") or {}).get("amount") or "",
    ]
    return hashlib.sha256("\x1f".join(parts).encode()).hexdigest()


def keyed(account, entries):
    """(key, entry) pairs; identical entries in one read get occurrence 0, 1, 2..."""
    occ = Counter()
    for e in entries:
        k = content_key(account, e)
        yield f"{k}:{occ[k]}", e
        occ[k] += 1


def balance_breaks(entries):
    """Entries whose availability does not follow from the previous one."""
    prev = None
    for e in entries:
        a = e.get("availability")
        if not a:
            prev = None
            continue
        bal = signed(cents(a["amount"]), a["creditDebitIndicator"])
        if prev is not None:
            expected = prev + signed(cents(e["amount"]["amount"]), e["creditDebitIndicator"])
            if expected != bal:
                yield e, expected, bal
        prev = bal

Run keyed() over the entries of one read (one window, all pages, in order) and insert each key only if it is new. The occurrence counter keeps two genuinely identical entries on the same day apart, while the same entry read again on the next poll maps to the same key. If your read covers the overlap between two pages, drop an exact repeat of the last entry of a page before keying, because the OpenAPI says the next page starts with the keyed entry. Because the key includes the running balance, two genuine entries are very unlikely to be exact repeats (see KI-07).

Changelog#

  • 2026-12-01: Copyright and disclaimer notice added.
  • 2026-12-01: Addresses now have no trailing slash.
  • 2026-11-30: Python sample handles Retry-After sent as an HTTP date, and prints entries with null fields safely.
  • 2026-11-29: First version.

Updated 2026-12-01