Create Dynamic Search Ads

To set up Dynamic Search Ads (DSAs) with the Google Ads API, follow these steps:

  1. Create a campaign and specify its domain.
  2. Create an ad group for features related to DSAs.
  3. Create one or more DSAs.
  4. Specify one or more criteria for showing the DSAs in the campaign.

Create the campaign

To tell Google Ads that you're going to be using DSAs with your campaign, you first need to create a Campaign with the field advertising_channel_type set to AdvertisingChannelType.SEARCH. Also, specify a domain on which the DSAs will operate. This is done by setting the field dynamic_search_ads_setting of the Campaign using a DynamicSearchAdsSetting.

The following example creates a DSA campaign.


private static String addCampaign(
    GoogleAdsClient googleAdsClient, long customerId, String budgetResourceName) {
  // Creates the campaign.
  Campaign campaign =
          .setName("Interplanetary Cruise #" + getPrintableDateTime())
          // Enables the campaign for DSAs.
          .setStartDate(new DateTime().plusDays(1).toString("yyyyMMdd"))
          .setEndDate(new DateTime().plusDays(30).toString("yyyyMMdd"))

  // Creates the operation.
  CampaignOperation operation = CampaignOperation.newBuilder().setCreate(campaign).build();

  // Creates the campaign service client.
  try (CampaignServiceClient campaignServiceClient =
      googleAdsClient.getLatestVersion().createCampaignServiceClient()) {
    // Adds the campaign.
    MutateCampaignsResponse response =
            Long.toString(customerId), ImmutableList.of(operation));

    String campaignResourceName = response.getResults(0).getResourceName();
    // Displays the results.
    System.out.printf("Added campaign with resource name '%s'.%n", campaignResourceName);
    return campaignResourceName;


private static string AddCampaign(GoogleAdsClient client, long customerId,
    string budgetResourceName)
    // Get the CampaignService.
    CampaignServiceClient campaignService = client.GetService(Services.V17.CampaignService);

    // Create the campaign.
    Campaign campaign = new Campaign()
        Name = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString(),
        AdvertisingChannelType = AdvertisingChannelType.Search,
        Status = CampaignStatus.Paused,
        ManualCpc = new ManualCpc(),
        CampaignBudget = budgetResourceName,

        // Enable the campaign for DSAs.
        DynamicSearchAdsSetting = new DynamicSearchAdsSetting()
            DomainName = "",
            LanguageCode = "en"

        StartDate = DateTime.Now.AddDays(1).ToString("yyyyMMdd"),
        EndDate = DateTime.Now.AddDays(30).ToString("yyyyMMdd")

    // Create the operation.
    CampaignOperation operation = new CampaignOperation()
        Create = campaign

    // Add the campaign.
    MutateCampaignsResponse response =
            new CampaignOperation[] { operation });

    // Displays the result.
    string campaignResourceName = response.Results[0].ResourceName;
    Console.WriteLine($"Added campaign with resource name '{campaignResourceName}'.");
    return campaignResourceName;


