Detect And Apply Recommendations

Java

// Copyright 2022 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.recommendations;

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.v16.common.KeywordInfo;
import com.google.ads.googleads.v16.errors.GoogleAdsError;
import com.google.ads.googleads.v16.errors.GoogleAdsException;
import com.google.ads.googleads.v16.resources.Recommendation;
import com.google.ads.googleads.v16.services.ApplyRecommendationOperation;
import com.google.ads.googleads.v16.services.ApplyRecommendationOperation.Builder;
import com.google.ads.googleads.v16.services.ApplyRecommendationResponse;
import com.google.ads.googleads.v16.services.ApplyRecommendationResult;
import com.google.ads.googleads.v16.services.GoogleAdsRow;
import com.google.ads.googleads.v16.services.GoogleAdsServiceClient;
import com.google.ads.googleads.v16.services.RecommendationServiceClient;
import com.google.ads.googleads.v16.services.SearchGoogleAdsStreamRequest;
import com.google.ads.googleads.v16.services.SearchGoogleAdsStreamResponse;
import com.google.api.gax.rpc.ServerStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * This example shows how to retrieve recommendations and apply them in a batch.
 *
 * <p>Recommendations should be applied shortly after they're retrieved. Depending on the
 * recommendation type, a recommendation can become obsolete quickly, and obsolete recommendations
 * throw an error when applied. For more details, see:
 * https://developers.google.com/google-ads/api/docs/recommendations#take_action
 *
 * <p>As of Google Ads API v15 users can subscribe to certain recommendation types to apply them
 * automatically. For more details, see:
 * https://developers.google.com/google-ads/api/docs/recommendations#auto-apply
 *
 * <p>As of Google Ads API v16 users can proactively generate certain recommendation types during
 * the campaign construction process. For more details see:
 * https://developers.google.com/google-ads/api/docs/recommendations#recommendations-in-campaign-construction
 */
public class DetectAndApplyRecommendations {

  private static class DetectAndApplyRecommendationsParams extends CodeSampleParams {

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

