Google Ads API is returning to beta status. Please read our blog post for more details.

Get Artifact Metadata

Java
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.ads.googleads.examples.basicoperations;

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.v2.errors.GoogleAdsException;
import com.google.ads.googleads.v2.errors.GoogleAdsError;
import com.google.ads.googleads.v2.resources.GoogleAdsField;
import com.google.ads.googleads.v2.services.GoogleAdsFieldServiceClient;
import com.google.ads.googleads.v2.services.GoogleAdsFieldServiceClient.SearchGoogleAdsFieldsPagedResponse;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.protobuf.BoolValue;
import com.google.protobuf.StringValue;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Gets the metadata, such as whether the artifact is selectable, filterable and
 * sortable, of an artifact. The artifact can be either a resource (such as customer, campaign) or a
 * field (such as metrics.impressions, campaign.id). It'll also show the data type and artifacts
 * that are selectable with the artifact.
 */
public class GetArtifactMetadata {

  private static class GetArtifactMetadataParams extends CodeSampleParams {

    @Parameter(names = ArgumentNames.ARTIFACT_NAME, required = true)
    private String artifactName;
  }

  public static void main(String[] args) {
    GetArtifactMetadataParams params = new GetArtifactMetadataParams();
    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.artifactName = "INSERT_ARTIFACT_NAME_HERE";
    }

    GoogleAdsClient googleAdsClient;
    try {
      googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
    } catch (FileNotFoundException fnfe) {
      System.err.printf(
          "Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe);
      return;
    } catch (IOException ioe) {
      System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe);
      return;
    }

    try {
      new GetArtifactMetadata().runExample(googleAdsClient, params.artifactName);
    } 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);
      }
    }
  }

  /**
   * Runs the example.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param artifactName the name of artifact to get its metadata.
   * @throws GoogleAdsException if an API request failed with one or more service errors.
   */
  private void runExample(GoogleAdsClient googleAdsClient, String artifactName) {
    try (GoogleAdsFieldServiceClient googleAdsFieldServiceClient =
        googleAdsClient.getLatestVersion().createGoogleAdsFieldServiceClient()) {
      // Searches for an artifact whose name is the same as the specified artifactName.
      SearchGoogleAdsFieldsPagedResponse searchGoogleAdsFieldsPagedResponse =
          googleAdsFieldServiceClient.searchGoogleAdsFields(
              String.format(
                  "SELECT name, category, selectable, filterable, sortable, selectable_with, "
                      + "data_type, is_repeated WHERE name = '%s'",
                  artifactName));

      // Gets all returned artifacts and prints out their metadata.
      List<GoogleAdsField> googleAdsFields =
          Lists.newArrayList(searchGoogleAdsFieldsPagedResponse.iterateAll());
      for (GoogleAdsField googleAdsField : googleAdsFields) {
        System.out.printf(
            "An artifact named '%s' with category '%s' and data type '%s' %s selectable, %s "
                + "filterable, %s sortable and %s repeated.%n%n",
            googleAdsField.getName().getValue(),
            googleAdsField.getCategory(),
            googleAdsField.getDataType(),
            getIsOrIsNot(googleAdsField.getSelectable()),
            getIsOrIsNot(googleAdsField.getFilterable()),
            getIsOrIsNot(googleAdsField.getSortable()),
            getIsOrIsNot(googleAdsField.getIsRepeated()));

        // Unwraps and sorts the list of artifact names that are selectable with the specified
        // artifact.
        List<String> selectableArtifacts =
            new ArrayList<>(
                Lists.transform(
                    googleAdsField.getSelectableWithList(),
                    new Function<StringValue, String>() {
                      @Override
                      public String apply(StringValue selectableWithField) {
                        return selectableWithField.getValue();
                      }
                    }));
        Collections.sort(selectableArtifacts);

        System.out.println("The artifact can be selected with the following artifacts:");
        for (String selectableField : selectableArtifacts) {
          System.out.println(selectableField);
        }
      }

      if (googleAdsFields.isEmpty()) {
        System.err.printf("The specified artifact '%s' doesn't exist.%n", artifactName);
      }
    }
  }

  /**
   * Returns "is" when the specified value is true and "is not" when the specified value is false.
   */
  private String getIsOrIsNot(BoolValue boolValue) {
    return boolValue.getValue() ? "is" : "is not";
  }
}
C#
// Copyright 2019 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 Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V2.Errors;
using Google.Ads.GoogleAds.V2.Resources;
using Google.Ads.GoogleAds.V2.Services;
using Google.Api.Gax;

using System;
using System.Collections.Generic;
using System.Linq;

