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

Generate Keyword Ideas

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

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.utils.ResourceNames;
import com.google.ads.googleads.v2.enums.KeywordPlanNetworkEnum.KeywordPlanNetwork;
import com.google.ads.googleads.v2.errors.GoogleAdsError;
import com.google.ads.googleads.v2.services.GenerateKeywordIdeaResponse;
import com.google.ads.googleads.v2.services.GenerateKeywordIdeaResult;
import com.google.ads.googleads.v2.services.GenerateKeywordIdeasRequest;
import com.google.ads.googleads.v2.services.KeywordPlanIdeaServiceClient;
import com.google.protobuf.StringValue;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Nullable;

/** Generates keyword ideas from a list of seed keywords. */
public class GenerateKeywordIdeas {

  private static class GenerateKeywordIdeasParams extends CodeSampleParams {

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

    @Parameter(
        names = ArgumentNames.LOCATION_ID,
        required = true,
        description =
            "Location criteria IDs. For example, specify 21167 for New York. For more information"
                + " on determining this value, see: "
                + " https://developers.google.com/adwords/api/docs/appendix/geotargeting.")
    private List<Long> locationIds;

    @Parameter(
        names = ArgumentNames.LANGUAGE_ID,
        required = true,
        description =
            "A language criterion ID. For example, specify 1000 for English. For more information"
                + " on determining this value, see: "
                + " https://developers.google.com/adwords/api/docs/appendix/codes-formats#languages")
    private Long languageId;

    @Parameter(names = ArgumentNames.KEYWORD_TEXT)
    private List<String> keywords = new ArrayList<>();

    @Parameter(
        names = ArgumentNames.PAGE_URL,
        description = "URL of a page related to your business")
    private String pageUrl;
  }

  public static void main(String[] args) throws IOException {
    GenerateKeywordIdeasParams params = new GenerateKeywordIdeasParams();
    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.locationIds =
          Arrays.asList(
              Long.parseLong("INSERT_LOCATION_ID_1_HERE"),
              Long.parseLong("INSERT_LOCATION_ID_2_HERE"));
      params.languageId = Long.parseLong("INSERT_LANGUAGE_ID_HERE");
      params.keywords = Arrays.asList("INSERT_KEYWORD_1_HERE", "INSERT_KEYWORD_2_HERE");
      // Optional: Use a URL related to your business to generate ideas.
      params.pageUrl = null;
    }

    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 GenerateKeywordIdeas()
          .runExample(
              googleAdsClient,
              params.customerId,
              params.languageId,
              params.locationIds,
              params.keywords,
              params.pageUrl);
    } 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 customerId the client customer ID.
   * @param languageId the language ID.
   * @param locationIds the location IDs.
   * @param keywords the list of keywords to use as a seed for ideas.
   * @param pageUrl optional URL related to your business to use as a seed for ideas.
   * @throws GoogleAdsException if an API request failed with one or more service errors.
   * @throws IllegalArgumentException if {@code keywords} is empty and {@code pageUrl} is null.
   * @throws Exception if the example failed due to other errors.
   */
  private void runExample(
      GoogleAdsClient googleAdsClient,
      long customerId,
      long languageId,
      List<Long> locationIds,
      List<String> keywords,
      @Nullable String pageUrl) {
    try (KeywordPlanIdeaServiceClient keywordPlanServiceClient =
        googleAdsClient.getLatestVersion().createKeywordPlanIdeaServiceClient()) {
      GenerateKeywordIdeasRequest.Builder requestBuilder =
          GenerateKeywordIdeasRequest.newBuilder()
              .setCustomerId(Long.toString(customerId))
              // Sets the language resource using the provided language ID.
              .setLanguage(StringValue.of(ResourceNames.languageConstant(languageId)))
              // Sets the network. To restrict to only Google Search, change the parameter below to
              // KeywordPlanNetwork.GOOGLE_SEARCH.
              .setKeywordPlanNetwork(KeywordPlanNetwork.GOOGLE_SEARCH_AND_PARTNERS);

      // Adds the resource name of each location ID to the request.
      for (Long locationId : locationIds) {
        requestBuilder.addGeoTargetConstants(
            StringValue.of(ResourceNames.geoTargetConstant(locationId)));
      }

      // Makes sure that keywords and/or page URL were specified. The request must have exactly one
      // of urlSeed, keywordSeed, or keywordAndUrlSeed set.
      if (keywords.isEmpty() && pageUrl == null) {
        throw new IllegalArgumentException(
            "At least one of keywords or page URL is required, but neither was specified.");
      }

      if (keywords.isEmpty()) {
        // Only page URL was specified, so use a UrlSeed.
        requestBuilder.getUrlSeedBuilder().setUrl(StringValue.of(pageUrl));
      } else if (pageUrl == null) {
        // Only keywords were specified, so use a KeywordSeed.
        requestBuilder
            .getKeywordSeedBuilder()
            .addAllKeywords(keywords.stream().map(StringValue::of).collect(Collectors.toList()));
      } else {
        // Both page URL and keywords were specified, so use a KeywordAndUrlSeed.
        requestBuilder
            .getKeywordAndUrlSeedBuilder()
            .setUrl(StringValue.of(pageUrl))
            .addAllKeywords(keywords.stream().map(StringValue::of).collect(Collectors.toList()));
      }

      // Sends the keyword ideas request.
      GenerateKeywordIdeaResponse response =
          keywordPlanServiceClient.generateKeywordIdeas(requestBuilder.build());
      // Prints each result in the response.
      for (GenerateKeywordIdeaResult result : response.getResultsList()) {
        System.out.printf(
            "Keyword idea text '%s' has %d average monthly searches and '%s' competition.%n",
            result.getText().getValue(),
            result.getKeywordIdeaMetrics().getAvgMonthlySearches().getValue(),
            result.getKeywordIdeaMetrics().getCompetition());
      }
    }
  }
}
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.Common;
using Google.Ads.GoogleAds.V2.Services;

