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

Get Geo Target Constant by Name

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.targeting;

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.services.GeoTargetConstantServiceClient;
import com.google.ads.googleads.v2.services.GeoTargetConstantSuggestion;
import com.google.ads.googleads.v2.services.SuggestGeoTargetConstantsRequest;
import com.google.ads.googleads.v2.services.SuggestGeoTargetConstantsResponse;
import com.google.protobuf.StringValue;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/** Gets GeoTargetConstants by given location names. */
public class GetGeoTargetConstantByName {

  public static void main(String[] args) {
    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 GetGeoTargetConstantByName().runExample(googleAdsClient);
    } 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);
      }
    }
  }

  private void runExample(GoogleAdsClient googleAdsClient) {
    GeoTargetConstantServiceClient geoTargetClient =
        googleAdsClient.getLatestVersion().createGeoTargetConstantServiceClient();

    SuggestGeoTargetConstantsRequest.Builder requestBuilder =
        SuggestGeoTargetConstantsRequest.newBuilder();

    // Locale is using ISO 639-1 format. If an invalid locale is given, 'en' is used by default.
    requestBuilder.setLocale(StringValue.of("en"));

    // A list of country codes can be referenced here:
    // https://developers.google.com/adwords/api/docs/appendix/geotargeting
    requestBuilder.setCountryCode(StringValue.of("FR"));

    requestBuilder
        .getLocationNamesBuilder()
        .addAllNames(
            Stream.of("Paris", "Quebec", "Spain", "Deutschland")
                .map(StringValue::of)
                .collect(Collectors.toList()));

    SuggestGeoTargetConstantsResponse response =
        geoTargetClient.suggestGeoTargetConstants(requestBuilder.build());

    for (GeoTargetConstantSuggestion suggestion : response.getGeoTargetConstantSuggestionsList()) {
      System.out.printf(
          "%s (%s,%s,%s,%s) is found in locale (%s) with reach (%d) for search term (%s).%n",
          suggestion.getGeoTargetConstant().getResourceName(),
          suggestion.getGeoTargetConstant().getName().getValue(),
          suggestion.getGeoTargetConstant().getCountryCode().getValue(),
          suggestion.getGeoTargetConstant().getTargetType().getValue(),
          suggestion.getGeoTargetConstant().getStatus().name(),
          suggestion.getLocale().getValue(),
          suggestion.getReach().getValue(),
          suggestion.getSearchTerm().getValue());
    }
  }
}
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.Services;

using System;

namespace Google.Ads.GoogleAds.Examples.V2
{
    /// <summary>
    /// This code example illustrates getting GeoTargetConstants by given location names.
    /// </summary>
    public class GetGeoTargetConstantsByName : 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)
        {
            GetGeoTargetConstantsByName codeExample = new GetGeoTargetConstantsByName();

            Console.WriteLine(codeExample.Description);

            codeExample.Run(new GoogleAdsClient());
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get
            {
                return "This code example illustrates getting GeoTargetConstants by " +
                    "given location names.";
            }
        }

        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        public void Run(GoogleAdsClient client)
        {
            // Get the GeoTargetConstantServiceClient.
            GeoTargetConstantServiceClient geoService =
                client.GetService(Services.V2.GeoTargetConstantService);

            // Locale is using ISO 639-1 format. If an invalid locale is given,
            // 'en' is used by default.
            string locale = "en";

            // A list of country codes can be referenced here:
            // https://developers.google.com/adwords/api/docs/appendix/geotargeting
            string countryCode = "FR";

            String[] locations = { "Paris", "Quebec", "Spain", "Deutschland" };

            SuggestGeoTargetConstantsRequest request = new SuggestGeoTargetConstantsRequest()
            {
                Locale = locale,
                CountryCode = countryCode,
                LocationNames = new SuggestGeoTargetConstantsRequest.Types.LocationNames()
            };

            request.LocationNames.Names.AddRange(locations);

            try
            {
                SuggestGeoTargetConstantsResponse response =
                    geoService.SuggestGeoTargetConstants(request);

                foreach (GeoTargetConstantSuggestion suggestion
                    in response.GeoTargetConstantSuggestions)
                {
                    Console.WriteLine(
                        $"{suggestion.GeoTargetConstant.ResourceName} " +
                        $"({suggestion.GeoTargetConstant.Name}, " +
                        $"{suggestion.GeoTargetConstant.CountryCode}, " +
                        $"{suggestion.GeoTargetConstant.TargetType}, " +
                        $"{suggestion.GeoTargetConstant.Status}) is found in locale " +
                        $"({suggestion.Locale}) with reach ({suggestion.Reach.Value}) " +
                        $"for search term ({suggestion.SearchTerm}).");
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
            }
        }
    }
}
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\Targeting;

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\GeoTargetConstantStatusEnum\GeoTargetConstantStatus;
use Google\Ads\GoogleAds\V2\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V2\Services\GeoTargetConstantSuggestion;
use Google\Ads\GoogleAds\V2\Services\SuggestGeoTargetConstantsRequest\LocationNames;
use Google\ApiCore\ApiException;
use Google\Protobuf\StringValue;

/**
 * This code example gets geo target constants by given location names.
 */
