Recommendation Service

Recommendations help you improve your campaigns by introducing new and relevant features, getting more out of your budget by improving bids, keywords and ads, and increasing the overall performance and efficiency of your campaigns.

Recommendation types

The Google Ads API currently supports four types of recommendations:

Recommendation Type Value
Fixing campaigns limited by budget CAMPAIGN_BUDGET
Adding new keywords KEYWORD
Adding ad suggestions TEXT_AD
Bidding with Target CPA TARGET_CPA_OPT_IN

Getting recommendations

The following sample code retrieves all the current available recommendations from an account using GoogleAdsService.Search:

Java

private void runExample(GoogleAdsClient googleAdsClient, long customerId) {
  try (GoogleAdsServiceClient googleAdsServiceClient =
      googleAdsClient.getGoogleAdsServiceClient()) {
    String query =
        "SELECT recommendation.type, "
            + "recommendation.campaign, "
            + "recommendation.text_ad_recommendation "
            + "FROM recommendation "
            + "WHERE recommendation.type = TEXT_AD";

    // Creates a request that will retrieve all recommendations using pages of the
    // specified page size.
    SearchGoogleAdsRequest request =
        SearchGoogleAdsRequest.newBuilder()
            .setCustomerId(Long.toString(customerId))
            .setPageSize(PAGE_SIZE)
            .setQuery(query)
            .build();
    // Issues the search request.
    SearchPagedResponse searchPagedResponse = googleAdsServiceClient.search(request);

    // Iterates over all rows in all pages and prints the requested field values for the
    // recommendation in each row.
    for (GoogleAdsRow googleAdsRow : searchPagedResponse.iterateAll()) {
      Recommendation recommendation = googleAdsRow.getRecommendation();
      Ad recommendedAd = recommendation.getTextAdRecommendation().getAd();

      System.out.printf(
          "Recommendation ('%s') was found for campaign '%s':%n",
          recommendation.getResourceName(), recommendation.getCampaign().getValue());
      if (recommendedAd.hasExpandedTextAd()) {
        ExpandedTextAdInfo eta = recommendedAd.getExpandedTextAd();
        System.out.printf(
            "\tHeadline 1 = '%s'%n" + "\tHeadline 2 = '%s'%n" + "\tDescription = '%s'%n",
            eta.getHeadlinePart1().getValue(),
            eta.getHeadlinePart2().getValue(),
            eta.getDescription().getValue());
      }
      if (recommendedAd.getDisplayUrl() != null) {
        System.out.printf("\tDisplay URL = '%s'%n", recommendedAd.getDisplayUrl().getValue());
      }
      for (StringValue url : recommendedAd.getFinalUrlsList()) {
        System.out.printf("\tFinal URL = '%s'%n", url.getValue());
      }
      for (StringValue url : recommendedAd.getFinalMobileUrlsList()) {
        System.out.printf("\tFinal Mobile URL = '%s'%n", url.getValue());
      }
    }
  }
}

C#

public void Run(GoogleAdsClient client, long customerId) {
  // Get the GoogleAdsServiceClient .
  GoogleAdsServiceClient service = client.GetService(Services.V0.GoogleAdsService);

  string query =
      @"SELECT
            recommendation.type,
            recommendation.campaign,
            recommendation.text_ad_recommendation
        FROM
            recommendation
        WHERE
            recommendation.type = TEXT_AD";

  // Create a request that will retrieve all recommendations using pages of the
  // specified page size.
  SearchGoogleAdsRequest request = new SearchGoogleAdsRequest() {
    CustomerId = customerId.ToString(),
    PageSize = PAGE_SIZE,
    Query = query
  };

  try {
    // Issue the search request.
    PagedEnumerable<SearchGoogleAdsResponse, GoogleAdsRow> searchPagedResponse =
        service.Search(customerId.ToString(), query);

    // Iterates over all rows in all pages and prints the requested field values for the
    // recommendation in each row.
    foreach (GoogleAdsRow googleAdsRow in searchPagedResponse) {
      Recommendation recommendation = googleAdsRow.Recommendation;
      Ad recommendedAd = recommendation.TextAdRecommendation.Ad;

      Console.WriteLine($"Recommendation ({recommendation.ResourceName}) was found for " +
          $"campaign {recommendation.Campaign}:");
      if (recommendedAd.ExpandedTextAd != null) {
        ExpandedTextAdInfo eta = recommendedAd.ExpandedTextAd;
        Console.WriteLine("\tHeadline 1 = {0}\n\tHeadline 2 = {1}\tDescription = {2}",
            eta.HeadlinePart1, eta.HeadlinePart2, eta.Description);
      }
      Console.WriteLine($"\tDisplay URL = {recommendedAd.DisplayUrl}");
      foreach (string url in recommendedAd.FinalUrls) {
        Console.WriteLine($"\tFinal URL = {url}");
      }
      foreach (string url in recommendedAd.FinalMobileUrls) {
        Console.WriteLine($"\tFinal Mobile URL = {url}");
      }
    }
  } catch (GoogleAdsException e) {
    Console.WriteLine("Failure:");
    Console.WriteLine($"Message: {e.Message}");
    Console.WriteLine($"Failure: {e.Failure}");
    Console.WriteLine($"Request ID: {e.RequestId}");
  }
}

