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): add 11 Amazon Ads entity tables (#99189)

Tom Owersac186b7e61f3
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 3492f2c9b909..c3494dea8f29 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
@@ -259,7 +259,7 @@ Note: Single /query endpoint parameterized by `function=`; the docs page exposes
## AmazonAds — **thin**
-Today (7): `profiles`, `sp_ad_groups`, `sp_campaign_reports`, `sp_campaigns`, `sp_keywords`, `sp_product_ads`, `sp_targets`
+Today (18): `portfolios`, `profiles`, `sb_ad_groups`, `sb_ads`, `sb_campaigns`, `sb_targets`, `sd_ad_groups`, `sd_ads`, `sd_campaigns`, `sd_targets`, `sp_ad_groups`, `sp_campaign_negative_keywords`, `sp_campaign_reports`, `sp_campaigns`, `sp_keywords`, `sp_negative_keywords`, `sp_product_ads`, `sp_targets`
Diffed against: <https://d1y2lf8k3vrkfu.cloudfront.net/openapi/en-us/dest/SponsoredProducts_prod_3p.json>
@@ -267,15 +267,17 @@ Diffed against: <https://d1y2lf8k3vrkfu.cloudfront.net/openapi/en-us/dest/Sponso
- [x] `POST /sp/productAds/list` — the ad (ASIN) level under the ad groups already synced (high)
- [x] `POST /sp/keywords/list` — keyword-level bids and state, the main optimization object (high)
- [x] `POST /sp/targets/list` — product and category targeting expressions with bids (high)
-- [ ] `POST /portfolios/list` — lookup resolving the portfolioId carried on the campaigns already synced (high)
-- [ ] `POST /sb/... campaigns, ad groups, ads and targets (AmazonAdsAPISBMerged_prod_3p.json)` — Sponsored Brands entities are entirely absent, so spend coverage is partial (high)
-- [ ] `POST /sd/... campaigns, ad groups, product ads and targets (AmazonAdsAPISDMerged_prod_3p.json)` — Sponsored Display entities are entirely absent (high)
-- [ ] `POST /sp/negativeKeywords/list and /sp/campaignNegativeKeywords/list` — negative keyword coverage, needed to explain traffic exclusions (medium)
+- [x] `POST /portfolios/list` — lookup resolving the portfolioId carried on the campaigns already synced (high)
+- [x] `POST /adsApi/v1/query/... campaigns, adGroups, ads and targets, filtered to SPONSORED_BRANDS (AmazonAdsAPISBMerged_prod_3p.json)` — Sponsored Brands entities, so spend coverage is no longer partial (high)
+- [x] `POST /adsApi/v1/query/... campaigns, adGroups, ads and targets, filtered to SPONSORED_DISPLAY (AmazonAdsAPISDMerged_prod_3p.json)` — Sponsored Display entities (high)
+- [x] `POST /sp/negativeKeywords/list and /sp/campaignNegativeKeywords/list` — negative keyword coverage, needed to explain traffic exclusions (medium)
- [ ] `POST /sp/negativeTargets/list and /sp/campaignNegativeTargets/list` — negative product/category targets alongside the positive targets (medium)
- [ ] `POST /history (Change History API)` — state-transition history of bids, budgets and status changes (medium)
- [ ] `POST /adsAccounts/list` — advertising account lookup above profiles, for multi-account rollups (medium)
- [ ] `GET /invoices and POST /invoiceSummaries/list (Advertising Billing API)` — billed spend reconciliation against reported spend (medium)
+Note: the Sponsored Brands and Sponsored Display rows above were audited as `POST /sb/...` and `POST /sd/...`, but neither merged spec serves those paths. Both products' campaigns, ad groups, ads and targets are served by the unified Ads API at `POST /adsApi/v1/query/{entity}`, which selects between them with a required `adProductFilter`. That is the surface implemented. The per-product alternatives are worse: Sponsored Brands v4 has no targets list endpoint at all, and Sponsored Display v3 is a separate offset-paginated GET surface.
+
Note: Static schema list. The Amazon Ads docs site is a Redocly SPA; the real spec index is https://d3a0d0y2hgofx6.cloudfront.net/en-us/toc2.json, which links ~130 OpenAPI documents. I also read OfflineReport_prod_3p.json, Portfolios_prod_3p.json, AmazonAdsAPIExports_prod_3p.json, Changehistory_prod_3p.json, AdvertisingBilling_prod_3p.json and AdvertisingAccounts_prod_3p.json. Nearly all list endpoints are POST /.../list rather than GET.
## Amplitude — gaps
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/amazon_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/amazon_ads.py
index 9489c194949b..db413ed8d6b2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/amazon_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/amazon_ads.py
@@ -28,7 +28,6 @@ AMAZON_ADS_HOSTS = {
}
# Login with Amazon token endpoint is global.
LWA_TOKEN_URL = "https://api.amazon.com/auth/o2/token"
-PAGE_SIZE = 500
REQUEST_TIMEOUT_SECONDS = 120
MAX_RETRY_ATTEMPTS = 5
@@ -231,6 +230,10 @@ def get_rows(
if config.media_type is not None and method == "POST":
headers["Content-Type"] = config.media_type
headers["Accept"] = config.media_type
+ if config.ads_api:
+ # The unified Ads API reads the client id from its own header rather than the
+ # `Amazon-Advertising-API-ClientId` one the session already sends.
+ headers["Amazon-Ads-ClientId"] = client_id
if extra_headers is not None:
headers.update(extra_headers)
if method == "POST":
@@ -354,11 +357,13 @@ def get_rows(
yield from report_rows(config.report, profile_ids)
return
- # Sponsored Products v3 list endpoints, fanned out per profile.
+ # Entity list endpoints, fanned out per profile.
for profile_id in profile_ids:
next_token: Optional[str] = None
while True:
- body: dict[str, Any] = {"maxResults": PAGE_SIZE}
+ body: dict[str, Any] = dict(config.filters or {})
+ if config.page_size is not None:
+ body["maxResults"] = config.page_size
if next_token:
body["nextToken"] = next_token
data = request("POST", config.path, profile_id=profile_id, body=body).json()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/canonical_descriptions.py
index b7a998e0c1d2..20443d0c0aa1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/canonical_descriptions.py
@@ -97,6 +97,209 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"_profile_id": "Advertising profile the target was synced from.",
},
},
+ "sp_negative_keywords": {
+ "description": "A Sponsored Products negative keyword on an ad group, excluding a shopper search from that ad group.",
+ "docs_url": "https://advertising.amazon.com/API/docs/en-us/sponsored-products/3-0/openapi/prod#tag/Negative-keywords",
+ "columns": {
+ "keywordId": "Unique identifier for the negative keyword.",
+ "adGroupId": "Identifier of the ad group the negative keyword excludes traffic from.",
+ "campaignId": "Identifier of the campaign the ad group belongs to.",
+ "keywordText": "Text of the negative keyword.",
+ "matchType": "How the negative keyword matches a shopper search: negative broad, phrase, or exact.",
+ "state": "Current state of the negative keyword: enabled, paused, or archived.",
+ "nativeLanguageKeyword": "Negative keyword text in the advertiser's preferred language.",
+ "nativeLanguageLocale": "Locale of the advertiser's preferred language, such as zh_CN.",
+ "globalKeywordId": "Identifier of the negative keyword across marketplaces.",
+ "_profile_id": "Advertising profile the negative keyword was synced from.",
+ },
+ },
+ "sp_campaign_negative_keywords": {
+ "description": "A Sponsored Products negative keyword on a campaign, excluding a shopper search from every ad group in it.",
+ "docs_url": "https://advertising.amazon.com/API/docs/en-us/sponsored-products/3-0/openapi/prod#tag/Campaign-negative-keywords",
+ "columns": {
+ "keywordId": "Unique identifier for the campaign negative keyword.",
+ "campaignId": "Identifier of the campaign the negative keyword excludes traffic from.",
+ "keywordText": "Text of the negative keyword.",
+ "matchType": "How the negative keyword matches a shopper search: negative phrase or negative exact.",
+ "state": "Current state of the negative keyword: enabled, paused, or archived.",
+ "globalKeywordId": "Identifier of the negative keyword across marketplaces.",
+ "_profile_id": "Advertising profile the campaign negative keyword was synced from.",
+ },
+ },
+ "portfolios": {
+ "description": "A portfolio: a group of campaigns that shares a budget, which resolves the portfolioId the campaign tables carry.",
+ "docs_url": "https://advertising.amazon.com/API/docs/en-us/reference/portfolios",
+ "columns": {
+ "portfolioId": "Unique identifier for the portfolio.",
+ "name": "Name of the portfolio.",
+ "state": "Current state of the portfolio: enabled, paused, or archived.",
+ "budget": "Budget for the portfolio, including its amount, currency, policy, and date range.",
+ "budgetControls": "Extra budget controls on the portfolio, such as how unspent campaign budget is shared.",
+ "inBudget": "Whether the portfolio is still within its budget.",
+ "extendedData": "Creation and last-update timestamps plus the portfolio's serving status.",
+ "_profile_id": "Advertising profile the portfolio was synced from.",
+ },
+ },
+ "sb_campaigns": {
+ "description": "A Sponsored Brands campaign that groups ad groups under a budget and a targeting strategy.",
+ "docs_url": "https://advertising.amazon.com/API/docs/en-us/sponsored-brands/3-0/openapi/prod",
+ "columns": {
+ "campaignId": "Unique identifier for the campaign.",
+ "name": "Name of the campaign.",
+ "adProduct": "Ad product the campaign belongs to.",
+ "state": "Current state of the campaign: enabled, paused, or archived.",
+ "status": "Serving status of the campaign, which reflects why it is or is not delivering.",
+ "budgets": "Budget details for the campaign, including amount, currency, and budget type.",
+ "costType": "How the campaign is charged, such as cost per click.",
+ "portfolioId": "Identifier of the portfolio the campaign belongs to, if any.",
+ "startDateTime": "Date and time the campaign starts running.",
+ "endDateTime": "Date and time the campaign stops running, if set.",
+ "creationDateTime": "Date and time the campaign was created.",
+ "lastUpdatedDateTime": "Date and time the campaign was last updated.",
+ "marketplaceScope": "Whether the campaign applies to one marketplace or to several.",
+ "marketplaces": "Amazon marketplaces the campaign runs in.",
+ "countries": "Countries whose Amazon retail supply the campaign targets.",
+ "tags": "Key-value labels applied to the campaign.",
+ "_profile_id": "Advertising profile the campaign was synced from.",
+ },
+ },
+ "sb_ad_groups": {
+ "description": "A Sponsored Brands ad group within a campaign, grouping its ads and targets.",
+ "docs_url": "https://advertising.amazon.com/API/docs/en-us/sponsored-brands/3-0/openapi/prod",
+ "columns": {
+ "adGroupId": "Unique identifier for the ad group.",
+ "campaignId": "Identifier of the campaign the ad group belongs to.",
+ "name": "Name of the ad group.",
+ "adProduct": "Ad product the ad group belongs to.",
+ "state": "Current state of the ad group: enabled, paused, or archived.",
+ "status": "Serving status of the ad group, which reflects why it is or is not delivering.",
+ "creationDateTime": "Date and time the ad group was created.",
+ "lastUpdatedDateTime": "Date and time the ad group was last updated.",
+ "marketplaceScope": "Whether the ad group applies to one marketplace or to several.",
+ "marketplaces": "Amazon marketplaces the ad group runs in.",
+ "_profile_id": "Advertising profile the ad group was synced from.",
+ },
+ },
+ "sb_ads": {
+ "description": "A Sponsored Brands ad: one creative inside an ad group.",
+ "docs_url": "https://advertising.amazon.com/API/docs/en-us/sponsored-brands/3-0/openapi/prod",
+ "columns": {
+ "adId": "Unique identifier for the ad.",
+ "adGroupId": "Identifier of the ad group the ad belongs to.",
+ "campaignId": "Identifier of the campaign the ad belongs to.",
+ "name": "Name of the ad.",
+ "adProduct": "Ad product the ad belongs to.",
+ "adType": "Type of the ad, which determines the creative it carries.",
+ "creative": "Creative content of the ad, such as its headline, assets, and promoted products.",
+ "state": "Current state of the ad: enabled, paused, or archived.",
+ "status": "Serving status of the ad, which reflects why it is or is not delivering.",
+ "creationDateTime": "Date and time the ad was created.",
+ "lastUpdatedDateTime": "Date and time the ad was last updated.",
+ "marketplaceScope": "Whether the ad applies to one marketplace or to several.",
+ "marketplaces": "Amazon marketplaces the ad runs in.",
+ "_profile_id": "Advertising profile the ad was synced from.",
+ },
+ },
+ "sb_targets": {
+ "description": "A Sponsored Brands target: one targeting expression with its bid, positive or negative.",
+ "docs_url": "https://advertising.amazon.com/API/docs/en-us/sponsored-brands/3-0/openapi/prod",
+ "columns": {
+ "targetId": "Unique identifier for the target.",
+ "adGroupId": "Identifier of the ad group the target belongs to. Set for ad-group level targets only.",
+ "campaignId": "Identifier of the campaign the target belongs to. Set for campaign-level targets only.",
+ "adProduct": "Ad product the target belongs to.",
+ "targetType": "Type of the target, such as a keyword, a product, or an audience.",
+ "targetLevel": "Whether the target applies at the campaign or the ad group level.",
+ "targetDetails": "The targeting expression itself, such as the keyword text or the targeted product.",
+ "negative": "Whether the target excludes traffic instead of buying it.",
+ "bid": "Bid for the target. A target with no bid inherits the ad group's bid.",
+ "state": "Current state of the target: enabled, paused, or archived.",
+ "status": "Serving status of the target, which reflects why it is or is not delivering.",
+ "creationDateTime": "Date and time the target was created.",
+ "lastUpdatedDateTime": "Date and time the target was last updated.",
+ "_profile_id": "Advertising profile the target was synced from.",
+ },
+ },
+ "sd_campaigns": {
+ "description": "A Sponsored Display campaign that groups ad groups under a budget and a targeting strategy.",
+ "docs_url": "https://advertising.amazon.com/API/docs/en-us/sponsored-display/3-0/openapi",
+ "columns": {
+ "campaignId": "Unique identifier for the campaign.",
+ "name": "Name of the campaign.",
+ "adProduct": "Ad product the campaign belongs to.",
+ "state": "Current state of the campaign: enabled, paused, or archived.",
+ "status": "Serving status of the campaign, which reflects why it is or is not delivering.",
+ "budgets": "Budget details for the campaign, including amount, currency, and budget type.",
+ "costType": "How the campaign is charged, such as cost per click.",
+ "portfolioId": "Identifier of the portfolio the campaign belongs to, if any.",
+ "startDateTime": "Date and time the campaign starts running.",
+ "endDateTime": "Date and time the campaign stops running, if set.",
+ "creationDateTime": "Date and time the campaign was created.",
+ "lastUpdatedDateTime": "Date and time the campaign was last updated.",
+ "marketplaceScope": "Whether the campaign applies to one marketplace or to several.",
+ "marketplaces": "Amazon marketplaces the campaign runs in.",
+ "countries": "Countries whose Amazon retail supply the campaign targets.",
+ "tags": "Key-value labels applied to the campaign.",
+ "_profile_id": "Advertising profile the campaign was synced from.",
+ },
+ },
+ "sd_ad_groups": {
+ "description": "A Sponsored Display ad group within a campaign, grouping its ads and targets.",
+ "docs_url": "https://advertising.amazon.com/API/docs/en-us/sponsored-display/3-0/openapi",
+ "columns": {
+ "adGroupId": "Unique identifier for the ad group.",
+ "campaignId": "Identifier of the campaign the ad group belongs to.",
+ "name": "Name of the ad group.",
+ "adProduct": "Ad product the ad group belongs to.",
+ "state": "Current state of the ad group: enabled, paused, or archived.",
+ "status": "Serving status of the ad group, which reflects why it is or is not delivering.",
+ "creationDateTime": "Date and time the ad group was created.",
+ "lastUpdatedDateTime": "Date and time the ad group was last updated.",
+ "marketplaceScope": "Whether the ad group applies to one marketplace or to several.",
+ "marketplaces": "Amazon marketplaces the ad group runs in.",
+ "_profile_id": "Advertising profile the ad group was synced from.",
+ },
+ },
+ "sd_ads": {
+ "description": "A Sponsored Display ad: one creative inside an ad group.",
+ "docs_url": "https://advertising.amazon.com/API/docs/en-us/sponsored-display/3-0/openapi",
+ "columns": {
+ "adId": "Unique identifier for the ad.",
+ "adGroupId": "Identifier of the ad group the ad belongs to.",
+ "campaignId": "Identifier of the campaign the ad belongs to.",
+ "name": "Name of the ad.",
+ "adProduct": "Ad product the ad belongs to.",
+ "adType": "Type of the ad, which determines the creative it carries.",
+ "creative": "Creative content of the ad, such as its headline, assets, and promoted products.",
+ "state": "Current state of the ad: enabled, paused, or archived.",
+ "status": "Serving status of the ad, which reflects why it is or is not delivering.",
+ "creationDateTime": "Date and time the ad was created.",
+ "lastUpdatedDateTime": "Date and time the ad was last updated.",
+ "marketplaceScope": "Whether the ad applies to one marketplace or to several.",
+ "marketplaces": "Amazon marketplaces the ad runs in.",
+ "_profile_id": "Advertising profile the ad was synced from.",
+ },
+ },
+ "sd_targets": {
+ "description": "A Sponsored Display target: one targeting expression with its bid, positive or negative.",
+ "docs_url": "https://advertising.amazon.com/API/docs/en-us/sponsored-display/3-0/openapi",
+ "columns": {
+ "targetId": "Unique identifier for the target.",
+ "adGroupId": "Identifier of the ad group the target belongs to. Set for ad-group level targets only.",
+ "campaignId": "Identifier of the campaign the target belongs to. Set for campaign-level targets only.",
+ "adProduct": "Ad product the target belongs to.",
+ "targetType": "Type of the target, such as a keyword, a product, or an audience.",
+ "targetLevel": "Whether the target applies at the campaign or the ad group level.",
+ "targetDetails": "The targeting expression itself, such as the keyword text or the targeted product.",
+ "negative": "Whether the target excludes traffic instead of buying it.",
+ "bid": "Bid for the target. A target with no bid inherits the ad group's bid.",
+ "state": "Current state of the target: enabled, paused, or archived.",
+ "status": "Serving status of the target, which reflects why it is or is not delivering.",
+ "creationDateTime": "Date and time the target was created.",
+ "lastUpdatedDateTime": "Date and time the target was last updated.",
+ "_profile_id": "Advertising profile the target was synced from.",
+ },
+ },
"sp_campaign_reports": {
"description": "Daily Sponsored Products performance for each campaign, from the async reporting API.",
"docs_url": "https://advertising.amazon.com/API/docs/en-us/guides/reporting/v3/report-types/campaign",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/settings.py
index 0fc12782baf6..84d0d3ad185f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/settings.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Any, Optional
from posthog.dataclasses import frozen
@@ -21,6 +21,17 @@ class AmazonAdsReportConfig:
retention_days: int = 95
+# Page size for the list endpoints that accept one. Amazon caps it per endpoint, so an endpoint
+# whose ceiling is lower carries its own.
+PAGE_SIZE = 500
+# The unified Ads API caps an entity query at 100 results, except for targets.
+ADS_API_PAGE_SIZE = 100
+ADS_API_TARGET_PAGE_SIZE = 5000
+
+SPONSORED_BRANDS = "SPONSORED_BRANDS"
+SPONSORED_DISPLAY = "SPONSORED_DISPLAY"
+
+
@frozen
class AmazonAdsEndpointConfig:
name: str
@@ -36,6 +47,32 @@ class AmazonAdsEndpointConfig:
# Set for the async reporting endpoints, which build their rows from a generated file
# rather than from a paginated list response.
report: Optional[AmazonAdsReportConfig] = None
+ # `maxResults` to send with each list request. None omits it, for an endpoint whose request
+ # schema declares no such field.
+ page_size: Optional[int] = PAGE_SIZE
+ # Request body fields every page of this endpoint repeats, such as the ad product a unified
+ # Ads API query selects on.
+ filters: Optional[dict[str, Any]] = None
+ # The unified Ads API (`/adsApi/v1/query/...`) serves the Sponsored Brands and Sponsored
+ # Display entities. It takes plain JSON, and it reads the client id from its own header.
+ ads_api: bool = False
+
+
+def ads_api_query(
+ name: str, entity: str, ad_product: str, id_field: str, page_size: int = ADS_API_PAGE_SIZE
+) -> AmazonAdsEndpointConfig:
+ """One unified Ads API entity query. Sponsored Brands and Sponsored Display share the paths,
+ so the ad product filter is what selects between them."""
+ return AmazonAdsEndpointConfig(
+ name=name,
+ path=f"/adsApi/v1/query/{entity}",
+ primary_keys=["_profile_id", id_field],
+ profile_scoped=True,
+ data_key=entity,
+ page_size=page_size,
+ filters={"adProductFilter": {"include": [ad_product]}},
+ ads_api=True,
+ )
# Sponsored Products campaign performance, one row per campaign per day. `date` is the only
@@ -160,6 +197,45 @@ AMAZON_ADS_ENDPOINTS: dict[str, AmazonAdsEndpointConfig] = {
media_type="application/vnd.spTargetingClause.v3+json",
data_key="targetingClauses",
),
+ "sp_negative_keywords": AmazonAdsEndpointConfig(
+ name="sp_negative_keywords",
+ path="/sp/negativeKeywords/list",
+ primary_keys=["_profile_id", "keywordId"],
+ profile_scoped=True,
+ media_type="application/vnd.spNegativeKeyword.v3+json",
+ data_key="negativeKeywords",
+ ),
+ "sp_campaign_negative_keywords": AmazonAdsEndpointConfig(
+ name="sp_campaign_negative_keywords",
+ path="/sp/campaignNegativeKeywords/list",
+ primary_keys=["_profile_id", "keywordId"],
+ profile_scoped=True,
+ media_type="application/vnd.spCampaignNegativeKeyword.v3+json",
+ data_key="campaignNegativeKeywords",
+ ),
+ # Portfolios sit above campaigns and resolve the portfolioId the campaign tables carry.
+ # Their list request schema has no `maxResults`, so none is sent.
+ "portfolios": AmazonAdsEndpointConfig(
+ name="portfolios",
+ path="/portfolios/list",
+ primary_keys=["_profile_id", "portfolioId"],
+ profile_scoped=True,
+ media_type="application/vnd.spPortfolio.v3+json",
+ data_key="portfolios",
+ page_size=None,
+ ),
+ "sb_campaigns": ads_api_query("sb_campaigns", "campaigns", SPONSORED_BRANDS, "campaignId"),
+ "sb_ad_groups": ads_api_query("sb_ad_groups", "adGroups", SPONSORED_BRANDS, "adGroupId"),
+ "sb_ads": ads_api_query("sb_ads", "ads", SPONSORED_BRANDS, "adId"),
+ "sb_targets": ads_api_query(
+ "sb_targets", "targets", SPONSORED_BRANDS, "targetId", page_size=ADS_API_TARGET_PAGE_SIZE
+ ),
+ "sd_campaigns": ads_api_query("sd_campaigns", "campaigns", SPONSORED_DISPLAY, "campaignId"),
+ "sd_ad_groups": ads_api_query("sd_ad_groups", "adGroups", SPONSORED_DISPLAY, "adGroupId"),
+ "sd_ads": ads_api_query("sd_ads", "ads", SPONSORED_DISPLAY, "adId"),
+ "sd_targets": ads_api_query(
+ "sd_targets", "targets", SPONSORED_DISPLAY, "targetId", page_size=ADS_API_TARGET_PAGE_SIZE
+ ),
"sp_campaign_reports": AmazonAdsEndpointConfig(
name="sp_campaign_reports",
path="/reporting/reports",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/source.py
index 67ad965da7ff..0e555d95e077 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/source.py
@@ -60,7 +60,7 @@ class AmazonAdsSource(ResumableSource[AmazonAdsSourceConfig, AmazonAdsResumeConf
label="Amazon Ads",
caption="""Connect your Amazon Ads account to pull your advertising entity data into the PostHog Data warehouse.
-You need a Login with Amazon (LWA) application with Advertising API access: enter its client ID and secret plus a refresh token authorized for your advertiser account. Pick the region that matches your advertising profiles (North America, Europe, or Far East). Your Sponsored Products entities and daily campaign performance are synced from every profile the token can access.""",
+You need a Login with Amazon (LWA) application with Advertising API access: enter its client ID and secret plus a refresh token authorized for your advertiser account. Pick the region that matches your advertising profiles (North America, Europe, or Far East). Your portfolios, your Sponsored Products, Sponsored Brands and Sponsored Display entities, and daily Sponsored Products campaign performance are synced from every profile the token can access.""",
iconPath="/static/services/amazon_ads.png",
docsUrl="https://posthog.com/docs/cdp/sources/amazon-ads",
releaseStatus=ReleaseStatus.ALPHA,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/tests/test_amazon_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/tests/test_amazon_ads.py
index 4931f6d9badd..8468aca0fd22 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/tests/test_amazon_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/tests/test_amazon_ads.py
@@ -12,7 +12,6 @@ import requests
from products.warehouse_sources.backend.temporal.data_imports.sources.amazon_ads.amazon_ads import (
LWA_TOKEN_URL,
- PAGE_SIZE,
REPORT_POLL_MAX_ATTEMPTS,
AmazonAdsReportError,
AmazonAdsResumeConfig,
@@ -25,6 +24,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.amazon_ads
from products.warehouse_sources.backend.temporal.data_imports.sources.amazon_ads.settings import (
AMAZON_ADS_ENDPOINTS,
ENDPOINTS,
+ PAGE_SIZE,
SP_CAMPAIGN_REPORT,
)
@@ -184,6 +184,60 @@ class TestGetRows:
second_list_call = mock_session.return_value.post.call_args_list[2]
assert second_list_call.kwargs["json"] == {"maxResults": PAGE_SIZE, "nextToken": "tok"}
+ @pytest.mark.parametrize(
+ "endpoint, expected_body",
+ [
+ ("sp_campaigns", {"maxResults": PAGE_SIZE}),
+ # `/portfolios/list` declares no `maxResults`, and rejects a body field it does not know.
+ ("portfolios", {}),
+ ("sp_negative_keywords", {"maxResults": PAGE_SIZE}),
+ # Sponsored Brands and Sponsored Display share the unified Ads API paths, so the ad
+ # product filter is the only thing that keeps one product's rows out of the other's
+ # table. Amazon caps `maxResults` at 100 per entity query, and at 5000 for targets.
+ ("sb_campaigns", {"maxResults": 100, "adProductFilter": {"include": ["SPONSORED_BRANDS"]}}),
+ ("sb_targets", {"maxResults": 5000, "adProductFilter": {"include": ["SPONSORED_BRANDS"]}}),
+ ("sd_ads", {"maxResults": 100, "adProductFilter": {"include": ["SPONSORED_DISPLAY"]}}),
+ ("sd_targets", {"maxResults": 5000, "adProductFilter": {"include": ["SPONSORED_DISPLAY"]}}),
+ ],
+ )
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_list_request_body_per_endpoint(self, mock_session, endpoint, expected_body):
+ config = AMAZON_ADS_ENDPOINTS[endpoint]
+ mock_session.return_value.post.side_effect = [
+ _token_response(),
+ _json_response({config.data_key: [{"id": 1}], "nextToken": "tok"}),
+ _json_response({config.data_key: [{"id": 2}]}),
+ ]
+ mock_session.return_value.get.return_value = _json_response([{"profileId": 1}])
+
+ list(get_rows("na", "cid", "sec", "rt", endpoint, mock.MagicMock()))
+
+ calls = mock_session.return_value.post.call_args_list
+ assert calls[1].kwargs["json"] == expected_body
+ assert calls[2].kwargs["json"] == {**expected_body, "nextToken": "tok"}
+
+ @pytest.mark.parametrize(
+ "endpoint, expected_client_id",
+ [
+ ("sb_campaigns", "cid"),
+ ("sd_campaigns", "cid"),
+ ("sp_campaigns", None),
+ ],
+ )
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_unified_ads_api_sends_its_own_client_id_header(self, mock_session, endpoint, expected_client_id):
+ config = AMAZON_ADS_ENDPOINTS[endpoint]
+ mock_session.return_value.post.side_effect = [
+ _token_response(),
+ _json_response({config.data_key: [{"id": 1}]}),
+ ]
+ mock_session.return_value.get.return_value = _json_response([{"profileId": 1}])
+
+ list(get_rows("na", "cid", "sec", "rt", endpoint, mock.MagicMock()))
+
+ headers = mock_session.return_value.post.call_args_list[1].kwargs["headers"]
+ assert headers.get("Amazon-Ads-ClientId") == expected_client_id
+
@mock.patch(f"{_MODULE}.make_tracked_session")
def test_remints_token_on_401(self, mock_session):
expired = mock.MagicMock()