Generate Keyword Ideas

Search for new keywords that are relevant to your Google Search campaign. You can provide keyword and URL seeds to generate ideas. Set targeting parameters such as locations, language, and network settings to narrow down your search. Historical statistics such as search volume data for these keywords are returned, so you can determine if you want to use the keyword for your campaign. For users familiar with the Google Ads UI, this is similar to Keyword Planner.

Generating ideas

Generate keyword ideas for a campaign with KeywordPlanIdeaService.GenerateKeywordIdeas.

There are several ways you can create seeds for generating new keywords:

  • For words or phrases that describe what you're advertising, use KeywordSeed. This could be a general type of business you are targeting such as plumbers, or it could be a product or service you offer such as drain cleaning.
  • For the URL of a webpage or entire website related to your business, use UrlSeed. The URL seed targets only a specific URL. If there are no hits, the search automatically expands up to the pages from the same domain.
  • For both keyword seeds and a URL seeds, use KeywordAndUrlSeed.
  • For an entire site, use SiteSeed. Given a top-level domain name, such as www.example.com, the site seed generates up to 250,000 keyword ideas from publicly available information.

To narrow down your targeting, you can set the language, location, network, and whether to include adult keywords in the GenerateKeywordIdeasRequest. This function supports pagination.

Ideas are returned with historical metrics which can be used to filter a list down to use with forecasts. For example, you might only want to target high search volumes to maximize the reach of your campaign, or you might want to target only higher competition scores to boost your awareness.

Java

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.
    GenerateKeywordIdeasPagedResponse response =
        keywordPlanServiceClient.generateKeywordIdeas(requestBuilder.build());
    // Prints each result in the response.
    for (GenerateKeywordIdeaResult result : response.iterateAll()) {
      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#

public void Run(GoogleAdsClient client, long customerId, long[] locationIds,
    long languageId, string[] keywordTexts, string pageUrl)
{
    KeywordPlanIdeaServiceClient keywordPlanIdeaService =
        client.GetService(Services.V5.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.
        var response =
            keywordPlanIdeaService.GenerateKeywordIdeas(request);

        // Iterate over the results and print its detail.
        foreach (GenerateKeywordIdeaResult result in response)
        {
            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}");
        throw;
    }
}
    

PHP

public static function runExample(
    GoogleAdsClient $googleAdsClient,
    int $customerId,
    array $locationIds,
    int $languageId,
    array $keywords,
    ?string $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(
        // Set the language resource using the provided language ID.
        new StringValue(['value' => ResourceNames::forLanguageConstant($languageId)]),
        [
            'customerId' => $customerId,
            // Add the resource name of each location ID to the request.
            'geoTargetConstants' => $geoTargetConstants,
            // Set the network. To restrict to only Google Search, change the parameter below to
            // KeywordPlanNetwork::GOOGLE_SEARCH.
            'keywordPlanNetwork' => KeywordPlanNetwork::GOOGLE_SEARCH_AND_PARTNERS
        ] + $requestOptionalArgs
    );

    // Iterate over the results and print its detail.
    foreach ($response->iterateAllElements() 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->getTextUnwrapped(),
            is_null($result->getKeywordIdeaMetrics()) ?
                0 : $result->getKeywordIdeaMetrics()->getAvgMonthlySearchesUnwrapped(),
            is_null($result->getKeywordIdeaMetrics()) ?
                0 : $result->getKeywordIdeaMetrics()->getCompetition(),
            PHP_EOL
        );
    }
}
    

Python

def main(
    client, customer_id, location_ids, language_id, keyword_texts, page_url
    

Ruby

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

  include_adult_keywords = true

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

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

Perl

sub generate_keyword_ideas {
  my (
    $api_client,  $customer_id,   $location_ids,
    $language_id, $keyword_texts, $page_url
  ) = @_;

  # Make sure that keywords and/or page URL were specified. The request must have
  # exactly one of urlSeed, keywordSeed, or keywordAndUrlSeed set.
  if (not scalar @$keyword_texts and not $page_url) {
    die "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.
  my $request_option_args = {};
  if (!scalar @$keyword_texts) {
    # Only page URL was specified, so use a UrlSeed.
    $request_option_args->{urlSeed} =
      Google::Ads::GoogleAds::V5::Services::KeywordPlanIdeaService::UrlSeed->
      new({
        url => $page_url
      });
  } elsif (not $page_url) {
    # Only keywords were specified, so use a KeywordSeed.
    $request_option_args->{keywordSeed} =
      Google::Ads::GoogleAds::V5::Services::KeywordPlanIdeaService::KeywordSeed
      ->new({
        keywords => $keyword_texts
      });
  } else {
    # Both page URL and keywords were specified, so use a KeywordAndUrlSeed.
    $request_option_args->{keywordAndUrlSeed} =
      Google::Ads::GoogleAds::V5::Services::KeywordPlanIdeaService::KeywordAndUrlSeed
      ->new({
        url      => $page_url,
        keywords => $keyword_texts
      });
  }

  # Create a list of geo target constants based on the resource name of specified
  # location IDs.
  my $geo_target_constants = [
    map (
      Google::Ads::GoogleAds::V5::Utils::ResourceNames::geo_target_constant($_),
      @$location_ids)];

  # Generate keyword ideas based on the specified parameters.
  my $keyword_ideas_response =
    $api_client->KeywordPlanIdeaService()->generate_keyword_ideas({
      customerId => $customer_id,
      # Set the language resource using the provided language ID.
      language =>
        Google::Ads::GoogleAds::V5::Utils::ResourceNames::language_constant(
        $language_id),
      # Add the resource name of each location ID to the request.
      geoTargetConstants => $geo_target_constants,
      # Set the network. To restrict to only Google Search, change the parameter below
      # to GOOGLE_SEARCH.
      keywordPlanNetwork => GOOGLE_SEARCH_AND_PARTNERS,
      %$request_option_args
    });

  # Iterate over the results and print its detail.
  foreach my $result (@{$keyword_ideas_response->{results}}) {
    printf "Keyword idea text '%s' has %d average monthly searches " .
      "and '%s' competition.\n", $result->{text},
      $result->{keywordIdeaMetrics}{avgMonthlySearches}
      ? $result->{keywordIdeaMetrics}{avgMonthlySearches}
      : 0,
      $result->{keywordIdeaMetrics}{competition}
      ? $result->{keywordIdeaMetrics}{competition}
      : "undef";
  }

  return 1;
}
    

Migrating from the AdWords API

KeywordPlanIdeaService.GenerateKeywordIdeas replaces AdWords API's TargetingIdeaService.get with RequestType=IDEAS. These keywords can be added to your Keyword Plans for forecasting or obtaining overall historical metrics for your plan. A key difference is that the API no longer returns the original seed keywords in the ideas list. This means that if you were using this to get historical metrics for an existing list of keywords, you'll need to set up a KeywordPlan.

Mapping to the UI

KeywordPlanIdeaService.GenerateKeywordIdeas has similar functionality in the UI's Keyword Planner.

Keyword Planner UI Google Ads API
Enter Keywords and URLs
Locations GenerateKeywordIdeasRequest.geo_target_constants
Adult Keywords GenerateKeywordIdeasRequest.include_adult_keywords
Language GenerateKeywordIdeasRequest.language
Search Networks GenerateKeywordIdeasRequest.keyword_plan_network
Results: Keyword GenerateKeywordIdeaResult.text
Results: Metrics GenerateKeywordIdeaResult.keyword_idea_metrics