Add Dynamic Search Ads

Java

// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.ads.googleads.examples.advancedoperations;

import static com.google.ads.googleads.examples.utils.CodeSampleHelper.getPrintableDateTime;

import com.beust.jcommander.Parameter;
import com.google.ads.googleads.examples.utils.ArgumentNames;
import com.google.ads.googleads.examples.utils.CodeSampleParams;
import com.google.ads.googleads.lib.GoogleAdsClient;
import com.google.ads.googleads.v9.common.ExpandedDynamicSearchAdInfo;
import com.google.ads.googleads.v9.common.ManualCpc;
import com.google.ads.googleads.v9.common.WebpageConditionInfo;
import com.google.ads.googleads.v9.common.WebpageInfo;
import com.google.ads.googleads.v9.enums.AdGroupAdStatusEnum.AdGroupAdStatus;
import com.google.ads.googleads.v9.enums.AdGroupCriterionStatusEnum.AdGroupCriterionStatus;
import com.google.ads.googleads.v9.enums.AdGroupStatusEnum.AdGroupStatus;
import com.google.ads.googleads.v9.enums.AdGroupTypeEnum.AdGroupType;
import com.google.ads.googleads.v9.enums.AdvertisingChannelTypeEnum.AdvertisingChannelType;
import com.google.ads.googleads.v9.enums.BudgetDeliveryMethodEnum.BudgetDeliveryMethod;
import com.google.ads.googleads.v9.enums.CampaignStatusEnum.CampaignStatus;
import com.google.ads.googleads.v9.enums.WebpageConditionOperandEnum.WebpageConditionOperand;
import com.google.ads.googleads.v9.errors.GoogleAdsError;
import com.google.ads.googleads.v9.errors.GoogleAdsException;
import com.google.ads.googleads.v9.resources.Ad;
import com.google.ads.googleads.v9.resources.AdGroup;
import com.google.ads.googleads.v9.resources.AdGroupAd;
import com.google.ads.googleads.v9.resources.AdGroupCriterion;
import com.google.ads.googleads.v9.resources.Campaign;
import com.google.ads.googleads.v9.resources.Campaign.DynamicSearchAdsSetting;
import com.google.ads.googleads.v9.resources.CampaignBudget;
import com.google.ads.googleads.v9.services.AdGroupAdOperation;
import com.google.ads.googleads.v9.services.AdGroupAdServiceClient;
import com.google.ads.googleads.v9.services.AdGroupCriterionOperation;
import com.google.ads.googleads.v9.services.AdGroupCriterionServiceClient;
import com.google.ads.googleads.v9.services.AdGroupOperation;
import com.google.ads.googleads.v9.services.AdGroupServiceClient;
import com.google.ads.googleads.v9.services.CampaignBudgetOperation;
import com.google.ads.googleads.v9.services.CampaignBudgetServiceClient;
import com.google.ads.googleads.v9.services.CampaignOperation;
import com.google.ads.googleads.v9.services.CampaignServiceClient;
import com.google.ads.googleads.v9.services.MutateAdGroupAdsResponse;
import com.google.ads.googleads.v9.services.MutateAdGroupCriteriaResponse;
import com.google.ads.googleads.v9.services.MutateAdGroupsResponse;
import com.google.ads.googleads.v9.services.MutateCampaignBudgetsResponse;
import com.google.ads.googleads.v9.services.MutateCampaignsResponse;
import com.google.common.collect.ImmutableList;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.joda.time.DateTime;

/** Adds a new dynamic search ad (DSA) and webpage targeting criteria for the DSA. */
public class AddDynamicSearchAds {
  private static class AddDynamicSearchAdsParams extends CodeSampleParams {

    @Parameter(names = ArgumentNames.CUSTOMER_ID, required = true)
    Long customerId;
  }

  public static void main(String[] args) {
    AddDynamicSearchAdsParams params = new AddDynamicSearchAdsParams();
    if (!params.parseArguments(args)) {
      // Either pass the required parameters for this example on the command line, or insert them
      // into the code here. See the parameter class definition above for descriptions.
      params.customerId = Long.parseLong("INSERT_CUSTOMER_ID_HERE");
    }

    GoogleAdsClient googleAdsClient = null;
    try {
      googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
    } catch (FileNotFoundException fnfe) {
      System.err.printf(
          "Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe);
      System.exit(1);
    } catch (IOException ioe) {
      System.err.printf("Failed to create GoogleAdsClient. Exception %s%n", ioe);
      System.exit(1);
    }

    try {
      new AddDynamicSearchAds().runExample(googleAdsClient, params.customerId);
    } catch (GoogleAdsException gae) {
      // GoogleAdsException is the base class for most exceptions thrown by an API request.
      // Instances of this exception have a message and a GoogleAdsFailure that contains a
      // collection of GoogleAdsErrors that indicate the underlying causes of the
      // GoogleAdsException.
      System.err.printf(
          "Request ID %s failed due to GoogleAdsException. Underlying errors:%n",
          gae.getRequestId());
      int i = 0;
      for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) {
        System.err.printf("  Error %d: %s%n", i++, googleAdsError);
      }
      System.exit(1);
    }
  }

  /**
   * Runs the example.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @throws GoogleAdsException if an API request failed with one or more service errors.
   */
  private static void runExample(GoogleAdsClient googleAdsClient, long customerId) {
    String budgetResourceName = addCampaignBudget(googleAdsClient, customerId);
    String campaignResourceName = addCampaign(googleAdsClient, customerId, budgetResourceName);
    String adGroupResourceName = addAdGroup(googleAdsClient, customerId, campaignResourceName);
    addExpandedDSA(googleAdsClient, customerId, adGroupResourceName);
    addWebPageCriteria(googleAdsClient, customerId, adGroupResourceName);
  }