PHP

<?php
/**
 * Copyright 2018 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\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\GoogleAdsException;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\V0\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V0\Services\GoogleAdsRow;
use Google\ApiCore\ApiException;
use Google\Protobuf\StringValue;

/** This example gets all `TEXT_AD` recommendations. */
class GetTextAdRecommendations
{
    const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';

    const PAGE_SIZE = 1000;

    public static function main()
    {
        // Either pass the required parameters for this example on the command line, or insert them
        // into the constants above.
        $options = 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
                );
            }
        } catch (ApiException $apiException) {
            printf(
                "ApiException was thrown with message '%s'.%s",
                $apiException->getMessage(),
                PHP_EOL
            );
        }
    }

    /**
     * Runs the example.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the client customer ID without hyphens
     */
    public static function runExample(GoogleAdsClient $googleAdsClient, $customerId)
    {
        $googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();
        // Creates a query that retrieves recommendations for text ads.
        $query = 'SELECT recommendation.type, recommendation.campaign, '
            . 'recommendation.text_ad_recommendation '
            . 'FROM recommendation '
            . 'WHERE recommendation.type = TEXT_AD';

        // Issues a search request by specifying page size.
        $response =
            $googleAdsServiceClient->search($customerId, $query, ['pageSize' => self::PAGE_SIZE]);

        // Iterates over all rows in all pages and prints the requested field values for
        // the recommendation in each row.
        foreach ($response->iterateAllElements() as $googleAdsRow) {
            /** @var GoogleAdsRow $googleAdsRow */
            $recommendation = $googleAdsRow->getRecommendation();
            printf(
                "Recommendation with resource name '%s' was found for campaign "
                . "with resource name '%s':%s",
                $recommendation->getResourceName(),
                $recommendation->getCampaign()->getValue(),
                PHP_EOL
            );
            $recommendedAd = $recommendation->getTextAdRecommendation()->getAd();
            if (!is_null($recommendedAd->getExpandedTextAd())) {
                $recommendedExpandedTextAd = $recommendedAd->getExpandedTextAd();
                printf(
                    "\tHeadline part 1 is '%s'.%s",
                    $recommendedExpandedTextAd->getHeadlinePart1()->getValue(),
                    PHP_EOL
                );
                printf(
                    "\tHeadline part 2 is '%s'.%s",
                    $recommendedExpandedTextAd->getHeadlinePart2()->getValue(),
                    PHP_EOL
                );
                printf(
                    "\tDescription is '%s'%s",
                    $recommendedExpandedTextAd->getDescription()->getValue(),
                    PHP_EOL
                );
            }
            if (!is_null($recommendedAd->getDisplayUrl())) {
                printf(
                    "\tDisplay URL is '%s'.%s",
                    $recommendedAd->getDisplayUrl()->getValue(),
                    PHP_EOL
                );
            }
            foreach ($recommendedAd->getFinalUrls() as $finalUrl) {
                /** @var StringValue $finalUrl */
                printf("\tFinal URL is '%s'.%s", $finalUrl->getValue(), PHP_EOL);
            }
            foreach ($recommendedAd->getFinalMobileUrls() as $finalMobileUrl) {
                /** @var StringValue $finalMobileUrl */
                printf("\tFinal Mobile URL is '%s'.%s", $finalMobileUrl->getValue(), PHP_EOL);
            }
        }
    }
}

GetTextAdRecommendations::main();

Applying a recommendation

You can apply recommendations to your account via the RecommendationService. To override recommended values, use ApplyRecommendationOperation with the additional parameters.

Java

private void runExample(
    GoogleAdsClient googleAdsClient, long customerId, String recommendationId) {
  String recommendationResourceName =
      RecommendationName.format(Long.toString(customerId), recommendationId);

  ApplyRecommendationOperation.Builder operationBuilder =
      ApplyRecommendationOperation.newBuilder().setResourceName(recommendationResourceName);
  // Each recommendation types has optional parameters to override the recommended values.
  // This is an example to override a recommended ad when a TextAdRecommendation is applied.
  // Please read
  // https://developers.google.com/google-ads/api/reference/rpc/google.ads.googleads.v0.services#google.ads.googleads.v0.services.ApplyRecommendationOperation
  // for details.
  // Note that additional import statements are needed for this example to work. And also, please
  // replace INSERT_AD_ID_HERE with a valid ad ID below.
  //
  // Ad overrideAd = Ad.newBuilder().setId(Int64Value.of(Long.parseLong(
  //     "INSERT_AD_ID_HERE"))).build();
  // operationBuilder.setTextAd(TextAdParameters.newBuilder().
  //     setAd(overrideAd).build()).build();
  List<ApplyRecommendationOperation> operations = new ArrayList<>();
  operations.add(operationBuilder.build());

  try (RecommendationServiceClient recommendationServiceClient =
      googleAdsClient.getRecommendationServiceClient()) {
    ApplyRecommendationResponse response =
        recommendationServiceClient.applyRecommendation(Long.toString(customerId), operations);
    System.out.printf("Applied %d recommendation:%n", response.getResultsCount());
    for (ApplyRecommendationResult result : response.getResultsList()) {
      System.out.println(result.getResourceName());
    }
  }
}

