Search for Google Ads Fields

Java

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

package com.google.ads.googleads.examples.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.v11.errors.GoogleAdsError;
import com.google.ads.googleads.v11.errors.GoogleAdsException;
import com.google.ads.googleads.v11.resources.GoogleAdsField;
import com.google.ads.googleads.v11.services.GoogleAdsFieldServiceClient;
import com.google.ads.googleads.v11.services.GoogleAdsFieldServiceClient.SearchGoogleAdsFieldsPagedResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Searches for {@link GoogleAdsField}s that match a given prefix, retrieving metadata such as
 * whether the field is selectable, filterable, or sortable, along with the data type and the fields
 * that are selectable with the field. Each {@link GoogleAdsField} represents either a resource
 * (such as {@code customer}, {@code campaign}) or a field (such as {@code metrics.impressions},
 * {@code campaign.id}).
 */
public class SearchForGoogleAdsFields {

  private static class SearchForGoogleAdsFieldsParams extends CodeSampleParams {

    @Parameter(names = ArgumentNames.NAME_PREFIX, required = true)
    private String namePrefix;
  }

  public static void main(String[] args) {
    SearchForGoogleAdsFieldsParams params = new SearchForGoogleAdsFieldsParams();
    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.namePrefix = "INSERT_NAME_PREFIX_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 SearchForGoogleAdsFields().runExample(googleAdsClient, params.namePrefix);
    } 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 namePrefix the name prefix to use in the query.
   * @throws GoogleAdsException if an API request failed with one or more service errors.
   */
  private void runExample(GoogleAdsClient googleAdsClient, String namePrefix) {
    try (GoogleAdsFieldServiceClient googleAdsFieldServiceClient =
        googleAdsClient.getLatestVersion().createGoogleAdsFieldServiceClient()) {
      // Searches for all fields whose name begins with the specified namePrefix.
      SearchGoogleAdsFieldsPagedResponse searchGoogleAdsFieldsPagedResponse =
          googleAdsFieldServiceClient.searchGoogleAdsFields(
              String.format(
                  "SELECT "
                      + "name, "
                      + "category, "
                      + "selectable, "
                      + "filterable, "
                      + "sortable, "
                      + "data_type, "
                      + "is_repeated, "
                      + "selectable_with "
                      // The double "%%" below will produce a single "%" in the string returned by
                      // String.format. A single "%" is the wildcard token in the Google Ads Query
                      // language.
                      + "WHERE name LIKE '%s%%'",
                  namePrefix));

      if (searchGoogleAdsFieldsPagedResponse.getPage().getResponse().getTotalResultsCount() == 0) {
        System.out.printf(
            "No GoogleAdsFields found with a name that begins with '%s'.%n", namePrefix);
        return;
      }

      // Retrieves each matching GoogleAdsField and prints its metadata.
      for (GoogleAdsField googleAdsField : searchGoogleAdsFieldsPagedResponse.iterateAll()) {
        System.out.printf("%s:%n", googleAdsField.getName());
        System.out.printf("  %-16s %s%n", "category:", googleAdsField.getCategory());
        System.out.printf("  %-16s %s%n", "data type:", googleAdsField.getDataType());
        System.out.printf("  %-16s %s%n", "selectable:", googleAdsField.getSelectable());
        System.out.printf("  %-16s %s%n", "filterable:", googleAdsField.getFilterable());
        System.out.printf("  %-16s %s%n", "sortable:", googleAdsField.getSortable());
        System.out.printf("  %-16s %s%n", "repeated:", googleAdsField.getIsRepeated());

        // Prints the list of fields that are selectable with the field.
        List<String> selectableWithFields = new ArrayList(googleAdsField.getSelectableWithList());
        if (!selectableWithFields.isEmpty()) {
          // Sorts and then prints the list.
          Collections.sort(selectableWithFields);
          System.out.printf("  %s%n", "selectable with:");
          for (String selectableWithField : selectableWithFields) {
            System.out.printf("    %s%n", selectableWithField);
          }
        }
      }
    }
  }
}

      

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 CommandLine;
using Google.Ads.Gax.Examples;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V11.Errors;
using Google.Ads.GoogleAds.V11.Resources;
using Google.Ads.GoogleAds.V11.Services;
using Google.Api.Gax;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Google.Ads.GoogleAds.Examples.V11
{
    /// <summary>
    /// This code example searches for <see cref="GoogleAdsField" /> that match a given prefix,
    /// retrieving metadata such as whether the field is selectable, filterable, or sortable,
    /// along with the data type and the fields that are selectable with the field. Each
    /// <code>GoogleAdsField</code> represents either a resource (such as <code>customer</code>,
    /// <code>campaign</code> or a field (such as <code>metrics.impressions</code>,
    /// <code>campaign.id</code>).
    /// </summary>
    public class SearchForGoogleAdsFields : ExampleBase
    {
        /// <summary>
        /// Command line options for running the <see cref="SearchForGoogleAdsFields"/> example.
        /// </summary>
        public class Options : OptionsBase
        {
            /// <summary>
            /// The name prefix to search for matching GoogleAdsFields.
            /// </summary>
            [Option("namePrefix", Required = true, HelpText =
                "The name prefix to search for matching GoogleAdsFields.")]
            public string NamePrefix { get; set; }
        }

        /// <summary>
        /// Main method, to run this code example as a standalone application.
        /// </summary>
        /// <param name="args">The command line arguments.</param>
        public static void Main(string[] args)
        {
            Options options = ExampleUtilities.ParseCommandLine<Options>(args);

            SearchForGoogleAdsFields codeExample = new SearchForGoogleAdsFields();
            Console.WriteLine(codeExample.Description);
            codeExample.Run(new GoogleAdsClient(), options.NamePrefix);
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description =>
            "This code example searches for <see cref='GoogleAdsField' /> that match a given " +
            "prefix retrieving metadata such as whether the field is selectable, filterable, " +
            "or sortable, along with the data type and the fields that are selectable with " +
            "the field. Each <code>GoogleAdsField</code> represents either a resource (such " +
            "as <code>customer</code>, <code>campaign</code> or a field (such as " +
            "<code>metrics.impressions</code>, <code>campaign.id</code>).";

        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="namePrefix">The name prefix to search for matching GoogleAdsFields.</param>
        public void Run(GoogleAdsClient client, string namePrefix)
        {
            // Get the GoogleAdsFieldService.
            GoogleAdsFieldServiceClient googleAdsFieldService = client.GetService(
                Services.V11.GoogleAdsFieldService);

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

            try
            {
                // Searches for all fields whose name begins with the specified namePrefix.
                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(googleAdsField.Name);
                        Console.WriteLine($"  Category: {googleAdsField.Category}");
                        Console.WriteLine($"  DataType: {googleAdsField.DataType}");
                        Console.WriteLine($"  Selectable: {googleAdsField.Selectable}");
                        Console.WriteLine($"  Filterable: {googleAdsField.Filterable}");
                        Console.WriteLine($"  Sortable: {googleAdsField.Sortable}");
                        Console.WriteLine($"  Repeated: {googleAdsField.IsRepeated}");

                        if (googleAdsField.SelectableWith.Count > 0)
                        {
                            List<string> selectableLists = new List<string>(
                                googleAdsField.SelectableWith);
                            selectableLists.Sort();

                            Console.WriteLine("  Selectable with:");
                            foreach (string item in selectableLists)
                            {
                                Console.WriteLine($"    {item}");
                            }
                        }
                        Console.WriteLine();
                    }
                }
                else
                {
                    Console.Error.WriteLine($"No GoogleAdsFields found with a name that " +
                        $"begins with '{namePrefix}'.");
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
    }
}

      

PHP

<?php

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

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

/**
 * Searches for GoogleAdsFields that match a given prefix, retrieving metadata such as
 * whether the field is selectable, filterable, or sortable, along with the data type and the fields
 * that are selectable with the field. Each GoogleAdsField represents either a resource (such as
 * customer, campaign) or a field (such as metrics.impressions, campaign.id).
 */
class SearchForGoogleAdsFields
{
    private const NAME_PREFIX = 'INSERT_NAME_PREFIX_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::NAME_PREFIX => 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::NAME_PREFIX] ?: self::NAME_PREFIX
            );
        } 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 string $namePrefix the name prefix to use in the query
     */
    public static function runExample(GoogleAdsClient $googleAdsClient, string $namePrefix)
    {
        $googleAdsFieldServiceClient = $googleAdsClient->getGoogleAdsFieldServiceClient();
        // Searches for all fields whose name begins with the specified namePrefix.
        // A single "%" is the wildcard token in the Google Ads Query language.
        $query = "SELECT name, category, selectable, filterable, sortable, selectable_with, "
            . "data_type, is_repeated WHERE name LIKE '$namePrefix%'";
        $response = $googleAdsFieldServiceClient->searchGoogleAdsFields($query);

        if (iterator_count($response->getIterator()) === 0) {
            printf(
                "No GoogleAdsFields found with a name that begins with %s.%s",
                $namePrefix,
                PHP_EOL
            );
            return;
        }
        // Iterates over all rows and prints our the metadata of each matching GoogleAdsField.
        foreach ($response->iterateAllElements() as $googleAdsField) {
            /** @var GoogleAdsField $googleAdsField */
            printf("%s:%s", $googleAdsField->getName(), PHP_EOL);
            printf(
                "  %-16s: %s%s",
                "category:",
                GoogleAdsFieldCategory::name($googleAdsField->getCategory()),
                PHP_EOL
            );
            printf(
                "  %-16s: %s%s",
                "data type:",
                GoogleAdsFieldDataType::name($googleAdsField->getDataType()),
                PHP_EOL
            );
            printf(
                "  %-16s: %s%s",
                "selectable:",
                $googleAdsField->getSelectable() ? 'true' : 'false',
                PHP_EOL
            );
            printf(
                "  %-16s: %s%s",
                "filterable:",
                $googleAdsField->getFilterable() ? 'true' : 'false',
                PHP_EOL
            );
            printf(
                "  %-16s: %s%s",
                "sortable:",
                $googleAdsField->getSortable() ? 'true' : 'false',
                PHP_EOL
            );
            printf(
                "  %-16s: %s%s",
                "repeated:",
                $googleAdsField->getIsRepeated() ? 'true' : 'false',
                PHP_EOL
            );

            if ($googleAdsField->getSelectableWith()->count() > 0) {
                // Prints the list of fields that are selectable with the field.
                $selectableWithFields =
                    iterator_to_array($googleAdsField->getSelectableWith()->getIterator());
                // Sorts and then prints the list.
                sort($selectableWithFields);
                print '  selectable with:' . PHP_EOL;
                foreach ($selectableWithFields as $selectableWithField) {
                    /** @var string $selectableWithField */
                    printf("    $selectableWithField%s", PHP_EOL);
                }
            }
        }
    }
}