  /**
   * Adds a campaign budget.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @return the campaign budget resource name.
   */
  private static String addCampaignBudget(GoogleAdsClient googleAdsClient, long customerId) {
    // Creates the budget.
    CampaignBudget campaignBudget =
        CampaignBudget.newBuilder()
            .setName("Interplanetary Cruise Budget #" + getPrintableDateTime())
            .setAmountMicros(3_000_000)
            .setDeliveryMethod(BudgetDeliveryMethod.STANDARD)
            .build();

    // Creates the operation.
    CampaignBudgetOperation operation =
        CampaignBudgetOperation.newBuilder().setCreate(campaignBudget).build();

    // Creates the campaign budget service client.
    try (CampaignBudgetServiceClient campaignBudgetServiceClient =
        googleAdsClient.getLatestVersion().createCampaignBudgetServiceClient()) {
      // Adds the campaign budget.
      MutateCampaignBudgetsResponse response =
          campaignBudgetServiceClient.mutateCampaignBudgets(
              Long.toString(customerId), ImmutableList.of(operation));
      // Displays the result.
      String budgetResourceName = response.getResults(0).getResourceName();
      System.out.printf("Added budget with resource name '%s'.%n", budgetResourceName);
      return budgetResourceName;
    }
  }

  /**
   * Adds a campaign.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @param budgetResourceName the campaign budget resource name.
   * @return the campaign resource name.
   */
  private static String addCampaign(
      GoogleAdsClient googleAdsClient, long customerId, String budgetResourceName) {
    // Creates the campaign.
    Campaign campaign =
        Campaign.newBuilder()
            .setName("Interplanetary Cruise #" + getPrintableDateTime())
            .setAdvertisingChannelType(AdvertisingChannelType.SEARCH)
            .setStatus(CampaignStatus.PAUSED)
            .setManualCpc(ManualCpc.newBuilder().build())
            .setCampaignBudget(budgetResourceName)
            // Enables the campaign for DSAs.
            .setDynamicSearchAdsSetting(
                DynamicSearchAdsSetting.newBuilder()
                    .setDomainName("example.com")
                    .setLanguageCode("en")
                    .build())
            .setStartDate(new DateTime().plusDays(1).toString("yyyyMMdd"))
            .setEndDate(new DateTime().plusDays(30).toString("yyyyMMdd"))
            .build();

    // 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 =
          campaignServiceClient.mutateCampaigns(
              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;
    }
  }

  /**
   * Adds an ad group.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @param campaignResourceName the campaign resource name.
   * @return the ad group resource name.
   */
  private static String addAdGroup(
      GoogleAdsClient googleAdsClient, long customerId, String campaignResourceName) {
    // Creates the ad group.
    AdGroup adGroup =
        AdGroup.newBuilder()
            .setName("Earth to Mars Cruises #" + getPrintableDateTime())
            .setCampaign(campaignResourceName)
            .setType(AdGroupType.SEARCH_DYNAMIC_ADS)
            .setStatus(AdGroupStatus.PAUSED)
            .setTrackingUrlTemplate("http://tracker.examples.com/traveltracker/{escapedlpurl}")
            .setCpcBidMicros(50_000)
            .build();

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

    // Creates the ad group service client.
    try (AdGroupServiceClient adGroupServiceClient =
        googleAdsClient.getLatestVersion().createAdGroupServiceClient()) {
      MutateAdGroupsResponse response =
          adGroupServiceClient.mutateAdGroups(
              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;
    }
  }

  /**
   * Adds an expanded dynamic search ad.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @param adGroupResourceName the ad group resource name.
   */
  private static void addExpandedDSA(
      GoogleAdsClient googleAdsClient, long customerId, String adGroupResourceName) {
    // Creates an ad group ad.
    AdGroupAd adGroupAd =
        AdGroupAd.newBuilder()
            .setAdGroup(adGroupResourceName)
            .setStatus(AdGroupAdStatus.PAUSED)
            // Sets the ad as an expanded dynamic search ad
            .setAd(
                Ad.newBuilder()
                    .setExpandedDynamicSearchAd(
                        ExpandedDynamicSearchAdInfo.newBuilder()
                            .setDescription("Buy tickets now!")
                            .build())
                    .build())
            .build();

    // 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 =
          adGroupAdServiceClient.mutateAdGroupAds(
              Long.toString(customerId), ImmutableList.of(operation));
      // Displays the response.
      System.out.printf(
          "Added ad group ad with resource name '%s'.%n", response.getResults(0).getResourceName());
    }
  }

  /**
   * Adds webpage targeting criteria for the DSA.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @param adGroupResourceName the ad group resource name.
   */
  private static void addWebPageCriteria(
      GoogleAdsClient googleAdsClient, long customerId, String adGroupResourceName) {
    // Creates the criteria.
    AdGroupCriterion adGroupCriterion =
        AdGroupCriterion.newBuilder()
            .setAdGroup(adGroupResourceName)
            .setCpcBidMicros(1_000_000)
            .setStatus(AdGroupCriterionStatus.PAUSED)
            // Sets the webpage targeting criteria.
            .setWebpage(
                WebpageInfo.newBuilder()
                    .setCriterionName("Special Offers")
                    // Adds the url targeting criteria.
                    .addConditions(
                        WebpageConditionInfo.newBuilder()
                            .setOperand(WebpageConditionOperand.URL)
                            .setArgument("/specialoffers")
                            .build())
                    // Adds the page title criteria.
                    // The list of webpage targeting conditions are
                    // and-ed together when evaluated for targeting.
                    .addConditions(
                        WebpageConditionInfo.newBuilder()
                            .setOperand(WebpageConditionOperand.PAGE_TITLE)
                            .setArgument("Special Offer")
                            .build())
                    .build())
            .build();

    // Creates the operation.
    AdGroupCriterionOperation operation =
        AdGroupCriterionOperation.newBuilder().setCreate(adGroupCriterion).build();

    // Creates the service client.
    try (AdGroupCriterionServiceClient adGroupCriterionServiceClient =
        googleAdsClient.getLatestVersion().createAdGroupCriterionServiceClient()) {
      // Adds the criteria.
      MutateAdGroupCriteriaResponse response =
          adGroupCriterionServiceClient.mutateAdGroupCriteria(
              Long.toString(customerId), ImmutableList.of(operation));
      // Displays the results.
      System.out.printf(
          "Added ad group criterion with resource name '%s'.%n",
          response.getResults(0).getResourceName());
    }
  }
}

      