namespace Google.Ads.GoogleAds.Examples.V2
{
    /// <summary>
    /// This code example gets the metadata, such as whether the artifact is selectable, filterable
    /// and sortable, of an artifact. The artifact can be either a resource (such as customer,
    /// campaign) or a field (such as metrics.impressions, campaign.id). It'll also show the data
    /// type and artifacts that are selectable with the artifact.
    /// </summary>
    public class GetArtifactMetadata : ExampleBase
    {
        /// <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)
        {
            GetArtifactMetadata codeExample = new GetArtifactMetadata();

            Console.WriteLine(codeExample.Description);

            // The Google Ads customer ID for which the call is made.
            long customerId = long.Parse("INSERT_CUSTOMER_ID_HERE");

            // The artifact for which metadata is retrieved.
            string artifactName = "INSERT_ARTIFACT_NAME_HERE";

            codeExample.Run(new GoogleAdsClient(), customerId, artifactName);
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get
            {
                return "This code example gets the metadata, such as whether the artifact is " +
                    "selectable, filterable and sortable, of an artifact. The artifact can be " +
                    "either a resource (such as customer, campaign) or a field (such as " +
                    "metrics.impressions, campaign.id). It'll also show the data type and " +
                    "artifacts that are selectable with the artifact.";
            }
        }

        /// <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="artifactName">The artifact for which metadata is retrieved.</param>
        public void Run(GoogleAdsClient client, long customerId, string artifactName)
        {
            // Get the GoogleAdsFieldService.
            GoogleAdsFieldServiceClient googleAdsFieldService = client.GetService(
                Services.V2.GoogleAdsFieldService);

            // Create the query.
            string searchQuery = $"SELECT name, category, selectable, filterable, sortable, " +
                $"selectable_with, data_type, is_repeated WHERE name = '{artifactName}'";

            try
            {
                // Search for an artifact whose name is the same as the specified artifactName.
                PagedEnumerable<SearchGoogleAdsFieldsResponse, GoogleAdsField> googleAdsFields =
                    googleAdsFieldService.SearchGoogleAdsFields(searchQuery);

                if (googleAdsFields.Any())
                {
                    // Get all returned artifacts and print out their metadata.
                    foreach (GoogleAdsField googleAdsField in googleAdsFields)
                    {
                        Console.WriteLine("An artifact named '{0}' with category '{1}' and " +
                            "data type '{2}' {3} selectable, {4} filterable, {5} sortable " +
                            "and {6} repeated.",
                            googleAdsField.Name, googleAdsField.Category, googleAdsField.DataType,
                            getIsOrIsNot(googleAdsField.Selectable),
                            getIsOrIsNot(googleAdsField.Filterable),
                            getIsOrIsNot(googleAdsField.Sortable),
                            getIsOrIsNot(googleAdsField.IsRepeated));

                        List<string> selectableLists = new List<string>(
                            googleAdsField.SelectableWith);
                        selectableLists.Sort();

                        Console.WriteLine("The artifact can be selected with the following " +
                            "artifacts:");
                        foreach (string item in selectableLists)
                        {
                            Console.WriteLine("- " + item);
                        }
                    }
                }
                else
                {
                    Console.Error.WriteLine($"The specified artifact '{artifactName}' " +
                        "doesn't exist.");
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
            }
        }

        /// <summary>
        /// Returns "is" when the specified value is true and "is not" when the specified value
        /// is false.
        /// </summary>
        /// <param name="boolValue">The bool value.</param>
        /// <returns>True, </returns>
        private String getIsOrIsNot(bool? boolValue)
        {
            return boolValue.Value ? "is" : "is not";
        }
    }
}
PHP
<?php
/**
 * Copyright 2018 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Google\Ads\GoogleAds\Examples\BasicOperations;

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\V2\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V2\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V2\GoogleAdsException;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\V2\Enums\GoogleAdsFieldCategoryEnum\GoogleAdsFieldCategory;
use Google\Ads\GoogleAds\V2\Enums\GoogleAdsFieldDataTypeEnum\GoogleAdsFieldDataType;
use Google\Ads\GoogleAds\V2\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V2\Resources\GoogleAdsField;
use Google\ApiCore\ApiException;
use Google\Protobuf\BoolValue;
use Google\Protobuf\StringValue;

/**
 * This example gets the metadata, such as whether the artifact is selectable, filterable and
 * sortable, of an artifact. The artifact can be either a resource (such as customer, campaign) or a
 * field (such as metrics.impressions, campaign.id). It'll also show the data type and artifacts
 * that are selectable with the artifact.
 */
class GetArtifactMetadata
{
    const ARTIFACT_NAME = 'INSERT_ARTIFACT_NAME_HERE';
    const PAGE_SIZE = 1000;

