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.v21.common.KeywordInfo 
 ; 
 import 
  
 com.google.ads.googleads.v21.errors.GoogleAdsError 
 ; 
 import 
  
 com.google.ads.googleads.v21.errors.GoogleAdsException 
 ; 
 import 
  
 com.google.ads.googleads.v21.resources.Recommendation 
 ; 
 import 
  
 com.google.ads.googleads.v21.services.ApplyRecommendationOperation 
 ; 
 import 
  
 com.google.ads.googleads.v21.services.ApplyRecommendationOperation.Builder 
 ; 
 import 
  
 com.google.ads.googleads.v21.services.ApplyRecommendationResponse 
 ; 
 import 
  
 com.google.ads.googleads.v21.services.ApplyRecommendationResult 
 ; 
 import 
  
 com.google.ads.googleads.v21.services.GoogleAdsRow 
 ; 
 import 
  
 com.google.ads.googleads.v21.services.GoogleAdsServiceClient 
 ; 
 import 
  
 com.google.ads.googleads.v21.services.RecommendationServiceClient 
 ; 
 import 
  
 com.google.ads.googleads.v21.services.SearchGoogleAdsStreamRequest 
 ; 
 import 
  
 com.google.ads.googleads.v21.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>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>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.V21.Common 
 ; 
 using 
  
 Google.Ads.GoogleAds.V21.Resources 
 ; 
 using 
  
 Google.Ads.GoogleAds.V21.Errors 
 ; 
 using 
  
 Google.Ads.GoogleAds.V21.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.V21 
 { 
  
 /// <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 
 . 
 V21 
 . 
 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 
 ( 
  
 BuildApplyRecommendationOperation 
 ( 
 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 
 ; 
  
 } 
  
 } 
  
 private 
  
 ApplyRecommendationOperation 
  
 BuildApplyRecommendationOperation 
 ( 
  
 string 
  
 recommendationResourceName 
  
 ) 
  
 { 
  
 // 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) 
  
 // 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/latest/ApplyRecommendationOperation. 
  
 /* 
 Ad overridingAd = new Ad() 
 { 
 Id = "INSERT_AD_ID_AS_LONG_HERE" 
 }; 
 applyRecommendationOperation.TextAd = new TextAdParameters() 
 { 
 Ad = overridingAd 
 }; 
 */ 
  
 ApplyRecommendationOperation 
  
 applyRecommendationOperation 
  
 = 
  
 new 
  
 ApplyRecommendationOperation 
 () 
  
 { 
  
 ResourceName 
  
 = 
  
 recommendationResourceName 
  
 }; 
  
 return 
  
 applyRecommendationOperation 
 ; 
  
 } 
  
 /// <summary> 
  
 /// Applies a list of recommendations. 
  
 /// </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 
 . 
 V21 
 . 
 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\OAuth2TokenBuilder; 
 use Google\Ads\GoogleAds\Lib\V21\GoogleAdsClient; 
 use Google\Ads\GoogleAds\Lib\V21\GoogleAdsClientBuilder; 
 use Google\Ads\GoogleAds\Lib\V21\GoogleAdsException; 
 use Google\Ads\GoogleAds\V21\Enums\KeywordMatchTypeEnum\KeywordMatchType; 
 use Google\Ads\GoogleAds\V21\Errors\GoogleAdsError; 
 use Google\Ads\GoogleAds\V21\Resources\Recommendation; 
 use Google\Ads\GoogleAds\V21\Services\ApplyRecommendationOperation; 
 use Google\Ads\GoogleAds\V21\Services\ApplyRecommendationRequest; 
 use Google\Ads\GoogleAds\V21\Services\GoogleAdsRow; 
 use Google\Ads\GoogleAds\V21\Services\SearchGoogleAdsRequest; 
 use Google\ApiCore\ApiException; 
 /** 
 * 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 
 * 
 * You 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 
 * 
 * You can also 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. 
 */ 
 class DetectAndApplyRecommendations 
 { 
 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) 
 { 
 $googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient(); 
 // Creates a query that retrieves keyword recommendations. 
 $query = 'SELECT recommendation.resource_name, recommendation.campaign, ' 
 . 'recommendation.keyword_recommendation ' 
 . 'FROM recommendation ' 
 . 'WHERE recommendation.type = KEYWORD '; 
 // Issues a search request to detect keyword recommendations that exist for the 
 // customer account. 
 $response = 
 $googleAdsServiceClient->search(SearchGoogleAdsRequest::build($customerId, $query)); 
 $operations = []; 
 // 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( 
 "Keyword recommendation with resource name '%s' was found for campaign " 
 . "with resource name '%s':%s", 
 $recommendation->getResourceName(), 
 $recommendation->getCampaign(), 
 PHP_EOL 
 ); 
 if (!is_null($recommendation->getKeywordRecommendation())) { 
 $keyword = $recommendation->getKeywordRecommendation()->getKeyword(); 
 printf( 
 "\tKeyword = '%s'%s\ttype = '%s'%s", 
 $keyword->getText(), 
 PHP_EOL, 
 KeywordMatchType::name($keyword->getMatchType()), 
 PHP_EOL 
 ); 
 } 
 // Creates an ApplyRecommendationOperation that will be used to apply this 
 // recommendation, and adds it to the list of operations. 
 $operations[] = self::buildRecommendationOperation($recommendation->getResourceName()); 
 } 
 // If there are operations present, send a request to apply the recommendations. 
 if (empty($operations)) { 
 print 'No recommendations found.' . PHP_EOL; 
 } else { 
 self::applyRecommendations($googleAdsClient, $customerId, $operations); 
 } 
 } 
 /** 
 * Creates a ApplyRecommendationOperation to apply the given recommendation. 
 * 
 * @param string $recommendationResourceName the resource name of the recommendation to apply 
 * @return ApplyRecommendationOperation the created ApplyRecommendationOperation 
 */ 
 private static function buildRecommendationOperation( 
 string $recommendationResourceName 
 ): ApplyRecommendationOperation { 
 // If you have a recommendation_id instead of the resource name, you can create a resource 
 // name from it like this: 
 /* 
 $recommendationResourceName = 
 ResourceNames::forRecommendation($customerId, $recommendationId); 
 */ 
 // 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/latest/ApplyRecommendationOperation. 
 /* 
 $overridingAd = new Ad([ 
 'id' => 'INSERT_AD_ID_AS_INTEGER_HERE' 
 ]); 
 $applyRecommendationOperation->setTextAd(new TextAdParameters(['ad' => $overridingAd])); 
 */ 
 // Issues a mutate request to apply the recommendation. 
 $applyRecommendationOperation = new ApplyRecommendationOperation(); 
 $applyRecommendationOperation->setResourceName($recommendationResourceName); 
 return $applyRecommendationOperation; 
 } 
 /** 
 * Applies a batch of recommendations. 
 * 
 * @param GoogleAdsClient $googleAdsClient the Google Ads API client 
 * @param int $customerId the customer ID 
 * @param array $operations the list of ApplyRecommendationOperation to be sent 
 */ 
 private static function applyRecommendations( 
 GoogleAdsClient $googleAdsClient, 
 int $customerId, 
 array $operations 
 ): void { 
 // Issues a mutate request to apply the recommendations. 
 $recommendationServiceClient = $googleAdsClient->getRecommendationServiceClient(); 
 $response = $recommendationServiceClient->applyRecommendation( 
 ApplyRecommendationRequest::build($customerId, $operations) 
 ); 
 foreach ($response->getResults() as $appliedRecommendation) { 
 /** @var Recommendation $appliedRecommendation */ 
 printf( 
 "Applied a recommendation with resource name: '%s'.%s", 
 $appliedRecommendation->getResourceName(), 
 PHP_EOL 
 ); 
 } 
 } 
 } 
 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 
  
 typing 
  
 import 
 List 
 , 
 Iterable 
 from 
  
 google.ads.googleads.client 
  
 import 
 GoogleAdsClient 
 from 
  
 google.ads.googleads.errors 
  
 import 
 GoogleAdsException 
 from 
  
 google.ads.googleads.v21.services.types.google_ads_service 
  
 import 
 ( 
 GoogleAdsRow 
 , 
 ) 
 from 
  
 google.ads.googleads.v21.services.types.recommendation_service 
  
 import 
 ( 
 ApplyRecommendationOperation 
 , 
 ApplyRecommendationResult 
 , 
 ) 
 def 
  
 main 
 ( 
 client 
 : 
 GoogleAdsClient 
 , 
 customer_id 
 : 
 str 
 ) 
 - 
