From 228d1a24dc305bebb91a65c290f6b1ed52614b25 Mon Sep 17 00:00:00 2001 From: Ali Hesari Date: Mon, 23 Nov 2026 23:18:27 +0100 Subject: [PATCH 1/3] refactor(ads): remove the campaign tree, creative, catalog and Ad Library methods The API no longer serves /v1/ads/accounts/{id}/tree, the campaign, ad set and network ad objects, creatives, catalogs or the Ad Library. Their methods and the models only they returned are removed. bulk_set_status, create and the /v1/ads/{id} methods are unchanged. --- src/fopost/__init__.py | 23 -- src/fopost/models.py | 196 ----------- src/fopost/resources/ads.py | 660 +----------------------------------- tests/test_ads.py | 79 +---- tests/test_ads_tiktok.py | 18 +- 5 files changed, 6 insertions(+), 970 deletions(-) diff --git a/src/fopost/__init__.py b/src/fopost/__init__.py index c72b68c..41f9a49 100644 --- a/src/fopost/__init__.py +++ b/src/fopost/__init__.py @@ -53,23 +53,16 @@ ActivityEvent, ActivityPage, Ad, - AdAccountTree, AdBusinessCenter, - AdCampaign, - AdCampaignNode, AdComment, AdCommentsPage, AdConnection, - AdCreative, AdIdentity, AdInsights, AdInsightsReport, - AdLibraryPage, AdPixel, AdPixelDetail, AdProvider, - AdSet, - AdSetNode, AdSource, AiCreditBalance, AiCredits, @@ -242,7 +235,6 @@ MetricChangePage, NativePost, NativePostMetrics, - NetworkAd, Page, PageMeta, PinterestBoard, @@ -401,17 +393,10 @@ "ActivityEvent", "ActivityPage", "Ad", - "AdAccountTree", - "AdCampaign", - "AdCampaignNode", "AdConnection", - "AdCreative", "AdInsights", - "AdLibraryPage", "AdProvider", "AdInsightsReport", - "AdSet", - "AdSetNode", "AdSource", "AiCreditBalance", "AiCredits", @@ -475,7 +460,6 @@ "LeadsFeedPage", "LeadsPage", "MediaItem", - "NetworkAd", "NotFoundError", "PLATFORMS", "POST_STATUSES", @@ -588,13 +572,7 @@ "ValidatePostResult", "Workspace", "__version__", - "AdAccountTree", - "AdCampaign", - "AdCampaignNode", - "AdCreative", "AdInsightsReport", - "AdSet", - "AdSetNode", "BulkAdStatusResult", "FeedLead", "GoogleAdScheduleSlot", @@ -619,7 +597,6 @@ "LeadPage", "LeadPageSubscription", "LeadsFeedPage", - "NetworkAd", "BidPricing", "ConversionMetrics", "ConversionRule", diff --git a/src/fopost/models.py b/src/fopost/models.py index 25e8543..c3d5d9c 100644 --- a/src/fopost/models.py +++ b/src/fopost/models.py @@ -52,15 +52,9 @@ "ActivityPage", "AccountRename", "Ad", - "AdAccountTree", - "AdCampaign", - "AdCampaignNode", "AdConnection", - "AdCreative", "AdInsights", "AdInsightsReport", - "AdSet", - "AdSetNode", "AdSource", "AiCreditBalance", "CollectPostDelivery", @@ -115,7 +109,6 @@ "LeadsFeedPage", "LeadsPage", "MediaItem", - "NetworkAd", "PLATFORMS", "POST_STATUSES", "Page", @@ -165,23 +158,12 @@ "ValidatePlatformCheck", "ValidatePostResult", "Workspace", - "AdAccountTree", "AdActivity", "AdActivityResult", - "AdCampaign", - "AdCampaignNode", - "AdCreative", "AdInsightsReport", "AdLabel", - "AdLibraryEntry", - "AdLibraryPage", - "AdSet", - "AdSetNode", "AdStudy", "BulkAdStatusResult", - "CatalogBatchResult", - "CatalogProduct", - "CatalogProductsPage", "FeedLead", "HighDemandPeriod", "InsightsMetrics", @@ -191,13 +173,7 @@ "LeadPage", "LeadPageSubscription", "LeadsFeedPage", - "NetworkAd", "PartnershipCreator", - "ProductCatalog", - "ProductCatalogsResult", - "ProductFeed", - "ProductFeedUpload", - "ProductSet", "ReachEstimate", "ReachFrequencyPrediction", "ReachFrequencyResult", @@ -1673,65 +1649,6 @@ class LeadsPage(FopostModel): next_cursor: str | None = None -class AdCampaign(FopostModel): - """A campaign on Meta, read live.""" - - id: str - name: str - status: str - effective_status: str | None = None - objective: str | None = None - #: None when the budget lives on the ad sets. - budget_minor: int | None = None - budget_type: str | None = None - created_at: str | None = None - - -class AdSet(FopostModel): - """An ad set on Meta, read live.""" - - id: str - name: str - campaign_id: str | None = None - status: str - effective_status: str | None = None - budget_minor: int | None = None - budget_type: str | None = None - end_at: str | None = None - optimization_goal: str | None = None - created_at: str | None = None - - -class NetworkAd(FopostModel): - """An ad inside an ad set on Meta, read live. Not the same as a FoPost ``Ad``.""" - - id: str - name: str - campaign_id: str | None = None - ad_set_id: str | None = None - creative_id: str | None = None - status: str - effective_status: str | None = None - created_at: str | None = None - - -class AdSetNode(AdSet): - ads: list[NetworkAd] = [] - - -class AdCampaignNode(AdCampaign): - ad_sets: list[AdSetNode] = [] - - -class AdAccountTree(FopostModel): - """Campaigns, their ad sets and their ads on one ad account.""" - - ad_account_id: str - currency: str | None = None - workspace_id: str | None = None - campaigns: list[AdCampaignNode] = [] - - class BulkAdStatusResult(FopostModel): id: str level: str @@ -1739,19 +1656,6 @@ class BulkAdStatusResult(FopostModel): error: str | None = None -class AdCreative(FopostModel): - id: str - name: str - format: str - status: str | None = None - title: str | None = None - body: str | None = None - link: str | None = None - thumbnail_url: str | None = None - call_to_action: str | None = None - url_tags: str | None = None - - class InsightsMetrics(FopostModel): impressions: int = 0 reach: int = 0 @@ -2006,77 +1910,6 @@ class LeadPageSubscription(FopostModel): backfilled: int = 0 -# ─── Product catalogs ────────────────────────────────────────────── - - -class ProductCatalog(FopostModel): - """A product catalog on the connection's business portfolio, read live.""" - - id: str - name: str - vertical: str | None = None - product_count: int | None = None - - -class ProductCatalogsResult(FopostModel): - catalogs: list[ProductCatalog] = [] - workspace_id: str | None = None - - -class CatalogProduct(FopostModel): - id: str - #: Your own key for the product. - retailer_id: str - name: str - description: str | None = None - availability: str | None = None - condition: str | None = None - #: Minor units of ``currency``. - price_minor: int | None = None - currency: str | None = None - image_url: str | None = None - url: str | None = None - - -class CatalogProductsPage(FopostModel): - products: list[CatalogProduct] = [] - next_cursor: str | None = None - - -class CatalogBatchResult(FopostModel): - handles: list[str] = [] - #: Products sent in this batch. - accepted: int = 0 - - -class ProductFeed(FopostModel): - id: str - name: str - #: Set when the network fetches the file on a schedule. - url: str | None = None - schedule: str | None = None - created_at: str | None = None - - -class ProductFeedUpload(FopostModel): - id: str - started_at: str | None = None - ended_at: str | None = None - status: str | None = None - error_count: int | None = None - warning_count: int | None = None - - -class ProductSet(FopostModel): - """The slice of a catalog one catalog ad runs from.""" - - id: str - name: str - product_count: int | None = None - #: The network's own product-set filter. - filter: dict[str, Any] | None = None - - # ─── Reach and frequency ─────────────────────────────────────────── @@ -2100,35 +1933,6 @@ class ReachFrequencyResult(FopostModel): workspace_id: str | None = None -# ─── Ad Library ──────────────────────────────────────────────────── - - -class AdLibraryEntry(FopostModel): - """One public archive entry. Read live on every search and stored nowhere.""" - - id: str - page_id: str | None = None - page_name: str | None = None - bodies: list[str] = [] - titles: list[str] = [] - link_urls: list[str] = [] - snapshot_url: str | None = None - publisher_platforms: list[str] = [] - started_at: str | None = None - ended_at: str | None = None - #: Only on the archive's disclosure entries. - currency: str | None = None - spend_lower: int | None = None - spend_upper: int | None = None - impressions_lower: int | None = None - impressions_upper: int | None = None - - -class AdLibraryPage(FopostModel): - entries: list[AdLibraryEntry] = [] - next_cursor: str | None = None - - # ─── Partnership ads ─────────────────────────────────────────────── diff --git a/src/fopost/resources/ads.py b/src/fopost/resources/ads.py index 453f2ab..d877d8b 100644 --- a/src/fopost/resources/ads.py +++ b/src/fopost/resources/ads.py @@ -1,11 +1,10 @@ -"""``client.ads`` — ads, catalogs, audiences, the ad archive, lead forms and ad comments. +"""``client.ads`` — ads, audiences, lead forms and ad comments. The connection decides which network a call reaches, so the same methods run Meta and TikTok; the Google-only surface is ``client.ads.google``. Every method needs the ``ads`` scope; ``boost``, ``create``, ``set_status``, -``delete``, ``bulk_set_status`` and every create, update, delete or duplicate on -campaigns, ad sets and network ads spend money and also need ``publish``. +``delete`` and ``bulk_set_status`` spend money and also need ``publish``. """ from __future__ import annotations @@ -17,21 +16,16 @@ from .._http import unwrap from ..models import ( Ad, - AdAccountTree, AdActivityResult, AdBusinessCenter, - AdCampaign, AdCommentsPage, AdConnection, - AdCreative, AdIdentity, AdInsightsReport, AdLabel, - AdLibraryPage, AdPixel, AdPixelDetail, AdProvider, - AdSet, AdSource, AdStudy, Audience, @@ -39,8 +33,6 @@ BidPricing, BoostablePost, BulkAdStatusResult, - CatalogBatchResult, - CatalogProductsPage, ConversionBatch, ConversionMetrics, ConversionRule, @@ -56,14 +48,8 @@ LeadPageSubscription, LeadsFeedPage, LeadsPage, - NetworkAd, PartnershipCreator, PixelStats, - ProductCatalog, - ProductCatalogsResult, - ProductFeed, - ProductFeedUpload, - ProductSet, ReachEstimate, ReachFrequencyPrediction, ReachFrequencyResult, @@ -81,7 +67,7 @@ class AdsResource(Resource): def __init__(self, http: Any) -> None: super().__init__(http) - #: The Search surface no other network has: keywords, assets, conversions, GAQL. + #: The Search surface no other network has: bid strategies, conversions, GAQL. self.google = GoogleAdsResource(http) def list(self, *, workspace_id: str | None = None) -> builtins.list[Ad]: @@ -378,222 +364,6 @@ def leads( ) ) - # ─── Campaign tree (Meta ids, read live, never stored) ────────────── - - def account_tree( - self, ad_account_id: str, *, connection_id: str, workspace_id: str | None = None - ) -> AdAccountTree: - """Every campaign on the ad account with its ad sets and their ads.""" - return AdAccountTree.model_validate( - unwrap( - self._http.get( - f"/ads/accounts/{ad_account_id}/tree", - {"workspace_id": workspace_id, "connection_id": connection_id}, - ) - ) - ) - - def create_campaign( - self, - *, - workspace_id: str, - connection_id: str, - ad_account_id: str, - name: str, - goal: str, - paused: bool | None = None, - smart_plus: bool | None = None, - ) -> AdCampaign: - """Starts paused unless ``paused=False``. - - ``smart_plus`` hands targeting and creative rotation to the network and - needs its ``smartPlus`` capability. - """ - body: dict[str, Any] = { - "workspaceId": workspace_id, - "connectionId": connection_id, - "adAccountId": ad_account_id, - "name": name, - "goal": goal, - } - if paused is not None: - body["paused"] = paused - if smart_plus is not None: - body["smartPlus"] = smart_plus - return AdCampaign.model_validate(unwrap(self._http.post("/ads/campaigns", body))) - - def get_campaign( - self, campaign_id: str, *, connection_id: str, workspace_id: str | None = None - ) -> AdCampaign: - return AdCampaign.model_validate( - unwrap(self._object("GET", "campaigns", campaign_id, workspace_id, connection_id)) - ) - - def update_campaign( - self, - campaign_id: str, - *, - workspace_id: str, - connection_id: str, - name: str | Any = UNSET, - status: str | Any = UNSET, - ) -> AdCampaign: - """Partial update; ``status`` is ``active`` or ``paused``.""" - body = drop_unset({"name": name, "status": status}) - return AdCampaign.model_validate( - unwrap( - self._object("PATCH", "campaigns", campaign_id, workspace_id, connection_id, body) - ) - ) - - def delete_campaign(self, campaign_id: str, *, workspace_id: str, connection_id: str) -> None: - self._object("DELETE", "campaigns", campaign_id, workspace_id, connection_id) - - def duplicate_campaign( - self, - campaign_id: str, - *, - workspace_id: str, - connection_id: str, - paused: bool | None = None, - ) -> str: - """Copy the campaign with its ad sets and ads; returns the copy's Meta id.""" - return self._duplicate("campaigns", campaign_id, workspace_id, connection_id, paused) - - def create_ad_set( - self, - *, - workspace_id: str, - connection_id: str, - campaign_id: str, - page_id: str, - name: str, - goal: str, - budget: Mapping[str, Any], - targeting: Mapping[str, Any], - paused: bool | None = None, - ) -> AdSet: - """Starts paused unless ``paused=False``.""" - body: dict[str, Any] = { - "workspaceId": workspace_id, - "connectionId": connection_id, - "campaignId": campaign_id, - "pageId": page_id, - "name": name, - "goal": goal, - "budget": dict(budget), - "targeting": dict(targeting), - } - if paused is not None: - body["paused"] = paused - return AdSet.model_validate(unwrap(self._http.post("/ads/ad-sets", body))) - - def get_ad_set( - self, ad_set_id: str, *, connection_id: str, workspace_id: str | None = None - ) -> AdSet: - return AdSet.model_validate( - unwrap(self._object("GET", "ad-sets", ad_set_id, workspace_id, connection_id)) - ) - - def update_ad_set( - self, - ad_set_id: str, - *, - workspace_id: str, - connection_id: str, - name: str | Any = UNSET, - status: str | Any = UNSET, - budget_minor: int | Any = UNSET, - end_at: str | Any = UNSET, - targeting: Mapping[str, Any] | Any = UNSET, - ) -> AdSet: - """Partial update. The budget type set at creation stays.""" - body = drop_unset( - { - "name": name, - "status": status, - "budgetMinor": budget_minor, - "endAt": end_at, - "targeting": dict(targeting) if targeting is not UNSET else UNSET, - } - ) - return AdSet.model_validate( - unwrap(self._object("PATCH", "ad-sets", ad_set_id, workspace_id, connection_id, body)) - ) - - def delete_ad_set(self, ad_set_id: str, *, workspace_id: str, connection_id: str) -> None: - self._object("DELETE", "ad-sets", ad_set_id, workspace_id, connection_id) - - def duplicate_ad_set( - self, - ad_set_id: str, - *, - workspace_id: str, - connection_id: str, - paused: bool | None = None, - ) -> str: - """Returns the copy's Meta id.""" - return self._duplicate("ad-sets", ad_set_id, workspace_id, connection_id, paused) - - def create_network_ad( - self, - *, - workspace_id: str, - connection_id: str, - ad_set_id: str, - creative_id: str, - name: str, - paused: bool | None = None, - ) -> NetworkAd: - """An ad inside an ad set, from a creative. Starts paused unless ``paused=False``.""" - body: dict[str, Any] = { - "workspaceId": workspace_id, - "connectionId": connection_id, - "adSetId": ad_set_id, - "creativeId": creative_id, - "name": name, - } - if paused is not None: - body["paused"] = paused - return NetworkAd.model_validate(unwrap(self._http.post("/ads/ads", body))) - - def get_network_ad( - self, ad_id: str, *, connection_id: str, workspace_id: str | None = None - ) -> NetworkAd: - return NetworkAd.model_validate( - unwrap(self._object("GET", "ads", ad_id, workspace_id, connection_id)) - ) - - def update_network_ad( - self, - ad_id: str, - *, - workspace_id: str, - connection_id: str, - name: str | Any = UNSET, - status: str | Any = UNSET, - creative_id: str | Any = UNSET, - ) -> NetworkAd: - """Partial update; ``creative_id`` swaps the ad's creative.""" - body = drop_unset({"name": name, "status": status, "creativeId": creative_id}) - return NetworkAd.model_validate( - unwrap(self._object("PATCH", "ads", ad_id, workspace_id, connection_id, body)) - ) - - def delete_network_ad(self, ad_id: str, *, workspace_id: str, connection_id: str) -> None: - self._object("DELETE", "ads", ad_id, workspace_id, connection_id) - - def duplicate_network_ad( - self, - ad_id: str, - *, - workspace_id: str, - connection_id: str, - paused: bool | None = None, - ) -> str: - """Returns the copy's Meta id.""" - return self._duplicate("ads", ad_id, workspace_id, connection_id, paused) - def bulk_set_status( self, *, @@ -615,75 +385,6 @@ def bulk_set_status( } return parse_list(BulkAdStatusResult, unwrap(self._http.post("/ads/status", body))) - # ─── Creatives ────────────────────────────────────────────────────── - - def creatives( - self, *, connection_id: str, ad_account_id: str, workspace_id: str | None = None - ) -> builtins.list[AdCreative]: - result = unwrap( - self._http.get( - "/ads/creatives", - { - "workspace_id": workspace_id, - "connection_id": connection_id, - "ad_account_id": ad_account_id, - }, - ) - ) - return parse_list(AdCreative, result.get("creatives") if isinstance(result, dict) else None) - - def create_creative( - self, - *, - workspace_id: str, - connection_id: str, - ad_account_id: str, - page_id: str, - name: str, - format: str, - text: str, - headline: str | None = None, - destination_url: str | None = None, - call_to_action: str | None = None, - url_tags: str | None = None, - media_url: str | None = None, - thumbnail_media_url: str | None = None, - cards: Sequence[Mapping[str, Any]] | None = None, - ) -> AdCreative: - """``format`` is ``image``, ``video`` (needs ``media_url``) or ``carousel`` (needs - 2-10 ``cards`` of ``mediaUrl``, ``destinationUrl``, ``headline``, ``description``). - """ - body: dict[str, Any] = { - "workspaceId": workspace_id, - "connectionId": connection_id, - "adAccountId": ad_account_id, - "pageId": page_id, - "name": name, - "format": format, - "text": text, - } - optional = { - "headline": headline, - "destinationUrl": destination_url, - "callToAction": call_to_action, - "urlTags": url_tags, - "mediaUrl": media_url, - "thumbnailMediaUrl": thumbnail_media_url, - "cards": [dict(c) for c in cards] if cards is not None else None, - } - body.update({k: v for k, v in optional.items() if v is not None}) - return AdCreative.model_validate(unwrap(self._http.post("/ads/creatives", body))) - - def get_creative( - self, creative_id: str, *, connection_id: str, workspace_id: str | None = None - ) -> AdCreative: - return AdCreative.model_validate( - unwrap(self._object("GET", "creatives", creative_id, workspace_id, connection_id)) - ) - - def delete_creative(self, creative_id: str, *, workspace_id: str, connection_id: str) -> None: - self._object("DELETE", "creatives", creative_id, workspace_id, connection_id) - # ─── Audiences ────────────────────────────────────────────────────── def get_audience( @@ -756,7 +457,7 @@ def add_audience_companies( added = result.get("added") if isinstance(result, dict) else None return int(added) if added is not None else 0 - # ─── Forecasts, conversions and the public ad library ─────────────── + # ─── Forecasts and conversions ────────────────────────────────────── def bid_pricing( self, @@ -967,37 +668,6 @@ def send_conversion_events( accepted = result.get("accepted") if isinstance(result, dict) else None return int(accepted) if accepted is not None else 0 - def ad_library( - self, - *, - connection_id: str, - workspace_id: str | None = None, - keyword: str | None = None, - advertiser: str | None = None, - countries: Sequence[str] | None = None, - since: str | None = None, - until: str | None = None, - cursor: str | None = None, - ) -> AdLibraryPage: - """The network's own public ad library, not the connection's ads.""" - return AdLibraryPage.model_validate( - unwrap( - self._http.get( - "/ads/ad-library", - { - "workspace_id": workspace_id, - "connection_id": connection_id, - "keyword": keyword, - "advertiser": advertiser, - "countries": ",".join(countries) if countries else None, - "since": since, - "until": until, - "cursor": cursor, - }, - ) - ) - ) - # ─── Reach and insights ───────────────────────────────────────────── def estimate_reach( @@ -1172,278 +842,6 @@ def goals(self, *, connection_id: str, workspace_id: str | None = None) -> built ) return [str(goal) for goal in result] if isinstance(result, list) else [] - # ─── Product catalogs ────────────────────────────────────────── - - def catalogs( - self, *, connection_id: str, workspace_id: str | None = None - ) -> ProductCatalogsResult: - """Catalogs the connection's business portfolios reach. Read live, never stored.""" - return ProductCatalogsResult.model_validate( - unwrap( - self._http.get( - "/ads/catalogs", - {"workspace_id": workspace_id, "connection_id": connection_id}, - ) - ) - ) - - def create_catalog( - self, - *, - workspace_id: str, - connection_id: str, - name: str, - vertical: str | None = None, - ) -> ProductCatalog: - """Created on the connection's business portfolio. Also needs ``publish``.""" - body: dict[str, Any] = { - "workspaceId": workspace_id, - "connectionId": connection_id, - "name": name, - } - if vertical is not None: - body["vertical"] = vertical - return ProductCatalog.model_validate(unwrap(self._http.post("/ads/catalogs", body))) - - def get_catalog( - self, catalog_id: str, *, connection_id: str, workspace_id: str | None = None - ) -> ProductCatalog: - return ProductCatalog.model_validate( - unwrap( - self._http.get( - f"/ads/catalogs/{catalog_id}", - {"workspace_id": workspace_id, "connection_id": connection_id}, - ) - ) - ) - - def update_catalog( - self, catalog_id: str, *, workspace_id: str, connection_id: str, name: str - ) -> ProductCatalog: - """Also needs ``publish``.""" - body = {"workspaceId": workspace_id, "connectionId": connection_id, "name": name} - return ProductCatalog.model_validate( - unwrap( - self._http.request( - "PATCH", - f"/ads/catalogs/{catalog_id}", - json=body, - params={"workspace_id": workspace_id, "connection_id": connection_id}, - ) - ) - ) - - def delete_catalog(self, catalog_id: str, *, workspace_id: str, connection_id: str) -> None: - """Deletes every product, feed and set in it. Also needs ``publish``.""" - self._http.request( - "DELETE", - f"/ads/catalogs/{catalog_id}", - params={"workspace_id": workspace_id, "connection_id": connection_id}, - ) - - def catalog_products( - self, - catalog_id: str, - *, - connection_id: str, - workspace_id: str | None = None, - after: str | None = None, - ) -> CatalogProductsPage: - """One page of products; pass ``next_cursor`` back as ``after``.""" - return CatalogProductsPage.model_validate( - unwrap( - self._http.get( - f"/ads/catalogs/{catalog_id}/products", - { - "workspace_id": workspace_id, - "connection_id": connection_id, - "after": after, - }, - ) - ) - ) - - def write_catalog_products( - self, - catalog_id: str, - *, - workspace_id: str, - connection_id: str, - products: Sequence[Mapping[str, Any]], - ) -> CatalogBatchResult: - """Up to 500 upserts and deletes in one batch, keyed by ``retailerId``. - - Also needs ``publish``. - """ - body = { - "workspaceId": workspace_id, - "connectionId": connection_id, - "products": [dict(p) for p in products], - } - return CatalogBatchResult.model_validate( - unwrap(self._http.post(f"/ads/catalogs/{catalog_id}/products", body)) - ) - - def product_feeds( - self, catalog_id: str, *, connection_id: str, workspace_id: str | None = None - ) -> builtins.list[ProductFeed]: - return parse_list( - ProductFeed, - unwrap( - self._http.get( - f"/ads/catalogs/{catalog_id}/feeds", - {"workspace_id": workspace_id, "connection_id": connection_id}, - ) - ), - ) - - def create_product_feed( - self, - catalog_id: str, - *, - workspace_id: str, - connection_id: str, - name: str, - url: str | None = None, - schedule: str | None = None, - ) -> ProductFeed: - """``schedule`` is ``HOURLY``, ``DAILY`` or ``WEEKLY`` and needs ``url``. - - Also needs ``publish``. - """ - body: dict[str, Any] = { - "workspaceId": workspace_id, - "connectionId": connection_id, - "name": name, - } - optional = {"url": url, "schedule": schedule} - body.update({k: v for k, v in optional.items() if v is not None}) - return ProductFeed.model_validate( - unwrap(self._http.post(f"/ads/catalogs/{catalog_id}/feeds", body)) - ) - - def delete_product_feed( - self, catalog_id: str, feed_id: str, *, workspace_id: str, connection_id: str - ) -> None: - """Also needs ``publish``.""" - self._http.request( - "DELETE", - f"/ads/catalogs/{catalog_id}/feeds/{feed_id}", - params={"workspace_id": workspace_id, "connection_id": connection_id}, - ) - - def feed_uploads( - self, - catalog_id: str, - feed_id: str, - *, - connection_id: str, - workspace_id: str | None = None, - ) -> builtins.list[ProductFeedUpload]: - """Each run the network made of the feed.""" - return parse_list( - ProductFeedUpload, - unwrap( - self._http.get( - f"/ads/catalogs/{catalog_id}/feeds/{feed_id}/uploads", - {"workspace_id": workspace_id, "connection_id": connection_id}, - ) - ), - ) - - def start_feed_upload( - self, - catalog_id: str, - feed_id: str, - *, - workspace_id: str, - connection_id: str, - url: str | None = None, - ) -> str: - """Fetches the feed now; the id of the run. Also needs ``publish``.""" - body: dict[str, Any] = {"workspaceId": workspace_id, "connectionId": connection_id} - if url is not None: - body["url"] = url - result = unwrap( - self._http.post(f"/ads/catalogs/{catalog_id}/feeds/{feed_id}/uploads", body) - ) - upload_id = result.get("id") if isinstance(result, dict) else None - return str(upload_id) if upload_id else "" - - def product_sets( - self, catalog_id: str, *, connection_id: str, workspace_id: str | None = None - ) -> builtins.list[ProductSet]: - """A catalog ad runs from a product set, not the whole catalog.""" - return parse_list( - ProductSet, - unwrap( - self._http.get( - f"/ads/catalogs/{catalog_id}/product-sets", - {"workspace_id": workspace_id, "connection_id": connection_id}, - ) - ), - ) - - def create_product_set( - self, - catalog_id: str, - *, - workspace_id: str, - connection_id: str, - name: str, - filter: Mapping[str, Any] | None = None, - ) -> ProductSet: - """Without a ``filter`` the set is the whole catalog. Also needs ``publish``.""" - body: dict[str, Any] = { - "workspaceId": workspace_id, - "connectionId": connection_id, - "name": name, - } - if filter is not None: - body["filter"] = dict(filter) - return ProductSet.model_validate( - unwrap(self._http.post(f"/ads/catalogs/{catalog_id}/product-sets", body)) - ) - - def update_product_set( - self, - catalog_id: str, - set_id: str, - *, - workspace_id: str, - connection_id: str, - name: str, - filter: Mapping[str, Any] | None = None, - ) -> ProductSet: - """Also needs ``publish``.""" - body: dict[str, Any] = { - "workspaceId": workspace_id, - "connectionId": connection_id, - "name": name, - } - if filter is not None: - body["filter"] = dict(filter) - return ProductSet.model_validate( - unwrap( - self._http.request( - "PATCH", - f"/ads/catalogs/{catalog_id}/product-sets/{set_id}", - json=body, - params={"workspace_id": workspace_id, "connection_id": connection_id}, - ) - ) - ) - - def delete_product_set( - self, catalog_id: str, set_id: str, *, workspace_id: str, connection_id: str - ) -> None: - """Also needs ``publish``.""" - self._http.request( - "DELETE", - f"/ads/catalogs/{catalog_id}/product-sets/{set_id}", - params={"workspace_id": workspace_id, "connection_id": connection_id}, - ) - # ─── Reach and frequency ─────────────────────────────────────── def reach_frequency( @@ -1531,37 +929,6 @@ def cancel_reach_frequency( prediction_id, "cancel", workspace_id, connection_id, ad_account_id ) - # ─── Ad Library ──────────────────────────────────────────────── - - def library( - self, - *, - connection_id: str, - countries: Sequence[str], - workspace_id: str | None = None, - q: str | None = None, - page_ids: Sequence[str] | None = None, - active_status: str | None = None, - limit: int | None = None, - after: str | None = None, - ) -> AdLibraryPage: - """The public ad archive: ads anyone is running, by keyword or by Page. - - Read live on every call and stored nowhere, so an ad that stops running - is simply absent from the next search. Search by ``q`` or ``page_ids``. - """ - params: dict[str, Any] = { - "workspace_id": workspace_id, - "connection_id": connection_id, - "countries": ",".join(countries), - "q": q, - "page_ids": ",".join(page_ids) if page_ids else None, - "active_status": active_status, - "limit": limit, - "after": after, - } - return AdLibraryPage.model_validate(unwrap(self._http.get("/ads/library", params))) - # ─── Partnership ads ─────────────────────────────────────────── def partnership_creators( @@ -2391,22 +1758,3 @@ def _rule( json=dict(body) if body is not None else None, params={"workspace_id": workspace_id, "connection_id": connection_id}, ) - - def _duplicate( - self, - kind: str, - object_id: str, - workspace_id: str, - connection_id: str, - paused: bool | None, - ) -> str: - result = unwrap( - self._http.request( - "POST", - f"/ads/{kind}/{object_id}/duplicate", - json={"paused": paused} if paused is not None else {}, - params={"workspace_id": workspace_id, "connection_id": connection_id}, - ) - ) - copy_id = result.get("id") if isinstance(result, dict) else None - return str(copy_id) if copy_id else "" diff --git a/tests/test_ads.py b/tests/test_ads.py index 074c66c..01d9929 100644 --- a/tests/test_ads.py +++ b/tests/test_ads.py @@ -184,68 +184,7 @@ def test_create_sends_url_tags(client: Fopost) -> None: @respx.mock -def test_account_tree_nests_campaigns_ad_sets_and_ads(client: Fopost) -> None: - route = respx.get(f"{BASE_URL}/ads/accounts/act_1/tree").mock( - return_value=httpx.Response( - 200, - json={ - "data": { - "adAccountId": "act_1", - "currency": "USD", - "workspaceId": "ws_1", - "campaigns": [ - { - "id": "c_1", - "name": "Autumn", - "status": "PAUSED", - "budgetMinor": None, - "adSets": [ - { - "id": "s_1", - "name": "US 21-45", - "status": "ACTIVE", - "campaignId": "c_1", - "budgetMinor": 2000, - "ads": [ - { - "id": "a_1", - "name": "Hero", - "status": "ACTIVE", - "adSetId": "s_1", - "creativeId": "cr_1", - } - ], - } - ], - } - ], - } - }, - ) - ) - - tree = client.ads.account_tree("act_1", connection_id="conn_1", workspace_id="ws_1") - - assert tree.ad_account_id == "act_1" - ad_set = tree.campaigns[0].ad_sets[0] - assert ad_set.budget_minor == 2000 - assert ad_set.ads[0].creative_id == "cr_1" - assert dict(route.calls.last.request.url.params) == { - "workspace_id": "ws_1", - "connection_id": "conn_1", - } - - -@respx.mock -def test_campaign_update_is_partial_and_duplicate_returns_the_copy_id(client: Fopost) -> None: - patch = respx.patch(f"{BASE_URL}/ads/campaigns/c_1").mock( - return_value=httpx.Response( - 200, json={"data": {"id": "c_1", "name": "Autumn", "status": "ACTIVE"}} - ) - ) - dup = respx.post(f"{BASE_URL}/ads/campaigns/c_1/duplicate").mock( - return_value=httpx.Response(201, json={"data": {"id": "c_2"}}) - ) +def test_bulk_set_status_reports_each_object(client: Fopost) -> None: status = respx.post(f"{BASE_URL}/ads/status").mock( return_value=httpx.Response( 200, @@ -258,22 +197,6 @@ def test_campaign_update_is_partial_and_duplicate_returns_the_copy_id(client: Fo ) ) - campaign = client.ads.update_campaign( - "c_1", workspace_id="ws_1", connection_id="conn_1", status="active" - ) - assert campaign.status == "ACTIVE" - assert json.loads(patch.calls.last.request.content) == {"status": "active"} - assert dict(patch.calls.last.request.url.params) == { - "workspace_id": "ws_1", - "connection_id": "conn_1", - } - - copy_id = client.ads.duplicate_campaign( - "c_1", workspace_id="ws_1", connection_id="conn_1", paused=False - ) - assert copy_id == "c_2" - assert json.loads(dup.calls.last.request.content) == {"paused": False} - results = client.ads.bulk_set_status( workspace_id="ws_1", connection_id="conn_1", diff --git a/tests/test_ads_tiktok.py b/tests/test_ads_tiktok.py index a557351..78204a5 100644 --- a/tests/test_ads_tiktok.py +++ b/tests/test_ads_tiktok.py @@ -46,16 +46,10 @@ def test_identities_and_spark_posts_read_the_right_paths(client: Fopost) -> None @respx.mock -def test_spark_post_id_and_smart_plus_travel_in_the_body(client: Fopost) -> None: +def test_spark_post_id_travels_in_the_body(client: Fopost) -> None: ad_route = respx.post(f"{BASE_URL}/ads").mock( return_value=httpx.Response(201, json={"data": AD_FIXTURE}) ) - campaign_route = respx.post(f"{BASE_URL}/ads/campaigns").mock( - return_value=httpx.Response( - 201, - json={"data": {"id": "c1", "name": "Smart", "status": "PAUSED"}}, - ) - ) client.ads.create( workspace_id="ws_1", @@ -71,16 +65,6 @@ def test_spark_post_id_and_smart_plus_travel_in_the_body(client: Fopost) -> None ) assert json.loads(ad_route.calls.last.request.content)["sparkPostId"] == "item_99" - client.ads.create_campaign( - workspace_id="ws_1", - connection_id="conn_1", - ad_account_id="7011", - name="Smart", - goal="traffic", - smart_plus=True, - ) - assert json.loads(campaign_route.calls.last.request.content)["smartPlus"] is True - @respx.mock def test_conversions_hash_nothing_locally_and_report_what_was_accepted(client: Fopost) -> None: From 29072d6c317236109ebcca43dfeea76c80f7f034 Mon Sep 17 00:00:00 2001 From: Ali Hesari Date: Mon, 23 Nov 2026 23:18:28 +0100 Subject: [PATCH 2/3] refactor(ads): remove the Google keyword, asset and recommendation methods client.ads.google keeps bid strategies, the ad schedule, Local Services leads, conversions and query. Keywords, keyword ideas and metrics, search terms, negative keyword lists, assets, asset groups, recommendations and the optimization score are removed with their models. --- src/fopost/__init__.py | 24 -- src/fopost/models.py | 100 -------- src/fopost/resources/google_ads.py | 384 +---------------------------- tests/test_google_ads.py | 102 -------- 4 files changed, 3 insertions(+), 607 deletions(-) diff --git a/src/fopost/__init__.py b/src/fopost/__init__.py index 41f9a49..cbef280 100644 --- a/src/fopost/__init__.py +++ b/src/fopost/__init__.py @@ -162,21 +162,9 @@ FrequencyBest, FrequencyWeek, GoogleAdScheduleSlot, - GoogleAsset, - GoogleAssetGroup, - GoogleAssetLink, - GoogleAssetsResult, GoogleBidStrategy, GoogleConversionAction, - GoogleKeyword, - GoogleKeywordIdea, GoogleLocalServicesLead, - GoogleOptimizationScore, - GoogleOptimizationScoreCampaign, - GoogleRecommendation, - GoogleRecommendationImpact, - GoogleSearchTerm, - GoogleSharedSet, HashedConversionEvent, InboxAccount, InboxAccountRef, @@ -576,21 +564,9 @@ "BulkAdStatusResult", "FeedLead", "GoogleAdScheduleSlot", - "GoogleAsset", - "GoogleAssetGroup", - "GoogleAssetLink", - "GoogleAssetsResult", "GoogleBidStrategy", "GoogleConversionAction", - "GoogleKeyword", - "GoogleKeywordIdea", "GoogleLocalServicesLead", - "GoogleOptimizationScore", - "GoogleOptimizationScoreCampaign", - "GoogleRecommendation", - "GoogleRecommendationImpact", - "GoogleSearchTerm", - "GoogleSharedSet", "InsightsMetrics", "InsightsRow", "LeadFormDetail", diff --git a/src/fopost/models.py b/src/fopost/models.py index c3d5d9c..4534495 100644 --- a/src/fopost/models.py +++ b/src/fopost/models.py @@ -2344,34 +2344,6 @@ def __getitem__(self, index: int) -> ActivityEvent: # ─── Google Ads ──────────────────────────────────────────────────── -class GoogleKeyword(FopostModel): - """``~keyword~~`` as ``id``.""" - - id: str - ad_group_id: str - text: str - match_type: str - status: str - #: Account currency, minor units. - cpc_bid_minor: int | None = None - negative: bool = False - - -class GoogleKeywordIdea(FopostModel): - text: str - avg_monthly_searches: int = 0 - competition: str | None = None - low_top_of_page_bid_minor: int | None = None - high_top_of_page_bid_minor: int | None = None - - -class GoogleSearchTerm(FopostModel): - term: str - ad_group_id: str | None = None - status: str | None = None - metrics: dict[str, Any] = {} - - class GoogleBidStrategy(FopostModel): id: str name: str @@ -2388,78 +2360,6 @@ class GoogleAdScheduleSlot(FopostModel): bid_modifier: float | None = None -class GoogleSharedSet(FopostModel): - id: str - name: str - type: str - member_count: int = 0 - - -class GoogleAsset(FopostModel): - id: str - name: str | None = None - type: str - #: What a sitelink, callout or snippet renders. - text: str | None = None - final_url: str | None = None - - -class GoogleAssetLink(FopostModel): - """Where an asset is attached; an asset with no links serves nowhere.""" - - id: str - asset_id: str - level: str - owner_id: str | None = None - field_type: str - status: str - - -class GoogleAssetsResult(FopostModel): - assets: list[GoogleAsset] = [] - links: list[GoogleAssetLink] = [] - - -class GoogleAssetGroup(FopostModel): - id: str - campaign_id: str - name: str - status: str - final_urls: list[str] = [] - - -class GoogleRecommendationImpact(FopostModel): - base_clicks: float | None = None - potential_clicks: float | None = None - base_cost_minor: int | None = None - potential_cost_minor: int | None = None - base_conversions: float | None = None - potential_conversions: float | None = None - - -class GoogleRecommendation(FopostModel): - """``id`` is the Google resource name, which is what apply and dismiss take.""" - - id: str - type: str - campaign_id: str | None = None - ad_group_id: str | None = None - dismissed: bool = False - impact: GoogleRecommendationImpact | None = None - - -class GoogleOptimizationScoreCampaign(FopostModel): - id: str - name: str - score: float | None = None - - -class GoogleOptimizationScore(FopostModel): - score: float | None = None - weight: float | None = None - campaigns: list[GoogleOptimizationScoreCampaign] = [] - - class GoogleLocalServicesLead(FopostModel): id: str category: str | None = None diff --git a/src/fopost/resources/google_ads.py b/src/fopost/resources/google_ads.py index 0e873fb..a88802d 100644 --- a/src/fopost/resources/google_ads.py +++ b/src/fopost/resources/google_ads.py @@ -1,9 +1,8 @@ """``client.ads.google`` — the Google Ads surface no other network has. -Campaigns, ad groups, ads, audiences and insights live on ``client.ads`` and -dispatch by connection. What is here — keywords, assets, Performance Max asset -groups, Local Services leads, conversions and raw GAQL — is Google only, and a -connection on another network answers 400. +Ads, audiences and insights live on ``client.ads`` and dispatch by connection. +What is here (bid strategies, the ad schedule, Local Services leads, conversions +and raw GAQL) is Google only, and a connection on another network answers 400. Every method needs the ``ads`` scope; anything that changes what a live account serves or bids also needs ``publish``. ``customer_id`` is digits only and has @@ -19,17 +18,9 @@ from .._http import unwrap from ..models import ( GoogleAdScheduleSlot, - GoogleAssetGroup, - GoogleAssetsResult, GoogleBidStrategy, GoogleConversionAction, - GoogleKeyword, - GoogleKeywordIdea, GoogleLocalServicesLead, - GoogleOptimizationScore, - GoogleRecommendation, - GoogleSearchTerm, - GoogleSharedSet, ) from ._base import Resource, parse_list @@ -37,135 +28,6 @@ class GoogleAdsResource(Resource): - # ── Keywords ── - - def keywords( - self, - *, - connection_id: str, - customer_id: str, - workspace_id: str | None = None, - ad_group_id: str | None = None, - ) -> builtins.list[GoogleKeyword]: - """Keywords on the account, or on one ad group.""" - return parse_list( - GoogleKeyword, - unwrap( - self._http.get( - "/ads/google/keywords", - _query(workspace_id, connection_id, customer_id, ad_group_id=ad_group_id), - ) - ), - ) - - def create_keyword( - self, - *, - workspace_id: str, - connection_id: str, - customer_id: str, - ad_group_id: str, - text: str, - match_type: str, - cpc_bid_minor: int | None = None, - ) -> str: - """The new keyword's id. Needs ``publish`` as well as ``ads``.""" - body = _scope(workspace_id, connection_id, customer_id) - body["adGroupId"] = ad_group_id - body["text"] = text - body["matchType"] = match_type - if cpc_bid_minor is not None: - body["cpcBidMinor"] = cpc_bid_minor - return _id(unwrap(self._http.post("/ads/google/keywords", body))) - - def update_keyword( - self, - keyword_id: str, - *, - workspace_id: str, - connection_id: str, - customer_id: str, - status: str | None = None, - cpc_bid_minor: int | None = None, - ) -> str: - """``status`` is ``active`` or ``paused``. Needs ``publish`` as well as ``ads``.""" - body = _scope(workspace_id, connection_id, customer_id) - if status is not None: - body["status"] = status - if cpc_bid_minor is not None: - body["cpcBidMinor"] = cpc_bid_minor - return _id( - unwrap(self._http.request("PATCH", f"/ads/google/keywords/{keyword_id}", json=body)) - ) - - def delete_keyword( - self, keyword_id: str, *, workspace_id: str, connection_id: str, customer_id: str - ) -> None: - """Needs ``publish`` as well as ``ads``.""" - self._http.delete( - f"/ads/google/keywords/{keyword_id}", - json=_scope(workspace_id, connection_id, customer_id), - ) - - def keyword_ideas( - self, - *, - workspace_id: str, - connection_id: str, - customer_id: str, - seeds: Sequence[str] | None = None, - url: str | None = None, - language_id: str | None = None, - geo_target_ids: Sequence[str] | None = None, - ) -> builtins.list[GoogleKeywordIdea]: - """Ideas from seed keywords, a landing page, or both.""" - body = _scope(workspace_id, connection_id, customer_id) - if seeds is not None: - body["seeds"] = list(seeds) - if url is not None: - body["url"] = url - if language_id is not None: - body["languageId"] = language_id - if geo_target_ids is not None: - body["geoTargetIds"] = list(geo_target_ids) - return parse_list( - GoogleKeywordIdea, unwrap(self._http.post("/ads/google/keyword-ideas", body)) - ) - - def keyword_metrics( - self, - *, - workspace_id: str, - connection_id: str, - customer_id: str, - keywords: Sequence[str], - ) -> builtins.list[GoogleKeywordIdea]: - body = _scope(workspace_id, connection_id, customer_id) - body["keywords"] = list(keywords) - return parse_list( - GoogleKeywordIdea, unwrap(self._http.post("/ads/google/keyword-metrics", body)) - ) - - def search_terms( - self, - *, - connection_id: str, - customer_id: str, - since: str, - until: str, - workspace_id: str | None = None, - ) -> builtins.list[GoogleSearchTerm]: - """What people actually searched, with the metrics each term earned.""" - return parse_list( - GoogleSearchTerm, - unwrap( - self._http.get( - "/ads/google/search-terms", - _query(workspace_id, connection_id, customer_id, since=since, until=until), - ) - ), - ) - # ── Bid strategies and ad schedule ── def bid_strategies( @@ -232,182 +94,6 @@ def set_ad_schedule( result = unwrap(self._http.put("/ads/google/ad-schedule", body)) return int(result.get("slots", 0)) if isinstance(result, dict) else 0 - # ── Negative keyword lists ── - - def negative_keyword_lists( - self, *, connection_id: str, customer_id: str, workspace_id: str | None = None - ) -> builtins.list[GoogleSharedSet]: - return parse_list( - GoogleSharedSet, - unwrap( - self._http.get( - "/ads/google/negative-keywords", - _query(workspace_id, connection_id, customer_id), - ) - ), - ) - - def create_negative_keyword_list( - self, *, workspace_id: str, connection_id: str, customer_id: str, name: str - ) -> str: - """Needs ``publish`` as well as ``ads``.""" - body = _scope(workspace_id, connection_id, customer_id) - body["name"] = name - return _id(unwrap(self._http.post("/ads/google/negative-keywords", body))) - - def add_negative_keywords( - self, - *, - workspace_id: str, - connection_id: str, - customer_id: str, - shared_set_id: str, - keywords: Sequence[Mapping[str, Any]], - ) -> int: - """How many were added. Needs ``publish`` as well as ``ads``.""" - body = _scope(workspace_id, connection_id, customer_id) - body["sharedSetId"] = shared_set_id - body["keywords"] = [dict(keyword) for keyword in keywords] - result = unwrap(self._http.post("/ads/google/negative-keywords/keywords", body)) - return int(result.get("added", 0)) if isinstance(result, dict) else 0 - - def attach_negative_keyword_list( - self, - *, - workspace_id: str, - connection_id: str, - customer_id: str, - shared_set_id: str, - campaign_id: str, - ) -> None: - """Needs ``publish`` as well as ``ads``.""" - body = _scope(workspace_id, connection_id, customer_id) - body["sharedSetId"] = shared_set_id - body["campaignId"] = campaign_id - self._http.post("/ads/google/negative-keywords/attach", body) - - # ── Assets ── - - def assets( - self, *, connection_id: str, customer_id: str, workspace_id: str | None = None - ) -> GoogleAssetsResult: - """Sitelinks, callouts and snippets, with the links that put each under an ad.""" - data = unwrap( - self._http.get("/ads/google/assets", _query(workspace_id, connection_id, customer_id)) - ) - return GoogleAssetsResult.model_validate(data if isinstance(data, dict) else {}) - - def create_asset( - self, - *, - workspace_id: str, - connection_id: str, - customer_id: str, - spec: Mapping[str, Any], - ) -> str: - """``spec`` is a sitelink, callout or snippet. Needs ``publish`` as well as ``ads``.""" - body = _scope(workspace_id, connection_id, customer_id) - body["spec"] = dict(spec) - return _id(unwrap(self._http.post("/ads/google/assets", body))) - - def attach_asset( - self, - *, - workspace_id: str, - connection_id: str, - customer_id: str, - asset_id: str, - field_type: str, - campaign_id: str | None = None, - ) -> None: - """Attaches to the account when ``campaign_id`` is left out. Needs ``publish``.""" - body = _scope(workspace_id, connection_id, customer_id) - body["assetId"] = asset_id - body["fieldType"] = field_type - if campaign_id is not None: - body["campaignId"] = campaign_id - self._http.post("/ads/google/assets/attach", body) - - def delete_asset( - self, asset_id: str, *, workspace_id: str, connection_id: str, customer_id: str - ) -> None: - """Removes the links that put it under an ad; on Google the asset itself is permanent.""" - self._http.delete( - f"/ads/google/assets/{asset_id}", - json=_scope(workspace_id, connection_id, customer_id), - ) - - # ── Performance Max asset groups ── - - def asset_groups( - self, - *, - connection_id: str, - customer_id: str, - workspace_id: str | None = None, - campaign_id: str | None = None, - ) -> builtins.list[GoogleAssetGroup]: - return parse_list( - GoogleAssetGroup, - unwrap( - self._http.get( - "/ads/google/asset-groups", - _query(workspace_id, connection_id, customer_id, campaign_id=campaign_id), - ) - ), - ) - - def create_asset_group( - self, - *, - workspace_id: str, - connection_id: str, - customer_id: str, - campaign_id: str, - name: str, - final_urls: Sequence[str], - status: str | None = None, - ) -> str: - """Starts paused unless ``status`` says otherwise. Needs ``publish``.""" - body = _scope(workspace_id, connection_id, customer_id) - body["campaignId"] = campaign_id - body["name"] = name - body["finalUrls"] = list(final_urls) - if status is not None: - body["status"] = status - return _id(unwrap(self._http.post("/ads/google/asset-groups", body))) - - def update_asset_group( - self, - asset_group_id: str, - *, - workspace_id: str, - connection_id: str, - customer_id: str, - name: str | None = None, - status: str | None = None, - ) -> str: - """Needs ``publish`` as well as ``ads``.""" - body = _scope(workspace_id, connection_id, customer_id) - if name is not None: - body["name"] = name - if status is not None: - body["status"] = status - return _id( - unwrap( - self._http.request("PATCH", f"/ads/google/asset-groups/{asset_group_id}", json=body) - ) - ) - - def delete_asset_group( - self, asset_group_id: str, *, workspace_id: str, connection_id: str, customer_id: str - ) -> None: - """Needs ``publish`` as well as ``ads``.""" - self._http.delete( - f"/ads/google/asset-groups/{asset_group_id}", - json=_scope(workspace_id, connection_id, customer_id), - ) - # ── Local Services leads ── def local_services_leads( @@ -493,70 +179,6 @@ def upload_conversion_adjustments( result = unwrap(self._http.post("/ads/google/conversions/adjustments", body)) return int(result.get("uploaded", 0)) if isinstance(result, dict) else 0 - # ── Recommendations ── - - def recommendations( - self, - *, - connection_id: str, - customer_id: str, - types: Sequence[str] | None = None, - workspace_id: str | None = None, - ) -> builtins.list[GoogleRecommendation]: - """Google's own read on what the account should change next.""" - params = _query(workspace_id, connection_id, customer_id) - if types: - params["types"] = ",".join(types) - return parse_list( - GoogleRecommendation, - unwrap(self._http.get("/ads/google/recommendations", params)), - ) - - def optimization_score( - self, - *, - connection_id: str, - customer_id: str, - workspace_id: str | None = None, - ) -> GoogleOptimizationScore: - """The account's score and weight, and the score of each live campaign.""" - return GoogleOptimizationScore.model_validate( - unwrap( - self._http.get( - "/ads/google/optimization-score", - _query(workspace_id, connection_id, customer_id), - ) - ) - ) - - def apply_recommendations( - self, - *, - workspace_id: str, - connection_id: str, - customer_id: str, - ids: Sequence[str], - ) -> int: - """Changes what the live account serves or bids. Needs ``publish`` as well as ``ads``.""" - body = _scope(workspace_id, connection_id, customer_id) - body["ids"] = list(ids) - result = unwrap(self._http.post("/ads/google/recommendations/apply", body)) - return int(result.get("applied", 0)) if isinstance(result, dict) else 0 - - def dismiss_recommendations( - self, - *, - workspace_id: str, - connection_id: str, - customer_id: str, - ids: Sequence[str], - ) -> int: - """Hides each recommendation. Needs ``publish`` as well as ``ads``.""" - body = _scope(workspace_id, connection_id, customer_id) - body["ids"] = list(ids) - result = unwrap(self._http.post("/ads/google/recommendations/dismiss", body)) - return int(result.get("dismissed", 0)) if isinstance(result, dict) else 0 - # ── GAQL ── def query( diff --git a/tests/test_google_ads.py b/tests/test_google_ads.py index 061604e..6dd38ba 100644 --- a/tests/test_google_ads.py +++ b/tests/test_google_ads.py @@ -1,7 +1,5 @@ from __future__ import annotations -import json - import httpx import respx @@ -10,61 +8,6 @@ SCOPE = {"workspace_id": "ws_1", "connection_id": "conn_1", "customer_id": "1234567890"} -KEYWORD_FIXTURE = { - "id": "1234567890~keyword~77~99", - "adGroupId": "1234567890~adGroup~77", - "text": "running shoes", - "matchType": "EXACT", - "status": "ENABLED", - "cpcBidMinor": 180, - "negative": False, -} - - -@respx.mock -def test_keywords_name_the_connection_and_the_customer(client: Fopost) -> None: - route = respx.get(f"{BASE_URL}/ads/google/keywords").mock( - return_value=httpx.Response(200, json={"data": [KEYWORD_FIXTURE]}) - ) - keywords = client.ads.google.keywords( - connection_id="conn_1", customer_id="1234567890", ad_group_id="1234567890~adGroup~77" - ) - assert keywords[0].cpc_bid_minor == 180 - assert keywords[0].match_type == "EXACT" - params = route.calls.last.request.url.params - assert params["connection_id"] == "conn_1" - assert params["customer_id"] == "1234567890" - assert params["ad_group_id"] == "1234567890~adGroup~77" - - -@respx.mock -def test_create_keyword_sends_the_camel_case_body(client: Fopost) -> None: - route = respx.post(f"{BASE_URL}/ads/google/keywords").mock( - return_value=httpx.Response(201, json={"data": {"id": "1234567890~keyword~77~99"}}) - ) - created = client.ads.google.create_keyword( - **SCOPE, ad_group_id="1234567890~adGroup~77", text="running shoes", match_type="EXACT" - ) - assert created == "1234567890~keyword~77~99" - body = json.loads(route.calls.last.request.content) - assert body["adGroupId"] == "1234567890~adGroup~77" - assert body["matchType"] == "EXACT" - assert body["customerId"] == "1234567890" - - -@respx.mock -def test_delete_carries_the_scope_in_the_body(client: Fopost) -> None: - route = respx.delete(f"{BASE_URL}/ads/google/assets/1234567890~asset~4321").mock( - return_value=httpx.Response(204) - ) - client.ads.google.delete_asset("1234567890~asset~4321", **SCOPE) - body = json.loads(route.calls.last.request.content) - assert body == { - "workspaceId": "ws_1", - "connectionId": "conn_1", - "customerId": "1234567890", - } - @respx.mock def test_ad_schedule_is_replaced_with_put(client: Fopost) -> None: @@ -101,48 +44,3 @@ def test_authorize_google_has_its_own_route(client: Fopost) -> None: url = client.ads.authorize_google(workspace_id="ws_1") assert url == "https://accounts.google.com/o/x" assert route.called - - -@respx.mock -def test_recommendations_joins_the_types_filter(client: Fopost) -> None: - route = respx.get(f"{BASE_URL}/ads/google/recommendations").mock( - return_value=httpx.Response( - 200, - json={ - "data": [ - { - "id": "customers/1234567890/recommendations/ABC~1", - "type": "KEYWORD", - "campaignId": "1234567890~campaign~55", - "dismissed": False, - "impact": {"baseClicks": 10, "potentialClicks": 25}, - } - ] - }, - ) - ) - rows = client.ads.google.recommendations( - connection_id="conn_1", - customer_id="1234567890", - types=["KEYWORD", "TARGET_CPA_OPT_IN"], - ) - assert rows[0].type == "KEYWORD" - assert rows[0].impact is not None and rows[0].impact.potential_clicks == 25 - assert route.calls.last.request.url.params["types"] == "KEYWORD,TARGET_CPA_OPT_IN" - - -@respx.mock -def test_apply_recommendations_sends_the_ids(client: Fopost) -> None: - route = respx.post(f"{BASE_URL}/ads/google/recommendations/apply").mock( - return_value=httpx.Response(200, json={"data": {"applied": 1}}) - ) - applied = client.ads.google.apply_recommendations( - workspace_id="ws_1", - connection_id="conn_1", - customer_id="1234567890", - ids=["customers/1234567890/recommendations/ABC~1"], - ) - assert applied == 1 - assert json.loads(route.calls.last.request.content)["ids"] == [ - "customers/1234567890/recommendations/ABC~1" - ] From e6e0451aff82b30551029c3a2b249cd3b3a12058 Mon Sep 17 00:00:00 2001 From: Ali Hesari Date: Mon, 23 Nov 2026 23:18:31 +0100 Subject: [PATCH 3/3] docs(ads): note the removed ads methods in the README and changelog --- CHANGELOG.md | 14 ++++++++++++++ README.md | 26 ++++++++++++-------------- 2 files changed, 26 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5fac58a..b22d40e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -74,6 +74,20 @@ All notable changes to `fopost` are documented here. articles), the `Blog*` models and `BLOG_*` constants, `ArticlePublishedPayload`, and `article.published` from the webhook event names. The API no longer serves them; articles are ordinary posts. `client.blogs` is unchanged. +- **Breaking:** the ads campaign tree, creatives, product catalogs and the Ad Library: + `ads.account_tree`, create, get, update, delete and duplicate for campaigns, ad sets and + network ads, `ads.creatives`, `create_creative`, `get_creative`, `delete_creative`, every + catalog, product, feed, feed upload and product set method, `ads.library` and + `ads.ad_library`, with the models only they returned (`AdAccountTree`, `AdCampaign`, + `AdCampaignNode`, `AdSet`, `AdSetNode`, `NetworkAd`, `AdCreative`, `ProductCatalog`, + `ProductCatalogsResult`, `CatalogProduct`, `CatalogProductsPage`, `CatalogBatchResult`, + `ProductFeed`, `ProductFeedUpload`, `ProductSet`, `AdLibraryEntry`, `AdLibraryPage`). The + API no longer serves them. `ads.create`, `ads.bulk_set_status` and the `/v1/ads/{id}` + methods are unchanged. +- **Breaking:** from `client.ads.google`, keywords, keyword ideas and metrics, search terms, + negative keyword lists, assets, asset groups, recommendations and the optimization score, + with their `Google*` models. Bid strategies, the ad schedule, Local Services leads, + conversions and `query` remain. ## 0.4.0 - 2026-10-18 diff --git a/README.md b/README.md index 8c9467c..65f6ec6 100644 --- a/README.md +++ b/README.md @@ -336,9 +336,9 @@ except FopostError as err: | `contacts` | `list`, `get`, `create`, `update`, `delete`, `conversations`, `import_csv`, `list_fields`, `create_field`, `update_field`, `delete_field`, `conversation_analytics` | | `broadcasts` | `list`, `get`, `create`, `update`, `delete`, `send`, `cancel`, `recipients` | | `sequences` | `list`, `get`, `create`, `update`, `delete`, `enroll`, `unenroll`, `enrollments` | -| `ads` | `list`, `external`, `boostable`, `connections`, `sources`, `providers`, `authorize`, `delete_connection`, `boost`, `create`, `refresh`, `set_status`, `delete`, `audiences`, `create_audience`, `search_targeting`, `lead_forms`, `create_lead_form`, `leads`, `account_tree`, `create_campaign`, `get_campaign`, `update_campaign`, `delete_campaign`, `duplicate_campaign`, `create_ad_set`, `get_ad_set`, `update_ad_set`, `delete_ad_set`, `duplicate_ad_set`, `create_network_ad`, `get_network_ad`, `update_network_ad`, `delete_network_ad`, `duplicate_network_ad`, `bulk_set_status`, `creatives`, `create_creative`, `get_creative`, `delete_creative`, `get_audience`, `update_audience`, `delete_audience`, `add_audience_users`, `add_audience_companies`, `estimate_reach`, `insights`, `ad_insights`, `get_lead_form`, `archive_lead_form`, `leads_feed`, `lead_pages`, `subscribe_lead_page`, `unsubscribe_lead_page`, `goals`, `catalogs`, `create_catalog`, `get_catalog`, `update_catalog`, `delete_catalog`, `catalog_products`, `write_catalog_products`, `product_feeds`, `create_product_feed`, `delete_product_feed`, `feed_uploads`, `start_feed_upload`, `product_sets`, `create_product_set`, `update_product_set`, `delete_product_set`, `reach_frequency`, `create_reach_frequency`, `get_reach_frequency`, `reserve_reach_frequency`, `cancel_reach_frequency`, `library`, `partnership_creators`, `request_partnership`, `revoke_partnership`, `account_activity`, `labels`, `create_label`, `update_label`, `delete_label`, `apply_label`, `studies`, `create_study`, `get_study`, `delete_study`, `ios_campaign_limits`, `high_demand_periods`, `create_high_demand_period`, `delete_high_demand_period`, `value_rule_sets`, `create_value_rule_set`, `delete_value_rule_set`, `bid_pricing`, `supply_forecast`, `conversion_rules`, `create_conversion_rule`, `get_conversion_rule`, `update_conversion_rule`, `delete_conversion_rule`, `attach_conversion_rule`, `detach_conversion_rule`, `conversion_metrics`, `send_conversion_events`, `upload_conversions`, `send_conversions`, `conversion_batches`, `pixels`, `create_pixel`, `get_pixel`, `update_pixel`, `share_pixel`, `pixel_stats`, `event_match_quality`, `custom_conversions`, `create_custom_conversion`, `get_custom_conversion`, `update_custom_conversion`, `delete_custom_conversion` | +| `ads` | `list`, `external`, `boostable`, `connections`, `sources`, `providers`, `authorize`, `delete_connection`, `boost`, `create`, `refresh`, `set_status`, `delete`, `audiences`, `create_audience`, `search_targeting`, `lead_forms`, `create_lead_form`, `leads`, `bulk_set_status`, `get_audience`, `update_audience`, `delete_audience`, `add_audience_users`, `add_audience_companies`, `estimate_reach`, `insights`, `ad_insights`, `get_lead_form`, `archive_lead_form`, `leads_feed`, `lead_pages`, `subscribe_lead_page`, `unsubscribe_lead_page`, `goals`, `reach_frequency`, `create_reach_frequency`, `get_reach_frequency`, `reserve_reach_frequency`, `cancel_reach_frequency`, `partnership_creators`, `request_partnership`, `revoke_partnership`, `account_activity`, `labels`, `create_label`, `update_label`, `delete_label`, `apply_label`, `studies`, `create_study`, `get_study`, `delete_study`, `ios_campaign_limits`, `high_demand_periods`, `create_high_demand_period`, `delete_high_demand_period`, `value_rule_sets`, `create_value_rule_set`, `delete_value_rule_set`, `bid_pricing`, `supply_forecast`, `conversion_rules`, `create_conversion_rule`, `get_conversion_rule`, `update_conversion_rule`, `delete_conversion_rule`, `attach_conversion_rule`, `detach_conversion_rule`, `conversion_metrics`, `send_conversion_events`, `upload_conversions`, `send_conversions`, `conversion_batches`, `pixels`, `create_pixel`, `get_pixel`, `update_pixel`, `share_pixel`, `pixel_stats`, `event_match_quality`, `custom_conversions`, `create_custom_conversion`, `get_custom_conversion`, `update_custom_conversion`, `delete_custom_conversion` | | `knowledge` | `list`, `create`, `update`, `delete`, `sync`, `search` | -| `ads` | `list`, `external`, `boostable`, `connections`, `sources`, `providers`, `authorize`, `delete_connection`, `boost`, `create`, `refresh`, `set_status`, `delete`, `audiences`, `create_audience`, `search_targeting`, `lead_forms`, `create_lead_form`, `leads`, `account_tree`, `create_campaign`, `get_campaign`, `update_campaign`, `delete_campaign`, `duplicate_campaign`, `create_ad_set`, `get_ad_set`, `update_ad_set`, `delete_ad_set`, `duplicate_ad_set`, `create_network_ad`, `get_network_ad`, `update_network_ad`, `delete_network_ad`, `duplicate_network_ad`, `bulk_set_status`, `creatives`, `create_creative`, `get_creative`, `delete_creative`, `get_audience`, `update_audience`, `delete_audience`, `add_audience_users`, `add_audience_companies`, `estimate_reach`, `insights`, `ad_insights`, `get_lead_form`, `archive_lead_form`, `leads_feed`, `lead_pages`, `subscribe_lead_page`, `unsubscribe_lead_page`, `bid_pricing`, `supply_forecast`, `conversion_rules`, `create_conversion_rule`, `get_conversion_rule`, `update_conversion_rule`, `delete_conversion_rule`, `attach_conversion_rule`, `detach_conversion_rule`, `conversion_metrics`, `send_conversion_events`, `upload_conversions`, `send_conversions`, `conversion_batches`, `pixels`, `create_pixel`, `get_pixel`, `update_pixel`, `share_pixel`, `pixel_stats`, `event_match_quality`, `custom_conversions`, `create_custom_conversion`, `get_custom_conversion`, `update_custom_conversion`, `delete_custom_conversion` | +| `ads` | `list`, `external`, `boostable`, `connections`, `sources`, `providers`, `authorize`, `delete_connection`, `boost`, `create`, `refresh`, `set_status`, `delete`, `audiences`, `create_audience`, `search_targeting`, `lead_forms`, `create_lead_form`, `leads`, `bulk_set_status`, `get_audience`, `update_audience`, `delete_audience`, `add_audience_users`, `add_audience_companies`, `estimate_reach`, `insights`, `ad_insights`, `get_lead_form`, `archive_lead_form`, `leads_feed`, `lead_pages`, `subscribe_lead_page`, `unsubscribe_lead_page`, `bid_pricing`, `supply_forecast`, `conversion_rules`, `create_conversion_rule`, `get_conversion_rule`, `update_conversion_rule`, `delete_conversion_rule`, `attach_conversion_rule`, `detach_conversion_rule`, `conversion_metrics`, `send_conversion_events`, `upload_conversions`, `send_conversions`, `conversion_batches`, `pixels`, `create_pixel`, `get_pixel`, `update_pixel`, `share_pixel`, `pixel_stats`, `event_match_quality`, `custom_conversions`, `create_custom_conversion`, `get_custom_conversion`, `update_custom_conversion`, `delete_custom_conversion` | | `google_business` | `get_location`, `update_location`, `get_attributes`, `update_attributes`, `get_menus`, `replace_menus`, `get_services`, `replace_services`, `list_media`, `add_media`, `delete_media`, `list_place_actions`, `create_place_action`, `update_place_action`, `delete_place_action`, `get_verification_options`, `start_verification`, `complete_verification`, `get_performance`, `get_search_keywords`, `assign` | | `blogs` | `list_blogs`, `list_articles`, `get_article`, `create_article`, `update_article`, `delete_article`, `list_products`, `update_product` | | `validate` | `post`, `length`, `media`, `subreddit` | @@ -459,27 +459,25 @@ Questions or a problem: [fopost.com/contact](https://fopost.com/contact). ### Google Ads -Campaigns, ad groups, ads, audiences and insights are on `client.ads` and dispatch by -connection. What only Google has is under `client.ads.google`: +Ads, audiences and insights are on `client.ads` and dispatch by connection. What only +Google has is under `client.ads.google`: ```python -keywords = client.ads.google.keywords( +strategies = client.ads.google.bid_strategies( connection_id="c4d5e6f7-…", customer_id="1234567890", ) -client.ads.google.create_keyword( +client.ads.google.create_bid_strategy( workspace_id="7d2b8c11-…", connection_id="c4d5e6f7-…", customer_id="1234567890", - ad_group_id="1234567890~adGroup~77", - text="running shoes", - match_type="EXACT", + name="Target CPA", + type="TARGET_CPA", + target_minor=2500, ) ``` -Also `keyword_ideas`, `keyword_metrics`, `search_terms`, `bid_strategies`, -`ad_schedule` and `set_ad_schedule`, the negative keyword lists, `assets` and -`asset_groups`, `local_services_leads`, the conversion methods, and `query` for a raw -read-only GAQL SELECT. Changes need the `publish` scope as well as `ads`; `customer_id` -has to name an account the connection's grant reaches. +Also `ad_schedule` and `set_ad_schedule`, `local_services_leads`, the conversion methods, +and `query` for a raw read-only GAQL SELECT. Changes need the `publish` scope as well as +`ads`; `customer_id` has to name an account the connection's grant reaches.