private static function createCampaign(
    GoogleAdsClient $googleAdsClient,
    int $customerId,
    string $campaignBudgetResourceName
) {
    $campaign = new Campaign([
        'name' => 'Interplanetary Cruise #' . Helper::getPrintableDatetime(),
        'advertising_channel_type' => AdvertisingChannelType::SEARCH,
        'status' => CampaignStatus::PAUSED,
        'manual_cpc' => new ManualCpc(),
        'campaign_budget' => $campaignBudgetResourceName,
        // Enables the campaign for DSAs.
        'dynamic_search_ads_setting' => new DynamicSearchAdsSetting([
            'domain_name' => '',
            'language_code' => 'en'
        // Optional: Sets the start and end dates for the campaign, beginning one day from
        // now and ending a month from now.
        'start_date' => date('Ymd', strtotime('+1 day')),
        'end_date' => date('Ymd', strtotime('+1 month'))

    // Creates a campaign operation.
    $campaignOperation = new CampaignOperation();

    // Issues a mutate request to add campaigns.
    $campaignServiceClient = $googleAdsClient->getCampaignServiceClient();
    /** @var MutateCampaignsResponse $campaignResponse */
    $campaignResponse = $campaignServiceClient->mutateCampaigns(
        MutateCampaignsRequest::build($customerId, [$campaignOperation])

    $campaignResourceName = $campaignResponse->getResults()[0]->getResourceName();
    printf("Added campaign named '%s'.%s", $campaignResourceName, PHP_EOL);

    return $campaignResourceName;


def create_campaign(client, customer_id, budget_resource_name):
    """Creates a Dynamic Search Ad Campaign under the given customer ID.

        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID str.
        budget_resource_name: a resource_name str for a Budget

        A resource_name str for the newly created Campaign.
    # Retrieve a new campaign operation object.
    campaign_operation = client.get_type("CampaignOperation")
    campaign = campaign_operation.create = f"Interplanetary Cruise #{uuid4()}"
    campaign.advertising_channel_type = (
    # 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.PAUSED
    campaign.manual_cpc.enhanced_cpc_enabled = True
    campaign.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 = ""
    campaign.dynamic_search_ads_setting.language_code = "en"
    # Optional: Sets the start and end dates for the campaign, beginning one day
    # from now and ending a month from now.
    campaign.start_date = ( + timedelta(days=1)).strftime(
    campaign.end_date = ( + timedelta(days=30)).strftime("%Y%m%d")

    # Retrieve the campaign service.
    campaign_service = client.get_service("CampaignService")

    # Issues a mutate request to add campaign.
    response = campaign_service.mutate_campaigns(
        customer_id=customer_id, operations=[campaign_operation]
    resource_name = response.results[0].resource_name

    print(f'Created campaign with resource_name: "{resource_name}"')


def create_campaign(client, customer_id, budget_resource_name)
  campaign = client.resource.campaign do |c| = "Interplanetary Cruise #{( * 1000).to_i}"

    c.advertising_channel_type = :SEARCH
    c.status = :PAUSED
    c.manual_cpc = client.resource.manual_cpc
    c.campaign_budget = budget_resource_name

    c.dynamic_search_ads_setting = client.resource.dynamic_search_ads_setting do |s|
      s.domain_name =  ""
      s.language_code =  "en"

    c.start_date = DateTime.parse(( + 1).to_s).strftime('%Y%m%d')
    c.end_date = DateTime.parse('%Y%m%d')

  operation = 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}")


sub create_campaign {
  my ($api_client, $customer_id, $campaign_budget_resource_name) = @_;

  # Create a campaign.
  my $campaign = Google::Ads::GoogleAds::V17::Resources::Campaign->new({
      name                   => "Interplanetary Cruise #" . uniqid(),
      advertisingChannelType => SEARCH,
      status => Google::Ads::GoogleAds::V17::Enums::CampaignStatusEnum::PAUSED,
      manualCpc      => Google::Ads::GoogleAds::V17::Common::ManualCpc->new(),
      campaignBudget => $campaign_budget_resource_name,
      # Enable the campaign for DSAs.
      dynamicSearchAdsSetting =>
          domainName   => "",
          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)),

  # Create a campaign operation.
  my $campaign_operation =
    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;

Create the ad group

To use DSA features, you need to create an AdGroup with the field type set to SEARCH_DYNAMIC_ADS. This ad group type enforces the following restrictions:

  • This ad group type can be added only to search campaigns.
  • There should be a valid DynamicSearchAdsSetting set at the campaign level
  • for the ad group to be added. An AdGroupError.CANNOT_ADD_ADGROUP_OF_TYPE_DSA_TO_CAMPAIGN_WITHOUT_DSA_SETTING error will be thrown if this setting is missing.
  • No positive keywords are allowed in this ad group type. Audience, dynamic ad targets and negative keywords are allowed.
  • As with all ad groups, the field type cannot be changed after construction.
  • Only ad formats related to DSAs are allowed in this ad group.

The code example below shows how to create a SEARCH_DYNAMIC_ADS ad group.


private static String addAdGroup(
    GoogleAdsClient googleAdsClient, long customerId, String campaignResourceName) {
  // Creates the ad group.
  AdGroup adGroup =
          .setName("Earth to Mars Cruises #" + getPrintableDateTime())

  // Creates the operation.
  AdGroupOperation operation = AdGroupOperation.newBuilder().setCreate(adGroup).build();

  // Creates the ad group service client.
  try (AdGroupServiceClient adGroupServiceClient =
      googleAdsClient.getLatestVersion().createAdGroupServiceClient()) {
    MutateAdGroupsResponse response =
            Long.toString(customerId), ImmutableList.of(operation));
    String adGroupResourceName = response.getResults(0).getResourceName();
    // Displays the results.
    System.out.printf("Added ad group with resource name '%s'.%n", adGroupResourceName);
    return adGroupResourceName;


private static string AddAdGroup(GoogleAdsClient client, long customerId,
    string campaignResourceName)
    // Get the AdGroupService.
    AdGroupServiceClient adGroupService = client.GetService(Services.V17.AdGroupService);

    // Create the ad group.
    AdGroup adGroup = new AdGroup()
        Name = "Earth to Mars Cruises #" + ExampleUtilities.GetRandomString(),
        Campaign = campaignResourceName,
        Type = AdGroupType.SearchDynamicAds,
        Status = AdGroupStatus.Paused,
        TrackingUrlTemplate = "{escapedlpurl}",
        CpcBidMicros = 50_000

    // Create the operation.
    AdGroupOperation operation = new AdGroupOperation()
        Create = adGroup

    // Add the ad group.
    MutateAdGroupsResponse response =
            new AdGroupOperation[] { operation });

    // Display the results.
    string adGroupResourceName = response.Results[0].ResourceName;
    Console.WriteLine($"Added ad group with resource name '{adGroupResourceName}'.");

    return adGroupResourceName;


private static function createAdGroup(
    GoogleAdsClient $googleAdsClient,
    int $customerId,
    string $campaignResourceName
) {
    // Constructs an ad group and sets an optional CPC value.
    $adGroup = new AdGroup([
        'name' => 'Earth to Mars Cruises #' . Helper::getPrintableDatetime(),
        'campaign' => $campaignResourceName,
        'status' => AdGroupStatus::PAUSED,
        'type' => AdGroupType::SEARCH_DYNAMIC_ADS,
        'tracking_url_template' => '{escapedlpurl}',
        'cpc_bid_micros' => 10000000

    // Creates an ad group operation.
    $adGroupOperation = new AdGroupOperation();

    // Issues a mutate request to add the ad groups.
    $adGroupServiceClient = $googleAdsClient->getAdGroupServiceClient();
    /** @var MutateAdGroupsResponse $adGroupResponse */
    $adGroupResponse = $adGroupServiceClient->mutateAdGroups(
        MutateAdGroupsRequest::build($customerId, [$adGroupOperation])

    $adGroupResourceName = $adGroupResponse->getResults()[0]->getResourceName();
    printf("Added ad group named '%s'.%s", $adGroupResourceName, PHP_EOL);

    return $adGroupResourceName;


def create_ad_group(client, customer_id, campaign_resource_name):
    """Creates a Dynamic Search Ad Group under the given Campaign.

        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID str.
        campaign_resource_name: a resource_name str for a Campaign.

        A resource_name str for the newly created Ad Group.
    # Retrieve a new ad group operation object.
    ad_group_operation = client.get_type("AdGroupOperation")
    # Create an ad group.
    ad_group = ad_group_operation.create
    # Required: set the ad group's type to Dynamic Search Ads.
    ad_group.type_ = client.enums.AdGroupTypeEnum.SEARCH_DYNAMIC_ADS = f"Earth to Mars Cruises {uuid4()}"
    ad_group.campaign = campaign_resource_name
    ad_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 = (
    # Optional: Set the ad group bid value.
    ad_group.cpc_bid_micros = 10000000

    # Retrieve the ad group service.
    ad_group_service = client.get_service("AdGroupService")

    # Issues a mutate request to add the ad group.
    response = ad_group_service.mutate_ad_groups(
        customer_id=customer_id, operations=[ad_group_operation]
    resource_name = response.results[0].resource_name

    print(f'Created Ad Group with resource_name: "{resource_name}"')


def create_ad_group(client, customer_id, campaign_resource_name)
  ad_group = client.resource.ad_group do |ag|
    ag.type = :SEARCH_DYNAMIC_ADS = "Earth to Mars Cruises #{( * 1000).to_i}"

    ag.campaign =  campaign_resource_name

    ag.status = :PAUSED
    ag.tracking_url_template = "{escapedlpurl}"

    ag.cpc_bid_micros = 3_000_000

  operation = 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}")


sub create_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::V17::Resources::AdGroup->new({
    name     => "Earth to Mars Cruises #" . uniqid(),
    campaign => $campaign_resource_name,
    status   => Google::Ads::GoogleAds::V17::Enums::AdGroupStatusEnum::PAUSED,
    type     => SEARCH_DYNAMIC_ADS,
    trackingUrlTemplate =>
    cpcBidMicros => 3000000

  # Create an ad group operation.
  my $ad_group_operation =
    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;

Create the DSA

To create the actual DSA, you need to use an ExpandedDynamicSearchAdInfo object and set its following fields:

  • Required: description
  • Optional: description2

This ad will have its headline, display URL, and final URL auto-generated at serving time according to domain name-specific information provided by the DynamicSearchAdsSetting set at the campaign level.


private static void addExpandedDSA(
    GoogleAdsClient googleAdsClient, long customerId, String adGroupResourceName) {
  // Creates an ad group ad.
  AdGroupAd adGroupAd =
          // Sets the ad as an expanded dynamic search ad
                          .setDescription("Buy tickets now!")

  // Creates the operation.
  AdGroupAdOperation operation = AdGroupAdOperation.newBuilder().setCreate(adGroupAd).build();

  // Creates the ad group ad service client.
  try (AdGroupAdServiceClient adGroupAdServiceClient =
      googleAdsClient.getLatestVersion().createAdGroupAdServiceClient()) {
    // Adds the dynamic search ad.
    MutateAdGroupAdsResponse response =
            Long.toString(customerId), ImmutableList.of(operation));
    // Displays the response.
        "Added ad group ad with resource name '%s'.%n", response.getResults(0).getResourceName());


private static void AddExpandedDSA(GoogleAdsClient client, long customerId,
    string adGroupResourceName)
    // Get the AdGroupAdService.
    AdGroupAdServiceClient adGroupAdService =

    // Create an ad group ad.
    AdGroupAd adGroupAd = new AdGroupAd()
        AdGroup = adGroupResourceName,
        Status = AdGroupAdStatus.Paused,

        // Set the ad as an expanded dynamic search ad.
        Ad = new Ad()
            ExpandedDynamicSearchAd = new ExpandedDynamicSearchAdInfo()
                Description = "Buy tickets now!"

    // Create the operation.
    AdGroupAdOperation operation = new AdGroupAdOperation()
        Create = adGroupAd

    // Add the dynamic search ad.
    MutateAdGroupAdsResponse response = adGroupAdService.MutateAdGroupAds(
        customerId.ToString(), new AdGroupAdOperation[] { operation });

    // Display the response.
    Console.WriteLine($"Added ad group ad with resource name " +


private static function createExpandedDSA(
    GoogleAdsClient $googleAdsClient,
    int $customerId,
    string $adGroupResourceName
) {
    $adGroupAd = new AdGroupAd([
        'ad_group' => $adGroupResourceName,
        'status' => AdGroupAdStatus::PAUSED,
        'ad' => new Ad([
            'expanded_dynamic_search_ad' => new ExpandedDynamicSearchAdInfo([
                'description' => 'Buy tickets now!'

    $adGroupAdOperation = new AdGroupAdOperation();

    // Issues a mutate request to add the ad group ads.
    $adGroupAdServiceClient = $googleAdsClient->getAdGroupAdServiceClient();
    /** @var MutateAdGroupAdsResponse $adGroupAdResponse */
    $adGroupAdResponse = $adGroupAdServiceClient->mutateAdGroupAds(
        MutateAdGroupAdsRequest::build($customerId, [$adGroupAdOperation])

    $adGroupAdResourceName = $adGroupAdResponse->getResults()[0]->getResourceName();
    printf("Added ad group ad named '%s'.%s", $adGroupAdResourceName, PHP_EOL);

    return $adGroupAdResourceName;


def create_expanded_dsa(client, customer_id, ad_group_resource_name):
    """Creates a dynamic search ad under the given ad group.

        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 = 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 = ad_group_ad_operation.create
    # Optional: set the ad status.
    ad_group_ad.status = client.enums.AdGroupAdStatusEnum.PAUSED
    # Set the ad description. = "Buy tickets now!"
    ad_group_ad.ad_group = ad_group_resource_name

    # Retrieve the ad group ad service.
    ad_group_ad_service = client.get_service("AdGroupAdService")

    # Submit the ad group ad operation to add the ad group ad.
    response = ad_group_ad_service.mutate_ad_group_ads(
        customer_id=customer_id, operations=[ad_group_ad_operation]
    resource_name = response.results[0].resource_name

    print(f'Created Ad Group Ad with resource_name: "{resource_name}"')


def create_expanded_dsa(client, customer_id, ad_group_resource_name)
  ad_group_ad = client.resource.ad_group_ad do |aga|
    aga.status = :PAUSED = do |ad|
      ad.expanded_dynamic_search_ad = client.resource.expanded_dynamic_search_ad_info do |info|
        info.description = "Buy tickets now!"

    aga.ad_group = ad_group_resource_name

  operation = 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}")


sub create_expanded_dsa {
  my ($api_client, $customer_id, $ad_group_resource_name) = @_;

  # Create an ad group ad.
  my $ad_group_ad = Google::Ads::GoogleAds::V17::Resources::AdGroupAd->new({
      adGroup => $ad_group_resource_name,
      status => Google::Ads::GoogleAds::V17::Enums::AdGroupAdStatusEnum::PAUSED,
      ad     => Google::Ads::GoogleAds::V17::Resources::Ad->new({
          expandedDynamicSearchAd =>
              description => "Buy tickets now!"

  # Create an ad group ad operation.
  my $ad_group_ad_operation =
    ->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 =

  printf "Created ad group ad '%s'.\n", $ad_group_ad_resource_name;

  return $ad_group_ad_resource_name;

The final_urls field 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 can specify which additional tracking parameters or redirects are needed using the tracking_url_template field. 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

Unescaped landing page URL—if you want to add something to the end, for example:



Escaped (URL encoded) landing page URL—if you want to redirect to a tracker, for example:{escapedurl}


Only the path and query params from the computed URL, for example:{lpurlpath}


Encodes ? and = of landing page URL, ends with search query. If found at the very beginning of the tracking_url_template field, it will actually be replaced by the {unescapedurl} value, for example:{lpurl}

For example:



Specify criteria for the DSA

Finally, you'll want to set up some criteria to trigger serving of the DSAs. This is done using the field webpage of AdGroupCriterion. This webpage field is set as a WebpageInfo object which allows between one and three conditions.

These conditions are WebpageConditionInfo instances 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:

WebpageConditionOperand Description
URL A string matching a partial URL of a page.
CATEGORY A string with a category to match against precisely.
PAGE_TITLE A string matching a partial page title.
PAGE_CONTENT A string matching some content within any given indexed page.
CUSTOM_LABEL A string matching a webpage custom label targeting condition. See Target page feed URLs using custom labels.

For example, you could create a webpage criterion that targets everything that is located in the /children branch of a vacation site (URL condition), but only those pages with "Special Offer" in the title (PAGE_TITLE condition).

Discovering site's categories

You can retrieve and filter the list of DomainCategorys that Google thinks apply to your site by selecting fields of the domain_category resource 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:

FROM domain_category
WHERE domain_category.domain = ''
  AND = campaign_id

Excluding site's parts

You can also use the AdGroupCriterionService to set up negative webpage 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 webpage 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.