class GetGeoTargetConstantByNames
{
    // Locale is using ISO 639-1 format. If an invalid locale is given, 'en' will be used by
    // default.
    const LOCALE = 'en';
    // A list of country codes can be referenced here:
    // https://developers.google.com/adwords/api/docs/appendix/geotargeting.
    const COUNTRY_CODE = 'FR';
    // The location names to get suggested geo target constants.
    private static $LOCATION_NAMES = ['Paris', 'Quebec', 'Spain', 'Deutschland'];

    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::LOCATION_NAMES => GetOpt::MULTIPLE_ARGUMENT,
            ArgumentNames::LOCALE => GetOpt::OPTIONAL_ARGUMENT,
            ArgumentNames::COUNTRY_CODE => GetOpt::OPTIONAL_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::LOCATION_NAMES] ?: self::$LOCATION_NAMES,
                $options[ArgumentNames::LOCALE] ?: self::LOCALE,
                $options[ArgumentNames::COUNTRY_CODE] ?: self::COUNTRY_CODE
            );
        } 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 array $locationNames the list of location names to get suggested geo target constants
     * @param string $locale the locale of the geo target constant to be retrieved
     * @param string $countryCode the country code of the geo target constant to be retrieved
     */
    public static function runExample(
        GoogleAdsClient $googleAdsClient,
        array $locationNames,
        string $locale,
        string $countryCode
    ) {
        $geoTargetConstantServiceClient = $googleAdsClient->getGeoTargetConstantServiceClient();

        $names = [];
        foreach ($locationNames as $locationName) {
            $names[] = new StringValue(['value' => $locationName]);
        }
        $response = $geoTargetConstantServiceClient->suggestGeoTargetConstants(
            new StringValue(['value' => $locale]),
            new StringValue(['value' => $countryCode]),
            ['locationNames' => new LocationNames(['names' => $names])]
        );

        // Iterates over all geo target constant suggestion objects and prints the requested field
        // values for each one.
        foreach ($response->getGeoTargetConstantSuggestions() as $geoTargetConstantSuggestion) {
            /** @var GeoTargetConstantSuggestion $geoTargetConstantSuggestion */
            printf(
                "Found '%s' ('%s','%s','%s',%s) in locale '%s' with reach %d"
                . " for the search term '%s'.%s",
                $geoTargetConstantSuggestion->getGeoTargetConstant()->getResourceName(),
                $geoTargetConstantSuggestion->getGeoTargetConstant()->getNameUnwrapped(),
                $geoTargetConstantSuggestion->getGeoTargetConstant()->getCountryCodeUnwrapped(),
                $geoTargetConstantSuggestion->getGeoTargetConstant()->getTargetTypeUnwrapped(),
                GeoTargetConstantStatus::name(
                    $geoTargetConstantSuggestion->getGeoTargetConstant()->getStatus()
                ),
                $geoTargetConstantSuggestion->getLocaleUnwrapped(),
                $geoTargetConstantSuggestion->getReachUnwrapped(),
                $geoTargetConstantSuggestion->getSearchTermUnwrapped(),
                PHP_EOL
            );
        }
    }
}

GetGeoTargetConstantByNames::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 getting GeoTargetConstants by given location names.
"""


import sys

import google.ads.google_ads.client


def main(client):
    gtc_service = client.get_service('GeoTargetConstantService', version='v2')

    location_names = (
        client.get_type('SuggestGeoTargetConstantsRequest',
                        version='v2').LocationNames())

    for location in ['Paris', 'Quebec', 'Spain', 'Deutschland']:
        location_name = location_names.names.add()
        location_name.value = location

    # Locale is using ISO 639-1 format. If an invalid locale is given,
    # 'en' is used by default.
    locale = client.get_type('StringValue', version='v2')
    locale.value = 'en'

    # A list of country codes can be referenced here:
    # https://developers.google.com/adwords/api/docs/appendix/geotargeting
    country_code = client.get_type('StringValue', version='v2')
    country_code.value = 'FR'

    results = gtc_service.suggest_geo_target_constants(
        locale, country_code, location_names=location_names)

    geo_target_constant_status_enum = client.get_type(
        'GeoTargetConstantStatusEnum').GeoTargetConstantStatus

    try:
        for suggestion in results.geo_target_constant_suggestions:
            geo_target_constant = suggestion.geo_target_constant
            print('%s (%s, %s, %s, %s) is found in locale (%s) with reach (%d) '
                  'from search term (%s).'
                  % (geo_target_constant.resource_name,
                     geo_target_constant.name.value,
                     geo_target_constant.country_code.value,
                     geo_target_constant.target_type.value,
                     geo_target_constant_status_enum.Name(
                         geo_target_constant.status),
                     suggestion.locale.value,
                     suggestion.reach.value,
                     suggestion.search_term.value))
    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())

    main(google_ads_client)
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 code example illustrates getting GeoTargetConstants by given
# location names

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

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

  gtc_service = client.service.geo_target_constant

  location_names = client.resource.location_names do |ln|
    ['Paris', 'Quebec', 'Spain', 'Deutschland'].each do |name|
      ln.names << name
    end
  end

  # Locale is using ISO 639-1 format. If an invalid locale is given,
  # 'en' is used by default.
  locale = 'en'

  # A list of country codes can be referenced here:
  # https://developers.google.com/adwords/api/docs/appendix/geotargeting
  country_code = 'FR'

  response = gtc_service.suggest_geo_target_constants(locale, country_code,
      location_names: location_names)

  response.geo_target_constant_suggestions.each do |suggestion|
    puts sprintf("%s (%s,%s,%s,%s) is found in locale (%s) with reach (%d)" \
        " from search term (%s).", suggestion.geo_target_constant.resource_name,
        suggestion.geo_target_constant.name,
        suggestion.geo_target_constant.country_code,
        suggestion.geo_target_constant.target_type,
        suggestion.geo_target_constant.status,
        suggestion.locale,
        suggestion.reach,
        suggestion.search_term)
  end
end

if __FILE__ == $PROGRAM_NAME
  options = {}

  # Running the example with -h will print the command line usage.
  OptionParser.new do |opts|
    opts.banner = sprintf('Usage: ruby %s ', File.basename(__FILE__))

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

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

  begin
    get_geo_target_constant_by_names()
    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
  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