> None 
 : 
  
 """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 
 : 
 GoogleAdsClient 
 , 
 customer_id 
 : 
 str 
 ) 
 - 
> None 
 : 
  
 """Detects recommendations and applies them. 
 Args: 
 client: an initialized GoogleAdsClient instance. 
 customer_id: a client customer ID. 
 """ 
 googleads_service 
 = 
 client 
 . 
 get_service 
 ( 
 "GoogleAdsService" 
 ) 
 query 
 : 
 str 
 = 
 """ 
 SELECT 
 recommendation.campaign, 
 recommendation.keyword_recommendation 
 FROM recommendation 
 WHERE 
 recommendation.type = KEYWORD""" 
 # Detects keyword recommendations that exist for the customer account. 
 response 
 : 
 Iterable 
 [ 
 GoogleAdsRow 
 ] 
 = 
 googleads_service 
 . 
 search 
 ( 
 customer_id 
 = 
 customer_id 
 , 
 query 
 = 
 query 
 ) 
 operations 
 : 
 List 
 [ 
 ApplyRecommendationOperation 
 ] 
 = 
 [] 
 for 
 row 
 in 
 response 
 : 
 recommendation 
 = 
 row 
 . 
 recommendation 
 print 
 ( 
 f 
 "Keyword recommendation (' 
 { 
 recommendation 
 . 
 resource_name 
 } 
 ') " 
 f 
 "was found for campaign ' 
 { 
 recommendation 
 . 
 campaign 
 } 
 ." 
 ) 
 keyword 
 = 
 recommendation 
 . 
 keyword_recommendation 
 . 
 keyword 
 print 
 ( 
 f 
 " 
 \t 
 Keyword = ' 
 { 
 keyword 
 . 
 text 
 } 
 ' 
 \n 
 " 
 f 
 " 
 \t 
 Type = ' 
 { 
 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 
 : 
 GoogleAdsClient 
 , 
 recommendation 
 : 
 str 
 ) 
 - 
> ApplyRecommendationOperation 
 : 
  
 """Creates a ApplyRecommendationOperation to apply the given recommendation. 
 Args: 
 client: an initialized GoogleAdsClient instance. 
 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 
 : 
 ApplyRecommendationOperation 
 = 
 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 
 : 
 GoogleAdsClient 
 , 
 customer_id 
 : 
 str 
 , 
 operations 
 : 
 List 
 [ 
 ApplyRecommendationOperation 
 ], 
 ) 
 - 