  public static void main(String[] args) throws IOException, InterruptedException {
    DetectAndApplyRecommendationsParams params = new DetectAndApplyRecommendationsParams();
    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 DetectAndApplyRecommendations().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 void runExample(GoogleAdsClient googleAdsClient, long customerId)
      throws InterruptedException {
    try (GoogleAdsServiceClient googleAdsServiceClient =
            googleAdsClient.getLatestVersion().createGoogleAdsServiceClient();
        RecommendationServiceClient recommendationServiceClient =
            googleAdsClient.getLatestVersion().createRecommendationServiceClient()) {
      // Creates a query that retrieves keyword recommendations.
      String query =
          "SELECT recommendation.resource_name, "
              + "  recommendation.campaign, "
              + "  recommendation.keyword_recommendation "
              + "FROM recommendation "
              + "WHERE recommendation.type = KEYWORD";
      // Constructs the SearchGoogleAdsStreamRequest.
      SearchGoogleAdsStreamRequest request =
          SearchGoogleAdsStreamRequest.newBuilder()
              .setCustomerId(Long.toString(customerId))
              .setQuery(query)
              .build();

      // Issues the search stream request to detect keyword recommendations that exist for the
      // customer account.
      ServerStream<SearchGoogleAdsStreamResponse> stream =
          googleAdsServiceClient.searchStreamCallable().call(request);

      // Creates apply operations for all the recommendations found.
      List<ApplyRecommendationOperation> applyRecommendationOperations = new ArrayList<>();
      for (SearchGoogleAdsStreamResponse response : stream) {
        for (GoogleAdsRow googleAdsRow : response.getResultsList()) {
          Recommendation recommendation = googleAdsRow.getRecommendation();
          System.out.printf(
              "Keyword recommendation '%s' was found for campaign '%s'%n",
              recommendation.getResourceName(), recommendation.getCampaign());
          KeywordInfo keyword = recommendation.getKeywordRecommendation().getKeyword();
          System.out.printf("\tKeyword = '%s'%n", keyword.getText());
          System.out.printf("\tMatch type = '%s'%n", keyword.getMatchType());

          // Creates an ApplyRecommendationOperation that will apply this recommendation, and adds
          // it to the list of operations.
          applyRecommendationOperations.add(buildRecommendationOperation(recommendation));
        }
      }

      // If there are operations present, sends a request to apply the recommendations.
      if (applyRecommendationOperations.isEmpty()) {
        System.out.println("No recommendations found.");
      } else {
        // Issues a mutate request to apply the recommendations.
        ApplyRecommendationResponse applyRecommendationsResponse =
            recommendationServiceClient.applyRecommendation(
                Long.toString(customerId), applyRecommendationOperations);
        for (ApplyRecommendationResult applyRecommendationResult :
            applyRecommendationsResponse.getResultsList()) {
          System.out.printf(
              "Applied recommendation with resource name: '%s'.%n",
              applyRecommendationResult.getResourceName());
        }
      }
    }
  }

  /** Creates and returns an ApplyRecommendationOperation to apply the given recommendation. */
  private ApplyRecommendationOperation buildRecommendationOperation(Recommendation recommendation) {
    // If you have a recommendation ID instead of a resource name, you can create a resource name
    // like this:
    // String resourceName = ResourceNames.recommendation(customerId, recommendationId);

    // Creates a builder to construct the operation.
    Builder operationBuilder = ApplyRecommendationOperation.newBuilder();

    // Each recommendation type has optional parameters to override the recommended values. Below is
    // an example showing how to override a recommended ad when a TextAdRecommendation is applied.
    // operationBuilder.getTextAdBuilder().getAdBuilder().setResourceName("INSERT_AD_RESOURCE_NAME");

    // Sets the operation's resource name to the resource name of the recommendation to apply.
    operationBuilder.setResourceName(recommendation.getResourceName());
    return operationBuilder.build();
  }
}

      

C#

// Copyright 2022 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.Gax.Examples;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V16.Common;
using Google.Ads.GoogleAds.V16.Resources;
using Google.Ads.GoogleAds.V16.Errors;
using Google.Ads.GoogleAds.V16.Services;
using System;
using System.Threading;
using System.Collections.Generic;
using Google.Ads.GoogleAds.Config;
using Google.Ads.GoogleAds.Extensions.Config;

namespace Google.Ads.GoogleAds.Examples.V16
{
    /// <summary>
    /// This example shows how to retrieve recommendations and apply them in a batch.
    /// Recommendations should be applied shortly after they're retrieved. Depending on the
    /// recommendation type, a recommendation can become obsolete quickly, and obsolete
    /// recommendations throw an error when applied. For more details, see:
    /// https://developers.google.com/google-ads/api/docs/recommendations#take_action
    ///
    /// As of Google Ads API V15, users can subscribe to certain recommendation types to apply
    /// them automatically. For more details, see:
    /// https://developers.google.com/google-ads/api/docs/recommendations#auto-apply
    ///
    /// As of Google Ads API V16, users can proactively generate certain recommendation types
    /// during the campaign construction process. For more details, see:
    /// https://developers.google.com/google-ads/api/docs/recommendations#recommendations-in-campaign-construction
    /// </summary>
    public class DetectAndApplyRecommendations : ExampleBase
    {
        /// <summary>
        /// Command line options for running the <see cref="DetectAndApplyRecommendations"/>
        /// 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 = ExampleUtilities.ParseCommandLine<Options>(args);

            DetectAndApplyRecommendations codeExample = new DetectAndApplyRecommendations();
            Console.WriteLine(codeExample.Description);
            GoogleAdsConfig config = new GoogleAdsConfig();
            config.LoadFromEnvironmentVariables();
            codeExample.Run(new GoogleAdsClient(config), options.CustomerId);
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description =>
            "This example shows how to retrieve recommendations and apply them in a batch.\n" +
            "Recommendations should be applied shortly after they're retrieved. Depending on the " +
            "recommendation type, a recommendation can become obsolete quickly, and obsolete " +
            "recommendations throw an error when applied. For more details, see: " +
            "https://developers.google.com/google-ads/api/docs/recommendations#take_action\n" +
            "As of Google Ads API V15, users can subscribe to certain recommendation types to " +
            "apply them automatically. For more details, see: " +
            "https://developers.google.com/google-ads/api/docs/recommendations#auto-apply\n" +
            "As of Google Ads API V16, users can proactively generate certain recommendation " +
            "types during the campaign construction process. For more details, see: " +
            "https://developers.google.com/google-ads/api/docs/recommendations#recommendations-in-campaign-construction";

