资源名称

Google Ads API 中实体的唯一标识符称为资源名称,表示为格式可预测的字符串。如果您知道资源名称的组成部分,则可以使用许多 Service 对象上提供的辅助方法生成资源名称。

服务路径方法

所有旨在处理 API 中特定类型对象的读取或更改操作的服务都提供了辅助方法,以便轻松构建 resource_names。例如,为 Campaign 对象创建资源名称:

from google.ads.googleads.client import GoogleAdsClient

client = GoogleAdsClient.load_from_storage()
customer_id = "7892134783"
campaign_id = "1234567890"
campaign_service = client.get_service("CampaignService")
resource_name = campaign_service.campaign_path(customer_id, campaign_id)

从客户端库 10.0.0 版开始,每项服务还附带一个 parse_*_path 方法,用于将 resource_name 解构为其各个细分,例如:

from google.ads.googleads.client import GoogleAdsClient

client = GoogleAdsClient.load_from_storage()
resource_name = "customers/7892134783/campaigns/1234567890"
campaign_service = client.get_service('CampaignService')
segments = campaign_service.parse_campaign_path(resource_name)
customer_id = segments["customer_id"]
campaign_id = segments["campaign_id"]

复合资源名称

从客户端库 9.0.0 版开始,服务上的路径帮助程序会构建资源名称的复合片段。该方法接受复合 ID 的不同部分作为单独的参数:

from google.ads.google_ads.client import GoogleAdsClient

customer_id = "0987654321"
ad_group_id = "1234567890"
criterion_id = "74932"

client = GoogleAdsClient.load_from_storage()
ad_group_criterion_service = client.get_service("AdGroupCriterionService")

# An AdGroupCriterion resource name that uses the above IDs looks like this:
# "customers/0987654321/adGroupCriteria/1234567890~74932"
resource_name = ad_group_criterion_service.ad_group_criterion_path(
    customer_id, ad_group_id, criterion_id
)

9.0.0 之前的版本

在 9.0.0 版之前,服务的路径帮助程序不会构建资源名称的复合部分。这些片段需要由调用方提供。客户端库提供了一个小实用程序来帮助您实现此目的:

from google.ads.google_ads.client import GoogleAdsClient
from google.ads.google_ads.util import ResourceName

customer_id = "0987654321"
ad_group_id = "1234567890"
criterion_id = "74932"

client = GoogleAdsClient.load_from_storage()
ad_group_criterion_service = client.get_service("AdGroupCriterionService")

# An AdGroupCriterion resource name that uses the above IDs looks like this:
# "customers/0987654321/adGroupCriteria/1234567890~74932"
composite_id = ResourceName.format_composite(ad_group_id, criterion_id)
resource_name = ad_group_criterion_service.ad_group_criterion_path(
    customer_id, composite_id
)