> None 
 : 
  
 """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 
 : 
 ApplyRecommendationResult 
 = 
 ( 
 recommendation_service 
 . 
 apply_recommendation 
 ( 
 customer_id 
 = 
 customer_id 
 , 
 operations 
 = 
 operations 
 ) 
 ) 
 for 
 result 
 in 
 response 
 . 
 results 
 : 
 print 
 ( 
 "Applied a recommendation with resource name: " 
 f 
 "' 
 { 
 result 
 . 
 resource_name 
 } 
 '." 
 ) 
 if 
 __name__ 
 == 
 "__main__" 
 : 
 parser 
 : 
 argparse 
 . 
 ArgumentParser 
 = 
 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 
 : 
 argparse 
 . 
 Namespace 
 = 
 parser 
 . 
 parse_args 
 () 
 # GoogleAdsClient will read the google-ads.yaml configuration file in the 
 # home directory if none is specified. 
 googleads_client 
 : 
 GoogleAdsClient 
 = 
 GoogleAdsClient 
 . 
 load_from_storage 
 ( 
 version 
 = 
 "v21" 
 ) 
 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 
 ' 
 \t 
 Error with message " 
 { 
 error 
 . 
 message 
 } 
 ".' 
 ) 
 if 
 error 
 . 
 location 
 : 
 for 
 field_path_element 
 in 
 error 
 . 
 location 
 . 
 field_path_elements 
 : 
 print 
 ( 
 f 
 " 
 \t\t 
 On 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. 
 # 
 # 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 
 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 
 , 
  
 recommendation 
 . 
 campaign 
 , 
  
 recommendation 
 . 
 keyword_recommendation 
  
 FROM 
  
 recommendation 
  
 WHERE 
  
 recommendation 
 . 
 type 
  
 = 
  
 KEYWORD 
  
 QUERY 
  
 google_ads_service 
  
 = 
  
 client 
 . 
 service 
 . 
 google_ads 
  
 response 
  
 = 
  
 google_ads_service 
 . 
 search 
 ( 
  
 customer_id 
 : 
  
 customer_id 
 , 
  
 query 
 : 
  
 query 
 , 
  
 ) 
  
 operations 
  
 = 
  
 response 
 . 
 each 
  
 do 
  
 | 
 row 
 | 
  
 recommendation 
  
 = 
  
 row 
 . 
 recommendation 
  
 puts 
  
 "Keyword recommendation (' 
 #{ 
 recommendation 
 . 
 resource_name 
 } 
 ') was found for " 
 \ 
  
 "campaign ' 
 #{ 
 recommendation 
 . 
 campaign 
 } 
 '." 
  
 if 
  
 recommendation 
 . 
 keyword_recommendation 
  
 keyword 
  
 = 
  
 recommendation 
 . 
 keyword_recommendation 
 . 
 keyword 
  
 puts 
  
 " 
 \t 
 Keyword = ' 
 #{ 
 keyword 
 . 
 text 
 } 
 '" 
  
 puts 
  
 " 
 \t 
 type = ' 
 #{ 
 keyword 
 . 
 match_type 
 } 
 '" 
  
 end 
  
 build_recommendation_operation 
 ( 
 client 
 , 
  
 recommendation 
 . 
 resource_name 
 ) 
  
 end 
  
 if 
  
 operations 
  
 apply_recommendations 
 ( 
 client 
 , 
  
 customer_id 
 , 
  
 recommendation 
 . 
 resource_name 
 ) 
  
 end 
 end 
 def 
  
 build_recommendation_operation 
 ( 
 client 
 , 
  
 recommendation 
 ) 
  
 # If you have a recommendation_id instead of the resource_name 
  
 # you can create a resource name from it like this: 
  
 # recommendation_resource = 
  
 #    client.path.recommendation(customer_id, recommendation_id) 
  
 operations 
  
 = 
  
 client 
 . 
 operation 
 . 
 apply_recommendation 
  
 operations 
 . 
 resource_name 
  
 = 
  
 recommendation_resource 
  
 # 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. 
  
 # 
  
 # text_ad_parameters = client.resource.text_ad_parameters do |tap| 
  
 #   tap.ad = client.resource.ad do |ad| 
  
 #     ad.id = "INSERT_AD_ID_AS_INTEGER_HERE" 
  
 #   end 
  
 # end 
  
 # operation.text_ad = text_ad_parameters 
  
 # 
  
 # For more details, see: 
  
 # https://developers.google.com/google-ads/api/reference/rpc/latest/ApplyRecommendationOperation#apply_parameters 
  
 return 
  
 operation 
 end 
 def 
  
 apply_recommendations 
 ( 
 client 
 , 
  
 customer_id 
 , 
  
 operations 
 ) 
  
 # Issues a mutate request to apply the recommendation. 
  
 recommendation_service 
  
 = 
  
 client 
 . 
 service 
 . 
 recommendation 
  
 response 
  
 = 
  
 recommendation_service 
 . 
 apply_recommendation 
 ( 
  
 customer_id 
 : 
  
 customer_id 
 , 
  
 operations 
 : 
  
 [ 
 operations 
 ] 
 , 
  
 ) 
  
 response 
 . 
 results 
 . 
 each 
  
 do 
  
 | 
 applied_recommendation 
 | 
  
 puts 
  
 "Applied recommendation with resource name: ' 
 #{ 
 applied_recommendation 
 . 
 resource_name 
 } 
 '." 
  
 end 
 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. 
  
 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 
 ( 
 " 
 \t 
 On 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 
 ( 
 " 
 \t 
 Type: %s 
 \n\t 
 Code: %s 
 \n 
 " 
 , 
  
 k 
 , 
  
 v 
 ) 
  
 end 
  
 end 
  
 raise 
  
 end 
 end 
  
  

Perl

 #!/usr/bin/perl -w 
 # 
 # Copyright 2024, 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 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 
 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::V21::Services::RecommendationService::ApplyRecommendationOperation 
 ; 
 use 
  
 Google::Ads::GoogleAds::V21::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 
 ; 
 sub 
  
 detect_and_apply_recommendations 
  
 { 
  
 my 
  
 ( 
 $api_client 
 , 
  
 $customer_id 
 ) 
  
 = 
  
 @_ 
 ; 
  
 # Create the search query. 
  
 my 
  
 $search_query 
  
 = 
  
 "SELECT recommendation.resource_name, " 
  
 . 
  
 "recommendation.campaign, recommendation.keyword_recommendation " 
  
 . 
  
 "FROM recommendation " 
  
 . 
  
 "WHERE recommendation.type = KEYWORD" 
 ; 
  
 # Get the GoogleAdsService. 
  
 my 
  
 $google_ads_service 
  
 = 
  
 $api_client 
 - 
> GoogleAdsService 
 (); 
  
 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 
 ; 
  
 my 
  
 $recommendation 
  
 = 
  
 $google_ads_row 
 - 
> { 
 recommendation 
 }; 
  
 printf 
  
 "Keyword recommendation '%s' was found for campaign '%s'.\n" 
 , 
  
 $recommendation 
 - 
> { 
 resourceName 
 }, 
  
 $recommendation 
 - 
> { 
 campaign 
 }; 
  
 my 
  
 $keyword 
  
 = 
  
 $recommendation 
 - 
> { 
 keywordRecommendation 
 }{ 
 keyword 
 }; 
  
 printf 
  
 "\tKeyword = '%s'\n" 
 , 
  
 $keyword 
 - 
> { 
 text 
 }; 
  
 printf 
  
 "\tMatch type = '%s'\n" 
 , 
  
 $keyword 
 - 
> { 
 matchType 
 }; 
  
 # Creates an ApplyRecommendationOperation that will apply this recommendation, and adds 
  
 # it to the list of operations. 
  
 push 
  
 @$apply_recommendation_operations 
 , 
  
 build_recommendation_operation 
 ( 
 $recommendation 
 ); 
  
 }); 
  
 if 
  
 ( 
 ! 
 defined 
  
 $apply_recommendation_operations 
 ) 
  
 { 
  
 print 
  
 "No recommendations found.\n" 
 ; 
  
 } 
  
 else 
  
 { 
  
 # Issue a mutate request to apply the recommendations. 
  
 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 
 }; 
  
 } 
  
 } 
  
 return 
  
 1 
 ; 
 } 
 sub 
  
 build_recommendation_operation 
  
 { 
  
 my 
  
 ( 
 $recommendation 
 ) 
  
 = 
  
 @_ 
 ; 
  
 # If you have a recommendation ID instead of a resource name, you can create a resource 
  
 # name like this: 
  
 # my $recommendation_resource_name = 
  
 #   Google::Ads::GoogleAds::V21::Utils::ResourceNames::recommendation( 
  
 #   $customer_id, $recommendation_id); 
  
 # 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. 
  
 # my $overriding_ad = Google::Ads::GoogleAds::V21::Resources::Ad->new({ 
  
 #   id => "INSERT_AD_ID_AS_INTEGER_HERE" 
  
 # }); 
  
 # my $text_ad_parameters = 
  
 #   Google::Ads::GoogleAds::V21::Services::RecommendationService::TextAdParameters 
  
 #   ->new({ad => $overriding_ad}); 
  
 # $apply_recommendation_operation->{textAd} = $text_ad_parameters; 
  
 # Create an apply recommendation operation. 
  
 my 
  
 $apply_recommendation_operation 
  
 = 
  
 Google::Ads::GoogleAds::V21::Services::RecommendationService:: 
 ApplyRecommendationOperation 
  
 - 
> new 
 ({ 
  
 resourceName 
  
 = 
>  
 $recommendation 
 - 
> { 
 resourceName 
 }}); 
  
 return 
  
 $apply_recommendation_operation 
 ; 
 } 
 # 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/-//g 
 r 
 ); 
 =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 
  
  

curl

 # 
Copyright  
 2025 
  
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. # 
Gets  
keyword  
recommendations. # 
 # 
Variables: # 
API_VERSION, # 
CUSTOMER_ID, # 
DEVELOPER_TOKEN, # 
MANAGER_CUSTOMER_ID, # 
OAUTH2_ACCESS_TOKEN: # 
See  
https://developers.google.com/google-ads/api/rest/auth#request_headers # 
 for 
  
details. curl -f --request POST \ 
 "https://googleads.googleapis.com/v${API_VERSION}/customers/${CUSTOMER_ID}/googleAds:search" \ 
 --header "Content-Type: application/json" \ 
 --header "developer-token: ${DEVELOPER_TOKEN}" \ 
 --header "login-customer-id: ${MANAGER_CUSTOMER_ID}" \ 
 --header "Authorization: Bearer ${OAUTH2_ACCESS_TOKEN}" \ 
 --data @- <<EOF 
 { 
 "query": " 
 SELECT 
 recommendation.campaign, 
 recommendation.keyword_recommendation 
 FROM recommendation 
 WHERE 
 recommendation.type = KEYWORD 
 " 
 } 
 EOF 
 # 
Applies  
a  
recommendation. # 
 # 
Variables: # 
API_VERSION, # 
CUSTOMER_ID, # 
DEVELOPER_TOKEN, # 
MANAGER_CUSTOMER_ID, # 
OAUTH2_ACCESS_TOKEN: # 
See  
https://developers.google.com/google-ads/api/rest/auth#request_headers # 
 for 
  
details. # 
 # 
RECOMMENDATION_RESOURCE_NAME:  
The  
resource  
name  
of  
the  
recommendation  
to # 
apply,  
from  
the  
previous  
request. curl -f --request POST \ 
 "https://googleads.googleapis.com/v${API_VERSION}/customers/${CUSTOMER_ID}/recommendations:apply" \ 
 --header "Content-Type: application/json" \ 
 --header "developer-token: ${DEVELOPER_TOKEN}" \ 
 --header "login-customer-id: ${MANAGER_CUSTOMER_ID}" \ 
 --header "Authorization: Bearer ${OAUTH2_ACCESS_TOKEN}" \ 
 --data @- <<EOF 
 { 
 "operations": [ 
 { 
 "resourceName": "${RECOMMENDATION_RESOURCE_NAME}" 
 } 
 ] 
 } 
 EOF  
 
Design a Mobile Site
View Site in Mobile | Classic
Share by: