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(data-warehouse): backend-driven account picker for pinterest ads (#70137)

Javier Bahamondes29c9f911860d
diff --git a/posthog/models/integration.py b/posthog/models/integration.py
index 3a0f243ece67..0a676cdee0fc 100644
--- a/posthog/models/integration.py
+++ b/posthog/models/integration.py
@@ -384,6 +384,9 @@ class Integration(models.Model):
@property
def display_name(self) -> str:
+ if self.kind == "pinterest-ads":
+ # Pinterest's OAuth username is an opaque hash, so prefer the business name when there is one.
+ return self.config.get("business_name") or self.config.get("username") or self.integration_id
if self.kind == "tiktok-ads":
# The OAuth id is a list of advertiser ids, so prefer whoever authorized the connection.
return self.config.get("user_email") or self.config.get("user_display_name") or self.integration_id
@@ -832,7 +835,7 @@ class OauthIntegration:
authorize_url="https://www.pinterest.com/oauth/",
token_url="https://api.pinterest.com/v5/oauth/token",
token_info_url="https://api.pinterest.com/v5/user_account",
- token_info_config_fields=["id", "username"],
+ token_info_config_fields=["id", "username", "business_name"],
client_id=settings.PINTEREST_ADS_CLIENT_ID,
client_secret=settings.PINTEREST_ADS_CLIENT_SECRET,
scope="ads:read user_accounts:read",
diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.py
index b581a4a3a0c1..7d1351e26ef6 100644
--- a/posthog/models/test/test_integration_model.py
+++ b/posthog/models/test/test_integration_model.py
@@ -2856,6 +2856,29 @@ class TestS3CompatibleIntegrationModel(BaseTest):
S3CompatibleIntegration(integration)
+class TestPinterestAdsIntegrationDisplayName(BaseTest):
+ @parameterized.expand(
+ [
+ (
+ "business",
+ {"id": "1", "username": "13x6ppss87fecv1q790xh1orhyp9th", "business_name": "Posthog Inc"},
+ "Posthog Inc",
+ ),
+ ("personal", {"id": "1", "username": "javierposthog", "business_name": ""}, "javierposthog"),
+ # Older connections predate business_name being stored.
+ ("legacy", {"id": "1", "username": "javierposthog"}, "javierposthog"),
+ ]
+ )
+ def test_display_name_prefers_business_name(self, _name: str, config: dict, expected: str) -> None:
+ integration = Integration.objects.create(
+ team=self.team,
+ kind="pinterest-ads",
+ config=config,
+ integration_id=config["id"],
+ )
+ assert integration.display_name == expected
+
+
class TestTikTokAdsIntegrationDisplayName(BaseTest):
@parameterized.expand(
[
diff --git a/products/data_warehouse/backend/tests/api/test_external_data_source.py b/products/data_warehouse/backend/tests/api/test_external_data_source.py
index 500b1c73f0d1..1aca2e91687b 100644
--- a/products/data_warehouse/backend/tests/api/test_external_data_source.py
+++ b/products/data_warehouse/backend/tests/api/test_external_data_source.py
@@ -11521,6 +11521,7 @@ class TestOAuthAccountsEndpoint(APIBaseTest):
)
_REDDIT_ADS_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.reddit_ads.source"
_LINKEDIN_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.linkedin_ads.source"
+ _PINTEREST_ADS_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.pinterest_ads.source"
_TIKTOK_ADS_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.tiktok_ads.source"
_SNAPCHAT_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.snapchat_ads.source"
_META_ADS_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.source"
@@ -11558,6 +11559,16 @@ class TestOAuthAccountsEndpoint(APIBaseTest):
created_by=self.user,
)
+ def _pinterest_integration(self) -> Integration:
+ return Integration.objects.create(
+ team=self.team,
+ kind="pinterest-ads",
+ config={},
+ sensitive_config={"access_token": "token", "refresh_token": "refresh"},
+ integration_id="pinterest_test",
+ created_by=self.user,
+ )
+
def _gsc_integration(self) -> Integration:
return Integration.objects.create(
team=self.team,
@@ -11613,6 +11624,62 @@ class TestOAuthAccountsEndpoint(APIBaseTest):
response = self.client.get(self._url("Salesforce", 1))
assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ def test_pinterest_ads_maps_accounts_with_permission_badges(self):
+ integration = self._pinterest_integration()
+ listed = [
+ {"id": "549770029420", "name": "Posthog Inc", "permissions": ["OWNER"]},
+ {"id": "111", "name": "Client", "permissions": ["CAMPAIGN_MANAGER"]},
+ ]
+ with (
+ patch(f"{self._PINTEREST_ADS_MODULE}.OauthIntegration") as mock_oauth,
+ patch(f"{self._PINTEREST_ADS_MODULE}.build_session"),
+ patch(f"{self._PINTEREST_ADS_MODULE}.list_ad_accounts", return_value=listed),
+ ):
+ mock_oauth.return_value.access_token_expired.return_value = False
+ response = self.client.get(self._url("PinterestAds", integration.id))
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ assert response.json()["accounts"] == [
+ {
+ "value": "549770029420",
+ "display_name": "Posthog Inc",
+ "is_primary": False,
+ "badges": ["Owner"],
+ "group": None,
+ "secondary_text": None,
+ },
+ {
+ "value": "111",
+ "display_name": "Client",
+ "is_primary": False,
+ "badges": ["Campaign manager"],
+ "group": None,
+ "secondary_text": None,
+ },
+ ]
+
+ def _pinterest_http_error(self, status_code: int) -> requests.HTTPError:
+ response = Mock()
+ response.status_code = status_code
+ return requests.HTTPError(f"{status_code} Client Error", response=response)
+
+ @parameterized.expand([(401,), (403,)])
+ def test_pinterest_ads_auth_error_returns_actionable_400(self, status_code: int):
+ integration = self._pinterest_integration()
+ with (
+ patch(f"{self._PINTEREST_ADS_MODULE}.OauthIntegration") as mock_oauth,
+ patch(f"{self._PINTEREST_ADS_MODULE}.build_session"),
+ patch(
+ f"{self._PINTEREST_ADS_MODULE}.list_ad_accounts",
+ side_effect=self._pinterest_http_error(status_code),
+ ),
+ ):
+ mock_oauth.return_value.access_token_expired.return_value = False
+ response = self.client.get(self._url("PinterestAds", integration.id))
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ assert "reconnect" in str(response.json()).lower()
+
def _tiktok_integration(self) -> Integration:
return Integration.objects.create(
team=self.team,
@@ -11632,6 +11699,58 @@ class TestOAuthAccountsEndpoint(APIBaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
assert "reconnect" in str(response.json()).lower()
+ @parameterized.expand([(429,), (500,), (503,)])
+ def test_pinterest_ads_transient_error_asks_the_user_to_retry(self, status_code: int):
+ # Pinterest rate-limits `/ad_accounts` and 5xxs during outages. Neither is a bug on our side,
+ # so the picker must say "try again" rather than blow up with a 500.
+ integration = self._pinterest_integration()
+ with (
+ patch(f"{self._PINTEREST_ADS_MODULE}.OauthIntegration") as mock_oauth,
+ patch(f"{self._PINTEREST_ADS_MODULE}.build_session"),
+ patch(
+ f"{self._PINTEREST_ADS_MODULE}.list_ad_accounts",
+ side_effect=self._pinterest_http_error(status_code),
+ ),
+ ):
+ mock_oauth.return_value.access_token_expired.return_value = False
+ response = self.client.get(self._url("PinterestAds", integration.id))
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ assert "try again" in str(response.json()).lower()
+
+ def test_pinterest_ads_non_auth_api_error_is_not_swallowed(self):
+ # A 404 means we built a request Pinterest doesn't recognise — our bug, so let it surface.
+ integration = self._pinterest_integration()
+ with (
+ patch(f"{self._PINTEREST_ADS_MODULE}.OauthIntegration") as mock_oauth,
+ patch(f"{self._PINTEREST_ADS_MODULE}.build_session"),
+ patch(
+ f"{self._PINTEREST_ADS_MODULE}.list_ad_accounts",
+ side_effect=self._pinterest_http_error(404),
+ ),
+ ):
+ mock_oauth.return_value.access_token_expired.return_value = False
+ response = self.client.get(self._url("PinterestAds", integration.id))
+
+ assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR, response.content
+
+ def test_pinterest_ads_unreachable_token_endpoint_returns_400(self):
+ # `refresh_access_token` reports a refusal via `integration.errors`, but a network failure (or
+ # an HTML error page it can't parse) escapes as an exception — that must not become a 500.
+ integration = self._pinterest_integration()
+ with (
+ patch(f"{self._PINTEREST_ADS_MODULE}.OauthIntegration") as mock_oauth,
+ patch(f"{self._PINTEREST_ADS_MODULE}.build_session"),
+ patch(f"{self._PINTEREST_ADS_MODULE}.list_ad_accounts") as mock_list,
+ ):
+ mock_oauth.return_value.access_token_expired.return_value = True
+ mock_oauth.return_value.refresh_access_token.side_effect = requests.ConnectionError("boom")
+ response = self.client.get(self._url("PinterestAds", integration.id))
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ assert "try again" in str(response.json()).lower()
+ mock_list.assert_not_called()
+
@parameterized.expand([(40016,), (40100,), (40101,), (40102,), (50000,), (51001,), (60001,)])
def test_tiktok_transient_error_returns_actionable_400_not_a_reconnect_prompt(self, api_code: int):
# 40100 ("requests made too frequently") used to be classified as an auth error, telling a
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/source.py
index c67a162d45b4..938cdf3d2ff7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/source.py
@@ -1,17 +1,19 @@
from typing import Optional, cast
+import requests
+
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
ReleaseStatus,
SourceConfig,
- SourceFieldInputConfig,
- SourceFieldInputConfigType,
+ SourceFieldOauthAccountSelectConfig,
SourceFieldOauthConfig,
SuggestedTable,
)
from posthog.exceptions_capture import capture_exception
+from posthog.models.integration import ERROR_TOKEN_REFRESH_FAILED, OauthIntegration
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
SourceInputs,
@@ -25,6 +27,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.bas
from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
CanonicalDescriptions,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.integration_accounts import (
+ IntegrationAccount,
+ IntegrationAccountListingError,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import OAuthMixin
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
@@ -35,9 +41,17 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.pinterest_
pinterest_ads_source,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.pinterest_ads.settings import PINTEREST_ADS_CONFIG
+from products.warehouse_sources.backend.temporal.data_imports.sources.pinterest_ads.utils import (
+ build_session,
+ list_ad_accounts,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
+def _format_permission(permission: str) -> str:
+ return permission.replace("_", " ").capitalize()
+
+
@SourceRegistry.register
class PinterestAdsSource(ResumableSource[PinterestAdsSourceConfig, PinterestAdsResumeConfig], OAuthMixin):
supported_versions = ("v5",)
@@ -71,20 +85,20 @@ class PinterestAdsSource(ResumableSource[PinterestAdsSourceConfig, PinterestAdsR
fields=cast(
list[FieldType],
[
- SourceFieldInputConfig(
- name="ad_account_id",
- label="Pinterest Ads Ad Account ID",
- type=SourceFieldInputConfigType.TEXT,
- required=True,
- placeholder="Your Pinterest Ads ad account ID",
- secret=False,
- ),
SourceFieldOauthConfig(
name="pinterest_ads_integration_id",
label="Pinterest Ads account",
required=True,
kind="pinterest-ads",
),
+ SourceFieldOauthAccountSelectConfig(
+ name="ad_account_id",
+ label="Pinterest Ads Ad Account ID",
+ integrationField="pinterest_ads_integration_id",
+ integrationKind="pinterest-ads",
+ required=True,
+ placeholder="Your Pinterest Ads ad account ID",
+ ),
],
),
suggestedTables=[
@@ -99,6 +113,73 @@ class PinterestAdsSource(ResumableSource[PinterestAdsSourceConfig, PinterestAdsR
],
)
+ def get_oauth_accounts(
+ self, integration_id: int, team_id: int, search: str | None = None
+ ) -> list[IntegrationAccount]:
+ # A user's ad accounts are few, so `search` is ignored here and the endpoint filters the list.
+ try:
+ integration = self.get_oauth_integration(integration_id, team_id)
+ except ValueError as e:
+ raise IntegrationAccountListingError(
+ "The linked Pinterest Ads integration could not be found. "
+ "Please reconnect your Pinterest Ads integration."
+ ) from e
+
+ oauth = OauthIntegration(integration)
+ if oauth.access_token_expired():
+ try:
+ oauth.refresh_access_token()
+ except (requests.RequestException, ValueError) as e:
+ # `refresh_access_token` only records failure in `integration.errors` when Pinterest
+ # answers with a parseable body. A network error, or an HTML error page it then fails
+ # to `.json()`, escapes instead — transient either way, so don't let it 500.
+ raise IntegrationAccountListingError(
+ "Could not reach Pinterest to refresh the credentials for this integration. "
+ "Please try again in a few minutes."
+ ) from e
+ if integration.errors == ERROR_TOKEN_REFRESH_FAILED or not integration.access_token:
+ raise IntegrationAccountListingError(
+ "Could not refresh the Pinterest Ads credentials. Please reconnect your Pinterest Ads integration."
+ )
+
+ try:
+ accounts = list_ad_accounts(build_session(integration.access_token))
+ except requests.HTTPError as e:
+ status_code = e.response.status_code if e.response is not None else None
+ if status_code in (401, 403):
+ raise IntegrationAccountListingError(
+ "Pinterest rejected the credentials for this integration. Please reconnect your Pinterest Ads "
+ "integration and make sure the connected account can access your ad accounts."
+ ) from e
+ if status_code == 429:
+ # Pinterest rate-limits `/ad_accounts`, so this is neither a bug nor the user's fault.
+ raise IntegrationAccountListingError(
+ "Pinterest is rate limiting this connection. Please wait a moment and try again."
+ ) from e
+ if status_code is not None and status_code >= 500:
+ raise IntegrationAccountListingError(
+ "Pinterest is having trouble responding right now. Please try again in a few minutes."
+ ) from e
+ # Any other status means we built a bad request, which the user cannot fix.
+ raise
+ except requests.RequestException as e:
+ # A connection error or read timeout that outlived the retry policy in `_make_request`
+ # (it retries transport failures but reraises once attempts are exhausted). This is a
+ # transient outage like a 5xx, not a bug, so surface the same actionable message instead
+ # of letting a bare `RequestException` escape as a 500.
+ raise IntegrationAccountListingError(
+ "Pinterest is having trouble responding right now. Please try again in a few minutes."
+ ) from e
+
+ return [
+ IntegrationAccount(
+ value=account["id"],
+ display_name=account.get("name") or "Unnamed account",
+ badges=tuple(_format_permission(p) for p in account.get("permissions") or []),
+ )
+ for account in accounts
+ ]
+
def validate_credentials(
self, config: PinterestAdsSourceConfig, team_id: int, schema_name: Optional[str] = None
) -> tuple[bool, str | None]:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/tests/test_pinterest_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/tests/test_pinterest_ads.py
index 68dbd87a4051..68a15c397269 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/tests/test_pinterest_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/tests/test_pinterest_ads.py
@@ -26,6 +26,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.pinterest_
fetch_entities,
fetch_entity_ids,
get_date_range,
+ list_ad_accounts,
)
@@ -163,6 +164,29 @@ class TestFetchEntities:
assert result == []
+class TestListAdAccounts:
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.pinterest_ads.utils._make_request")
+ def test_walks_every_bookmarked_page(self, mock_request):
+ # A user with many ad accounts gets them across pages: the picker must list all of them, not
+ # just the first page, and must pass the previous page's bookmark back to Pinterest.
+ mock_request.side_effect = [
+ {"items": [{"id": "549770029420"}], "bookmark": "page_2"},
+ {"items": [{"id": "111"}], "bookmark": None},
+ ]
+ session = mock.MagicMock()
+
+ result = list_ad_accounts(session)
+
+ assert [account["id"] for account in result] == ["549770029420", "111"]
+ assert mock_request.call_count == 2
+
+ first_call, second_call = mock_request.call_args_list
+ assert first_call[0][1] == "https://api.pinterest.com/v5/ad_accounts"
+ assert "bookmark" not in first_call[0][2]
+ assert second_call[0][1] == "https://api.pinterest.com/v5/ad_accounts"
+ assert second_call[0][2]["bookmark"] == "page_2"
+
+
class TestFetchEntityIds:
@mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.pinterest_ads.utils.fetch_entities")
def test_extracts_ids(self, mock_fetch):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/tests/test_pinterest_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/tests/test_pinterest_source.py
index 7f3e2625bb24..3503f2409111 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/tests/test_pinterest_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/tests/test_pinterest_source.py
@@ -1,8 +1,13 @@
import pytest
from unittest import mock
-from posthog.schema import SourceFieldInputConfig, SourceFieldOauthConfig
+import requests
+from posthog.schema import SourceFieldOauthAccountSelectConfig, SourceFieldOauthConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.integration_accounts import (
+ IntegrationAccountListingError,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import PinterestAdsSourceConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.pinterest_ads.source import PinterestAdsSource
from products.warehouse_sources.backend.types import ExternalDataSourceType
@@ -26,17 +31,19 @@ class TestPinterestAdsSource:
assert config.featureFlag is None
assert len(config.fields) == 2
- account_field = config.fields[0]
- assert isinstance(account_field, SourceFieldInputConfig)
- assert account_field.name == "ad_account_id"
- assert account_field.required is True
-
- oauth_field = config.fields[1]
+ oauth_field = config.fields[0]
assert isinstance(oauth_field, SourceFieldOauthConfig)
assert oauth_field.name == "pinterest_ads_integration_id"
assert oauth_field.kind == "pinterest-ads"
assert oauth_field.required is True
+ account_field = config.fields[1]
+ assert isinstance(account_field, SourceFieldOauthAccountSelectConfig)
+ assert account_field.name == "ad_account_id"
+ assert account_field.required is True
+ assert account_field.integrationField == "pinterest_ads_integration_id"
+ assert account_field.integrationKind == "pinterest-ads"
+
def test_validate_credentials_missing_account_id(self):
invalid_config = PinterestAdsSourceConfig(pinterest_ads_integration_id=456, ad_account_id="")
is_valid, error_message = self.source.validate_credentials(invalid_config, self.team_id)
@@ -156,3 +163,30 @@ class TestPinterestAdsSource:
inputs.job_id = "job-1"
manager = self.source.get_resumable_source_manager(inputs)
assert manager._data_class.__name__ == "PinterestAdsResumeConfig"
+
+ @pytest.mark.parametrize(
+ "transport_error",
+ [requests.ConnectionError("connection reset"), requests.ReadTimeout("read timed out")],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.pinterest_ads.source.list_ad_accounts"
+ )
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.pinterest_ads.source.build_session")
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.pinterest_ads.source.OauthIntegration"
+ )
+ @mock.patch.object(PinterestAdsSource, "get_oauth_integration")
+ def test_get_oauth_accounts_maps_transport_failure_to_listing_error(
+ self, mock_get_oauth, mock_oauth_integration, mock_build_session, mock_list_ad_accounts, transport_error
+ ):
+ # A connection error / read timeout survives the retry policy and reaches the picker as a
+ # RequestException (not an HTTPError); it must become an actionable transient error, not a 500.
+ integration = mock.MagicMock()
+ integration.errors = ""
+ integration.access_token = "token"
+ mock_get_oauth.return_value = integration
+ mock_oauth_integration.return_value.access_token_expired.return_value = False
+ mock_list_ad_accounts.side_effect = transport_error
+
+ with pytest.raises(IntegrationAccountListingError, match="Pinterest is having trouble responding"):
+ self.source.get_oauth_accounts(456, self.team_id)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/utils.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/utils.py
index 05a449e54e05..b2ae038c2f42 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/utils.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/utils.py
@@ -104,14 +104,8 @@ def _make_request(session: requests.Session, url: str, params: Optional[dict] =
return response.json()
-def fetch_entities(
- session: requests.Session,
- ad_account_id: str,
- endpoint_name: str,
-) -> list[dict[str, Any]]:
- path = ENTITY_ENDPOINT_PATHS[endpoint_name].format(ad_account_id=ad_account_id)
- url = f"{BASE_URL}{path}"
-
+def _paginate_items(session: requests.Session, url: str) -> list[dict[str, Any]]:
+ """Collect every item from a bookmark-paginated Pinterest list endpoint."""
all_items: list[dict[str, Any]] = []
bookmark: Optional[str] = None
@@ -123,8 +117,7 @@ def fetch_entities(
params["bookmark"] = bookmark
data = _make_request(session, url, params)
- items = data.get("items", [])
- all_items.extend(items)
+ all_items.extend(data.get("items", []))
bookmark = data.get("bookmark")
if not bookmark:
@@ -133,6 +126,20 @@ def fetch_entities(
return all_items
+def list_ad_accounts(session: requests.Session) -> list[dict[str, Any]]:
+ """Every ad account the connected Pinterest user can access."""
+ return _paginate_items(session, f"{BASE_URL}/ad_accounts")
+
+
+def fetch_entities(
+ session: requests.Session,
+ ad_account_id: str,
+ endpoint_name: str,
+) -> list[dict[str, Any]]:
+ path = ENTITY_ENDPOINT_PATHS[endpoint_name].format(ad_account_id=ad_account_id)
+ return _paginate_items(session, f"{BASE_URL}{path}")
+
+
def fetch_entity_ids(
session: requests.Session,
ad_account_id: str,