        /// <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)
        {
            // Get the GoogleAdsServiceClient.
            GoogleAdsServiceClient googleAdsService = client.GetService(
                Services.V16.GoogleAdsService);

            // Creates a query that retrieves keyword recommendations.
            string query = "SELECT recommendation.resource_name, " +
                "recommendation.campaign, recommendation.keyword_recommendation " +
                "FROM recommendation WHERE " +
                $"recommendation.type = KEYWORD";

            List<ApplyRecommendationOperation> operations =
                new List<ApplyRecommendationOperation>();

            try
            {
                // Issue a search request.
                googleAdsService.SearchStream(customerId.ToString(), query,
                    delegate (SearchGoogleAdsStreamResponse resp)
                    {
                        Console.WriteLine($"Found {resp.Results.Count} recommendations.");
                        foreach (GoogleAdsRow googleAdsRow in resp.Results)
                        {
                            Recommendation recommendation = googleAdsRow.Recommendation;
                            Console.WriteLine("Keyword recommendation " +
                                $"{recommendation.ResourceName} was found for campaign " +
                                $"{recommendation.Campaign}.");

                            if (recommendation.KeywordRecommendation != null)
                            {
                                KeywordInfo keyword =
                                    recommendation.KeywordRecommendation.Keyword;
                                Console.WriteLine($"Keyword = {keyword.Text}, type = " +
                                    "{keyword.MatchType}");
                            }

                            operations.Add(new ApplyRecommendationOperation()
                            {
                                // If you have a recommendation_id instead of the resource_name
                                // you can create a resource name from it like this:
                                // string recommendationResourceName =
                                //    ResourceNames.Recommendation(customerId, recommendationId)
                                ResourceName = recommendation.ResourceName
                            });
                        }
                    }
                );
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }

        /// <summary>
        /// Applies a list of recommendation.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The customer ID for which the call is made.</param>
        /// <param name="operations">The recommendations to apply.</param>
        private void ApplyRecommendation(GoogleAdsClient client, long customerId,
            List<ApplyRecommendationOperation> operations)
        {
            // Get the RecommendationServiceClient.
            RecommendationServiceClient recommendationService = client.GetService(
                Services.V16.RecommendationService);

            ApplyRecommendationRequest applyRecommendationRequest = new ApplyRecommendationRequest()
            {
                CustomerId = customerId.ToString(),
            };

            applyRecommendationRequest.Operations.AddRange(operations);

            ApplyRecommendationResponse response =
                recommendationService.ApplyRecommendation(applyRecommendationRequest);
            foreach (ApplyRecommendationResult result in response.Results)
            {
                Console.WriteLine("Applied a recommendation with resource name: " +
                    result.ResourceName);
            }
        }
    }
}
      

PHP

<?php

/**
 * Copyright 2022 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\Recommendations;

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\Lib\V16\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V16\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V16\GoogleAdsException;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Lib\V16\GoogleAdsServerStreamDecorator;
use Google\Ads\GoogleAds\V16\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V16\Services\ApplyRecommendationOperation;
use Google\Ads\GoogleAds\V16\Services\ApplyRecommendationResult;
use Google\Ads\GoogleAds\V16\Services\GoogleAdsRow;
use Google\Ads\GoogleAds\V16\Services\SearchGoogleAdsStreamRequest;
use Google\ApiCore\ApiException;

/**
 * The auto-apply feature, which automatically applies recommendations as they become eligible,
 * is currently supported by the Google Ads UI but not by the Google Ads API. See
 * https://support.google.com/google-ads/answer/10279006 for more information on using auto-apply
 * in the Google Ads UI.
 *
 * This example demonstrates how an alternative can be implemented with the features that are
 * currently supported by the Google Ads API. It periodically retrieves and applies `KEYWORD`
 * recommendations with default parameters.
 */
class DetectAndApplyRecommendations
{
    private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';