using System;
using static Google.Ads.GoogleAds.V2.Enums.KeywordPlanNetworkEnum.Types;

namespace Google.Ads.GoogleAds.Examples.V2
{
    /// <summary>
    /// This code example generates keyword ideas from a list of seed keywords or a seed page URL.
    /// </summary>
    public class GenerateKeywordIdeas : 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)
        {
            GenerateKeywordIdeas codeExample = new GenerateKeywordIdeas();
            Console.WriteLine(codeExample.Description);

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

            // Location criteria IDs. For example, specify 21167 for New York. For more information
            // on determining this value, see
            // https://developers.google.com/adwords/api/docs/appendix/geotargeting.
            long locationId1 = long.Parse("INSERT_LOCATION_ID_1_HERE");
            long locationId2 = long.Parse("INSERT_LOCATION_ID_2_HERE");

            // A language criterion ID. For example, specify 1000 for English. For more information
            // on determining this value, see
            // https://developers.google.com/adwords/api/docs/appendix/codes-formats#languages.
            long languageId = long.Parse("INSERT_LANGUAGE_ID_HERE");

            string keywordText1 = "INSERT_KEYWORD_TEXT_1_HERE";
            string keywordText2 = "INSERT_KEYWORD_TEXT_2_HERE";

            // Optional: Specify a URL string related to your business to generate ideas.
            string pageUrl = null;

            codeExample.Run(new GoogleAdsClient(), customerId,
                new long[] { locationId1, locationId2}, languageId,
                new string[] { keywordText1, keywordText2}, pageUrl);
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get
            {
                return "This code example generates keyword ideas from a list of seed keywords " +
                    "or a seed page URL";
            }
        }

        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The customer ID for which the call is made.</param>
        /// <param name="locationIds">The list of location IDs to restrict the search.</param>
        /// <param name="languageId">The language to restrict the search.</param>
        /// <param name="keywordTexts">The list of seed keywords.</param>
        /// <param name="pageUrl">The seed page URL.</param>
        public void Run(GoogleAdsClient client, long customerId, long[] locationIds,
            long languageId, string[] keywordTexts, string pageUrl)
        {
            KeywordPlanIdeaServiceClient keywordPlanIdeaService =
                client.GetService(Services.V2.KeywordPlanIdeaService);

            // Make sure that keywords and/or page URL were specified. The request must have
            // exactly one of urlSeed, keywordSeed, or keywordAndUrlSeed set.
            if (keywordTexts.Length == 0 && string.IsNullOrEmpty(pageUrl))
            {
                throw new ArgumentException("At least one of keywords or page URL is required, " +
                    "but neither was specified.");
            }

            // Specify the optional arguments of the request as a keywordSeed, UrlSeed,
            // or KeywordAndUrlSeed.
            GenerateKeywordIdeasRequest request = new GenerateKeywordIdeasRequest()
            {
                CustomerId = customerId.ToString(),
            };

            if (keywordTexts.Length == 0)
            {
                // Only page URL was specified, so use a UrlSeed.
                request.UrlSeed = new UrlSeed()
                {
                    Url = pageUrl
                };
            }
            else if (string.IsNullOrEmpty(pageUrl))
            {
                // Only keywords were specified, so use a KeywordSeed.
                request.KeywordSeed = new KeywordSeed();
                request.KeywordSeed.Keywords.AddRange(keywordTexts);
            }
            else
            {
                // Both page URL and keywords were specified, so use a KeywordAndUrlSeed.
                request.KeywordAndUrlSeed = new KeywordAndUrlSeed();
                request.KeywordAndUrlSeed.Url = pageUrl;
                request.KeywordAndUrlSeed.Keywords.AddRange(keywordTexts);
            }


            // Create a list of geo target constants based on the resource name of specified
            // location IDs.
            foreach (long locationId in locationIds)
            {
                request.GeoTargetConstants.Add(ResourceNames.GeoTargetConstant(locationId));
            }

            request.Language = ResourceNames.LanguageConstant(languageId);
            // Set the network. To restrict to only Google Search, change the parameter below to
            // KeywordPlanNetwork.GoogleSearch.
            request.KeywordPlanNetwork = KeywordPlanNetwork.GoogleSearchAndPartners;

            try
            {
                // Generate keyword ideas based on the specified parameters.
                GenerateKeywordIdeaResponse response =
                    keywordPlanIdeaService.GenerateKeywordIdeas(request);

                // Iterate over the results and print its detail.
                foreach (GenerateKeywordIdeaResult result in response.Results)
                {
                    KeywordPlanHistoricalMetrics metrics = result.KeywordIdeaMetrics;
                    Console.WriteLine($"Keyword idea text '{result.Text}' has " +
                        $"{metrics.AvgMonthlySearches} average monthly searches and competition " +
                        $"is {metrics.Competition}.");
                }
            }
            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\Planning;

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\Util\V2\ResourceNames;
use Google\Ads\GoogleAds\V2\Enums\KeywordPlanNetworkEnum\KeywordPlanNetwork;
use Google\Ads\GoogleAds\V2\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V2\Services\GenerateKeywordIdeaResult;
use Google\Ads\GoogleAds\V2\Services\KeywordAndUrlSeed;
use Google\Ads\GoogleAds\V2\Services\KeywordSeed;
use Google\Ads\GoogleAds\V2\Services\UrlSeed;
use Google\ApiCore\ApiException;
use Google\Protobuf\StringValue;

/** This example generates keyword ideas from a list of seed keywords or a seed page URL. */
class GenerateKeywordIdeas
{
    const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
    // Location criteria IDs. For example, specify 21167 for New York. For more information
    // on determining this value, see
    // https://developers.google.com/adwords/api/docs/appendix/geotargeting.
    const LOCATION_ID_1 = 'INSERT_LOCATION_ID_1_HERE';
    const LOCATION_ID_2 = 'INSERT_LOCATION_ID_2_HERE';

    // A language criterion ID. For example, specify 1000 for English. For more information
    // on determining this value, see
    // https://developers.google.com/adwords/api/docs/appendix/codes-formats#languages.
    const LANGUAGE_ID = 'INSERT_LANGUAGE_ID_HERE';

    const KEYWORD_TEXT_1 = 'INSERT_KEYWORD_TEXT_1_HERE';
    const KEYWORD_TEXT_2 = 'INSERT_KEYWORD_TEXT_2_HERE';

    // Optional: Specify a URL string related to your business to generate ideas.
    const PAGE_URL = null;

    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::CUSTOMER_ID => GetOpt::REQUIRED_ARGUMENT,
            ArgumentNames::LOCATION_ID => GetOpt::MULTIPLE_ARGUMENT,
            ArgumentNames::LANGUAGE_ID => GetOpt::REQUIRED_ARGUMENT,
            ArgumentNames::KEYWORD_TEXT => GetOpt::MULTIPLE_ARGUMENT,
            ArgumentNames::PAGE_URL => 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::CUSTOMER_ID] ?: self::CUSTOMER_ID,
                $options[ArgumentNames::LOCATION_ID] ?:
                    [self::LOCATION_ID_1, self::LOCATION_ID_2],
                $options[ArgumentNames::LANGUAGE_ID] ?: self::LANGUAGE_ID,
                $options[ArgumentNames::KEYWORD_TEXT] ?:
                    [self::KEYWORD_TEXT_1, self::KEYWORD_TEXT_2],
                $options[ArgumentNames::PAGE_URL] ?: self::PAGE_URL
            );
        } 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 $customerId the client customer ID without hyphens
     * @param int[] $locationIds the location IDs
     * @param int $languageId the language ID
     * @param string[] $keywords the list of keywords to use as a seed for ideas
     * @param string $pageUrl optional URL related to your business to use as a seed for ideas
     */
    public static function runExample(
        GoogleAdsClient $googleAdsClient,
        $customerId,
        array $locationIds,
        $languageId,
        array $keywords,
        $pageUrl
    ) {
        $keywordPlanIdeaServiceClient = $googleAdsClient->getKeywordPlanIdeaServiceClient();

        // Make sure that keywords and/or page URL were specified. The request must have exactly one
        // of urlSeed, keywordSeed, or keywordAndUrlSeed set.
        if (empty($keywords) && is_null($pageUrl)) {
            throw new \InvalidArgumentException(
                'At least one of keywords or page URL is required, but neither was specified.'
            );
        }

        // Specify the optional arguments of the request as a keywordSeed, urlSeed,
        // or keywordAndUrlSeed.
        $requestOptionalArgs = [];
        if (empty($keywords)) {
            // Only page URL was specified, so use a UrlSeed.
            $requestOptionalArgs['urlSeed'] =
                new UrlSeed(['url' => new StringValue(['value' => $pageUrl])]);
        } elseif (is_null($pageUrl)) {
            // Only keywords were specified, so use a KeywordSeed.
            $requestOptionalArgs['keywordSeed'] = new KeywordSeed([
                'keywords' => array_map(function ($keyword) {
                    return new StringValue(['value' => $keyword]);
                }, $keywords)
            ]);
        } else {
            // Both page URL and keywords were specified, so use a KeywordAndUrlSeed.
            $requestOptionalArgs['keywordAndUrlSeed'] = new KeywordAndUrlSeed([
                'url' => new StringValue(['value' => $pageUrl]),
                'keywords' => array_map(function ($keyword) {
                    return new StringValue(['value' => $keyword]);
                }, $keywords)
            ]);
        }

        // Create a list of geo target constants based on the resource name of specified location
        // IDs.
        $geoTargetConstants =  array_map(function ($locationId) {
            return new StringValue(
                ['value' => ResourceNames::forGeoTargetConstant($locationId)]
            );
        }, $locationIds);

        // Generate keyword ideas based on the specified parameters.
        $response = $keywordPlanIdeaServiceClient->generateKeywordIdeas(
            $customerId,
            // Set the language resource using the provided language ID.
            new StringValue(['value' => ResourceNames::forLanguageConstant($languageId)]),
            // Add the resource name of each location ID to the request.
            $geoTargetConstants,
            // Set the network. To restrict to only Google Search, change the parameter below to
            // KeywordPlanNetwork::GOOGLE_SEARCH.
            KeywordPlanNetwork::GOOGLE_SEARCH_AND_PARTNERS,
            $requestOptionalArgs
        );

        // Iterate over the results and print its detail.
        foreach ($response->getResults() as $result) {
            /** @var GenerateKeywordIdeaResult $result */
            // Note that the competition printed below is enum value.
            // For example, a value of 2 will be returned when the competition is 'LOW'.
            // A mapping of enum names to values can be found at KeywordPlanCompetitionLevel.php.
            printf(
                "Keyword idea text '%s' has %d average monthly searches and competition as %d.%s",
                $result->getText()->getValue(),
                is_null($result->getKeywordIdeaMetrics()) ?
                    0 : $result->getKeywordIdeaMetrics()->getAvgMonthlySearches()->getValue(),
                is_null($result->getKeywordIdeaMetrics()) ?
                    0 : $result->getKeywordIdeaMetrics()->getCompetition(),
                PHP_EOL
            );
        }
    }
}

