4384978714615885469

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
//
//     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.campaignmanagement;

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.v10.common.ExpandedTextAdInfo;
import com.google.ads.googleads.v10.common.PolicyTopicEntry;
import com.google.ads.googleads.v10.enums.AdGroupAdStatusEnum.AdGroupAdStatus;
import com.google.ads.googleads.v10.errors.GoogleAdsError;
import com.google.ads.googleads.v10.errors.GoogleAdsException;
import com.google.ads.googleads.v10.errors.PolicyFindingErrorEnum.PolicyFindingError;
import com.google.ads.googleads.v10.resources.Ad;
import com.google.ads.googleads.v10.resources.AdGroupAd;
import com.google.ads.googleads.v10.services.AdGroupAdOperation;
import com.google.ads.googleads.v10.services.AdGroupAdServiceClient;
import com.google.ads.googleads.v10.services.MutateAdGroupAdsRequest;
import com.google.ads.googleads.v10.services.MutateAdGroupAdsResponse;
import com.google.ads.googleads.v10.utils.ResourceNames;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Shows how to use the validateOnly header to validate an expanded text ad. No ads will be created,
 * but exceptions will still be thrown.
 */
public class ValidateTextAd {

  private static class ValidateTextAdParams extends CodeSampleParams {

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

    @Parameter(names = ArgumentNames.AD_GROUP_ID, required = true)
    private Long adGroupId;
  }

  public static void main(String[] args) {
    ValidateTextAdParams params = new ValidateTextAdParams();
    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.adGroupId = Long.parseLong("INSERT_AD_GROUP_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 ValidateTextAd().runExample(googleAdsClient, params.customerId, params.adGroupId);
    } 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.
   * @param adGroupId the ad group ID.
   * @throws GoogleAdsException if an API request failed with one or more service errors.
   */
  private void runExample(GoogleAdsClient googleAdsClient, long customerId, long adGroupId) {
    String adGroupResourceName = ResourceNames.adGroup(customerId, adGroupId);

    // Creates the expanded text ad info.
    ExpandedTextAdInfo expandedTextAdInfo =
        ExpandedTextAdInfo.newBuilder()
            .setDescription("Luxury Cruise to Mars")
            .setHeadlinePart1("Visit the Red Planet in style")
            // Adds a headline that will trigger a policy violation to demonstrate error handling.
            .setHeadlinePart2("Low-gravity fun for everyone!!")
            .build();

    // Wraps the info in an Ad object.
    Ad ad =
        Ad.newBuilder()
            .setExpandedTextAd(expandedTextAdInfo)
            .addFinalUrls("http://www.example.com")
            .build();

    // Builds the final ad group ad representation.
    AdGroupAd adGroupAd =
        AdGroupAd.newBuilder()
            .setAdGroup(adGroupResourceName)
            .setStatus(AdGroupAdStatus.PAUSED)
            .setAd(ad)
            .build();

    AdGroupAdOperation operation = AdGroupAdOperation.newBuilder().setCreate(adGroupAd).build();

    try (AdGroupAdServiceClient adGroupAdServiceClient =
        googleAdsClient.getLatestVersion().createAdGroupAdServiceClient()) {
      // Issues the mutate request setting validateOnly=true.
      MutateAdGroupAdsResponse response =
          adGroupAdServiceClient.mutateAdGroupAds(
              MutateAdGroupAdsRequest.newBuilder()
                  .setCustomerId(String.valueOf(customerId))
                  .setCustomerId(Long.toString(customerId))
                  .addOperations(operation)
                  .setValidateOnly(true)
                  .build());
      // Since validation is ON, result will be null.
      System.out.println("Expanded text ad validated successfully.");
    } catch (GoogleAdsException e) {
      // This block will be hit if there is a validation error from the server.
      System.out.println("There were validation error(s) while adding expanded text ad.");

      if (e.getGoogleAdsFailure() != null) {
        // Note: Policy violation errors are returned as PolicyFindingErrors. See
        // https://developers.google.com/google-ads/api/docs/policy-exemption/overview
        // for additional details.
        List<GoogleAdsError> policyFindingErrors =
            e.getGoogleAdsFailure().getErrorsList().stream()
                .filter(
                    err ->
                        err.getErrorCode().getPolicyFindingError()
                            == PolicyFindingError.POLICY_FINDING)
                .collect(Collectors.toList());
        int count = 1;
        for (GoogleAdsError policyFindingError : policyFindingErrors) {
          if (policyFindingError.getDetails().hasPolicyFindingDetails()) {
            List<PolicyTopicEntry> policyTopicEntries =
                policyFindingError
                    .getDetails()
                    .getPolicyFindingDetails()
                    .getPolicyTopicEntriesList();
            for (PolicyTopicEntry policyTopicEntry : policyTopicEntries) {
              System.out.printf(
                  "%d Policy topic entry with topic '%s' and type '%s' was found.%n",
                  count, policyTopicEntry.getTopic(), policyTopicEntry.getType());
            }
            count++;
          }
        }
      }
    } catch (Exception e) {
      System.out.printf("Failure: Message '%s'.%n", e.getMessage());
      System.exit(1);
    }
  }
}

      

C#

// 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.

using CommandLine;
using Google.Ads.Gax.Examples;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V10.Common;
using Google.Ads.GoogleAds.V10.Errors;
using Google.Ads.GoogleAds.V10.Resources;
using Google.Ads.GoogleAds.V10.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using static Google.Ads.GoogleAds.V10.Enums.AdGroupAdStatusEnum.Types;
using static Google.Ads.GoogleAds.V10.Errors.PolicyFindingErrorEnum.Types;

namespace Google.Ads.GoogleAds.Examples.V10
{
    /// <summary>
    /// This code example shows how to use the validateOnly header to validate an expanded text ad.
    /// No objects will be created, but exceptions will still be thrown.
    /// </summary>
    public class ValidateTextAd : ExampleBase
    {
        /// <summary>
        /// Command line options for running the <see cref="ValidateTextAd"/> example.
        /// </summary>
        public class Options : OptionsBase
        {
            /// <summary>
            /// The Google Ads customer ID for which the call is made.
            /// </summary>
            [Option("customerId", Required = true, HelpText =
                "The Google Ads customer ID for which the call is made.")]
            public long CustomerId { get; set; }

