Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(brex): sync cards, accounts, transfers and spend limits (#100150)

Tom Owersdcaf83da9f0c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 8d0bbf98658f..48d782becd87 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -959,14 +959,14 @@ Note: BreezoMeter is now Google Maps Platform: the connector calls airquality.go
## Brex — gaps
-Today (8): `budgets`, `card_transactions`, `cash_transactions`, `departments`, `expenses`, `locations`, `users`, `vendors`
+Today (13): `budgets`, `card_accounts`, `card_transactions`, `cards`, `cash_accounts`, `cash_transactions`, `departments`, `expenses`, `locations`, `spend_limits`, `transfers`, `users`, `vendors`
Diffed against: <https://developer.brex.com/llms.txt>
-- [ ] `GET /v2/cards (Team API)` — lookup resolving the card id carried on card transactions and expenses (high)
-- [ ] `GET /v2/accounts/card and GET /v2/accounts/cash (Transactions API)` — lookup resolving the account ids on both transaction tables; cash accounts are already fetched internally but not exposed (high)
-- [ ] `GET /v1/transfers (Payments API)` — outbound bill-pay/ACH/wire transactions, entirely absent from card and cash transactions (high)
-- [ ] `GET /v2/spend_limits (Budgets API v2)` — the limit objects budgets and cards are governed by; budgets alone do not show spend controls (high)
+- [x] `GET /v2/cards (Team API)` — lookup resolving the card id carried on card transactions and expenses (high)
+- [x] `GET /v2/accounts/card and GET /v2/accounts/cash (Transactions API)` — lookup resolving the account ids on both transaction tables; cash accounts are already fetched internally but not exposed (high)
+- [x] `GET /v1/transfers (Payments API)` — outbound bill-pay/ACH/wire transactions, entirely absent from card and cash transactions (high)
+- [x] `GET /v2/spend_limits (Budgets API v2)` — the limit objects budgets and cards are governed by; budgets alone do not show spend controls (high)
- [ ] `GET /v3/accounting/records (Accounting API)` — the accounting ledger export — how finance teams reconcile Brex spend to the GL (high)
- [ ] `GET /v1/fields and GET /v1/fields/{field_id}/values (Fields API)` — lookup resolving the custom field ids/values tagged on expenses and transactions (medium)
- [ ] `GET /v2/titles (Team API)` — lookup resolving the title id on users, alongside the departments and locations already synced (medium)
@@ -976,7 +976,7 @@ Diffed against: <https://developer.brex.com/llms.txt>
- [ ] `GET /v1/linked_accounts (Payments API)` — lookup resolving the external bank accounts transfers move money to and from (medium)
- [ ] `GET /v2/legal_entities (Team API)` — lookup for multi-entity companies, needed to split spend by entity (low)
-Note: developer.brex.com serves an SPA (the openapi.json URLs return HTML), but the llms.txt index plus the per-API markdown mirrors (e.g. https://developer.brex.com/openapi/team\_api.md) list every operation with its literal path. Brex ships nine APIs — Accounting, Budgets, Expenses, Fields, Onboarding, Payments, Team, Transactions, Travel — and the connector covers pieces of only four. Note the connector already calls /v2/accounts/cash internally to fan out cash transactions but never exposes it as a table.
+Note: developer.brex.com serves an SPA (the openapi.json URLs return HTML), but the llms.txt index plus the per-API markdown mirrors (e.g. https://developer.brex.com/openapi/team\_api.md) list every operation with its literal path. Brex ships nine APIs — Accounting, Budgets, Expenses, Fields, Onboarding, Payments, Team, Transactions, Travel — and the connector covers pieces of only four. The connector now also exposes /v2/accounts/cash as its own table, alongside the fan-out it already drove.
## Browserbase — **thin**
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/brex/brex.py b/products/warehouse_sources/backend/temporal/data_imports/sources/brex/brex.py
index 3b09e306f640..9f2da3e8ceb2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/brex/brex.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/brex/brex.py
@@ -38,7 +38,8 @@ PAGE_SIZE = 100
CASH_ACCOUNTS_PATH = "/v2/accounts/cash"
# Injected into cash transaction rows so rows from different cash accounts stay distinguishable.
CASH_ACCOUNT_ID_KEY = "account_id"
-# Parent resource name in the cash-transactions fan-out config. With include_from_parent=["id"]
+# Parent resource name in the cash-transactions fan-out config — also the name of the
+# standalone cash accounts table, since both page the same endpoint. With include_from_parent=["id"]
# the framework injects the parent account id into child rows as `_cash_accounts_id`; a data_map
# renames it to the `account_id` key the rows carried before the rest_source migration.
_CASH_ACCOUNTS_PARENT = "cash_accounts"
@@ -99,15 +100,19 @@ def _client_config(api_key: str) -> ClientConfig:
"headers": {"Accept": "application/json"},
"auth": {"type": "bearer", "token": api_key},
"paginator": _paginator(),
+ # cash_accounts responses carry account_number/routing_number under generic field names
+ # the name-based sample scrubber doesn't recognise, so keep all Brex bodies out of HTTP
+ # sample capture rather than special-casing one endpoint.
+ "capture": False,
}
def _endpoint_config(config: BrexEndpointConfig, path: str, should_use_incremental_field: bool) -> Endpoint:
- endpoint: Endpoint = {
- "path": path,
- "params": {"limit": PAGE_SIZE},
- "data_selector": "items",
- }
+ endpoint: Endpoint = {"path": path, "data_selector": config.data_selector}
+ if config.paginated:
+ endpoint["params"] = {"limit": PAGE_SIZE}
+ else:
+ endpoint["paginator"] = "single_page"
if should_use_incremental_field and config.incremental_param is not None:
# Brex docs don't state whether the cursor re-encodes the original filters, so the
# timestamp filter is re-sent on every page to be safe.
@@ -164,11 +169,9 @@ def brex_source(
"resources": [
{
"name": _CASH_ACCOUNTS_PARENT,
- "endpoint": {
- "path": CASH_ACCOUNTS_PATH,
- "params": {"limit": PAGE_SIZE},
- "data_selector": "items",
- },
+ "endpoint": _endpoint_config(
+ BREX_ENDPOINTS[_CASH_ACCOUNTS_PARENT], CASH_ACCOUNTS_PATH, should_use_incremental_field=False
+ ),
},
{
"name": endpoint,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/brex/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/brex/canonical_descriptions.py
index 549c3e842821..418682733713 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/brex/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/brex/canonical_descriptions.py
@@ -37,6 +37,32 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"posted_at_date": "Date the transaction posted to the account.",
},
},
+ "card_accounts": {
+ "description": "A Brex card account, with its current balance, credit limit and current statement period.",
+ "docs_url": "https://developer.brex.com/openapi/transactions_api/#tag/Accounts/operation/listCardAccounts",
+ "columns": {
+ "id": "Unique identifier of the card account, as referenced by card transactions.",
+ "status": "Status of the card account.",
+ "current_balance": "Balance currently owed on the account, with amount and currency.",
+ "available_balance": "Amount still available to spend on the account, with amount and currency.",
+ "account_limit": "Total credit limit of the account, with amount and currency.",
+ "current_statement_period": "Start and end dates of the statement period in progress.",
+ },
+ },
+ "cash_accounts": {
+ "description": "A Brex cash account, with its balances and bank details. Resolves the account_id carried on cash transactions.",
+ "docs_url": "https://developer.brex.com/openapi/transactions_api/#tag/Accounts/operation/listAccounts",
+ "columns": {
+ "id": "Unique identifier of the cash account, as referenced by cash transactions.",
+ "name": "Name of the cash account.",
+ "status": "Status of the cash account.",
+ "current_balance": "Balance held in the account, with amount and currency.",
+ "available_balance": "Amount available to spend from the account, with amount and currency.",
+ "account_number": "Bank account number of the cash account.",
+ "routing_number": "Bank routing number of the cash account.",
+ "primary": "Whether this is the account's single primary cash account.",
+ },
+ },
"expenses": {
"description": "An expense in Brex — a recorded spend item with receipts, status, and accounting details.",
"docs_url": "https://developer.brex.com/openapi/expenses_api/#tag/Expenses/operation/listExpenses",
@@ -86,6 +112,27 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"description": "Description of the location.",
},
},
+ "cards": {
+ "description": "A Brex card issued to a user or vendor, with its spend controls. Resolves the card_id carried on card transactions.",
+ "docs_url": "https://developer.brex.com/openapi/team_api/#tag/Cards/operation/listCardsByUserId",
+ "columns": {
+ "id": "Unique identifier of the card.",
+ "owner": "The user the card belongs to.",
+ "status": "Status of the card (ACTIVE, SHIPPED, LOCKED, or TERMINATED).",
+ "last_four": "Last four digits of the card number.",
+ "card_name": "Name given to the card.",
+ "card_type": "Whether the card is VIRTUAL or PHYSICAL.",
+ "limit_type": "CARD for vendor cards with their own limit, USER for corporate cards on the user's limit.",
+ "spend_controls": "Spend limit, remaining spend, refresh frequency and merchant restrictions. Only set when limit_type is CARD.",
+ "billing_address": "Billing address on the card.",
+ "mailing_address": "Shipping address a physical card was sent to.",
+ "expiration_date": "Expiration month and year of the card.",
+ "has_been_transferred": "Whether the card has been transferred, which restricts it to vendors it was used at before.",
+ "budget_id": "Identifier of the budget the card draws from.",
+ "partner": "The partner that manages the card, if any.",
+ "created_at": "Time at which the card was created.",
+ },
+ },
"vendors": {
"description": "A vendor (payee) configured in Brex for bill payments.",
"docs_url": "https://developer.brex.com/openapi/payments_api/#tag/Vendors/operation/listVendors",
@@ -97,6 +144,26 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"payment_accounts": "Payment account details configured for the vendor.",
},
},
+ "transfers": {
+ "description": "An outbound payment from a Brex account — an ACH, wire, cheque or book transfer. Not covered by the card or cash transaction tables.",
+ "docs_url": "https://developer.brex.com/openapi/payments_api/#tag/Transfers/operation/listTransfers",
+ "columns": {
+ "id": "Unique identifier of the transfer.",
+ "counterparty": "Details of the vendor or account the money is sent to.",
+ "description": "Description of the transfer.",
+ "payment_type": "Payment rail used (e.g. ACH, DOMESTIC_WIRE, CHEQUE, INTERNATIONAL_WIRE).",
+ "amount": "Monetary amount of the transfer, with amount and currency.",
+ "process_date": "Date the transfer is processed.",
+ "originating_account": "The Brex account the money is sent from.",
+ "status": "Status of the transfer (PROCESSING, SCHEDULED, PENDING_APPROVAL, FAILED, or PROCESSED).",
+ "cancellation_reason": "Why the transfer did not complete, when it failed.",
+ "estimated_delivery_date": "Estimated date the money arrives.",
+ "creator_user_id": "Identifier of the user who initiated the transfer.",
+ "created_at": "Time at which the transfer was created.",
+ "display_name": "Human readable name for the transfer.",
+ "external_memo": "Memo sent with the payment to the recipient.",
+ },
+ },
"budgets": {
"description": "A budget in Brex that controls and tracks spend for a group or purpose.",
"docs_url": "https://developer.brex.com/openapi/budgets_api/#tag/Budgets/operation/listBudgets",
@@ -111,4 +178,22 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"period_type": "Recurrence period of the budget (e.g. MONTHLY, QUARTERLY, YEARLY, ONE_TIME).",
},
},
+ "spend_limits": {
+ "description": "A spend limit in Brex — the control that caps what a budget or card can spend over a period.",
+ "docs_url": "https://developer.brex.com/openapi/budgets_api/#tag/Spend-Limits-v2/operation/listSpendLimits",
+ "columns": {
+ "id": "Unique identifier of the spend limit.",
+ "account_id": "Identifier of the Brex account the spend limit belongs to.",
+ "name": "Name of the spend limit.",
+ "description": "Description of what the spend limit is used for.",
+ "parent_budget_id": "Identifier of the budget the spend limit sits under.",
+ "status": "Status of the spend limit (ACTIVE, EXPIRED, ARCHIVED, or DELETED).",
+ "period_recurrence_type": "How often the limit refreshes (e.g. PER_MONTH, PER_QUARTER, ONE_TIME).",
+ "start_date": "Date the spend limit starts counting.",
+ "end_date": "Date the spend limit expires.",
+ "start_time_utc": "UTC time the spend limit starts counting.",
+ "end_time_utc": "UTC time the spend limit expires.",
+ "authorization_settings": "Base limit, buffer percentage, hard or soft authorization, and rollover behavior.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/brex/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/brex/settings.py
index a9ed140771d9..92a27da23b98 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/brex/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/brex/settings.py
@@ -4,7 +4,7 @@ from typing import Optional
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
-@dataclass
+@dataclass(frozen=True)
class BrexEndpointConfig:
name: str
path: str
@@ -18,6 +18,11 @@ class BrexEndpointConfig:
# When True, the endpoint is paged once per cash account listed from /v2/accounts/cash,
# with `{account_id}` in the path resolved per account.
fan_out_cash_accounts: bool = False
+ # Response envelope key holding the rows. None when the endpoint returns a bare JSON array.
+ data_selector: Optional[str] = "items"
+ # False for the endpoints Brex documents no `cursor`/`limit` params on — the whole
+ # collection arrives in a single response.
+ paginated: bool = True
# Per-version `path` overrides, keyed by the source's supported version labels. Brex
# versions each product API independently in the URL (transactions/users on /v2,
# expenses/vendors on /v1) with no global version header or segment, and every endpoint
@@ -32,8 +37,8 @@ class BrexEndpointConfig:
#
# Incremental sync is only advertised where Brex exposes a server-side timestamp filter:
# transactions support `posted_at_start` (filters on `posted_at_date`) and expenses support
-# `updated_at_start` (filters on `updated_at`). Team/vendors/budgets endpoints have no such
-# filter, so they are full refresh only.
+# `updated_at_start` (filters on `updated_at`). The account, team, payments and budgets
+# endpoints have no such filter, so they are full refresh only.
BREX_ENDPOINTS: dict[str, BrexEndpointConfig] = {
"card_transactions": BrexEndpointConfig(
name="card_transactions",
@@ -67,6 +72,19 @@ BREX_ENDPOINTS: dict[str, BrexEndpointConfig] = {
},
],
),
+ "card_accounts": BrexEndpointConfig(
+ name="card_accounts",
+ path="/v2/accounts/card",
+ # The only Brex endpoint that answers with a bare JSON array rather than the
+ # `{items, next_cursor}` envelope, and the only one with no pagination params.
+ data_selector=None,
+ paginated=False,
+ ),
+ "cash_accounts": BrexEndpointConfig(
+ name="cash_accounts",
+ # Listed as its own table, and paged as the parent of the cash transactions fan-out.
+ path="/v2/accounts/cash",
+ ),
"expenses": BrexEndpointConfig(
name="expenses",
path="/v1/expenses",
@@ -94,15 +112,31 @@ BREX_ENDPOINTS: dict[str, BrexEndpointConfig] = {
name="locations",
path="/v2/locations",
),
+ "cards": BrexEndpointConfig(
+ name="cards",
+ path="/v2/cards",
+ # `user_id` is an optional filter; omitting it lists every card on the account.
+ partition_key="created_at",
+ ),
"vendors": BrexEndpointConfig(
name="vendors",
path="/v1/vendors",
),
+ "transfers": BrexEndpointConfig(
+ name="transfers",
+ path="/v1/transfers",
+ # No partition key: `created_at` is nullable on the transfer object.
+ ),
"budgets": BrexEndpointConfig(
name="budgets",
path="/v2/budgets",
primary_keys=["budget_id"],
),
+ "spend_limits": BrexEndpointConfig(
+ name="spend_limits",
+ path="/v2/spend_limits",
+ # No partition key: every date field on a spend limit is nullable.
+ ),
}
ENDPOINTS = tuple(BREX_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/brex/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/brex/source.py
index 903fffc07723..7ba0c8ba4b4b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/brex/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/brex/source.py
@@ -73,7 +73,7 @@ class BrexSource(ResumableSource[BrexSourceConfig, BrexResumeConfig]):
label="Brex",
caption="""Enter your Brex API user token to pull your Brex data into the PostHog Data warehouse.
-You can create a token in your [Brex dashboard](https://dashboard.brex.com/settings/developer) under Settings → Developer. Grant read access to the data you want to sync: Transactions and Accounts (card and cash transactions), Expenses, Team (users, departments, locations), Payments (vendors), and Budgets.
+You can create a token in your [Brex dashboard](https://dashboard.brex.com/settings/developer) under Settings → Developer. Grant read access to the data you want to sync: Transactions and Accounts (card and cash transactions, card and cash accounts), Expenses, Team (users, departments, locations, cards), Payments (vendors, transfers), and Budgets (budgets, spend limits).
Note: Brex tokens expire after 90 days without API activity, so a token that hasn't been used recently may need to be regenerated.""",
iconPath="/static/services/brex.png",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/brex/tests/test_brex.py b/products/warehouse_sources/backend/temporal/data_imports/sources/brex/tests/test_brex.py
index 7ec0421127f8..ae596c7e7f03 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/brex/tests/test_brex.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/brex/tests/test_brex.py
@@ -33,7 +33,7 @@ CASH_TX_PATH = BREX_ENDPOINTS["cash_transactions"].path
def _response(
- payload: dict[str, Any],
+ payload: Any,
status_code: int = 200,
headers: dict[str, str] | None = None,
) -> Response:
@@ -241,7 +241,10 @@ class TestGetRows:
assert "updated_at_start" not in snapshots[0]["params"]
- @pytest.mark.parametrize("endpoint", ["users", "departments", "locations", "vendors", "budgets"])
+ @pytest.mark.parametrize(
+ "endpoint",
+ ["users", "departments", "locations", "cards", "vendors", "transfers", "budgets", "spend_limits"],
+ )
@mock.patch(CLIENT_SESSION_PATCH)
def test_incremental_value_ignored_for_full_refresh_endpoints(self, MockSession, endpoint):
session = MockSession.return_value
@@ -335,6 +338,30 @@ class TestGetRows:
assert session.send.call_count == 1
+class TestGetRowsCardAccounts:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_reads_rows_from_a_bare_array_body(self, MockSession):
+ session = MockSession.return_value
+ snapshots = _wire(session, [_response([{"id": "acc_1"}, {"id": "acc_2"}])])
+
+ manager = _make_manager()
+ rows = _rows(_source("card_accounts", manager))
+
+ assert [row["id"] for row in rows] == ["acc_1", "acc_2"]
+ assert snapshots[0]["url"] == "https://api.brex.com/v2/accounts/card"
+ # Brex documents no cursor/limit params on this endpoint.
+ assert snapshots[0]["params"] == {}
+ assert session.send.call_count == 1
+ manager.save_state.assert_not_called()
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_empty_array_body_yields_no_rows(self, MockSession):
+ session = MockSession.return_value
+ _wire(session, [_response([])])
+
+ assert _rows(_source("card_accounts", _make_manager())) == []
+
+
class TestGetRowsCashFanOut:
@mock.patch(CLIENT_SESSION_PATCH)
def test_fans_out_over_cash_accounts_and_injects_account_id(self, MockSession):
@@ -532,9 +559,10 @@ class TestBrexSourceResponse:
assert response.primary_keys == ["budget_id"]
@pytest.mark.parametrize("config", list(BREX_ENDPOINTS.values()))
- def test_partition_keys_are_stable_posted_dates(self, MockSession, config):
+ def test_partition_keys_are_stable_creation_dates(self, MockSession, config):
+ # Never an updated_at-style field, which would rewrite partitions on every sync.
if config.partition_key:
- assert config.partition_key == "posted_at_date"
+ assert config.partition_key in {"posted_at_date", "created_at"}
def test_incremental_fields_only_declared_for_filterable_endpoints(self, MockSession):
assert set(INCREMENTAL_FIELDS.keys()) == {"card_transactions", "cash_transactions", "expenses"}
@@ -546,9 +574,14 @@ class TestPathResolution:
"endpoint, expected_path",
[
("users", "/v2/users"),
+ ("cards", "/v2/cards"),
("expenses", "/v1/expenses"),
+ ("card_accounts", "/v2/accounts/card"),
+ ("cash_accounts", "/v2/accounts/cash"),
("vendors", "/v1/vendors"),
+ ("transfers", "/v1/transfers"),
("budgets", "/v2/budgets"),
+ ("spend_limits", "/v2/spend_limits"),
],
)
def test_resolve_path_matches_current_paths_for_every_version(self, api_version, endpoint, expected_path):