    // The maximum number of recommendations to periodically retrieve and apply.  In a real
    // application, such a limit would typically not be used.
    private const MAX_RESULT_SIZE = 2;
    // The number of times to retrieve and apply recommendations. In a real application, such a
    // limit would typically not be used.
    private const NUMBER_OF_RUNS = 3;
    // The time to wait between two runs. In a real application, this would typically be set to
    // minutes or hours instead of seconds.
    private const PERIOD_IN_SECONDS = 5;

    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)
            // We set this value to true to show how to use GAPIC v2 source code. You can remove the
            // below line if you wish to use the old-style source code. Note that in that case, you
            // probably need to modify some parts of the code below to make it work.
            // For more information, see
            // https://developers.devsite.corp.google.com/google-ads/api/docs/client-libs/php/gapic.
            ->usingGapicV2Source(true)
            ->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)
    {
        $googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();
        // Creates a query that retrieves keyword recommendations.
        $query = 'SELECT recommendation.resource_name '
            . 'FROM recommendation '
            . 'WHERE recommendation.type = KEYWORD '
            . 'LIMIT ' . self::MAX_RESULT_SIZE;

        $recommendationServiceClient = $googleAdsClient->getRecommendationServiceClient();
        for ($i = 0; $i < self::NUMBER_OF_RUNS; $i++) {
            // Issues a search stream request.
            /* @var GoogleAdsServerStreamDecorator $stream */
            $stream = $googleAdsServiceClient->searchStream(
                SearchGoogleAdsStreamRequest::build($customerId, $query)
            );

            // Creates apply operations for all the recommendations found.
            $applyRecommendationOperations = [];
            foreach ($stream->iterateAllElements() as $googleAdsRow) {
                /** @var GoogleAdsRow $googleAdsRow */
                $applyRecommendationOperations[] = new ApplyRecommendationOperation([
                    'resource_name' => $googleAdsRow->getRecommendation()->getResourceName()
                ]);
            }

            if ($applyRecommendationOperations) {
                // Sends the apply recommendation request and prints information.
                $response = $recommendationServiceClient->applyRecommendation(
                    $customerId,
                    $applyRecommendationOperations
                );
                foreach ($response->getResults() as $result) {
                    /** @var ApplyRecommendationResult $result */
                    printf(
                        'Applied recommendation with resource name: "%s".%s',
                        $result->getResourceName(),
                        PHP_EOL
                    );
                }
            } else {
                print 'No recommendations were found.' . PHP_EOL;
            }
            print PHP_EOL;

            if ($i < self::NUMBER_OF_RUNS - 1) {
                printf(
                    "Waiting %d seconds before checking for additional recommendations.%s",
                    self::PERIOD_IN_SECONDS,
                    PHP_EOL
                );
                sleep(self::PERIOD_IN_SECONDS);
            }
        }
    }
}

DetectAndApplyRecommendations::main();

      

Python

#!/usr/bin/env python
# Copyright 2023 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 example shows how to retrieve recommendations and apply them in a batch.

Recommendations should be applied shortly after they're retrieved. Depending on
the recommendation type, a recommendation can become obsolete quickly, and
obsolete recommendations throw an error when applied. For more details, see:
https://developers.google.com/google-ads/api/docs/recommendations#take_action

As of Google Ads API v15 users can subscribe to certain recommendation types to
apply them automatically. For more details, see:
https://developers.google.com/google-ads/api/docs/recommendations#auto-apply

As of Google Ads API v16 users can proactively generate certain recommendation
types during the campaign construction process. For more details see:
https://developers.google.com/google-ads/api/docs/recommendations#recommendations-in-campaign-construction
"""


import argparse
import sys

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.
    """
    detect_and_apply_recommendations(client, customer_id)


def detect_and_apply_recommendations(client, customer_id):
    """Detects recommendations and applies them.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID.
    """
    googleads_service = client.get_service("GoogleAdsService")
    query = f"""
        SELECT
          recommendation.campaign,
          recommendation.keyword_recommendation
        FROM recommendation
        WHERE
          recommendation.type = KEYWORD"""