GenerateKeywordIdeas::main();
Ruby
#!/usr/bin/env ruby
# Encoding: utf-8
#
# 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 all campaigns. To add campaigns, run add_campaigns.rb.

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

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

  # Make sure that keywords and/or page URL were specified. The request must
  # have exactly one of urlSeed, keywordSeed, or keywordAndUrlSeed set.
  if keywords.reject {|k| k.nil?}.empty? && page_url.nil?
    raise "At least one of keywords or page URL is required."
  end

  kp_idea_service = client.service.keyword_plan_idea

  options_hash = if keywords.empty?
                   seed = client.resource.url_seed do |seed|
                     seed.url = page_url
                   end
                   {url_seed: seed}
                 elsif page_url.nil?
                   seed = client.resource.keyword_seed do |seed|
                     keywords.each do |keyword|
                       seed.keywords << keyword
                     end
                   end
                   {keyword_seed: seed}
                 else
                   seed = client.resource.keyword_and_url_seed do |seed|
                     seed.url = page_url
                     keywords.each do |keyword|
                       seed.keywords << client.wrapper.string(keyword)
                     end
                   end
                   {keyword_and_url_seed: seed}
                 end

  geo_target_constants = location_ids.map do |location_id|
    client.path.geo_target_constant(location_id)
  end

  response = kp_idea_service.generate_keyword_ideas(
    customer_id,
    client.wrapper.string(client.path.language_constant(language_id)),
    geo_target_constants,
    # To restrict to only Google Search, change the parameter below to
    # :GOOGLE_SEARCH
    :GOOGLE_SEARCH_AND_PARTNERS,
    **options_hash
  )

  response.results.each do |result|
    monthly_searches = if result.keyword_idea_metrics.nil?
                         0
                       else
                         result.keyword_idea_metrics.avg_monthly_searches
                       end
    competition = if result.keyword_idea_metrics.nil?
                    :UNSPECIFIED
                  else
                    result.keyword_idea_metrics.competition
                  end
    puts "Keyword idea text #{result.text} has #{monthly_searches} average " +
        "monthly searches and competition as #{competition}."
  end
