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(warehouse_sources): support Brex API version v2 (#71671)

Tom Owers3e13df760dbb
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 2f087e391f63..363ce327a9f1 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
@@ -18,6 +18,15 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.htt
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
BREX_BASE_URL = "https://api.brex.com"
+
+# Brex versions each product API independently in the URL path (transactions/users on /v2,
+# expenses/vendors on /v1) — there is no global version header or segment. The source already
+# targets each API's current path, so both labels resolve to identical requests today; the
+# version seam (`BrexEndpointConfig.versioned_paths`) exists for when a specific API ships a
+# new path under a new version.
+BREX_API_VERSION_V1 = "v1"
+BREX_API_VERSION_V2 = "v2"
+
# Expenses caps `limit` at 100; other endpoints don't document a max, so 100 is used uniformly.
PAGE_SIZE = 100
REQUEST_TIMEOUT_SECONDS = 60
@@ -69,6 +78,12 @@ def _to_rfc3339(value: Any) -> Optional[str]:
return None
+def _resolve_path(config: BrexEndpointConfig, api_version: str) -> str:
+ """Path for the endpoint under the resolved vendor API version, honoring any per-version
+ override. Falls back to the endpoint's default path when the version has none."""
+ return config.versioned_paths.get(api_version, config.path)
+
+
def _build_url(path: str, params: dict[str, Any]) -> str:
clean_params = {key: value for key, value in params.items() if value is not None}
if not clean_params:
@@ -169,10 +184,12 @@ def get_rows(
endpoint: str,
logger: FilteringBoundLogger,
resumable_source_manager: ResumableSourceManager[BrexResumeConfig],
+ api_version: str,
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Any = None,
) -> Iterator[list[dict[str, Any]]]:
config = BREX_ENDPOINTS[endpoint]
+ path = _resolve_path(config, api_version)
fetch_page = _make_page_fetcher(api_key, logger)
incremental_value = _to_rfc3339(db_incremental_field_last_value) if should_use_incremental_field else None
@@ -186,14 +203,14 @@ def get_rows(
if config.fan_out_cash_accounts:
yield from _get_fan_out_rows(
- config, fetch_page, logger, resumable_source_manager, resume_config, incremental_value
+ config, path, fetch_page, logger, resumable_source_manager, resume_config, incremental_value
)
return
cursor = resume_config.cursor if resume_config is not None else None
while True:
- url = _build_url(config.path, _build_params(config, cursor, incremental_value))
+ url = _build_url(path, _build_params(config, cursor, incremental_value))
data = fetch_page(url)
items = data.get("items", []) or []
@@ -211,6 +228,7 @@ def get_rows(
def _get_fan_out_rows(
config: BrexEndpointConfig,
+ path: str,
fetch_page: PageFetcher,
logger: FilteringBoundLogger,
resumable_source_manager: ResumableSourceManager[BrexResumeConfig],
@@ -227,10 +245,10 @@ def _get_fan_out_rows(
continue
cursor = resume_config.cursor if resume_config is not None and resume_config.account_id == account_id else None
- path = config.path.format(account_id=account_id)
+ account_path = path.format(account_id=account_id)
while True:
- url = _build_url(path, _build_params(config, cursor, incremental_value))
+ url = _build_url(account_path, _build_params(config, cursor, incremental_value))
data = fetch_page(url)
items = data.get("items", []) or []
@@ -259,6 +277,7 @@ def brex_source(
endpoint: str,
logger: FilteringBoundLogger,
resumable_source_manager: ResumableSourceManager[BrexResumeConfig],
+ api_version: str,
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Optional[Any] = None,
) -> SourceResponse:
@@ -271,6 +290,7 @@ def brex_source(
endpoint=endpoint,
logger=logger,
resumable_source_manager=resumable_source_manager,
+ api_version=api_version,
should_use_incremental_field=should_use_incremental_field,
db_incremental_field_last_value=db_incremental_field_last_value,
),
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 a55a891b3ebb..a9ed140771d9 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
@@ -18,6 +18,12 @@ 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
+ # 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
+ # already targets the current path for its API — so this stays empty until a specific
+ # Brex API ships a new path under a new version.
+ versioned_paths: dict[str, str] = field(default_factory=dict)
# Brex splits its data across sub-APIs (Transactions, Expenses, Team, Payments, Budgets) that
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 61433e87aa94..a085ac77420c 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
@@ -14,6 +14,8 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
SourceResponse,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.brex.brex import (
+ BREX_API_VERSION_V1,
+ BREX_API_VERSION_V2,
BrexResumeConfig,
brex_source,
validate_credentials as validate_brex_credentials,
@@ -33,7 +35,10 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
class BrexSource(ResumableSource[BrexSourceConfig, BrexResumeConfig]):
lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
- api_docs_url = "https://developer.brex.com/"
+ api_docs_url = "https://developer.brex.com/changelog"
+
+ supported_versions = (BREX_API_VERSION_V1, BREX_API_VERSION_V2)
+ default_version = BREX_API_VERSION_V2
@property
def source_type(self) -> ExternalDataSourceType:
@@ -129,6 +134,7 @@ Note: Brex tokens expire after 90 days without API activity, so a token that has
endpoint=inputs.schema_name,
logger=inputs.logger,
resumable_source_manager=resumable_source_manager,
+ api_version=self.resolve_api_version(inputs.api_version),
should_use_incremental_field=inputs.should_use_incremental_field,
db_incremental_field_last_value=inputs.db_incremental_field_last_value
if inputs.should_use_incremental_field
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 bf9bfdb1b682..fb8adbe826e0 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
@@ -1,3 +1,4 @@
+import dataclasses
from datetime import UTC, date, datetime
from typing import Any
@@ -7,12 +8,15 @@ from unittest import mock
import requests
from products.warehouse_sources.backend.temporal.data_imports.sources.brex.brex import (
+ BREX_API_VERSION_V1,
+ BREX_API_VERSION_V2,
BrexResumeConfig,
_build_params,
_build_url,
+ _resolve_path,
_to_rfc3339,
- brex_source,
- get_rows,
+ brex_source as _brex_source,
+ get_rows as _get_rows,
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.brex.settings import (
@@ -22,6 +26,19 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.brex.setti
)
+# Both supported versions resolve to identical Brex paths today (Brex versions each product API
+# in the URL, with no global segment), so the behavior tests below run under the default version;
+# `TestPathResolution` pins the dispatched path per version.
+def get_rows(*args, **kwargs):
+ kwargs.setdefault("api_version", BREX_API_VERSION_V2)
+ return _get_rows(*args, **kwargs)
+
+
+def brex_source(*args, **kwargs):
+ kwargs.setdefault("api_version", BREX_API_VERSION_V2)
+ return _brex_source(*args, **kwargs)
+
+
def _make_manager(resume_state: BrexResumeConfig | None = None) -> mock.MagicMock:
manager = mock.MagicMock()
manager.can_resume.return_value = resume_state is not None
@@ -410,3 +427,35 @@ class TestBrexSourceResponse:
def test_incremental_fields_only_declared_for_filterable_endpoints(self):
assert set(INCREMENTAL_FIELDS.keys()) == {"card_transactions", "cash_transactions", "expenses"}
+
+
+class TestPathResolution:
+ @pytest.mark.parametrize("api_version", [BREX_API_VERSION_V1, BREX_API_VERSION_V2])
+ @pytest.mark.parametrize(
+ "endpoint, expected_path",
+ [
+ ("users", "/v2/users"),
+ ("expenses", "/v1/expenses"),
+ ("vendors", "/v1/vendors"),
+ ("budgets", "/v2/budgets"),
+ ],
+ )
+ def test_resolve_path_matches_current_paths_for_every_version(self, api_version, endpoint, expected_path):
+ # Both versions must keep hitting each API's current path — expenses/vendors have no v2.
+ assert _resolve_path(BREX_ENDPOINTS[endpoint], api_version) == expected_path
+
+ def test_resolve_path_honors_per_version_override(self):
+ config = BREX_ENDPOINTS["users"]
+ overridden = dataclasses.replace(config, versioned_paths={BREX_API_VERSION_V2: "/v3/users"})
+ assert _resolve_path(overridden, BREX_API_VERSION_V2) == "/v3/users"
+ assert _resolve_path(overridden, BREX_API_VERSION_V1) == config.path
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.brex.brex.make_tracked_session")
+ def test_resolved_path_is_wired_into_request_url(self, mock_session):
+ # Guards that _resolve_path feeds get_rows' URL building; per-version path coverage
+ # lives in test_resolve_path_matches_current_paths_for_every_version.
+ mock_session.return_value.get.return_value = _response(_page([{"id": "u1"}], None))
+
+ list(_get_rows("bxt_token", "users", mock.MagicMock(), _make_manager(), api_version=BREX_API_VERSION_V2))
+
+ assert mock_session.return_value.get.call_args.args[0] == "https://api.brex.com/v2/users?limit=100"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/brex/tests/test_brex_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/brex/tests/test_brex_source.py
index aa5f210e2303..61c8d58a1ed6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/brex/tests/test_brex_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/brex/tests/test_brex_source.py
@@ -3,7 +3,11 @@ from unittest import mock
from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
-from products.warehouse_sources.backend.temporal.data_imports.sources.brex.brex import BrexResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.brex.brex import (
+ BREX_API_VERSION_V1,
+ BREX_API_VERSION_V2,
+ BrexResumeConfig,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.brex.settings import ENDPOINTS, INCREMENTAL_FIELDS
from products.warehouse_sources.backend.temporal.data_imports.sources.brex.source import BrexSource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
@@ -20,6 +24,15 @@ class TestBrexSource:
def test_source_type(self):
assert self.source.source_type == ExternalDataSourceType.BREX
+ def test_supported_versions_and_default(self):
+ # New sources are stamped with the default; v1 stays supported so existing pins keep working.
+ assert self.source.supported_versions == (BREX_API_VERSION_V1, BREX_API_VERSION_V2)
+ assert self.source.default_version == BREX_API_VERSION_V2
+
+ def test_resolve_api_version_falls_back_to_default_and_honors_pin(self):
+ assert self.source.resolve_api_version(None) == BREX_API_VERSION_V2
+ assert self.source.resolve_api_version(BREX_API_VERSION_V1) == BREX_API_VERSION_V1
+
def test_get_source_config(self):
config = self.source.get_source_config
@@ -140,6 +153,7 @@ class TestBrexSource:
inputs.schema_name = "expenses"
inputs.should_use_incremental_field = True
inputs.db_incremental_field_last_value = "2024-01-01T00:00:00Z"
+ inputs.api_version = None
manager = mock.MagicMock()
self.source.source_for_pipeline(self.config, manager, inputs)
@@ -151,6 +165,18 @@ class TestBrexSource:
assert kwargs["resumable_source_manager"] is manager
assert kwargs["should_use_incremental_field"] is True
assert kwargs["db_incremental_field_last_value"] == "2024-01-01T00:00:00Z"
+ # Unpinned source resolves to the default version at the source class.
+ assert kwargs["api_version"] == BREX_API_VERSION_V2
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.brex.source.brex_source")
+ def test_source_for_pipeline_passes_pinned_api_version(self, mock_brex_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "users"
+ inputs.api_version = BREX_API_VERSION_V1
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_brex_source.call_args.kwargs["api_version"] == BREX_API_VERSION_V1
@mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.brex.source.brex_source")
def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_brex_source):