SearchForGoogleAdsFields::main();

      

Python

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

Retrieves metadata such as whether the field is selectable, filterable, or
sortable, along with the data type and the fields that are selectable with the
field. Each GoogleAdsField represents either a resource (such as customer,
campaign) or a field (such as metrics.impressions, campaign.id).
"""


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


_DEFAULT_PAGE_SIZE = 1000


def main(client, name_prefix, page_size):
    """The main method that creates all necessary entities for the example.

    Args:
        client: an initialized GoogleAdsClient instance.
        name_prefix: the name prefix to use when searching for Google Ads field
            names.
        page_size: the number of rows to return per page.
    """
    gaf_service = client.get_service("GoogleAdsFieldService")

    # Searches for all fields whose name begins with the specified name prefix.
    query = f"""
        SELECT
          name,
          category,
          selectable,
          filterable,
          sortable,
          selectable_with,
          data_type,
          is_repeated
        WHERE name LIKE '{name_prefix}%'"""

    request = client.get_type("SearchGoogleAdsFieldsRequest")
    request.query = query
    request.page_size = page_size

    response = gaf_service.search_google_ads_fields(request=request)

    # Checks if any results were returned and exits if not.
    if response.total_results_count == 0:
        print(
            "No GoogleAdsFields found with a name that begins with "
            f"'{name_prefix}'."
        )
        sys.exit(0)

    # Retrieves each matching GoogleAdsField and prints its metadata.
    for googleads_field in response:
        print(f"{googleads_field.name}:")
        # These statements format the printed string so that the left side is
        # always a 16-character string so that the values on the right line up
        # vertically.
        print(f"{'  category:':<16}", googleads_field.category.name)
        print(f"{'  data type:':<16}", googleads_field.data_type.name)
        print(f"{'  selectable:':<16}", googleads_field.selectable)
        print(f"{'  filterable:':<16}", googleads_field.filterable)
        print(f"{'  sortable:':<16}", googleads_field.sortable)
        print(f"{'  repeated:':<16}", googleads_field.is_repeated)

        # Prints the list of fields that are selectable with the field.
        if googleads_field.selectable_with:
            # Sorts the selectable_with list then prints each field name.
            googleads_field.selectable_with.sort()
            print("  selectable with:")
            for selectable_with_field in googleads_field.selectable_with:
                print(f"    {selectable_with_field}")

        # Print an extra line to visually separate each GoogleAdsField.
        print()


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

    parser = argparse.ArgumentParser(
        description="Lists metadata for the specified artifact."
    )
    # The following argument(s) should be provided to run the example.
    parser.add_argument(
        "-n",
        "--name_prefix",
        type=str,
        required=True,
        help="The name prefix to use when searching for Google Ads field names",
    )
    args = parser.parse_args()

    try:
        main(googleads_client, args.name_prefix, _DEFAULT_PAGE_SIZE)
    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

This example is not yet available in Ruby; you can take a look at the other languages.
    

Perl

#!/usr/bin/perl -w
#
# 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.
#
# This example searches for GoogleAdsFields that match a given prefix, retrieving
# metadata such as whether the field is selectable, filterable, or sortable, along
# with the data type and the fields that are selectable with the field. Each
# GoogleAdsField represents either a resource (such as customer or campaign) or
# a field (such as metrics.impressions or campaign.id).

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 Getopt::Long qw(:config auto_help);
use Pod::Usage;
use Cwd qw(abs_path);

my $name_prefix = undef;

sub search_for_google_ads_fields {
  my ($api_client, $name_prefix) = @_;

  # Create the search query.
  # A single % is the wildcard token in the Google Ads Query language.
  my $search_query =
    "SELECT name, category, selectable, filterable, sortable, selectable_with, "
    . "data_type, is_repeated WHERE name LIKE '${name_prefix}%'";

  my $search_google_ads_fields_response =
    $api_client->GoogleAdsFieldService()->search({
      query => $search_query
    });

  if (!$search_google_ads_fields_response->{results}) {
    printf "No GoogleAdsField found with a name that begins with '%s'.\n",
      $name_prefix;
    return;
  }

  # Retrieves each matching GoogleAdsField and prints its metadata.
  foreach
    my $google_ads_field (@{$search_google_ads_fields_response->{results}})
  {
    printf "%s:\n",        $google_ads_field->{name};
    printf "  %-16s %s\n", "category:",   $google_ads_field->{category};
    printf "  %-16s %s\n", "data type:",  $google_ads_field->{dataType};
    printf "  %-16s %s\n", "selectable:", $google_ads_field->{selectable};
    printf "  %-16s %s\n", "filterable:", $google_ads_field->{filterable};
    printf "  %-16s %s\n", "sortable:",   $google_ads_field->{sortable};
    printf "  %-16s %s\n", "repeated:",   $google_ads_field->{isRepeated};

    # Prints the list of fields that are selectable with the field.
    if ($google_ads_field->{selectableWith}) {
      # Sorts and then prints the list.
      my $sorted_selectable_field = $google_ads_field->{selectableWith};
      @$sorted_selectable_field = sort @$sorted_selectable_field;
      printf "  %s\n", "selectable with:";
      foreach my $selectable_field (@{$google_ads_field->{selectableWith}}) {
        printf "    %s\n", $selectable_field;
      }
    }
  }

  return 1;
}

# Returns "is" when the specified value is true and "is not" when the
# specified value is false.
sub is_or_not {
  shift ? "is" : "is not";
}

# 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("name_prefix=s" => \$name_prefix);

# Print the help message if the parameters are not initialized in the code nor
# in the command line.
pod2usage(2) if not check_params($name_prefix);

# Call the example.
search_for_google_ads_fields($api_client, $name_prefix);

=pod

=head1 NAME

search_for_google_ads_fields

=head1 DESCRIPTION

This example searches for GoogleAdsFields that match a given prefix, retrieving
metadata such as whether the field is selectable, filterable, or sortable, along
with the data type and the fields that are selectable with the field. Each
GoogleAdsField represents either a resource (such as customer or campaign) or
a field (such as metrics.impressions or campaign.id).

=head1 SYNOPSIS

search_for_google_ads_fields.pl [options]

    -help                       Show the help message.
    -name_prefix				The name prefix to use in the query.

=cut