end

if __FILE__ == $0
  PAGE_SIZE = 1000

  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[:location_id_1] = 'INSERT_LOCATION_ID_1_HERE'
  options[:location_id_2] = 'INSERT_LOCATION_ID_2_HERE'

  options[:language_id] = 'INSERT_LANGUAGE_ID_HERE'

  # Optional but recommended
  options[:keyword_text_1] = 'INSERT_KEYWORD_TEXT_1_HERE'
  options[:keyword_text_2] = 'INSERT_KEYWORD_TEXT_2_HERE'

  # Optional: Specify a URL string related to your business to generate ideas.
  options[:page_url] = nil

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

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

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

    opts.on('-L', '--location-id-1 LOCATION-ID-1', String,
        'Location ID 1') do |v|
      options[:location_id_1] = v
    end

    opts.on('-l', '--location-id-2 LOCATION-ID-2', String,
        'Location ID 2') do |v|
      options[:location_id_2] = v
    end

    opts.on('-a', '--language-id LANGUAGE-ID', String, 'Language ID') do |v|
      options[:language_id] = v
    end

    opts.on('-K', '--keyword-text-1 KEYWORD-TEXT-1', String,
        'Keyword Text 1') do |v|
      options[:keyword_text_1] = v
    end

    opts.on('-k', '--keyword-text-2 KEYWORD-TEXT-2', String,
        'Keyword Text 2') do |v|
      options[:keyword_text_2] = v
    end

    opts.on('-p', '--page-url PAGE-URL', String, 'Page URL') do |v|
      options[:page_url] = v
    end

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

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

  begin
    generate_keyword_ideas(
      options.fetch(:customer_id).tr("-", ""),
      [options.fetch(:location_id_1), options.fetch(:location_id_2)],
      options.fetch(:language_id),
      [options[:keyword_text_1], options[:keyword_text_2]],
      options[:page_url]
    )
  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

Envoyer des commentaires concernant…

Google Ads API Beta
Google Ads API Beta
Besoin d'aide ? Consultez notre page d'assistance.