    # Detects keyword recommendations that exist for the customer account.
    response = googleads_service.search(customer_id=customer_id, query=query)

    operations = []
    for row in response.results:
        recommendation = row.recommendation
        print(
            f"Keyword recommendation ('{recommendation.resource_name}') "
            f"was found for campaign '{recommendation.campaign}."
        )

        keyword = recommendation.keyword_recommendation.keyword
        print(
            f"\tKeyword = '{keyword.text}'\n" f"\tType = '{keyword.match_type}'"
        )

        # Create an ApplyRecommendationOperation that will be used to apply
        # this recommendation, and add it to the list of operations.
        operations.append(
            build_recommendation_operation(client, recommendation.resource_name)
        )

    # If there are operations present, send a request to apply the
    # recommendations.
    if operations:
        apply_recommendations(client, customer_id, operations)


def build_recommendation_operation(client, recommendation):
    """Creates a ApplyRecommendationOperation to apply the given recommendation.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID.
        recommendation: a resource name for the recommendation to be applied.
    """
    # If you have a recommendation ID instead of a resource name, you can create
    # a resource name like this:
    #
    # googleads_service = client.get_service("GoogleAdsService")
    # resource_name = googleads_service.recommendation_path(
    #   customer_id, recommendation.id
    # )

    operation = client.get_type("ApplyRecommendationOperation")

    # Each recommendation type has optional parameters to override the
    # recommended values. Below is an example showing how to override a
    # recommended ad when a TextAdRecommendation is applied.
    #
    # operation.text_ad.ad.resource_name = "INSERT_AD_RESOURCE_NAME"
    #
    # For more details, see:
    # https://developers.google.com/google-ads/api/reference/rpc/latest/ApplyRecommendationOperation#apply_parameters

    operation.resource_name = recommendation
    return operation


def apply_recommendations(client, customer_id, operations):
    """Applies a batch of recommendations.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID.
        operations: a list of ApplyRecommendationOperation messages.
    """
    # Issues a mutate request to apply the recommendations.
    recommendation_service = client.get_service("RecommendationService")
    response = recommendation_service.apply_recommendation(
        customer_id=customer_id, operations=operations
    )