C#

public void Run(GoogleAdsClient client, long customerId, long recommendationId) {
  // Get the RecommendationServiceClient.
  RecommendationServiceClient service = client.GetService(
      Services.V0.RecommendationService);

  ApplyRecommendationOperation operation = new ApplyRecommendationOperation() {
    ResourceName = ResourceNames.Recommendation(customerId, recommendationId),

    // Each recommendation types has optional parameters to override the recommended values.
    // For example, you can override a recommended ad when a TextAdRecommendation is applied,
    // as shown below.
    // Please read https://developers.google.com/google-ads/api/reference/rpc/google.ads.googleads.v0.services#google.ads.googleads.v0.services.ApplyRecommendationOperation
    // for details.
    // TextAd = new TextAdParameters() {
    //   Ad = new Ad() {
    //     Id = long.Parse("INSERT_AD_ID_HERE")
    //   }
    // }
  };

  try {
    ApplyRecommendationResponse response = service.ApplyRecommendation(customerId.ToString(),
        new ApplyRecommendationOperation[] { operation });
    Console.WriteLine($"Applied {0} recommendation(s):", response.Results.Count);
    foreach (ApplyRecommendationResult result in response.Results) {
      Console.WriteLine($"- {result.ResourceName}");
    }
  } catch (GoogleAdsException e) {
    Console.WriteLine("Failure:");
    Console.WriteLine($"Message: {e.Message}");
    Console.WriteLine($"Failure: {e.Failure}");
    Console.WriteLine($"Request ID: {e.RequestId}");
  }
}

PHP

<?php
/**
 * Copyright 2018 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\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\GoogleAdsException;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Util\ResourceNames;
use Google\Ads\GoogleAds\V0\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V0\Resources\Recommendation;
use Google\Ads\GoogleAds\V0\Services\ApplyRecommendationOperation;
use Google\ApiCore\ApiException;

/**
 * This example applies a given recommendation. To retrieve recommendations for text ads,
 * run GetTextAdRecommendations.php.
 */
class ApplyRecommendation
{
    const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
    // Recommendation ID is the last alphanumeric portion of the value from
    // ResourceNames::forRecommendation(), which has the format of
    // `customers/<customer_id>/recommendations/<recommendation_id>`.
    // Its example can be retrieved from GetTextAdRecommendations.php
    const RECOMMENDATION_ID = 'INSERT_RECOMMENDATION_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 = ArgumentParser::parseCommandArguments([
            ArgumentNames::CUSTOMER_ID => GetOpt::REQUIRED_ARGUMENT,
            ArgumentNames::RECOMMENDATION_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,
                $options[ArgumentNames::RECOMMENDATION_ID] ?: self::RECOMMENDATION_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
                );
            }
        } catch (ApiException $apiException) {
            printf(
                "ApiException was thrown with message '%s'.%s",
                $apiException->getMessage(),
                PHP_EOL
            );
        }
    }

    /**
     * Runs the example.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the client customer ID without hyphens
     * @param string $recommendationId the recommendation ID to apply
     */
    public static function runExample(
        GoogleAdsClient $googleAdsClient,
        $customerId,
        $recommendationId
    ) {
        $recommendationResourceName =
            ResourceNames::forRecommendation($customerId, $recommendationId);

        $applyRecommendationOperation = new ApplyRecommendationOperation();
        $applyRecommendationOperation->setResourceName($recommendationResourceName);

        // Each recommendation type has optional parameters to override the recommended values.
        // This is an example to override a recommended ad when a TextAdRecommendation is applied.
        // For details, please read
        // https://developers.google.com/google-ads/api/reference/rpc/google.ads.googleads.v0.services#google.ads.googleads.v0.services.ApplyRecommendationOperation.
        /*
        $overridingAd = new Ad();
        $wrappedId = new Int64Value();
        $wrappedId->setValue('INSERT_AD_ID_AS_INTEGER_HERE');
        $overridingAd->setId($wrappedId);
        $textAdParameters = new ApplyRecommendationOperation_TextAdParameters();
        $textAdParameters->setAd($overridingAd);
        $applyRecommendationOperation->setTextAd($textAdParameters);
        */
        // Issues a mutate request to apply the recommendation.
        $recommendationServiceClient = $googleAdsClient->getRecommendationServiceClient();
        $response = $recommendationServiceClient->applyRecommendation(
            $customerId,
            [$applyRecommendationOperation]
        );
        /** @var Recommendation $appliedRecommendation */
        $appliedRecommendation = $response->getResults()[0];

        printf(
            "Applied recommendation with resource name: '%s'.%s",
            $appliedRecommendation->getResourceName(),
            PHP_EOL
        );
    }
}

ApplyRecommendation::main();

Send feedback about...

Google Ads API Beta
Google Ads API Beta
Need help? Visit our support page.