    public static function main()
    {
        // Either pass the required parameters for this example on the command line, or insert them
        // into the constants above.
        $options = (new ArgumentParser())->parseCommandArguments([
            ArgumentNames::ARTIFACT_NAME => 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::ARTIFACT_NAME] ?: self::ARTIFACT_NAME
            );
        } catch (GoogleAdsException $googleAdsException) {
            printf(
                "Request with ID '%s' has failed.%sGoogle Ads failure details:%s",
                $googleAdsException->getRequestId(),
                PHP_EOL,
                PHP_EOL
            );
            foreach ($googleAdsException->getGoogleAdsFailure()->getErrors() as $error) {
                /** @var GoogleAdsError $error */
                printf(
                    "\t%s: %s%s",
                    $error->getErrorCode()->getErrorCode(),
                    $error->getMessage(),
                    PHP_EOL
                );
            }
        } catch (ApiException $apiException) {
            printf(
                "ApiException was thrown with message '%s'.%s",
                $apiException->getMessage(),
                PHP_EOL
            );
        }
    }

    /**
     * Runs the example.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $artifactName the name of artifact to get its metadata
     */
    public static function runExample(GoogleAdsClient $googleAdsClient, int $artifactName)
    {
        $googleAdsFieldServiceClient = $googleAdsClient->getGoogleAdsFieldServiceClient();
        // Searches for an artifact whose name is the same as the specified artifactName.
        $query = "SELECT name, category, selectable, filterable, sortable, selectable_with, "
            . "data_type, is_repeated WHERE name = '$artifactName'";
        $response = $googleAdsFieldServiceClient->searchGoogleAdsFields($query);

        // Iterates over all rows and prints our the metadata of the returned artifacts
        foreach ($response->iterateAllElements() as $googleAdsField) {
            /** @var GoogleAdsField $googleAdsField */
            printf(
                "An artifact named '%s' with category '%s' and data type '%s' %s selectable, %s "
                . "filterable, %s sortable and %s repeated.%s",
                $googleAdsField->getNameUnwrapped(),
                GoogleAdsFieldCategory::name($googleAdsField->getCategory()),
                GoogleAdsFieldDataType::name($googleAdsField->getDataType()),
                self::getIsOrIsNot($googleAdsField->getSelectable()),
                self::getIsOrIsNot($googleAdsField->getFilterable()),
                self::getIsOrIsNot($googleAdsField->getSortable()),
                self::getIsOrIsNot($googleAdsField->getIsRepeated()),
                PHP_EOL
            );
            if ($googleAdsField->getSelectableWith()->count() > 0) {
                $selectableArtifacts = [];
                foreach ($googleAdsField->getSelectableWith() as $wrappedSelectableArtifact) {
                    /** @var StringValue $wrappedSelectableArtifact */
                    $selectableArtifacts[] = $wrappedSelectableArtifact->getValue();
                }
                printf(
                    '%1$sThe artifact can be selected with the following artifacts:%1$s',
                    PHP_EOL
                );
                foreach ($selectableArtifacts as $selectableArtifact) {
                    print $selectableArtifact . PHP_EOL;
                }
            }
        }
    }

    /**
     * Returns 'is' when the provided boolean value is true or 'is not' when it's false.
     *
     * @param BoolValue $boolValue the boolean value
     */
    private static function getIsOrIsNot(BoolValue $boolValue)
    {
        return $boolValue->getValue() ? 'is' : 'is not';
    }
}

GetArtifactMetadata::main();
Python
#!/usr/bin/env python
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example illustrates how to retrieve artifact metadata.

