Java
// Copyright 2020 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. package com.google.ads.googleads.examples.extensions; 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.v15.enums.ExtensionTypeEnum.ExtensionType; import com.google.ads.googleads.v15.errors.GoogleAdsError; import com.google.ads.googleads.v15.errors.GoogleAdsException; import com.google.ads.googleads.v15.services.CampaignExtensionSettingOperation; import com.google.ads.googleads.v15.services.ExtensionFeedItemOperation; import com.google.ads.googleads.v15.services.GoogleAdsRow; import com.google.ads.googleads.v15.services.GoogleAdsServiceClient; import com.google.ads.googleads.v15.services.MutateGoogleAdsResponse; import com.google.ads.googleads.v15.services.MutateOperation; import com.google.ads.googleads.v15.services.MutateOperationResponse; import com.google.ads.googleads.v15.services.SearchGoogleAdsStreamRequest; import com.google.ads.googleads.v15.services.SearchGoogleAdsStreamResponse; import com.google.ads.googleads.v15.utils.ResourceNames; import com.google.api.gax.rpc.ServerStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** * Removes the entire sitelink campaign extension setting by removing both the sitelink campaign * extension setting itself and its associated sitelink extension feed items. This requires two * steps, since removing the campaign extension setting doesn't automatically remove its extension * feed items. * * <p>To make this example work with other types of extensions, find {@link ExtensionType#SITELINK} * and replace it with the extension type you wish to remove. */ public class RemoveEntireSitelinkCampaignExtensionSetting { private static class RemoveEntireSitelinkCampaignExtensionSettingParams extends CodeSampleParams { @Parameter(names = ArgumentNames.CUSTOMER_ID, required = true) private long customerId; @Parameter(names = ArgumentNames.CAMPAIGN_ID, required = true) private long campaignId; } public static void main(String[] args) { RemoveEntireSitelinkCampaignExtensionSettingParams params = new RemoveEntireSitelinkCampaignExtensionSettingParams(); 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"); params.campaignId = Long.parseLong("INSERT_CAMPAIGN_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 RemoveEntireSitelinkCampaignExtensionSetting() .runExample(googleAdsClient, params.customerId, params.campaignId); } 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. */ private void runExample(GoogleAdsClient googleAdsClient, long customerId, long campaignId) { // Retrieves all sitelink extension feed items for a customer and campaign. List<String> extensionFeedItemResourceNames = getSitelinkExtensionFeedItems(googleAdsClient, customerId, campaignId); // Constructs operations to remove the extension feed items. List<MutateOperation> feedItemMutateOperations = extensionFeedItemResourceNames.stream() .map( feedItem -> MutateOperation.newBuilder() .setExtensionFeedItemOperation( ExtensionFeedItemOperation.newBuilder().setRemove(feedItem)) .build()) .collect(Collectors.toList()); // Creates a list of operations that contains both the campaign extension setting and the feed // item operations. List<MutateOperation> allOperations = new ArrayList(); // Adds an operation to remove the campaign extension setting. allOperations.add( MutateOperation.newBuilder() .setCampaignExtensionSettingOperation( CampaignExtensionSettingOperation.newBuilder() .setRemove( ResourceNames.campaignExtensionSetting( customerId, campaignId, ExtensionType.SITELINK)) .build()) .build()); // Adds the operations to remove the feed items. allOperations.addAll(feedItemMutateOperations); // Connects to the API. try (GoogleAdsServiceClient client = googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) { // Issues the request. MutateGoogleAdsResponse response = client.mutate(String.valueOf(customerId), allOperations); // Prints the result of removing the campaign extension setting. // Each mutate operation response is returned in the same order as we passed its // corresponding operation. Therefore, the first belongs to the campaign setting operation, // and the rest belong to the extension feed item operations. System.out.printf( "Removed a campaign extension setting with resource name: '%s'.%n", response .getMutateOperationResponses(0) .getCampaignExtensionSettingResult() .getResourceName()); // Prints the result of removing the extension feed items. for (MutateOperationResponse mutateResponse : response .getMutateOperationResponsesList() .subList(1, response.getMutateOperationResponsesList().size())) { System.out.printf( "Removed an extension feed item with resource name: '%s'.%n", mutateResponse.getExtensionFeedItemResult().getResourceName()); } } } /** Retrieves all sitelink extension feed items for a customer + campaign combination. */ private List<String> getSitelinkExtensionFeedItems( GoogleAdsClient googleAdsClient, long customerId, long campaignId) { // Defines a query to retrieve the sitelink extension feed items. String query = String.format( "SELECT campaign_extension_setting.campaign, " + " campaign_extension_setting.extension_type, " + " campaign_extension_setting.extension_feed_items " + "FROM " + " campaign_extension_setting " + "WHERE " + " campaign_extension_setting.campaign = '%s' " + " AND campaign_extension_setting.extension_type = SITELINK", ResourceNames.campaign(customerId, campaignId)); // Connects to the API. try (GoogleAdsServiceClient client = googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) { // Issues the search request. ServerStream<SearchGoogleAdsStreamResponse> response = client .searchStreamCallable() .call( SearchGoogleAdsStreamRequest.newBuilder() .setCustomerId(String.valueOf(customerId)) .setQuery(query) .build()); // Constructs the result (a list of resource names matching the query). List<String> result = new ArrayList(); for (SearchGoogleAdsStreamResponse page : response) { for (GoogleAdsRow row : page.getResultsList()) { result.addAll(row.getCampaignExtensionSetting().getExtensionFeedItemsList()); } } if (result.isEmpty()) { System.out.println( "The specified campaign does not contain a sitelink campaign extension setting."); } return result; } } }
C#
This example is not yet available in C#; you can take a look at the other languages.
PHP
<?php /** * Copyright 2020 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\Extensions; 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\V15\GoogleAdsClient; use Google\Ads\GoogleAds\Lib\V15\GoogleAdsClientBuilder; use Google\Ads\GoogleAds\Lib\V15\GoogleAdsException; use Google\Ads\GoogleAds\Lib\V15\GoogleAdsServerStreamDecorator; use Google\Ads\GoogleAds\Util\V15\ResourceNames; use Google\Ads\GoogleAds\V15\Enums\ExtensionTypeEnum\ExtensionType; use Google\Ads\GoogleAds\V15\Errors\GoogleAdsError; use Google\Ads\GoogleAds\V15\Services\CampaignExtensionSettingOperation; use Google\Ads\GoogleAds\V15\Services\Client\GoogleAdsServiceClient; use Google\Ads\GoogleAds\V15\Services\ExtensionFeedItemOperation; use Google\Ads\GoogleAds\V15\Services\GoogleAdsRow; use Google\Ads\GoogleAds\V15\Services\MutateGoogleAdsRequest; use Google\Ads\GoogleAds\V15\Services\MutateOperation; use Google\Ads\GoogleAds\V15\Services\SearchGoogleAdsStreamRequest; use Google\ApiCore\ApiException; /** * Removes the entire sitelink campaign extension setting by removing both the sitelink campaign * extension setting itself and its associated sitelink extension feed items. This requires two * steps, since removing the campaign extension setting doesn't automatically remove its extension * feed items. * * To make this example work with other types of extensions, find `ExtensionType::SITELINK` and * replace it with the extension type you wish to remove. */ class RemoveEntireSitelinkCampaignExtensionSetting { private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE'; private const CAMPAIGN_ID = 'INSERT_CAMPAIGN_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, ArgumentNames::CAMPAIGN_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, $options[ArgumentNames::CAMPAIGN_ID] ?: self::CAMPAIGN_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 client customer ID * @param int $campaignId the campaign ID */ public static function runExample( GoogleAdsClient $googleAdsClient, int $customerId, int $campaignId ) { $mutateOperations = []; // Creates a mutate operation that contains the campaign extension setting operation // to remove the specified sitelink campaign extension setting. $mutateOperations[] = self::createSitelinkCampaignExtensionSettingMutateOperation($customerId, $campaignId); // Gets all sitelink extension feed items of the specified campaign. $googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient(); $extensionFeedItemResourceNames = self::getAllSitelinkExtensionFeedItems( $googleAdsServiceClient, $customerId, $campaignId ); // Creates mutate operations, each of which contains an extension feed item operation // to remove the specified extension feed items. $mutateOperations = array_merge( $mutateOperations, self::createExtensionFeedItemMutateOperations($extensionFeedItemResourceNames) ); // Issues a mutate request to remove the campaign extension setting and its extension // feed items. $response = $googleAdsServiceClient->mutate( MutateGoogleAdsRequest::build($customerId, $mutateOperations) ); $mutateOperationResponses = $response->getMutateOperationResponses(); // Prints the information on the removed campaign extension setting and its extension feed // items. // Each mutate operation response is returned in the same order as we passed its // corresponding operation. Therefore, the first belongs to the campaign setting operation, // and the rest belong to the extension feed item operations. printf( "Removed a campaign extension setting with resource name: '%s'.%s", $mutateOperationResponses[0]->getCampaignExtensionSettingResult()->getResourceName(), PHP_EOL ); for ($i = 1; $i < count($mutateOperationResponses); $i++) { printf( "Removed an extension feed item with resource name: '%s'.%s", $mutateOperationResponses[$i]->getExtensionFeedItemResult()->getResourceName(), PHP_EOL ); } } /** * Creates a mutate operation for the sitelink campaign extension setting that will be removed. * * @param int $customerId the client customer ID * @param int $campaignId the campaign ID * @return MutateOperation the created mutate operation for the sitelink campaign extension * setting */ private static function createSitelinkCampaignExtensionSettingMutateOperation( int $customerId, int $campaignId ): MutateOperation { // Creates the resource name of a campaign extension setting to remove. $campaignExtensionSettingResourceName = ResourceNames::forCampaignExtensionSetting( $customerId, $campaignId, ExtensionType::name(ExtensionType::SITELINK) ); // Creates a campaign extension setting operation. $campaignExtensionSettingOperation = new CampaignExtensionSettingOperation(); $campaignExtensionSettingOperation->setRemove($campaignExtensionSettingResourceName); // Creates a mutate operation for the campaign extension setting operation. return new MutateOperation([ 'campaign_extension_setting_operation' => $campaignExtensionSettingOperation]); } /** * Returns all sitelink extension feed items associated to the specified campaign extension * setting. * * @param GoogleAdsServiceClient $googleAdsServiceClient the Google Ads API service client * @param int $customerId the client customer ID * @param int $campaignId the campaign ID to get the sitelink extension feed items from * @return string[] the array of resource names of extension feed items */ private static function getAllSitelinkExtensionFeedItems( GoogleAdsServiceClient $googleAdsServiceClient, int $customerId, int $campaignId ): array { // Creates a query that retrieves all campaigns. $query = sprintf( "SELECT campaign_extension_setting.campaign, " . "campaign_extension_setting.extension_type, " . "campaign_extension_setting.extension_feed_items " . "FROM campaign_extension_setting " . "WHERE campaign_extension_setting.campaign = '%s' " . "AND campaign_extension_setting.extension_type = %s", ResourceNames::forCampaign($customerId, $campaignId), ExtensionType::name(ExtensionType::SITELINK) ); // Issues a search stream request. /** @var GoogleAdsServerStreamDecorator $stream */ $stream = $googleAdsServiceClient->searchStream( SearchGoogleAdsStreamRequest::build($customerId, $query) ); $extensionFeedItemResourceNames = []; // Iterates over all rows in all messages and prints the requested field values for // the campaign extension setting in each row. foreach ($stream->iterateAllElements() as $googleAdsRow) { /** @var GoogleAdsRow $googleAdsRow */ $extensionFeedItems = $googleAdsRow->getCampaignExtensionSetting()->getExtensionFeedItems(); foreach ($extensionFeedItems as $extensionFeedItem) { /** @var string $extensionFeedItem */ $extensionFeedItemResourceNames[] = $extensionFeedItem; printf( "Extension feed item with resource name '%s' was found.%s", $extensionFeedItem, PHP_EOL ); } } if (empty($extensionFeedItemResourceNames)) { throw new \InvalidArgumentException( 'The specified campaign does not contain a sitelink campaign extension setting.' ); } return $extensionFeedItemResourceNames; } /** * Creates mutate operations for the sitelink extension feed items that will be removed. * * @param string[] $extensionFeedItemResourceNames the extension feed item resource names * @return MutateOperation[] the array of created mutate operations for the extension feed items */ private static function createExtensionFeedItemMutateOperations( array $extensionFeedItemResourceNames ): array { $mutateOperations = []; foreach ($extensionFeedItemResourceNames as $extensionFeedItemResourceName) { // Creates an operation to remove the extension feed item. $extensionFeedItemOperation = new ExtensionFeedItemOperation(); $extensionFeedItemOperation->setRemove($extensionFeedItemResourceName); // Creates a mutate operation for each extension feed item operation. $mutateOperations [] = new MutateOperation([ 'extension_feed_item_operation' => $extensionFeedItemOperation ]); } return $mutateOperations; } } RemoveEntireSitelinkCampaignExtensionSetting::main();
Python
#!/usr/bin/env python # Copyright 2020 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. """Removes the entire sitelink campaign extension setting. Removes both the sitelink campaign extension setting itself and its associated sitelink extension feed items. This requires two steps, since removing the campaign extension setting doesn't automatically remove its extension feed items. To make this example work with other types of extensions, replace ExtensionType.SITELINK with the extension type you wish to remove. """ import argparse import sys from google.ads.googleads.client import GoogleAdsClient from google.ads.googleads.errors import GoogleAdsException def main(client, customer_id, campaign_id): """The main method that creates all necessary entities for the example. Args: client: an initialized GoogleAdsClient instance. customer_id: a client customer ID. campaign_id: the campaign ID. """ # Initialize an array of MutateOperations mutate_operations = [] sitelink_campaign_extension_setting_mutate_operation = ( create_sitelink_campaign_extension_setting_mutate_operation( client, customer_id, campaign_id ) ) mutate_operations.append( sitelink_campaign_extension_setting_mutate_operation ) ga_service = client.get_service("GoogleAdsService") extension_feed_item_resource_names = get_all_sitelink_extension_feed_items( client, ga_service, customer_id, campaign_id ) extension_feed_item_mutate_operations = ( create_extension_feed_item_mutate_operations( client, extension_feed_item_resource_names ) ) mutate_operations.extend(extension_feed_item_mutate_operations) # Issue a mutate request to remove the campaign extension setting and # its extension feed items. response = ga_service.mutate( customer_id=customer_id, mutate_operations=mutate_operations ) mutate_operation_responses = response.mutate_operation_responses # The order of response messages corresponds to the order of operations # passed into the mutate method. Since the first operation sent in the # request was to remove a campaign extension setting, we can read the # resource name of that object in the first message in the response list. print( "Removed a campaign extension setting with resource name " f'"{mutate_operation_responses[0].campaign_extension_setting_result.resource_name}".' ) # Since we read the result of the first remove operation above, next we # read the results for the remaining remove operations by iterating over all # but the first message in the response list. for mutate_operation_response in mutate_operation_responses[1:]: print( "Removed an extension feed item with resource name " f'"{mutate_operation_response.extension_feed_item_result.resource_name}".' ) def create_sitelink_campaign_extension_setting_mutate_operation( client, customer_id, campaign_id ): """Creates a MutateOperation for the sitelink campaign extension setting that will be removed. Args: client: an initialized GoogleAdsClient instance customer_id: the client customer ID. campaign_id: the campaign ID. Returns: The created MutateOperation for the sitelink campaign extension setting. """ extension_type_enum = client.enums.ExtensionTypeEnum # Construct the campaign extension setting resource name, in format: # customers/{customer_id}/campaignExtensionSettings/{campaign_id}~{extension_type} resource_name = client.get_service( "CampaignExtensionSettingService" ).campaign_extension_setting_path( customer_id, campaign_id, extension_type_enum.SITELINK.name ) # Create a MutateOperation for the campaign extension setting. mutate_operation = client.get_type("MutateOperation") mutate_operation.campaign_extension_setting_operation.remove = resource_name return mutate_operation def get_all_sitelink_extension_feed_items( client, ga_service, customer_id, campaign_id ): """Gets all sitelink extension feed items associated to the specified campaign extension setting. Args: client: an initialized GoogleAdsClient instance. ga_service: the Google Ads API service client. customer_id: the client customer ID. campaign_id: the ID of the campaign to get the sitelink extension feed items from. Returns: An array of str resource names of extension feed items. """ campaign_resource_name = client.get_service( "CampaignService" ).campaign_path(customer_id, campaign_id) extension_type_enum = client.enums.ExtensionTypeEnum extension_type_name = extension_type_enum.SITELINK.name # Construct the query. query = f""" SELECT campaign_extension_setting.campaign, campaign_extension_setting.extension_type, campaign_extension_setting.extension_feed_items FROM campaign_extension_setting WHERE campaign_extension_setting.campaign = '{campaign_resource_name}' AND campaign_extension_setting.extension_type = '{extension_type_name}'""" # Issue a search request using streaming. stream = ga_service.search_stream(customer_id=customer_id, query=query) extension_feed_item_resource_names = [] # Iterate through each row and append the extension feed item resource # names to the return array. for batch in stream: for row in batch.results: extension_feed_item_resource_names.extend( row.campaign_extension_setting.extension_feed_items ) if len(extension_feed_item_resource_names) == 0: print( "The specified campaign does not contain a sitelink campaign " "extension setting." ) sys.exit(1) return extension_feed_item_resource_names def create_extension_feed_item_mutate_operations( client, extension_feed_item_resource_names ): """Creates MutateOperations for the sitelink extension feed items that will be removed. Args: client: an initialized GoogleAdsClient instance. extension_feed_item_resource_names: the extension feed item resource names. Returns: An array of MutateOperations for the extension feed items. """ mutate_operations = [] # Create a MutateOperation for each extension feed item to remove. for resource_name in extension_feed_item_resource_names: mutate_operation = client.get_type("MutateOperation") mutate_operation.extension_feed_item_operation.remove = resource_name mutate_operations.append(mutate_operation) return mutate_operations 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="v15") parser = argparse.ArgumentParser( description="Removes the entire sitelink campaign extension setting." ) # 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", ) parser.add_argument( "-i", "--campaign_id", type=str, required=True, help="The campaign ID", ) args = parser.parse_args() try: main(googleads_client, args.customer_id, args.campaign_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 2020 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. # # Removes the entire sitelink campaign extension setting by removing both the # sitelink campaign extension setting itself and its associated sitelink # extension feed items. This requires two steps, since removing the campaign # extension setting doesn't automatically remove its extension feed items. # # To make this example work with other types of extensions, find # `ExtensionType::SITELINK` and replace it with the extension type you wish to # remove. require 'optparse' require 'google/ads/google_ads' require 'date' def remove_entire_sitelink_campaign_extension_setting(customer_id, campaign_id) # GoogleAdsClient will read a config file from # ENV['HOME']/google_ads_config.rb when called without parameters client = Google::Ads::GoogleAds::GoogleAdsClient.new mutate_operations = [] # Creates a mutate operation that contains the campaign extension setting # operation to remove the specified sitelink campaign extension setting. mutate_operations << create_sitelink_campaign_extension_setting_mutate_operation( client, customer_id, campaign_id, ) # Gets all sitelink extension feed items of the specified campaign. google_ads_service = client.service.google_ads extension_feed_item_resource_names = get_all_sitelink_extension_feed_items( client, google_ads_service, customer_id, campaign_id, ) # Creates mutate operations, each of which contains an extension feed item # operation to remove the specified extension feed items. mutate_operations += create_extension_feed_item_mutate_operations( client, extension_feed_item_resource_names, ) # Issues a mutate request to remove the campaign extension setting and its # extension feed items. response = google_ads_service.mutate( customer_id: customer_id, mutate_operations: mutate_operations, ) mutate_operation_responses = response.mutate_operation_responses # Prints the information on the removed campaign extension setting and its # extension feed items. # Each mutate operation response is returned in the same order as we passed # its corresponding operation. Therefore, the first belongs to the campaign # setting operation, and the rest belong to the extension feed item operations. puts "Removed a campaign extension setting with resource name: " \ "#{mutate_operation_responses[0].campaign_extension_setting_result.resource_name}" for i in 1..mutate_operation_responses.size - 1 puts "Removed an extension feed item with resource name: " \ "#{mutate_operation_responses[i].extension_feed_item_result.resource_name}" end end # Creates a mutate operation for the sitelink campaign extension setting that # will be removed. def create_sitelink_campaign_extension_setting_mutate_operation( client, customer_id, campaign_id ) # Creates a mutate operation for the campaign extension setting operation. mutate_op = client.operation.mutate mutate_op.campaign_extension_setting_operation = \ client.operation.remove_resource.campaign_extension_setting( client.path.campaign_extension_setting( customer_id, campaign_id, :SITELINK)) mutate_op end # Returns all sitelink extension feed items associated to the specified # campaign extension setting. def get_all_sitelink_extension_feed_items( client, google_ads_service, customer_id, campaign_id ) # Creates a query that retrieves all campaigns. query = <<~QUERY SELECT campaign_extension_setting.campaign, campaign_extension_setting.extension_type, campaign_extension_setting.extension_feed_items FROM campaign_extension_setting WHERE campaign_extension_setting.campaign = '#{client.path.campaign(customer_id, campaign_id)}' AND campaign_extension_setting.extension_type = 'SITELINK' QUERY # Issues a search stream request stream = google_ads_service.search_stream( customer_id: customer_id, query: query, ) extension_feed_item_resource_names = [] # Iterates over all rows in all messages and prints the requested field values # for the campaign extension setting in each row. stream.each do |response| response.results.each do |row| extension_feed_items = row.campaign_extension_setting.extension_feed_items extension_feed_items.each do |item| extension_feed_item_resource_names << item puts "Extension feed item with resource name #{item} was found." end end end extension_feed_item_resource_names end # Creates mutate operations for the sitelink extension feed items that will be # removed. def create_extension_feed_item_mutate_operations( client, extension_feed_item_resource_names ) mutate_operations = [] extension_feed_item_resource_names.each do |resource_name| # Creates a mutate operation to remove the extension feed item. mutate_op = client.operation.mutate mutate_op.extension_feed_item_operation = \ client.operation.remove_resource.extension_feed_item(resource_name) mutate_operations << mutate_op end mutate_operations end if __FILE__ == $0 options = {} # The following parameter(s) should be provided to run the example. You can # either specify these by changing the INSERT_XXX_ID_HERE values below, or on # the command line. # # Parameters passed on the command line will override any parameters set in # code. # # Running the example with -h will print the command line usage. options[:customer_id] = 'INSERT_CUSTOMER_ID_HERE' options[:campaign_id] = 'INSERT_CAMPAIGN_ID_HERE' 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.on('-c', '--campaign-id CAMPAIGN-ID', String, 'Campaign ID') do |v| options[:campaign_id] = v end opts.separator '' opts.separator 'Help:' opts.on_tail('-h', '--help', 'Show this message') do puts opts exit end end.parse! begin remove_entire_sitelink_campaign_extension_setting( options.fetch(:customer_id).tr("-", ""), options.fetch(:campaign_id), ) 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 2020, 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. # # Removes the entire sitelink campaign extension setting by removing both the # sitelink campaign extension setting itself and its associated sitelink # extension feed items. This requires two steps, since removing the campaign # extension setting doesn't automatically remove its extension feed items. # # To make this example work with other types of extensions, find references to # 'SITELINK' and replace it with the extension type you wish to remove. 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::V15::Enums::ExtensionTypeEnum qw(SITELINK); use Google::Ads::GoogleAds::V15::Services::CampaignExtensionSettingService::CampaignExtensionSettingOperation; use Google::Ads::GoogleAds::V15::Services::ExtensionFeedItemService::ExtensionFeedItemOperation; use Google::Ads::GoogleAds::V15::Services::GoogleAdsService::MutateOperation; use Google::Ads::GoogleAds::V15::Services::GoogleAdsService::SearchGoogleAdsStreamRequest; use Google::Ads::GoogleAds::V15::Utils::ResourceNames; use Getopt::Long qw(:config auto_help); use Pod::Usage; use Cwd qw(abs_path); # The following parameter(s) should be provided to run the example. You can # either specify these by changing the INSERT_XXX_ID_HERE values below, or on # the command line. # # Parameters passed on the command line will override any parameters set in # code. # # Running the example with -h will print the command line usage. my $customer_id = "INSERT_CUSTOMER_ID_HERE"; my $campaign_id = "INSERT_CAMPAIGN_ID_HERE"; sub remove_entire_sitelink_campaign_extension_setting { my ($api_client, $customer_id, $campaign_id) = @_; my $mutate_operations = []; # Create a mutate operation that contains the campaign extension setting operation # to remove the specified sitelink campaign extension setting. push( @$mutate_operations, create_sitelink_campaign_extension_setting_mutate_operation( $customer_id, $campaign_id )); # Get all sitelink extension feed items of the specified campaign. my $extension_feed_item_resource_names = get_all_sitelink_extension_feed_items($api_client, $customer_id, $campaign_id); # Create mutate operations, each of which contains an extension feed item operation # to remove the specified extension feed items. push( @$mutate_operations, create_extension_feed_item_mutate_operations( $extension_feed_item_resource_names)); # Issue a mutate request to remove the campaign extension setting and its # extension feed items. my $mutate_google_ads_response = $api_client->GoogleAdsService()->mutate({ customerId => $customer_id, mutateOperations => $mutate_operations }); my $mutate_operation_responses = $mutate_google_ads_response->{mutateOperationResponses}; # Print the information on the removed campaign extension setting and its # extension feed items. # Each mutate operation response is returned in the same order as we passed # its corresponding operation. Therefore, the first belongs to the campaign # setting operation, and the rest belong to the extension feed item operations. printf "Removed a campaign extension setting with resource name '%s'.\n", @$mutate_operation_responses[0] ->{campaignExtensionSettingResult}{resourceName}; shift(@$mutate_operation_responses); foreach my $response (@$mutate_operation_responses) { printf "Removed an extension feed item with resource name '%s'.\n", $response->{extensionFeedItemResult}{resourceName}; } return 1; } # Creates a mutate operation for the sitelink campaign extension setting that # will be removed. sub create_sitelink_campaign_extension_setting_mutate_operation { my ($customer_id, $campaign_id) = @_; # Construct the resource name of the campaign extension setting to remove. my $campaign_extension_setting_resource_name = Google::Ads::GoogleAds::V15::Utils::ResourceNames::campaign_extension_setting( $customer_id, $campaign_id, SITELINK); # Create a campaign extension setting operation. my $campaign_extension_setting_operation = Google::Ads::GoogleAds::V15::Services::CampaignExtensionSettingService::CampaignExtensionSettingOperation ->new({ remove => $campaign_extension_setting_resource_name }); # Create and return a mutate operation for the campaign extension setting # operation. return Google::Ads::GoogleAds::V15::Services::GoogleAdsService::MutateOperation-> new({ campaignExtensionSettingOperation => $campaign_extension_setting_operation }); } # Return all sitelink extension feed items associated to the specified campaign # extension setting. sub get_all_sitelink_extension_feed_items { my ($api_client, $customer_id, $campaign_id) = @_; my $extension_feed_item_resource_names = []; # Issue a search stream request, then iterate over all responses. my $search_stream_request = Google::Ads::GoogleAds::V15::Services::GoogleAdsService::SearchGoogleAdsStreamRequest ->new({ customerId => $customer_id, query => sprintf( "SELECT campaign_extension_setting.campaign, " . "campaign_extension_setting.extension_type, " . "campaign_extension_setting.extension_feed_items " . "FROM campaign_extension_setting " . "WHERE campaign_extension_setting.campaign = '%s' " . "AND campaign_extension_setting.extension_type = 'SITELINK'", Google::Ads::GoogleAds::V15::Utils::ResourceNames::campaign( $customer_id, $campaign_id ))}); my $search_stream_handler = Google::Ads::GoogleAds::Utils::SearchStreamHandler->new({ service => $api_client->GoogleAdsService(), request => $search_stream_request }); # Print out and store in a list each extension feed item's resource name. $search_stream_handler->process_contents( sub { # Display the results and add the resource names to the list. my $google_ads_row = shift; foreach my $extension_feed_item_resource_name ( @{$google_ads_row->{campaignExtensionSetting}{extensionFeedItems}}) { push(@$extension_feed_item_resource_names, $extension_feed_item_resource_name); printf "Extension feed item with resource name '%s' was found.\n", $extension_feed_item_resource_name; } }); if (!@$extension_feed_item_resource_names) { die("The specified campaign does not contain a sitelink campaign " . "extension setting.\n"); } return $extension_feed_item_resource_names; } # Creates mutate operations for the sitelink extension feed items that will be # removed. sub create_extension_feed_item_mutate_operations { my ($extension_feed_item_resource_names) = @_; my $operations = []; foreach my $extension_feed_item_resource_name (@$extension_feed_item_resource_names) { my $operation = Google::Ads::GoogleAds::V15::Services::ExtensionFeedItemService::ExtensionFeedItemOperation ->new({ remove => $extension_feed_item_resource_name }); push( @$operations, Google::Ads::GoogleAds::V15::Services::GoogleAdsService::MutateOperation ->new({ extensionFeedItemOperation => $operation })); } return $operations; } # 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, "campaign_id=i" => \$campaign_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, $campaign_id); # Call the example. remove_entire_sitelink_campaign_extension_setting($api_client, $customer_id =~ s/-//gr, $campaign_id); =pod =head1 NAME remove_entire_sitelink_campaign_extension_setting =head1 DESCRIPTION Removes the entire sitelink campaign extension setting by removing both the sitelink campaign extension setting itself and its associated sitelink extension feed items. This requires two steps, since removing the campaign extension setting doesn't automatically remove its extension feed items. To make this example work with other types of extensions, find references to 'SITELINK' and replace it with the extension type you wish to remove. =head1 SYNOPSIS remove_entire_sitelink_campaign_extension_setting.pl [options] -help Show the help message. -customer_id The Google Ads customer ID. -campaign_id ID of the campaign from which sitelinks will be removed. =cut