C#

// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using CommandLine;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V9.Common;
using Google.Ads.GoogleAds.V9.Errors;
using Google.Ads.GoogleAds.V9.Resources;
using Google.Ads.GoogleAds.V9.Services;
using System;
using System.Collections.Generic;
using static Google.Ads.GoogleAds.V9.Enums.AdGroupAdStatusEnum.Types;
using static Google.Ads.GoogleAds.V9.Enums.AdGroupCriterionStatusEnum.Types;
using static Google.Ads.GoogleAds.V9.Enums.AdGroupStatusEnum.Types;
using static Google.Ads.GoogleAds.V9.Enums.AdGroupTypeEnum.Types;
using static Google.Ads.GoogleAds.V9.Enums.AdvertisingChannelTypeEnum.Types;
using static Google.Ads.GoogleAds.V9.Enums.BudgetDeliveryMethodEnum.Types;
using static Google.Ads.GoogleAds.V9.Enums.CampaignStatusEnum.Types;
using static Google.Ads.GoogleAds.V9.Enums.WebpageConditionOperandEnum.Types;
using static Google.Ads.GoogleAds.V9.Resources.Campaign.Types;

namespace Google.Ads.GoogleAds.Examples.V9
{
    /// <summary>
    /// This code example adds dynamic search ads to a given ad group. To list
    /// ad groups, run GetAdGroups.cs.
    /// </summary>
    public class AddDynamicSearchAds : ExampleBase
    {
        /// <summary>
        /// Command line options for running the <see cref="AddDynamicSearchAds"/> example.
        /// </summary>
        public class Options : OptionsBase
        {
            /// <summary>
            /// The customer ID for which the call is made.
            /// </summary>
            [Option("customerId", Required = true, HelpText =
                "The customer ID for which the call is made.")]
            public long CustomerId { get; set; }
        }