The metadata retrieved can provide additional context about the artifact,
such as whether it is selectable, filterable, or sortable. The artifact can be
either a resource (such as customer, or campaign) or a field (such as
metrics.impressions, campaign.id). It also shows the data type and artifacts
that are selectable with the artifact.
"""

from __future__ import absolute_import

import argparse
import six
import sys
import google.ads.google_ads.client


_DEFAULT_PAGE_SIZE = 1000


def _is_or_is_not(bool_value):
    """Produces display text for whether metadata is applicable to artifact.

    Args:
        bool_value: a BoolValue instance.

    Returns:
        A str with value "is" if bool_value is True, else "is not".
    """
    return 'is' if bool_value.value else 'isn\'t'


def main(client, artifact_name, page_size):
    gaf_service = client.get_service('GoogleAdsFieldService', version='v2')

    # Searches for an artifact with the specified name.
    query = ('SELECT name, category, selectable, filterable, sortable, '
             'selectable_with, data_type, is_repeated '
             'WHERE name = \'%s\'') % artifact_name

    response = gaf_service.search_google_ads_fields(
        query=query, page_size=page_size)

    # Iterates over all rows and prints out the metadata of the returned
    # artifacts.
    try:
        for google_ads_field in response:
            # Note that the category and data type printed below are enum
            # values. For example, a value of 2 will be returned when the
            # category is "RESOURCE".
            #
            # A mapping of enum names to values can be found in
            # GoogleAdsFieldCategoryEnum for the category and
            # GoogleAdsFieldDataTypeEnum for the data type.
            selectable = _is_or_is_not(google_ads_field.selectable)
            filterable = _is_or_is_not(google_ads_field.filterable)
            sortable = _is_or_is_not(google_ads_field.sortable)
            is_repeated = _is_or_is_not(google_ads_field.is_repeated)

            print('An artifact named "%s" with category %d and data type %d %s '
                  'selectable, %s filterable, %s sortable, and %s repeated.'
                  % (google_ads_field.name.value, google_ads_field.category,
                     google_ads_field.data_type, selectable, filterable,
                     sortable, is_repeated))

            if len(google_ads_field.selectable_with) > 0:
                selectable_artifacts = [
                    wrapped_selectable_artifact.value
                    for wrapped_selectable_artifact
                    in google_ads_field.selectable_with]

                print('')
                print('The artifact can be selected with the following '
                      'artifacts:')
                for artifact in selectable_artifacts:
                    print(artifact)
    except google.ads.google_ads.errors.GoogleAdsException as ex:
        print('Request with ID "%s" failed with status "%s" and includes the '
              'following errors:' % (ex.request_id, ex.error.code().name))
        for error in ex.failure.errors:
            print('\tError with message "%s".' % error.message)
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print('\t\tOn field: %s' % 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.
    google_ads_client = (google.ads.google_ads.client.GoogleAdsClient
                         .load_from_storage())

    parser = argparse.ArgumentParser(
        description='Lists metadata for the specified artifact.')
    # The following argument(s) should be provided to run the example.
    parser.add_argument('-a', '--artifact_name', type=six.text_type,
                        required=True,
                        help='The name of the artifact for which we are '
                        'retrieving metadata.')
    args = parser.parse_args()

    main(google_ads_client, args.artifact_name, _DEFAULT_PAGE_SIZE)
Ruby
#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This example gets the metadata, such as whether the artifact is selectable,
# filterable and sortable, of an artifact. The artifact can be either a resource
# (such as customer, campaign) or a field (such as metrics.impressions,
# campaign.id). It'll also show the data type and artifacts that are
# selectable with the artifact.

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

def get_artifact_metadata(artifact_name)
  # 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
      name,
      category,
      selectable,
      filterable,
      sortable,
      selectable_with,
      data_type,
      is_repeated
    WHERE name = '#{artifact_name}'
  QUERY

  response = client.service.google_ads_field.search_google_ads_fields(query)

  if response.response.results.empty?
    puts "The specified artifact '#{artifact_name}' doesn't exist"
    return
  end

  response.each do |row|
    puts "An artifact named '#{row.name}' with category '#{row.category}' and data type " \
        "#{row.data_type} #{is_or_not(row.selectable.value)} selectable, " \
        "#{is_or_not(row.filterable.value)} filterable, #{is_or_not(row.sortable.value)} " \
        "sortable, and #{is_or_not(row.is_repeated.value)} repeated."

    if !row.selectable_with.empty?
      puts "The artifact can be selected with the following artifacts:"
      puts (row.selectable_with.sort_by { |field| field.value })
    end
  end
end

# Returns "is" when the specified value is true and "is not" when the
# specified value is false
def is_or_not(bool)
  bool ? 'is' : 'is not'
end

if __FILE__ == $PROGRAM_NAME
  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[:artifact_name] = 'campaign'

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

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

    help_msg = 'Artifact Name (e.g. a resource such as customer, campaign' \
        ' or a field such as metrics.impressions, campaign.id)'

    opts.on('-A', '--artifact-name ARTIFACT-NAME', String, help_msg) do |v|
      options[:artifact_name] = v
    end

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

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

  begin
    get_artifact_metadata(options[:artifact_name])
  rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e
    e.failure.errors.each do |error|
      error.error_code.to_h.each do |k, v|
        next if v == :UNSPECIFIED
        STDERR.printf("Error: %s\nDetails: %s\n", k, v)
      end
    end
  rescue Google::Gax::RetryError => e
    STDERR.printf("Error: '%s'\n\tCause: '%s'\n\tCode: %d\n\tDetails: '%s'\n" \
        "\tRequest-Id: '%s'\n", e.message, e.cause.message, e.cause.code,
        e.cause.details, e.cause.metadata['request-id'])
  end
end

Send feedback about...

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