defcreate_campaign(client:GoogleAdsClient,customer_id:str,budget_resource_name:str)->str:"""Creates a Dynamic Search Ad Campaign under the given customer ID.Args:client: an initialized GoogleAdsClient instance.customer_id: a client customer ID str.budget_resource_name: a resource_name str for a BudgetReturns:A resource_name str for the newly created Campaign."""# Retrieve a new campaign operation object.campaign_operation:CampaignOperation=client.get_type("CampaignOperation")campaign:Campaign=campaign_operation.createcampaign.name=f"Interplanetary Cruise #{uuid4()}"campaign.advertising_channel_type=(client.enums.AdvertisingChannelTypeEnum.SEARCH)# Recommendation: Set the campaign to PAUSED when creating it to prevent the# ads from immediately serving. Set to ENABLED once you've added targeting# and the ads are ready to serve.campaign.status=client.enums.CampaignStatusEnum.PAUSEDcampaign.manual_cpc.enhanced_cpc_enabled=Truecampaign.campaign_budget=budget_resource_name# Required: Enable the campaign for DSAs by setting the campaign's dynamic# search ads setting domain name and language.campaign.dynamic_search_ads_setting.domain_name="example.com"campaign.dynamic_search_ads_setting.language_code="en"# Declare whether or not this campaign serves political ads targeting the# EU. Valid values are:# CONTAINS_EU_POLITICAL_ADVERTISING# DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISINGcampaign.contains_eu_political_advertising=(client.enums.EuPoliticalAdvertisingStatusEnum.DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING)# Optional: Sets the start and end dates for the campaign, beginning one day# from now and ending a month from now.campaign.start_date=(datetime.now()+timedelta(days=1)).strftime("%Y%m%d")campaign.end_date=(datetime.now()+timedelta(days=30)).strftime("%Y%m%d")# Retrieve the campaign service.campaign_service:CampaignServiceClient=client.get_service("CampaignService")# Issues a mutate request to add campaign.response:MutateCampaignsResponse=campaign_service.mutate_campaigns(customer_id=customer_id,operations=[campaign_operation])resource_name:str=response.results[0].resource_nameprint(f'Created campaign with resource_name: "{resource_name}"')
defcreate_campaign(client,customer_id,budget_resource_name)campaign=client.resource.campaigndo|c|c.name="Interplanetary Cruise#{(Time.now.to_f*1000).to_i}"c.advertising_channel_type=:SEARCHc.status=:PAUSEDc.manual_cpc=client.resource.manual_cpcc.campaign_budget=budget_resource_namec.dynamic_search_ads_setting=client.resource.dynamic_search_ads_settingdo|s|s.domain_name="example.com"s.language_code="en"end# Declare whether or not this campaign serves political ads targeting the EU.# Valid values are CONTAINS_EU_POLITICAL_ADVERTISING and# DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING.c.contains_eu_political_advertising=:DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISINGc.start_date=DateTime.parse((Date.today+1).to_s).strftime('%Y%m%d')c.end_date=DateTime.parse(Date.today.next_year.to_s).strftime('%Y%m%d')endoperation=client.operation.create_resource.campaign(campaign)response=client.service.campaign.mutate_campaigns(customer_id:customer_id,operations:[operation],)puts("Created campaign with ID:#{response.results.first.resource_name}")response.results.first.resource_nameend
subcreate_campaign{my($api_client,$customer_id,$campaign_budget_resource_name)=@_;# Create a campaign.my$campaign=Google::Ads::GoogleAds::V21::Resources::Campaign->new({name=>"Interplanetary Cruise #".uniqid(),advertisingChannelType=>SEARCH,status=>Google::Ads::GoogleAds::V21::Enums::CampaignStatusEnum::PAUSED,manualCpc=>Google::Ads::GoogleAds::V21::Common::ManualCpc->new(),campaignBudget=>$campaign_budget_resource_name,# Enable the campaign for DSAs.dynamicSearchAdsSetting=>Google::Ads::GoogleAds::V21::Resources::DynamicSearchAdsSetting->new({domainName=>"example.com",languageCode=>"en"}),# Optional: Set the start and end dates for the campaign, beginning one day from# now and ending a month from now.startDate=>strftime("%Y%m%d",localtime(time+60*60*24)),endDate=>strftime("%Y%m%d",localtime(time+60*60*24*30)),# Declare whether or not this campaign serves political ads targeting the EU.# Valid values are CONTAINS_EU_POLITICAL_ADVERTISING and# DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING.containsEuPoliticalAdvertising=>DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING});# Create a campaign operation.my$campaign_operation=Google::Ads::GoogleAds::V21::Services::CampaignService::CampaignOperation->new({create=>$campaign});# Add the campaign.my$campaigns_response=$api_client->CampaignService()->mutate({customerId=>$customer_id,operations=>[$campaign_operation]});my$campaign_resource_name=$campaigns_response->{results}[0]{resourceName};printf"Created campaign '%s'.\n",$campaign_resource_name;return$campaign_resource_name;}
defcreate_ad_group(client:GoogleAdsClient,customer_id:str,campaign_resource_name:str)->str:"""Creates a Dynamic Search Ad Group under the given Campaign.Args:client: an initialized GoogleAdsClient instance.customer_id: a client customer ID str.campaign_resource_name: a resource_name str for a Campaign.Returns:A resource_name str for the newly created Ad Group."""# Retrieve a new ad group operation object.ad_group_operation:AdGroupOperation=client.get_type("AdGroupOperation")# Create an ad group.ad_group:AdGroup=ad_group_operation.create# Required: set the ad group's type to Dynamic Search Ads.ad_group.type_=client.enums.AdGroupTypeEnum.SEARCH_DYNAMIC_ADSad_group.name=f"Earth to Mars Cruises{uuid4()}"ad_group.campaign=campaign_resource_namead_group.status=client.enums.AdGroupStatusEnum.PAUSED# Recommended: set a tracking URL template for your ad group if you want to# use URL tracking software.ad_group.tracking_url_template=("http://tracker.example.com/traveltracker/{escapedlpurl}")# Optional: Set the ad group bid value.ad_group.cpc_bid_micros=10000000# Retrieve the ad group service.ad_group_service:AdGroupServiceClient=client.get_service("AdGroupService")# Issues a mutate request to add the ad group.response:MutateAdGroupsResponse=ad_group_service.mutate_ad_groups(customer_id=customer_id,operations=[ad_group_operation])resource_name:str=response.results[0].resource_nameprint(f'Created Ad Group with resource_name: "{resource_name}"')
defcreate_ad_group(client,customer_id,campaign_resource_name)ad_group=client.resource.ad_groupdo|ag|ag.type=:SEARCH_DYNAMIC_ADSag.name="Earth to Mars Cruises#{(Time.now.to_f*1000).to_i}"ag.campaign=campaign_resource_nameag.status=:PAUSEDag.tracking_url_template="http://tracker.example.com/traveltracker/{escapedlpurl}"ag.cpc_bid_micros=3_000_000endoperation=client.operation.create_resource.ad_group(ad_group)response=client.service.ad_group.mutate_ad_groups(customer_id:customer_id,operations:[operation],)puts("Created ad group with ID:#{response.results.first.resource_name}")response.results.first.resource_nameend
subcreate_ad_group{my($api_client,$customer_id,$campaign_resource_name)=@_;# Construct an ad group and set an optional CPC value.my$ad_group=Google::Ads::GoogleAds::V21::Resources::AdGroup->new({name=>"Earth to Mars Cruises #".uniqid(),campaign=>$campaign_resource_name,status=>Google::Ads::GoogleAds::V21::Enums::AdGroupStatusEnum::PAUSED,type=>SEARCH_DYNAMIC_ADS,trackingUrlTemplate=>"http://tracker.examples.com/traveltracker/{escapedlpurl}",cpcBidMicros=>3000000});# Create an ad group operation.my$ad_group_operation=Google::Ads::GoogleAds::V21::Services::AdGroupService::AdGroupOperation->new({create=>$ad_group});# Add the ad group.my$ad_groups_response=$api_client->AdGroupService()->mutate({customerId=>$customer_id,operations=>[$ad_group_operation]});my$ad_group_resource_name=$ad_groups_response->{results}[0]{resourceName};printf"Created ad group '%s'.\n",$ad_group_resource_name;return$ad_group_resource_name;}
This ad will have its headline, display URL, and final URL auto-generated at
serving time according to domain name-specific information provided by theDynamicSearchAdsSettingset at the campaign level.
defcreate_expanded_dsa(client:GoogleAdsClient,customer_id:str,ad_group_resource_name:str)->None:"""Creates a dynamic search ad under the given ad group.Args:client: an initialized GoogleAdsClient instance.customer_id: a client customer ID str.ad_group_resource_name: a resource_name str for an Ad Group."""# Retrieve a new ad group ad operation object.ad_group_ad_operation:AdGroupAdOperation=client.get_type("AdGroupAdOperation")# Create and expanded dynamic search ad. This ad will have its headline,# display URL and final URL auto-generated at serving time according to# domain name specific information provided by DynamicSearchAdSetting at# the campaign level.ad_group_ad:AdGroupAd=ad_group_ad_operation.create# Optional: set the ad status.ad_group_ad.status=client.enums.AdGroupAdStatusEnum.PAUSED# Set the ad description.ad_group_ad.ad.expanded_dynamic_search_ad.description="Buy tickets now!"ad_group_ad.ad_group=ad_group_resource_name# Retrieve the ad group ad service.ad_group_ad_service:AdGroupAdServiceClient=client.get_service("AdGroupAdService")# Submit the ad group ad operation to add the ad group ad.response:MutateAdGroupAdsResponse=(ad_group_ad_service.mutate_ad_group_ads(customer_id=customer_id,operations=[ad_group_ad_operation]))resource_name:str=response.results[0].resource_nameprint(f'Created Ad Group Ad with resource_name: "{resource_name}"')
defcreate_expanded_dsa(client,customer_id,ad_group_resource_name)ad_group_ad=client.resource.ad_group_addo|aga|aga.status=:PAUSEDaga.ad=client.resource.addo|ad|ad.expanded_dynamic_search_ad=client.resource.expanded_dynamic_search_ad_infodo|info|info.description="Buy tickets now!"endendaga.ad_group=ad_group_resource_nameendoperation=client.operation.create_resource.ad_group_ad(ad_group_ad)response=client.service.ad_group_ad.mutate_ad_group_ads(customer_id:customer_id,operations:[operation],)puts("Created ad group ad with ID:#{response.results.first.resource_name}")end
subcreate_expanded_dsa{my($api_client,$customer_id,$ad_group_resource_name)=@_;# Create an ad group ad.my$ad_group_ad=Google::Ads::GoogleAds::V21::Resources::AdGroupAd->new({adGroup=>$ad_group_resource_name,status=>Google::Ads::GoogleAds::V21::Enums::AdGroupAdStatusEnum::PAUSED,ad=>Google::Ads::GoogleAds::V21::Resources::Ad->new({expandedDynamicSearchAd=>Google::Ads::GoogleAds::V21::Common::ExpandedDynamicSearchAdInfo->new({description=>"Buy tickets now!"})})});# Create an ad group ad operation.my$ad_group_ad_operation=Google::Ads::GoogleAds::V21::Services::AdGroupAdService::AdGroupAdOperation->new({create=>$ad_group_ad});# Add the ad group ad.my$ad_group_ads_response=$api_client->AdGroupAdService()->mutate({customerId=>$customer_id,operations=>[$ad_group_ad_operation]});my$ad_group_ad_resource_name=$ad_group_ads_response->{results}[0]{resourceName};printf"Created ad group ad '%s'.\n",$ad_group_ad_resource_name;return$ad_group_ad_resource_name;}
Thefinal_urlsfield is computed by Google Ads when it creates the
DSA. As a result, you can't set this field when creating DSAs. To use URL
tracking software, you canspecifywhich additional
tracking parameters or redirects are needed using thetracking_url_templatefield. When specifying this
field, you must include one of the following parameters to allow Google Ads to
put in the resulting matched final URL:
Parameter
Explanation
{unescapedlpurl}
Unescaped landing page URL—if you want to add something to the end, for example:
{unescapedlpurl}?dsa=true
{escapedlpurl}
Escaped (URL encoded) landing page URL—if you want to redirect to a tracker, for example:
http://tracking.com/lp={escapedurl}
{lpurlpath}
Only the path and query params from the computed URL, for example:
http://tracking.com.com/track/{lpurlpath}
{lpurl}
Encodes?and=of landing page URL,
ends with search query. If found at the very beginning of thetracking_url_templatefield,
it will actually be replaced by the{unescapedurl}value, for example:
Finally, you'll want to set up some criteria to trigger serving of the DSAs.
This is done using the fieldwebpageofAdGroupCriterion. Thiswebpagefield is
set as aWebpageInfoobject which allows between
one and threeconditions.
TheseconditionsareWebpageConditionInfoinstances that let you specify exactly what to filter or search on within
the domain specified previously in the campaign settings. There are five items
you can filter on within a domain:
For example, you could create a web page criterion that targets everything
that is located in the/childrenbranch of a vacation site (URLcondition),
but only those pages with "Special Offer" in the title (PAGE_TITLEcondition).
Discovering site's categories
You can retrieve and filter the list ofDomainCategorys that Google thinks apply to
your site by selecting fields of thedomain_categoryresource in a GAQL query.
The following GAQL query retrieves the list of domain categories for a specific
site and a specific campaign, filtering on its ID:
You can also use theAdGroupCriterionServiceto set up
negative web page criteria. You could use this, for example, to exclude pages
with a particular title that you want to manage with another campaign or ad
group.
Other criteria
DSA campaigns and ad groups are not restricted to only web page criteria; you
can continue to use other criterion types to further refine and improve the
quality of your ads. You should be judicious in your use of additional criteria,
however, as adding too many can diminish the effectiveness of a DSA's
auto-targeting.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-09-03 UTC."],[[["\u003cp\u003eDynamic Search Ads (DSAs) are set up using the Google Ads API through campaign and ad group creation, followed by DSA creation and targeting.\u003c/p\u003e\n"],["\u003cp\u003eDSAs leverage auto-generated headlines and URLs based on your website content but allow customization for descriptions and tracking.\u003c/p\u003e\n"],["\u003cp\u003eTargeting is primarily achieved using webpage criteria like URL, category, page title, and content for precise ad delivery.\u003c/p\u003e\n"],["\u003cp\u003eNegative criteria can exclude specific website sections from DSA targeting, refining the audience reach.\u003c/p\u003e\n"],["\u003cp\u003eGoogle Ads provides website categorization data to inform DSA setup and targeting strategies through domain category information.\u003c/p\u003e\n"]]],[],null,[]]