            /// <summary>
            /// ID of the ad group to which ads are added.
            /// </summary>
            [Option("adGroupId", Required = true, HelpText =
                "ID of the ad group to which ads are added.")]
            public long AdGroupId { get; set; }
        }

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

                    // ID of the ad group to which ads are added.
                    options.AdGroupId = long.Parse("INSERT_AD_GROUP_ID_HERE");

                    return 0;
                });

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

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description =>
            "This code example shows how to use the validateOnly header to validate an expanded " +
            "text ad. No objects will be created, but exceptions will still be thrown.";

        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="adGroupId">ID of the ad group to which ads are added.</param>
        public void Run(GoogleAdsClient client, long customerId, long adGroupId)
        {
            // Get the AdGroupAdService.
            AdGroupAdServiceClient adGroupAdService = client.GetService(
                Services.V10.AdGroupAdService);

            // Create the ad group ad object.
            AdGroupAd adGroupAd = new AdGroupAd
            {
                AdGroup = ResourceNames.AdGroup(customerId, adGroupId),
                // Optional: Set the status.
                Status = AdGroupAdStatus.Paused,
                Ad = new Ad
                {
                    ExpandedTextAd = new ExpandedTextAdInfo
                    {
                        Description = "Luxury Cruise to Mars",
                        HeadlinePart1 = "Visit the Red Planet in style.",
                        HeadlinePart2 = "Low-gravity fun for everyone!!",
                    },
                    FinalUrls = { "http://www.example.com/" },
                }
            };

            // Create the operation.
            AdGroupAdOperation operation = new AdGroupAdOperation
            {
                Create = adGroupAd
            };

            try
            {
                // Create the ads, while setting validateOnly = true.
                MutateAdGroupAdsResponse response = adGroupAdService.MutateAdGroupAds(
                    new MutateAdGroupAdsRequest()
                    {
                        CustomerId = customerId.ToString(),
                        Operations = { operation },
                        PartialFailure = false,
                        ValidateOnly = true
                    });

                // Since validation is ON, result will be null.
                Console.WriteLine("Expanded text ad validated successfully.");
            }
            catch (GoogleAdsException e)
            {
                // This block will be hit if there is a validation error from the server.
                Console.WriteLine(
                    "There were validation error(s) while adding expanded text ad.");

                if (e.Failure != null)
                {
                    // Note: Policy violation errors are returned as PolicyFindingErrors. See
                    // https://developers.google.com/google-ads/api/docs/policy-exemption/overview
                    // for additional details.
                    e.Failure.Errors
                        .Where(err =>
                            err.ErrorCode.PolicyFindingError == PolicyFindingError.PolicyFinding)
                        .ToList()
                        .ForEach(delegate (GoogleAdsError err)
                        {
                            int count = 1;
                            if (err.Details.PolicyFindingDetails != null)
                            {
                                foreach (PolicyTopicEntry entry in
                                    err.Details.PolicyFindingDetails.PolicyTopicEntries)
                                {
                                    Console.WriteLine($"{count}) Policy topic entry with topic = " +
                                        $"\"{entry.Topic}\" and type = \"{entry.Type}\" " +
                                        $"was found.");
                                }
                            }
                            count++;
                        });
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
            }
        }
    }
}

      

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\CampaignManagement;

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\V10\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V10\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V10\GoogleAdsException;
use Google\Ads\GoogleAds\Util\V10\ResourceNames;
use Google\Ads\GoogleAds\V10\Common\ExpandedTextAdInfo;
use Google\Ads\GoogleAds\V10\Common\PolicyTopicEntry;
use Google\Ads\GoogleAds\V10\Enums\AdGroupAdStatusEnum\AdGroupAdStatus;
use Google\Ads\GoogleAds\V10\Enums\PolicyTopicEntryTypeEnum\PolicyTopicEntryType;
use Google\Ads\GoogleAds\V10\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V10\Errors\PolicyFindingErrorEnum\PolicyFindingError;
use Google\Ads\GoogleAds\V10\Resources\Ad;
use Google\Ads\GoogleAds\V10\Resources\AdGroupAd;
use Google\Ads\GoogleAds\V10\Services\AdGroupAdOperation;
use Google\ApiCore\ApiException;