        /// <summary>
        /// Main method, to run this code example as a standalone application.
        /// </summary>
        /// <param name="args">The command line arguments.</param>
        public static void Main(string[] args)
        {
            Options options = new Options();
            CommandLine.Parser.Default.ParseArguments<Options>(args).MapResult(
                delegate (Options o)
                {
                    options = o;
                    return 0;
                }, delegate (IEnumerable<Error> errors)
                {
                    // The customer ID for which the call is made.
                    options.CustomerId = long.Parse("INSERT_CUSTOMER_ID_HERE");

                    return 0;
                });

            AddDynamicSearchAds codeExample = new AddDynamicSearchAds();
            Console.WriteLine(codeExample.Description);
            codeExample.Run(new GoogleAdsClient(), options.CustomerId);
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description =>
            "This code example adds dynamic search ads to a given ad group. To list ad groups, " +
            "run GetAdGroups.cs.";

        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The customer ID for which the call is made.</param>
        public void Run(GoogleAdsClient client, long customerId)
        {
            try
            {
                string budgetResourceName = AddCampaignBudget(client, customerId);
                string campaignResourceName = AddCampaign(client, customerId, budgetResourceName);
                string adGroupResourceName = AddAdGroup(client, customerId, campaignResourceName);
                AddExpandedDSA(client, customerId, adGroupResourceName);
                AddWebPageCriteria(client, customerId, adGroupResourceName);
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }

        /// <summary>
        /// Adds a campaign budget.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <returns>The campaign budget resource name.</returns>
        private static string AddCampaignBudget(GoogleAdsClient client, long customerId)
        {
            // Get the CampaignBudgetService.
            CampaignBudgetServiceClient campaignBudgetService =
                client.GetService(Services.V9.CampaignBudgetService);

            // Create the budget.
            CampaignBudget campaignBudget = new CampaignBudget()
            {
                Name = "Interplanetary Cruise Budget #" + ExampleUtilities.GetRandomString(),
                AmountMicros = 3_000_000,
                DeliveryMethod = BudgetDeliveryMethod.Standard
            };

            // Create the operation.
            CampaignBudgetOperation operation = new CampaignBudgetOperation()
            {
                Create = campaignBudget
            };

            // Add the campaign budget.
            MutateCampaignBudgetsResponse response =
                campaignBudgetService.MutateCampaignBudgets(customerId.ToString(),
                    new CampaignBudgetOperation[] { operation });
            // Display the result.

            string budgetResourceName = response.Results[0].ResourceName;
            Console.WriteLine($"Added budget with resource name '{budgetResourceName}'.");
            return budgetResourceName;
        }

        /// <summary>
        /// Adds a campaign.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="budgetResourceName">The campaign budget resource name.</param>
        /// <returns>The campaign resource name.</returns>
        private static string AddCampaign(GoogleAdsClient client, long customerId,
            string budgetResourceName)
        {
            // Get the CampaignService.
            CampaignServiceClient campaignService = client.GetService(Services.V9.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 = "example.com",
                    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 =
                campaignService.MutateCampaigns(customerId.ToString(),
                    new CampaignOperation[] { operation });

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

        /// <summary>Adds an ad group.</summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="campaignResourceName">The campaign resource name.</param>
        /// <returns>The ad group resource name.</returns>
        private static string AddAdGroup(GoogleAdsClient client, long customerId,
            string campaignResourceName)
        {
            // Get the AdGroupService.
            AdGroupServiceClient adGroupService = client.GetService(Services.V9.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 = "http://tracker.examples.com/traveltracker/{escapedlpurl}",
                CpcBidMicros = 50_000
            };

            // Create the operation.
            AdGroupOperation operation = new AdGroupOperation()
            {
                Create = adGroup
            };

            // Add the ad group.
            MutateAdGroupsResponse response =
                adGroupService.MutateAdGroups(customerId.ToString(),
                    new AdGroupOperation[] { operation });

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

            return adGroupResourceName;
        }

        /// <summary>Adds an expanded dynamic search ad.</summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="adGroupResourceName">The ad group resource name.</param>
        private static void AddExpandedDSA(GoogleAdsClient client, long customerId,
            string adGroupResourceName)
        {
            // Get the AdGroupAdService.
            AdGroupAdServiceClient adGroupAdService =
                client.GetService(Services.V9.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 " +
                $"'{response.Results[0].ResourceName}'.");
        }

        /// <summary>Add webpage targeting criteria for the DSA ad group.</summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="adGroupResourceName">The resource name of the ad group for which targeting
        /// is aded.</param>
        private static void AddWebPageCriteria(GoogleAdsClient client, long customerId,
            string adGroupResourceName)
        {
            // Get the AdGroupCriterionService.
            AdGroupCriterionServiceClient adGroupCriterionService =
                client.GetService(Services.V9.AdGroupCriterionService);

            // Create the criterion.
            AdGroupCriterion adGroupCriterion = new AdGroupCriterion()
            {
                AdGroup = adGroupResourceName,
                CpcBidMicros = 1_000_000,
                Status = AdGroupCriterionStatus.Paused,

                // Set the webpage targeting criteria.
                Webpage = new WebpageInfo()
                {
                    CriterionName = "Special Offers",
                    Conditions =
                    {
                        // Adds the url targeting criteria.
                        new WebpageConditionInfo()
                        {
                            Operand = WebpageConditionOperand.Url,
                            Argument = "/specialoffers"
                        },
                        // Adds the page title criteria.
                        // The list of webpage targeting conditions are
                        // and-ed together when evaluated for targeting.
                        new WebpageConditionInfo()
                        {
                            Operand = WebpageConditionOperand.PageTitle,
                            Argument = "Special Offer"
                        }
                    }
                }
            };

            // Create the operation.
            AdGroupCriterionOperation operation = new AdGroupCriterionOperation()
            {
                Create = adGroupCriterion
            };

            // Add the webpage criteria.
            MutateAdGroupCriteriaResponse response =
                adGroupCriterionService.MutateAdGroupCriteria(
                    customerId.ToString(), new[] { operation });
            // Displays the results.
            Console.WriteLine($"Added ad group criterion with resource name " +
                $"'{response.Results[0].ResourceName}'");
        }
    }
}

      

PHP

<?php

/**
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Google\Ads\GoogleAds\Examples\AdvancedOperations;

require __DIR__ . '/../../vendor/autoload.php';

use GetOpt\GetOpt;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentNames;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentParser;
use Google\Ads\GoogleAds\Examples\Utils\Helper;
use Google\Ads\GoogleAds\Lib\V9\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V9\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V9\GoogleAdsException;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\V9\Common\ExpandedDynamicSearchAdInfo;
use Google\Ads\GoogleAds\V9\Common\ManualCpc;
use Google\Ads\GoogleAds\V9\Common\WebpageConditionInfo;
use Google\Ads\GoogleAds\V9\Common\WebpageInfo;
use Google\Ads\GoogleAds\V9\Enums\AdGroupAdStatusEnum\AdGroupAdStatus;
use Google\Ads\GoogleAds\V9\Enums\AdGroupCriterionStatusEnum\AdGroupCriterionStatus;
use Google\Ads\GoogleAds\V9\Enums\AdGroupStatusEnum\AdGroupStatus;
use Google\Ads\GoogleAds\V9\Enums\AdGroupTypeEnum\AdGroupType;
use Google\Ads\GoogleAds\V9\Enums\AdvertisingChannelTypeEnum\AdvertisingChannelType;
use Google\Ads\GoogleAds\V9\Enums\BudgetDeliveryMethodEnum\BudgetDeliveryMethod;
use Google\Ads\GoogleAds\V9\Enums\CampaignStatusEnum\CampaignStatus;
use Google\Ads\GoogleAds\V9\Enums\WebpageConditionOperandEnum\WebpageConditionOperand;
use Google\Ads\GoogleAds\V9\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V9\Resources\Ad;
use Google\Ads\GoogleAds\V9\Resources\AdGroup;
use Google\Ads\GoogleAds\V9\Resources\AdGroupCriterion;
use Google\Ads\GoogleAds\V9\Resources\AdGroupAd;
use Google\Ads\GoogleAds\V9\Resources\Campaign;
use Google\Ads\GoogleAds\V9\Resources\Campaign\DynamicSearchAdsSetting;
use Google\Ads\GoogleAds\V9\Resources\CampaignBudget;
use Google\Ads\GoogleAds\V9\Services\AdGroupCriterionOperation;
use Google\Ads\GoogleAds\V9\Services\AdGroupOperation;
use Google\Ads\GoogleAds\V9\Services\AdGroupAdOperation;
use Google\Ads\GoogleAds\V9\Services\CampaignBudgetOperation;
use Google\Ads\GoogleAds\V9\Services\CampaignOperation;
use Google\Ads\GoogleAds\V9\Services\MutateAdGroupAdsResponse;
use Google\Ads\GoogleAds\V9\Services\MutateAdGroupsResponse;
use Google\Ads\GoogleAds\V9\Services\MutateAdGroupCriteriaResponse;
use Google\Ads\GoogleAds\V9\Services\MutateCampaignBudgetsResponse;
use Google\Ads\GoogleAds\V9\Services\MutateCampaignsResponse;
use Google\ApiCore\ApiException;

/**
 * This example adds a new dynamic search ad (DSA) and a webpage targeting criterion for the DSA.
 */
class AddDynamicSearchAds
{
    private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';

    public static function main()
    {
        // Either pass the required parameters for this example on the command line, or insert them
        // into the constants above.
        $options = (new ArgumentParser())->parseCommandArguments([
            ArgumentNames::CUSTOMER_ID => GetOpt::REQUIRED_ARGUMENT
        ]);

        // Generate a refreshable OAuth2 credential for authentication.
        $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();

        // Construct a Google Ads client configured from a properties file and the
        // OAuth2 credentials above.
        $googleAdsClient = (new GoogleAdsClientBuilder())->fromFile()
            ->withOAuth2Credential($oAuth2Credential)
            ->build();

        try {
            self::runExample(
                $googleAdsClient,
                $options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID
            );
        } catch (GoogleAdsException $googleAdsException) {
            printf(
                "Request with ID '%s' has failed.%sGoogle Ads failure details:%s",
                $googleAdsException->getRequestId(),
                PHP_EOL,
                PHP_EOL
            );
            foreach ($googleAdsException->getGoogleAdsFailure()->getErrors() as $error) {
                /** @var GoogleAdsError $error */
                printf(
                    "\t%s: %s%s",
                    $error->getErrorCode()->getErrorCode(),
                    $error->getMessage(),
                    PHP_EOL
                );
            }
            exit(1);
        } catch (ApiException $apiException) {
            printf(
                "ApiException was thrown with message '%s'.%s",
                $apiException->getMessage(),
                PHP_EOL
            );
            exit(1);
        }
    }

    /**
     * Runs the example.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     */
    public static function runExample(
        GoogleAdsClient $googleAdsClient,
        int $customerId
    ) {
        $budgetResourceName = self::createCampaignBudget($googleAdsClient, $customerId);
        $campaignResourceName = self::createCampaign(
            $googleAdsClient,
            $customerId,
            $budgetResourceName
        );
        $adGroupResourceName = self::createAdGroup(
            $googleAdsClient,
            $customerId,
            $campaignResourceName
        );
        self::createExpandedDSA($googleAdsClient, $customerId, $adGroupResourceName);
        self::createWebPageCriterion($googleAdsClient, $customerId, $adGroupResourceName);
    }

    /**
     * Creates a campaign budget.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @return string the campaign budget resource name
     */
    private static function createCampaignBudget(
        GoogleAdsClient $googleAdsClient,
        int $customerId
    ) {
        $campaignBudget = new CampaignBudget([
            'name' => 'Interplanetary Cruise Budget #' . Helper::getPrintableDatetime(),
            'delivery_method' => BudgetDeliveryMethod::STANDARD,
            'amount_micros' => 500000
        ]);

        // Creates a campaign budget operation.
        $campaignBudgetOperation = new CampaignBudgetOperation();
        $campaignBudgetOperation->setCreate($campaignBudget);

        // Issues a mutate request to add campaign budgets.
        $campaignBudgetServiceClient = $googleAdsClient->getCampaignBudgetServiceClient();
        /** @var MutateCampaignBudgetsResponse $campaignBudgetResponse */
        $campaignBudgetResponse = $campaignBudgetServiceClient->mutateCampaignBudgets(
            $customerId,
            [$campaignBudgetOperation]
        );

        $campaignBudgetResourceName = $campaignBudgetResponse->getResults()[0]->getResourceName();
        printf("Added budget named '%s'.%s", $campaignBudgetResourceName, PHP_EOL);

        return $campaignBudgetResourceName;
    }

    /**
     * Creates a campaign.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @param string $campaignBudgetResourceName the resource name of the campaign budget
     * @return string the resource name of the newly created campaign
     */
    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' => 'example.com',
                '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();
        $campaignOperation->setCreate($campaign);

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

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

        return $campaignResourceName;
    }

    /**
     * Creates an ad group.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @param string $campaignResourceName the resource name of the campaign
     * @return string the resource name of the newly created ad group
     */
    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' => 'http://tracker.examples.com/traveltracker/{escapedlpurl}',
            'cpc_bid_micros' => 10000000
        ]);