    for result in response.results:
        print(
            "Applied a recommendation with resource name: "
            f"'{result[0].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="v16")

    parser = argparse.ArgumentParser(
        description=(
            "Retrieves keyword recommendations for specified customer and "
            "applies them."
        )
    )
    # 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 2022 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.
#
# The auto-apply feature, which automatically applies recommendations as they
# become eligible, is currently supported by the Google Ads UI but not by the
# Google Ads API. See https://support.google.com/google-ads/answer/10279006 for
# more information on using auto-apply in the Google Ads UI.
#
# This example demonstrates how an alternative can be implemented with the
# features that are currently supported by the Google Ads API. It periodically
# retrieves and applies `KEYWORD` recommendations with default parameters.

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

def detect_and_apply_recommendations(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

  query = <<~QUERY
    SELECT recommendation.resource_name
    FROM recommendation
    WHERE recommendation.type = KEYWORD
    LIMIT #{MAX_RESULT_SIZE}
  QUERY

  reccomendation_service = client.service.recommendation
  google_ads_service = client.service.google_ads
  NUMBER_OF_RUNS.times do |i|
    search_response = google_ads_service.search(
      customer_id: customer_id,
      query: query,
    )
    operations = search_response.map do |row|
      client.operation.apply_recommendation do |aro|
        aro.resource_name = row.recommendation.resource_name
      end
    end

    unless operations.empty?
      response = recommendation_service.apply_recommendation(
        customer_id: customer_id,
        operations: operations,
      )

      response.each do |result|
        puts "Applied recommendation with resource name #{result.resource_name}."
      end
    end

    if i < NUMBER_OF_RUNS - 1
      puts "Waiting #{PERIOD_IN_SECONDS} seconds before applying more recommendations."
      sleep(PERIOD_IN_SECONDS)
    end
  end
end

if __FILE__ == $0
  MAX_RESULT_SIZE = 2
  NUMBER_OF_RUNS = 3
  PERIOD_IN_SECONDS = 5

  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.

  OptionParser.new do |opts|
    opts.banner = sprintf('Usage: %s [options]', File.basename(__FILE__))

    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
    detect_and_apply_recommendations(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 2022, 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.
#
# The auto-apply feature, which automatically applies recommendations as they become eligible,
# is currently supported by the Google Ads UI but not by the Google Ads API. See
# https://support.google.com/google-ads/answer/10279006 for more information on using auto-apply
# in the Google Ads UI.
#
# This example demonstrates how an alternative can be implemented with the features that are
# currently supported by the Google Ads API. It periodically retrieves and applies `KEYWORD`
# recommendations with default parameters.

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::Utils::SearchStreamHandler;
use
  Google::Ads::GoogleAds::V16::Services::RecommendationService::ApplyRecommendationOperation;
use
  Google::Ads::GoogleAds::V16::Services::GoogleAdsService::SearchGoogleAdsStreamRequest;

use Getopt::Long qw(:config auto_help);
use Pod::Usage;
use Cwd         qw(abs_path);
use Time::HiRes qw(sleep);

my $customer_id;

# The maximum number of recommendations to periodically retrieve and apply.
# In a real application, such a limit would typically not be used.
use constant MAX_RESULT_SIZE => 2;

# The number of times to retrieve and apply recommendations. In a real application,
# such a limit would typically not be used.
use constant NUMBER_OF_RUNS => 3;

# The time to wait between two runs. In a real application, this would typically be set to
# minutes or hours instead of seconds.
use constant PERIOD_IN_SECONDS => 5;

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

  # Create the search query.
  my $search_query =
    "SELECT recommendation.resource_name FROM recommendation " .
    "WHERE recommendation.type = KEYWORD LIMIT " . MAX_RESULT_SIZE;

  # Get the GoogleAdsService.
  my $google_ads_service = $api_client->GoogleAdsService();

  for my $i (1 .. NUMBER_OF_RUNS) {
    my $search_stream_handler =
      Google::Ads::GoogleAds::Utils::SearchStreamHandler->new({
        service => $google_ads_service,
        request => {
          customerId => $customer_id,
          query      => $search_query
        }});

    # Create apply operations for all the recommendations found.
    my $apply_recommendation_operations = ();
    $search_stream_handler->process_contents(
      sub {
        my $google_ads_row = shift;
        push @$apply_recommendation_operations,
          Google::Ads::GoogleAds::V16::Services::RecommendationService::ApplyRecommendationOperation
          ->new({
            resourceName => $google_ads_row->{recommendation}{resource_name}});
      });

    if (defined $apply_recommendation_operations) {
      # Send the apply recommendation request and print information.
      my $apply_recommendation_response =
        $api_client->RecommendationService()->apply({
          customerId => $customer_id,
          operations => $apply_recommendation_operations
        });

      foreach my $result (@{$apply_recommendation_response->{results}}) {
        printf "Applied recommendation with resource name: '%s'.\n",
          $result->{resourceName};
      }
    }

    if ($i < NUMBER_OF_RUNS) {
      printf
        "Waiting %d seconds before checking for additional recommendations.\n",
        PERIOD_IN_SECONDS;
      sleep(PERIOD_IN_SECONDS);
    }

  }

  return 1;
}

# 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.
detect_and_apply_recommendations($api_client, $customer_id =~ s/-//gr);

=pod

=head1 NAME

detect_and_apply_recommendations

=head1 DESCRIPTION

The auto-apply feature, which automatically applies recommendations as they become eligible,
is currently supported by the Google Ads UI but not by the Google Ads API. See
https://support.google.com/google-ads/answer/10279006 for more information on using auto-apply
in the Google Ads UI.

This example demonstrates how an alternative can be implemented with the features that are
currently supported by the Google Ads API. It periodically retrieves and applies `KEYWORD`
recommendations with default parameters.

=head1 SYNOPSIS

detect_and_apply_recommendations.pl [options]

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

=cut