/**
 * This code example shows how to use the validateOnly header to validate
 * an expanded text ad. No objects will be created, but exceptions will
 * still be thrown.
 */
class ValidateTextAd
{
    private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
    private const AD_GROUP_ID = 'INSERT_AD_GROUP_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::AD_GROUP_ID => GetOpt::REQUIRED_ARGUMENT
        ]);

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

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

        try {
            self::runExample(
                $googleAdsClient,
                $options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID,
                $options[ArgumentNames::AD_GROUP_ID] ?: self::AD_GROUP_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
     * @param int $adGroupId the ad group ID to validate the ad against
     */
    public static function runExample(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        int $adGroupId
    ) {
        // Creates the expanded text ad info.
        $expandedTextAdInfo = new ExpandedTextAdInfo([
            'description' => 'Luxury Cruise to Mars',
            'headline_part1' => 'Visit the Red Planet in style.',
            // Adds a headline that will trigger a policy violation to demonstrate error handling.
            'headline_part2' => 'Low-gravity fun for everyone!!'
        ]);

        // Sets the expanded text ad info on an ad.
        $ad = new Ad([
            'expanded_text_ad' => $expandedTextAdInfo,
            'final_urls' => ['http://www.example.com']
        ]);

        // Creates an ad group ad to hold the above ad.
        $adGroupAd = new AdGroupAd([
            'ad_group' => ResourceNames::forAdGroup($customerId, $adGroupId),
            // Optional: Set the status.
            'status' => AdGroupAdStatus::PAUSED,
            'ad' => $ad
        ]);

        // Creates the ad group ad operation.
        $adGroupAdOperation = new AdGroupAdOperation();
        $adGroupAdOperation->setCreate($adGroupAd);
        $adGroupAdServiceClient = $googleAdsClient->getAdGroupAdServiceClient();

        try {
            // Try sending a mutate request to add the ad group ad.
            $adGroupAdServiceClient->mutateAdGroupAds(
                $customerId,
                [$adGroupAdOperation],
                ['validateOnly' => true]
            );

            // Since validation is ON, result will be null.
            printf("Expanded text ad validated successfully.%s", PHP_EOL);
        } catch (GoogleAdsException $googleAdsException) {
            // This block will be hit if there is a validation error from the server.
            printf("There were validation error(s) while adding expanded text ad.%s", PHP_EOL);

            $count = 1;
            foreach ($googleAdsException->getGoogleAdsFailure()->getErrors() as $googleAdsError) {
                // Note: Policy violation errors are returned as PolicyFindingErrors. See
                // https://developers.google.com/google-ads/api/docs/policy-exemption/overview
                // for additional details.
                /** @var GoogleAdsError $googleAdsError */
                if (
                    $googleAdsError->getErrorCode()->getPolicyFindingError() ==
                    PolicyFindingError::POLICY_FINDING
                ) {
                    if ($googleAdsError->getDetails()->getPolicyFindingDetails()) {
                        $details = $googleAdsError->getDetails()->getPolicyFindingDetails();
                        foreach ($details->getPolicyTopicEntries() as $entry) {
                            /** @var PolicyTopicEntry $entry */
                            printf(
                                "%d) Policy topic entry with topic '%s' and type '%s'" .
                                " was found.%s",
                                $count,
                                $entry->getTopic(),
                                PolicyTopicEntryType::name($entry->getType()),
                                PHP_EOL
                            );
                        }
                    }
                    $count++;
                }
            }
        }
    }
}

ValidateTextAd::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.
"""This example shows use of the validateOnly header for an expanded text ad.

No objects will be created, but exceptions will still be thrown.
"""


import argparse
import sys

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


def main(client, customer_id, ad_group_id):
    ad_group_ad_operation = client.get_type("AdGroupAdOperation")
    ad_group_ad = ad_group_ad_operation.create
    ad_group_service = client.get_service("AdGroupService")
    ad_group_ad.ad_group = ad_group_service.ad_group_path(
        customer_id, ad_group_id
    )
    ad_group_ad.status = client.enums.AdGroupAdStatusEnum.PAUSED

    # Create an expanded text ad.
    ad_group_ad.ad.expanded_text_ad.description = "Luxury Cruise to Mars"
    ad_group_ad.ad.expanded_text_ad.headline_part1 = (
        "Visit the Red Planet in style."
    )
    # Adds a headline that will trigger a policy violation to demonstrate error
    # handling.
    ad_group_ad.ad.expanded_text_ad.headline_part2 = (
        "Low-gravity fun for everyone!!"
    )
    ad_group_ad.ad.final_urls.append("http://www.example.com/")

    ad_group_ad_service = client.get_service("AdGroupAdService")
    # Attempt the mutate with validate_only=True.
    try:
        request = client.get_type("MutateAdGroupAdsRequest")
        request.customer_id = customer_id
        request.operations.append(ad_group_ad_operation)
        request.partial_failure = False
        request.validate_only = True
        response = ad_group_ad_service.mutate_ad_group_ads(request=request)
        print('"Expanded text ad validated successfully.')
    except GoogleAdsException as ex:
        # This will be hit if there is a validation error from the server.
        print(
            f'Request with ID "{ex.request_id}" failed with status '
            f'"{ex.error.code().name}".'
        )
        print(
            "There may have been validation error(s) while adding expanded "
            "text ad."
        )
        policy_error_enum = client.get_type(
            "PolicyFindingErrorEnum"
        ).PolicyFindingError.POLICY_FINDING

        count = 1
        for error in ex.failure.errors:
            # Note: Policy violation errors are returned as PolicyFindingErrors.
            # For additional details, see
            # https://developers.google.com/google-ads/api/docs/policy-exemption/overview
            if error.error_code.policy_finding_error == policy_error_enum:
                if error.details.policy_finding_details:
                    details = (
                        error.details.policy_finding_details.policy_topic_entries
                    )
                    for entry in details:
                        print(f"{count}) Policy topic entry: \n{entry}\n")
                count += 1
            else:
                print(
                    f"\tNon-policy finding error with message "
                    f'"{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)


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="v10")

    parser = argparse.ArgumentParser(
        description="Shows how to use the ValidateOnly header."
    )

    # 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(
        "-a", "--ad_group_id", type=str, required=True, help="The Ad Group ID."
    )
    args = parser.parse_args()

    main(googleads_client, args.customer_id, args.ad_group_id)

      

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.
#
# This example shows use of the validate_only header for an expanded text ad.
# No objects will be created, but exceptions will still be thrown.

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

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

  operation = client.operation.create_resource.ad_group_ad do |aga|
    aga.ad_group = client.path.ad_group(customer_id, ad_group_id)
    aga.status = :PAUSED

    aga.ad = client.resource.ad do |ad|
      ad.final_urls << "http://www.example.com"

      ad.expanded_text_ad = client.resource.expanded_text_ad_info do |eta|
        eta.description = "Luxury Cruise to Mars"
        eta.headline_part1 = "Visit the Red Planet in style."
        # Adds a headline that will trigger a policy violation to demonstrate
        # error handling.
        eta.headline_part2 = "Low-gravity fun for everyone!!"
      end
    end
  end

  begin
    response = client.service.ad_group_ad.mutate_ad_group_ads(
      customer_id: customer_id,
      operations: [operation],
      validate_only: true,
    )
    puts "Expanded text ad validated successfully."
  rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e
    # This code path will be reached if there is a validation error from the server.
    e.failure.errors.each do |error|
      if error.error_code.policy_finding_error == :POLICY_FINDING
        error.details.policy_finding_details&.
            policy_topic_entries.each_with_index do |entry, i|
          puts "#{i + 1}) #{entry.to_json}"
        end
      else
        puts "Non-policy finding with message: #{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
      end
    end
  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.
  options[:customer_id] = 'INSERT_CUSTOMER_ID_HERE'
  options[:ad_group_id] = 'INSERT_AD_GROUP_ID_HERE'

  OptionParser.new do |opts|
    opts.banner = sprintf('Usage: add_campaigns.rb [options]')

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

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

    opts.on('-A','--ad-group-id AD-GROUP-ID', String, 'Ad Group ID') do |v|
      options[:ad_group_id] = v
    end

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

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

  begin
    validate_text_ad(
      options.fetch(:customer_id).tr("-", ""),
      options.fetch(:ad_group_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.
#
# This example shows how to use the validateOnly field to validate an expanded
# text ad. No objects will be created, but exceptions will still be returned.

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::V10::Resources::AdGroupAd;
use Google::Ads::GoogleAds::V10::Resources::Ad;
use Google::Ads::GoogleAds::V10::Common::ExpandedTextAdInfo;
use Google::Ads::GoogleAds::V10::Enums::AdGroupAdStatusEnum qw(PAUSED);
use Google::Ads::GoogleAds::V10::Services::AdGroupAdService::AdGroupAdOperation;
use Google::Ads::GoogleAds::V10::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 $ad_group_id = "INSERT_AD_GROUP_ID_HERE";

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

  # Create an ad group ad object.
  my $ad_group_ad = Google::Ads::GoogleAds::V10::Resources::AdGroupAd->new({
      adGroup => Google::Ads::GoogleAds::V10::Utils::ResourceNames::ad_group(
        $customer_id, $ad_group_id
      ),
      # Optional: Set the status.
      status => PAUSED,
      ad     => Google::Ads::GoogleAds::V10::Resources::Ad->new({
          expandedTextAd =>
            Google::Ads::GoogleAds::V10::Common::ExpandedTextAdInfo->new({
              description   => "Luxury Cruise to Mars",
              headlinePart1 => "Visit the Red Planet in style.",
              # Add a headline that will trigger a policy violation to demonstrate
              # error handling.
              headlinePart2 => "Low-gravity fun for everyone!!"
            }
            ),
          finalUrls => ["http://www.example.com/"]})});

  # Create an ad group ad operation.
  my $ad_group_ad_operation =
    Google::Ads::GoogleAds::V10::Services::AdGroupAdService::AdGroupAdOperation
    ->new({create => $ad_group_ad});

  # Add the ad group ad, while setting validateOnly to "true".
  my $response = $api_client->AdGroupAdService()->mutate({
    customerId     => $customer_id,
    operations     => [$ad_group_ad_operation],
    partialFailure => "false",
    validateOnly   => "true"
  });

  if (not $response->isa("Google::Ads::GoogleAds::GoogleAdsException")) {
    # Since validateOnly is set to "true", result will be null.
    print "Expanded text ad validated successfully.\n";
  } else {
    # This block will be hit if there is a validation error from the server.
    print "There were validation error(s) while adding expanded text ad.\n";

    # Note: Policy violation errors are returned as PolicyFindingErrors. See
    # https://developers.google.com/google-ads/api/docs/policy-exemption/overview
    # for additional details.
    my $count = 1;
    foreach my $error (@{$response->get_google_ads_failure()->{errors}}) {
      next
        unless ($error->{errorCode}{policyFindingError}
        and $error->{errorCode}{policyFindingError} eq "POLICY_FINDING");

      foreach my $entry (
        @{$error->{details}{policyFindingDetails}{policyTopicEntries}})
      {
        printf "%d) Policy topic entry with topic = '%s' and type = '%s' " .
          "was found.\n", $count, $entry->{topic}, $entry->{type};
      }

      $count++;
    }
  }

  return 1;
}

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

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

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

# Parameters passed on the command line will override any parameters set in code.
GetOptions("customer_id=s" => \$customer_id, "ad_group_id=i" => \$ad_group_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, $ad_group_id);

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

=pod

=head1 NAME

validate_text_ad

=head1 DESCRIPTION

This example shows how to use the validateOnly field to validate an expanded
text ad. No objects will be created, but exceptions will still be returned.

=head1 SYNOPSIS

validate_text_ad.pl [options]

    -help                       Show the help message.
    -customer_id                The Google Ads customer ID.
    -ad_group_id                The ad group ID to which ads are added.

=cut