        // Creates an ad group operation.
        $adGroupOperation = new AdGroupOperation();
        $adGroupOperation->setCreate($adGroup);

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

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

        return $adGroupResourceName;
    }

    /**
     * Creates an expanded dynamic search ad.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @param string $adGroupResourceName the ad group 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();
        $adGroupAdOperation->setCreate($adGroupAd);

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

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

        return $adGroupAdResourceName;
    }

    /**
     * Creates a webpage targeting criterion for the DSA.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @param string $adGroupResourceName the resource name of the ad group
     */
    private static function createWebPageCriterion(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        string $adGroupResourceName
    ) {
        $adGroupCriterion = new AdGroupCriterion([
            'ad_group' => $adGroupResourceName,
            'status' => AdGroupCriterionStatus::PAUSED,
            'cpc_bid_micros' => 10000000,
            // Sets the criterion to match a specific page URL and title.
            'webpage' => new WebpageInfo([
                'criterion_name' => 'Special Offers',
                'conditions' => [
                    new WebpageConditionInfo([
                        'operand' => WebpageConditionOperand::URL,
                        'argument' => '/specialoffers'
                    ]),
                    new WebpageConditionInfo([
                        'operand' => WebpageConditionOperand::PAGE_TITLE,
                        'argument' => 'Special Offers'
                    ])
                ]
            ])
        ]);

        $adGroupCriterionOperation = new AdGroupCriterionOperation();
        $adGroupCriterionOperation->setCreate($adGroupCriterion);

        // Issues a mutate request to add the ad group criterion.
        $adGroupCriterionServiceClient = $googleAdsClient->getAdGroupCriterionServiceClient();
        /** @var MutateAdGroupCriteriaResponse $adGroupCriterionResponse */
        $adGroupCriterionResponse = $adGroupCriterionServiceClient->mutateAdGroupCriteria(
            $customerId,
            [$adGroupCriterionOperation]
        );

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

AddDynamicSearchAds::main();

      

Python

#!/usr/bin/env python
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This code example adds a new dynamic search ad (DSA).

It also creates a webpage targeting criteria for the DSA.
"""


import argparse
from datetime import datetime, timedelta
import sys
from uuid import uuid4

from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException


def main(client, customer_id):
    """The main method that creates all necessary entities for the example.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID str.
    """
    budget_resource_name = _create_budget(client, customer_id)
    campaign_resource_name = _create_campaign(
        client, customer_id, budget_resource_name
    )
    ad_group_resource_name = _create_ad_group(
        client, customer_id, campaign_resource_name
    )
    _create_expanded_dsa(client, customer_id, ad_group_resource_name)
    _add_webpage_criterion(client, customer_id, ad_group_resource_name)


def _create_budget(client, customer_id):
    """Creates a budget under the given customer ID.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID str.

    Returns:
        A resource_name str for the newly created Budget.
    """
    # Retrieve the campaign budget service.
    campaign_budget_service = client.get_service("CampaignBudgetService")
    # Creates a campaign budget operation.
    campaign_budget_operation = client.get_type("CampaignBudgetOperation")
    # Issues a mutate request to add campaign budgets.
    campaign_budget = campaign_budget_operation.create
    campaign_budget.name = f"Interplanetary Cruise #{uuid4()}"
    campaign_budget.amount_micros = 50000000
    campaign_budget.delivery_method = (
        client.enums.BudgetDeliveryMethodEnum.STANDARD
    )

    # Submit the campaign budget operation to add the campaign budget.
    response = campaign_budget_service.mutate_campaign_budgets(
        customer_id=customer_id, operations=[campaign_budget_operation]
    )
    resource_name = response.results[0].resource_name

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

    return resource_name


def _create_campaign(client, customer_id, budget_resource_name):
    """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 Budget

    Returns:
        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
    campaign.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.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 = "example.com"
    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 = (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 = 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}"')

    return resource_name


def _create_ad_group(client, customer_id, campaign_resource_name):
    """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 = 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
    ad_group.name = 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 = (
        "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 = 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}"')

    return resource_name


def _create_expanded_dsa(client, customer_id, ad_group_resource_name):
    """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 = 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.
    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 = 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 _add_webpage_criterion(client, customer_id, ad_group_resource_name):
    """Creates a web page criterion to 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 criterion operation.
    ad_group_criterion_operation = client.get_type("AdGroupCriterionOperation")
    # Create an ad group criterion for special offers for Mars Cruise.
    criterion = ad_group_criterion_operation.create
    criterion.ad_group = ad_group_resource_name
    # Optional: set custom bid amount.
    criterion.cpc_bid_micros = 10000000
    # Optional: set the status.
    criterion.status = client.enums.AdGroupCriterionStatusEnum.PAUSED

    # Sets the criterion to match a specific page URL and title.
    criterion.webpage.criterion_name = "Special Offers"
    # First condition info - URL
    webpage_condition_info_url = client.get_type("WebpageConditionInfo")
    webpage_condition_info_url.operand = (
        client.enums.WebpageConditionOperandEnum.URL
    )
    webpage_condition_info_url.argument = "/specialoffers"
    # Second condition info - Page title
    webpage_condition_info_page_title = client.get_type("WebpageConditionInfo")
    webpage_condition_info_page_title.operand = (
        client.enums.WebpageConditionOperandEnum.PAGE_TITLE
    )
    webpage_condition_info_page_title.argument = "Special Offer"
    # Add first and second condition info
    criterion.webpage.conditions.extend(
        [webpage_condition_info_url, webpage_condition_info_page_title]
    )

    # Retrieve the ad group criterion service.
    ad_group_criterion_service = client.get_service("AdGroupCriterionService")

    # Issues a mutate request to add the ad group criterion.
    response = ad_group_criterion_service.mutate_ad_group_criteria(
        customer_id=customer_id, operations=[ad_group_criterion_operation]
    )
    resource_name = response.results[0].resource_name

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


if __name__ == "__main__":
    # GoogleAdsClient will read the google-ads.yaml configuration file in the
    # home directory if none is specified.
    googleads_client = GoogleAdsClient.load_from_storage(version="v9")

    parser = argparse.ArgumentParser(
        description=(
            "Adds a dynamic search ad under the specified customer ID."
        )
    )
    # The following argument(s) should be provided to run the example.
    parser.add_argument(
        "-c",
        "--customer_id",
        type=str,
        required=True,
        help="The Google Ads customer ID.",
    )
    args = parser.parse_args()

    try:
        main(googleads_client, args.customer_id)
    except GoogleAdsException as ex:
        print(
            f'Request with ID "{ex.request_id}" failed with status '
            f'"{ex.error.code().name}" and includes the following errors:'
        )
        for error in ex.failure.errors:
            print(f'\tError with message "{error.message}".')
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print(f"\t\tOn field: {field_path_element.field_name}")
        sys.exit(1)

      

Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2019, Google Inc. All Rights Reserved.
#
# License:: Licensed under the Apache License, Version 2.0 (the "License");
#           you may not use this file except in compliance with the License.
#           You may obtain a copy of the License at
#
#           http://www.apache.org/licenses/LICENSE-2.0
#
#           Unless required by applicable law or agreed to in writing, software
#           distributed under the License is distributed on an "AS IS" BASIS,
#           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
#           implied.
#           See the License for the specific language governing permissions and
#           limitations under the License.
#
# This code example adds a Dynamic Search Ads campaign. To get campaigns, run
# get_campaigns.rb.

require 'optparse'
require 'google/ads/google_ads'

def add_dynamic_search_ads(customer_id)
  # GoogleAdsClient will read a config file from
  # ENV['HOME']/google_ads_config.rb when called without parameters
  client = Google::Ads::GoogleAds::GoogleAdsClient.new

  budget_resource_name = create_budget(client, customer_id)
  campaign_resource_name = create_campaign(
    client,
    customer_id,
    budget_resource_name,
  )

  ad_group_resource_name = create_ad_group(
    client,
    customer_id,
    campaign_resource_name,
  )

  create_expanded_dsa(client, customer_id, ad_group_resource_name)
  add_web_page_criteria(client, customer_id, ad_group_resource_name)
end

def create_budget(client, customer_id)
  campaign_budget = client.resource.campaign_budget do |b|
    b.name = "Interplanetary Cruise #{(Time.now.to_f * 1000).to_i}"
    b.amount_micros =  50_000_000
    b.delivery_method = :STANDARD
  end

  operation = client.operation.create_resource.campaign_budget(campaign_budget)

  response = client.service.campaign_budget.mutate_campaign_budgets(
    customer_id: customer_id,
    operations: [operation],
  )

  puts("Created campaign budget with ID: #{response.results.first.resource_name}")
  response.results.first.resource_name
end

def create_campaign(client, customer_id, budget_resource_name)
  campaign = client.resource.campaign do |c|
    c.name = "Interplanetary Cruise #{(Time.now.to_f * 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 =  "example.com"
      s.language_code =  "en"
    end

    c.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')
  end

  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}")
  response.results.first.resource_name
end

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

    ag.campaign =  campaign_resource_name

    ag.status = :PAUSED
    ag.tracking_url_template = "http://tracker.example.com/traveltracker/{escapedlpurl}"

    ag.cpc_bid_micros = 3_000_000
  end

  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}")
  response.results.first.resource_name
end

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

    aga.ad_group = ad_group_resource_name
  end

  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}")
end

def add_web_page_criteria(client, customer_id, ad_group_resource_name)
  criterion = client.resource.ad_group_criterion do |agc|
    agc.ad_group = ad_group_resource_name
    agc.cpc_bid_micros = 10_000_000

    agc.status = :PAUSED
    agc.webpage = client.resource.webpage_info do |wi|
      wi.criterion_name = "Special Offers"
    end
  end

  webpage_info_url = client.resource.webpage_condition_info do |wci|
    wci.operand = :URL
    wci.argument = "/specialoffers"
  end

  webpage_info_page_title = client.resource.webpage_condition_info do |wci|
    wci.operand = :PAGE_TITLE
    wci.argument = "Special Offer"
  end

  criterion.webpage.conditions << webpage_info_url
  criterion.webpage.conditions << webpage_info_page_title

  operation = client.operation.create_resource.ad_group_criterion(criterion)

  response = client.service.ad_group_criterion.mutate_ad_group_criteria(
    customer_id: customer_id,
    operations: [operation],
  )
  puts("Created ad group criterion with ID: #{response.results.first.resource_name}")
end

if __FILE__ == $0
  options = {}
  # The following parameter(s) should be provided to run the example. You can
  # either specify these by changing the INSERT_XXX_ID_HERE values below, or on
  # the command line.
  #
  # Parameters passed on the command line will override any parameters set in
  # code.
  #
  # Running the example with -h will print the command line usage.
  options[:customer_id] = 'INSERT_CUSTOMER_ID_HERE'

  OptionParser.new do |opts|
    opts.banner = sprintf("Usage: #{__FILE__} [options]")

    opts.separator ''
    opts.separator 'Options:'

    opts.on('-C', '--customer-id CUSTOMER-ID', String, 'Customer ID') do |v|
      options[:customer_id] = v
    end

    opts.separator ''
    opts.separator 'Help:'

    opts.on_tail('-h', '--help', 'Show this message') do
      puts opts
      exit
    end
  end.parse!

  begin
    add_dynamic_search_ads(options.fetch(:customer_id).tr("-", ""))
  rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e
    e.failure.errors.each do |error|
      STDERR.printf("Error with message: %s\n", error.message)
      if error.location
        error.location.field_path_elements.each do |field_path_element|
          STDERR.printf("\tOn field: %s\n", field_path_element.field_name)
        end
      end
      error.error_code.to_h.each do |k, v|
        next if v == :UNSPECIFIED
        STDERR.printf("\tType: %s\n\tCode: %s\n", k, v)
      end
    end
    raise
  end
end

      

Perl

#!/usr/bin/perl -w
#
# Copyright 2019, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This example adds a new dynamic search ad (DSA) and a webpage targeting
# criterion for the DSA.

use strict;
use warnings;
use utf8;

use FindBin qw($Bin);
use lib "$Bin/../../lib";
use Google::Ads::GoogleAds::Client;
use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;
use Google::Ads::GoogleAds::V9::Resources::CampaignBudget;
use Google::Ads::GoogleAds::V9::Resources::Campaign;
use Google::Ads::GoogleAds::V9::Resources::DynamicSearchAdsSetting;
use Google::Ads::GoogleAds::V9::Resources::AdGroup;
use Google::Ads::GoogleAds::V9::Resources::AdGroupAd;
use Google::Ads::GoogleAds::V9::Resources::Ad;
use Google::Ads::GoogleAds::V9::Resources::AdGroupCriterion;
use Google::Ads::GoogleAds::V9::Common::ManualCpc;
use Google::Ads::GoogleAds::V9::Common::ExpandedDynamicSearchAdInfo;
use Google::Ads::GoogleAds::V9::Common::WebpageInfo;
use Google::Ads::GoogleAds::V9::Common::WebpageConditionInfo;
use Google::Ads::GoogleAds::V9::Enums::BudgetDeliveryMethodEnum qw(STANDARD);
use Google::Ads::GoogleAds::V9::Enums::AdvertisingChannelTypeEnum qw(SEARCH);
use Google::Ads::GoogleAds::V9::Enums::CampaignStatusEnum;
use Google::Ads::GoogleAds::V9::Enums::AdGroupStatusEnum;
use Google::Ads::GoogleAds::V9::Enums::AdGroupTypeEnum qw(SEARCH_DYNAMIC_ADS);
use Google::Ads::GoogleAds::V9::Enums::AdGroupAdStatusEnum;
use Google::Ads::GoogleAds::V9::Enums::AdGroupCriterionStatusEnum;
use Google::Ads::GoogleAds::V9::Enums::WebpageConditionOperandEnum
  qw(URL PAGE_TITLE);
use
  Google::Ads::GoogleAds::V9::Services::CampaignBudgetService::CampaignBudgetOperation;
use Google::Ads::GoogleAds::V9::Services::CampaignService::CampaignOperation;
use Google::Ads::GoogleAds::V9::Services::AdGroupService::AdGroupOperation;
use Google::Ads::GoogleAds::V9::Services::AdGroupAdService::AdGroupAdOperation;
use
  Google::Ads::GoogleAds::V9::Services::AdGroupCriterionService::AdGroupCriterionOperation;
use Google::Ads::GoogleAds::V9::Utils::ResourceNames;

use Getopt::Long qw(:config auto_help);
use Pod::Usage;
use Cwd qw(abs_path);
use Data::Uniqid qw(uniqid);
use POSIX qw(strftime);

# The following parameter(s) should be provided to run the example. You can
# either specify these by changing the INSERT_XXX_ID_HERE values below, or on
# the command line.
#
# Parameters passed on the command line will override any parameters set in
# code.
#
# Running the example with -h will print the command line usage.
my $customer_id = "INSERT_CUSTOMER_ID_HERE";

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

  my $campaign_budget_resource_name =
    create_campaign_budget($api_client, $customer_id);
  my $campaign_resource_name =
    create_campaign($api_client, $customer_id, $campaign_budget_resource_name);
  my $ad_group_resource_name =
    create_ad_group($api_client, $customer_id, $campaign_resource_name);

  create_expanded_dsa($api_client, $customer_id, $ad_group_resource_name);
  add_web_page_criterion($api_client, $customer_id, $ad_group_resource_name);

  return 1;
}

# Creates a campaign budget.
sub create_campaign_budget {
  my ($api_client, $customer_id) = @_;

  # Create a campaign budget.
  my $campaign_budget =
    Google::Ads::GoogleAds::V9::Resources::CampaignBudget->new({
      name           => "Interplanetary Cruise Budget #" . uniqid(),
      deliveryMethod => STANDARD,
      amountMicros   => 50000000
    });

  # Create a campaign budget operation.
  my $campaign_budget_operation =
    Google::Ads::GoogleAds::V9::Services::CampaignBudgetService::CampaignBudgetOperation
    ->new({create => $campaign_budget});

  # Add the campaign budget.
  my $campaign_budgets_response = $api_client->CampaignBudgetService()->mutate({
      customerId => $customer_id,
      operations => [$campaign_budget_operation]});

  my $campaign_budget_resource_name =
    $campaign_budgets_response->{results}[0]{resourceName};
  printf "Created campaign budget '%s'.\n", $campaign_budget_resource_name;

  return $campaign_budget_resource_name;
}

# Creates a campaign.
sub create_campaign {
  my ($api_client, $customer_id, $campaign_budget_resource_name) = @_;

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

  # Create a campaign operation.
  my $campaign_operation =
    Google::Ads::GoogleAds::V9::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;
}

# Creates an ad group.
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::V9::Resources::AdGroup->new({
    name     => "Earth to Mars Cruises #" . uniqid(),
    campaign => $campaign_resource_name,
    status   => Google::Ads::GoogleAds::V9::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::V9::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;
}

# Creates an expanded dynamic search ad.
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::V9::Resources::AdGroupAd->new({
      adGroup => $ad_group_resource_name,
      status  => Google::Ads::GoogleAds::V9::Enums::AdGroupAdStatusEnum::PAUSED,
      ad      => Google::Ads::GoogleAds::V9::Resources::Ad->new({
          expandedDynamicSearchAd =>
            Google::Ads::GoogleAds::V9::Common::ExpandedDynamicSearchAdInfo->
            new({
              description => "Buy tickets now!"
            })})});

  # Create an ad group ad operation.
  my $ad_group_ad_operation =
    Google::Ads::GoogleAds::V9::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;
}

# Creates a webpage targeting criterion for the DSA.
sub add_web_page_criterion {
  my ($api_client, $customer_id, $ad_group_resource_name) = @_;

  # Create an ad group criterion.
  my $ad_group_criterion =
    Google::Ads::GoogleAds::V9::Resources::AdGroupCriterion->new({
      adGroup => $ad_group_resource_name,
      status  =>
        Google::Ads::GoogleAds::V9::Enums::AdGroupCriterionStatusEnum::PAUSED,
      cpcBidMicros => 10000000,
      webpage      => Google::Ads::GoogleAds::V9::Common::WebpageInfo->new({
          criterionName => "Special Offers",
          conditions    => [
            Google::Ads::GoogleAds::V9::Common::WebpageConditionInfo->new({
                operand  => URL,
                argument => "/specialoffers"

              }
            ),
            Google::Ads::GoogleAds::V9::Common::WebpageConditionInfo->new({
                operand  => PAGE_TITLE,
                argument => "Special Offers"
              })]})});

  # Create an ad group criterion operation.
  my $ad_group_criterion_operation =
    Google::Ads::GoogleAds::V9::Services::AdGroupCriterionService::AdGroupCriterionOperation
    ->new({create => $ad_group_criterion});

  # Add the ad group criterion.
  my $ad_group_criteria_response =
    $api_client->AdGroupCriterionService()->mutate({
      customerId => $customer_id,
      operations => [$ad_group_criterion_operation]});

  my $ad_group_criterion_resource_name =
    $ad_group_criteria_response->{results}[0]{resourceName};

  printf "Created ad group criterion '%s'.\n",
    $ad_group_criterion_resource_name;
}

# Don't run the example if the file is being included.
if (abs_path($0) ne abs_path(__FILE__)) {
  return 1;
}

# Get Google Ads Client, credentials will be read from ~/googleads.properties.
my $api_client = Google::Ads::GoogleAds::Client->new();

# By default examples are set to die on any server returned fault.
$api_client->set_die_on_faults(1);

# Parameters passed on the command line will override any parameters set in code.
GetOptions("customer_id=s" => \$customer_id);

# Print the help message if the parameters are not initialized in the code nor
# in the command line.
pod2usage(2) if not check_params($customer_id);

# Call the example.
add_dynamic_search_ads($api_client, $customer_id =~ s/-//gr);

=pod

=head1 NAME

add_dynamic_search_ads

=head1 DESCRIPTION

This example adds a new dynamic search ad (DSA) and a webpage targeting criterion
for the DSA.

=head1 SYNOPSIS

add_dynamic_search_ads.pl [options]

    -help                       Show the help message.
    -customer_id                The Google Ads customer ID.

=cut