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.v4.enums.KeywordPlanNetworkEnum.KeywordPlanNetwork;
import com.google.ads.googleads.v4.errors.GoogleAdsError;
import com.google.ads.googleads.v4.errors.GoogleAdsException;
import com.google.ads.googleads.v4.services.GenerateKeywordIdeaResponse;
import com.google.ads.googleads.v4.services.GenerateKeywordIdeaResult;
import com.google.ads.googleads.v4.services.GenerateKeywordIdeasRequest;
import com.google.ads.googleads.v4.services.KeywordPlanIdeaServiceClient;
import com.google.ads.googleads.v4.services.KeywordPlanIdeaServiceClient.GenerateKeywordIdeasPagedResponse;
import com.google.ads.googleads.v4.utils.ResourceNames;
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.
      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#

// 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.V4.Errors;
using Google.Ads.GoogleAds.V4.Common;
using Google.Ads.GoogleAds.V4.Services;

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

namespace Google.Ads.GoogleAds.Examples.V4
{
    /// <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[] locationIds = new long[] {
                long.Parse("INSERT_LOCATION_ID_1_HERE"),
                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");

            // List of seed keywords.
            string[] keywordTexts = new string[] {
                "INSERT_KEYWORD_TEXT_1_HERE",
                "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, locationIds, languageId,
                keywordTexts, 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.V4.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

<?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\V4\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V4\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V4\GoogleAdsException;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Util\V4\ResourceNames;
use Google\Ads\GoogleAds\V4\Enums\KeywordPlanNetworkEnum\KeywordPlanNetwork;
use Google\Ads\GoogleAds\V4\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V4\Services\GenerateKeywordIdeaResult;
use Google\Ads\GoogleAds\V4\Services\KeywordAndUrlSeed;
use Google\Ads\GoogleAds\V4\Services\KeywordSeed;
use Google\Ads\GoogleAds\V4\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
{
    private 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.
    private const LOCATION_ID_1 = 'INSERT_LOCATION_ID_1_HERE';
    private 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.
    private const LANGUAGE_ID = 'INSERT_LANGUAGE_ID_HERE';

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

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

    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_IDS => GetOpt::MULTIPLE_ARGUMENT,
            ArgumentNames::LANGUAGE_ID => GetOpt::REQUIRED_ARGUMENT,
            ArgumentNames::KEYWORD_TEXTS => 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_IDS] ?:
                    [self::LOCATION_ID_1, self::LOCATION_ID_2],
                $options[ArgumentNames::LANGUAGE_ID] ?: self::LANGUAGE_ID,
                $options[ArgumentNames::KEYWORD_TEXTS] ?:
                    [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
                );
            }
            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 int $customerId the customer ID
     * @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|null $pageUrl optional URL related to your business to use as a seed for ideas
     */
    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->getText()->getValue(),
                is_null($result->getKeywordIdeaMetrics()) ?
                    0 : $result->getKeywordIdeaMetrics()->getAvgMonthlySearches()->getValue(),
                is_null($result->getKeywordIdeaMetrics()) ?
                    0 : $result->getKeywordIdeaMetrics()->getCompetition(),
                PHP_EOL
            );
        }
    }
}

GenerateKeywordIdeas::main();

Python

#!/usr/bin/env python
# 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
#
#     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 generates keyword ideas from a list of seed keywords."""


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

# Location IDs are listed here: https://developers.google.com/adwords/api/docs/appendix/geotargeting
# and they can also be retrieved using the GeoTargetConstantService as shown
# here: https://developers.google.com/google-ads/api/docs/targeting/location-targeting
_DEFAULT_LOCATION_IDS = ['1023191']  # location ID for New York, NY
# A language criterion ID. For example, specify 1000 for English. For more
# information on determining this value, see the below link:
# https://developers.google.com/adwords/api/docs/appendix/codes-formats#languages.
_DEFAULT_LANGUAGE_ID = '1000'  # language ID for English


def main(client, customer_id, location_ids, language_id, keyword_texts,
         page_url):
    keyword_plan_idea_service = client.get_service('KeywordPlanIdeaService',
                                                   version='v4')
    keyword_competition_level_enum = client.get_type(
        'KeywordPlanCompetitionLevelEnum',
            version='v4').KeywordPlanCompetitionLevel
    keyword_plan_network = client.get_type(
        'KeywordPlanNetworkEnum', version='v4').GOOGLE_SEARCH_AND_PARTNERS
    locations = map_locations_to_string_values(client, location_ids)
    language = map_language_to_string_value(client, language_id)

    # Only one of these values will be passed to the KeywordPlanIdeaService
    # depending on whether keywords, a page_url or both were given.
    url_seed = None
    keyword_seed = None
    keyword_url_seed = None

    # Either keywords or a page_url are required to generate keyword ideas
    # so this raises an error if neither are provided.
    if not (keyword_texts or page_url):
        raise ValueError('At least one of keywords or page URL is required, '
                         'but neither was specified.')

    # To generate keyword ideas with only a page_url and no keywords we need
    # to initialize a UrlSeed object with the page_url as the "url" field.
    if not keyword_texts and page_url:
        url_seed = client.get_type('UrlSeed', version='v4')
        url_seed.url.value = page_url


    # To generate keyword ideas with only a list of keywords and no page_url
    # we need to initialize a KeywordSeed object and set the "keywords" field
    # to be a list of StringValue objects.
    if keyword_texts and not page_url:
        keyword_seed = client.get_type('KeywordSeed', version='v4')
        keyword_protos = map_keywords_to_string_values(client, keyword_texts)
        keyword_seed.keywords.extend(keyword_protos)

    # To generate keyword ideas using both a list of keywords and a page_url we
    # need to initialize a KeywordAndUrlSeed object, setting both the "url" and
    # "keywords" fields.
    if keyword_texts and page_url:
        keyword_url_seed = client.get_type('KeywordAndUrlSeed', version='v4')
        keyword_url_seed.url.value = page_url
        keyword_protos = map_keywords_to_string_values(client, keyword_textss)
        keyword_url_seed.keywords.extend(keyword_protos)

    try:
        keyword_ideas = keyword_plan_idea_service.generate_keyword_ideas(
            customer_id, language, locations, False, keyword_plan_network,
            url_seed=url_seed, keyword_seed=keyword_seed,
            keyword_and_url_seed=keyword_url_seed)

        for idea in keyword_ideas:
            competition_value = keyword_competition_level_enum.Name(
                idea.keyword_idea_metrics.competition)
            print(f'Keyword idea text "{idea.text.value}" has '
                  f'"{idea.keyword_idea_metrics.avg_monthly_searches.value}" '
                  f'average monthly searches and "{competition_value}" '
                  'competition.\n')
    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)


def map_keywords_to_string_values(client, keyword_texts):
    keyword_protos = []
    for keyword in keyword_texts:
        string_val = client.get_type('StringValue', version='v4')
        string_val.value = keyword
        keyword_protos.append(string_val)
    return keyword_protos


def map_locations_to_string_values(client, location_ids):
    gtc_service = client.get_service('GeoTargetConstantService', version='v4')
    locations = []
    for location_id in location_ids:
        location = client.get_type('StringValue', version='v4')
        location.value = gtc_service.geo_target_constant_path(location_id)
        locations.append(location)
    return locations


def map_language_to_string_value(client, language_id):
    language = client.get_type('StringValue')
    language.value = client.get_service('LanguageConstantService',
                                        version='v4').language_constant_path(
                                            language_id)
    return language


if __name__ == '__main__':
    # GoogleAdsClient will read the google-ads.yaml configuration file in the
    # home directory if none is specified.
    google_ads_client = GoogleAdsClient.load_from_storage()

    parser = argparse.ArgumentParser(
        description='Generates keyword ideas from a list of seed keywords.')

    # The following argument(s) should be provided to run the example.
    parser.add_argument('-c', '--customer_id', type=str,
                        required=True, help='The Google Ads customer ID.')
    parser.add_argument('-k', '--keyword_texts', nargs='+', type=str,
                        required=False, default=[],
                        help='Space-delimited list of starter keywords')
    # To determine the appropriate location IDs, see:
    # https://developers.google.com/adwords/api/docs/appendix/geotargeting.
    parser.add_argument('-l', '--location_ids', nargs='+', type=str,
                        required=False, default=_DEFAULT_LOCATION_IDS,
                        help='Space-delimited list of location criteria IDs')
    # To determine the appropriate language ID, see:
    # https://developers.google.com/adwords/api/docs/appendix/codes-formats#languages.
    parser.add_argument('-i', '--language_id', type=str,
                        required=False, default=_DEFAULT_LANGUAGE_ID,
                        help='The language criterion ID.')
    # Optional: Specify a URL string related to your business to generate ideas.
    parser.add_argument('-p', '--page_url', type=str, required=False,
                        help='A URL string related to your business')

    args = parser.parse_args()

    main(google_ads_client, args.customer_id, args.location_ids,
         args.language_id, args.keyword_texts, args.page_url)

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

  include_adult_keywords = true

  response = kp_idea_service.generate_keyword_ideas(
    customer_id,
    client.wrapper.string(client.path.language_constant(language_id)),
    geo_target_constants,
    include_adult_keywords,
    # To restrict to only Google Search, change the parameter below to
    # :GOOGLE_SEARCH
    :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

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_ids] = ['INSERT_LOCATION_ID_1_HERE', 'INSERT_LOCATION_ID_2_HERE']

  options[:language_id] = 'INSERT_LANGUAGE_ID_HERE'

  # Optional but recommended
  options[:keyword_texts] = ['INSERT_KEYWORD_TEXT_1_HERE', '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-ids LOCATION-IDS', String,
        'Location IDs (comma separated)') do |v|
      options[:location_ids] = v.split(',')
    end

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

    opts.on('-K', '--keyword-texts KEYWORD-TEXTS', String,
        'Keyword Texts (comma separated)') do |v|
      options[:keyword_texts] = v.split(',')
    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_ids),
      options.fetch(:language_id),
      options.fetch(:keyword_texts),
      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
    raise
  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'])
    raise
  end
end

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 generates keyword ideas from a list of seed keywords or a seed
# page URL.

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 Google::Ads::GoogleAds::V4::Enums::KeywordPlanNetworkEnum
  qw(GOOGLE_SEARCH GOOGLE_SEARCH_AND_PARTNERS);
use Google::Ads::GoogleAds::V4::Services::KeywordPlanIdeaService::UrlSeed;
use Google::Ads::GoogleAds::V4::Services::KeywordPlanIdeaService::KeywordSeed;
use
  Google::Ads::GoogleAds::V4::Services::KeywordPlanIdeaService::KeywordAndUrlSeed;
use Google::Ads::GoogleAds::V4::Utils::ResourceNames;

use Getopt::Long qw(:config auto_help);
use Pod::Usage;
use Cwd qw(abs_path);

# 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.
my $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.
my $location_id_1 = "INSERT_LOCATION_ID_1_HERE";
my $location_id_2 = "INSERT_LOCATION_ID_2_HERE";
my $location_ids  = [];

# 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.
my $language_id = "INSERT_LANGUAGE_ID_HERE";

my $keyword_text_1 = "INSERT_KEYWORD_TEXT_1_HERE";
my $keyword_text_2 = "INSERT_KEYWORD_TEXT_2_HERE";
my $keyword_texts  = [];

# Optional: Specify a URL string related to your business to generate ideas.
my $page_url = undef;

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::V4::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::V4::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::V4::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::V4::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::V4::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;
}

# 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(
  "customer_id=s"   => \$customer_id,
  "location_ids=i"  => \@$location_ids,
  "language_id=i"   => \$language_id,
  "keyword_texts=s" => \@$keyword_texts,
  "page_url=s"      => \$page_url,
);
$location_ids  = [$location_id_1,  $location_id_2]  unless @$location_ids;
$keyword_texts = [$keyword_text_1, $keyword_text_2] unless @$keyword_texts;

# Print the help message if the parameters are not initialized in the code nor
# in the command line.
pod2usage(2)
  if
  not check_params($customer_id, $location_ids, $language_id, $keyword_texts);

# Call the example.
generate_keyword_ideas($api_client, $customer_id =~ s/-//gr,
  $location_ids, $language_id, $keyword_texts, $page_url);

=pod

=head1 NAME

generate_keyword_ideas

=head1 DESCRIPTION

This example generates keyword ideas from a list of seed keywords or a seed page URL.

=head1 SYNOPSIS

generate_keyword_ideas.pl [options]

    -help                       Show the help message.
    -customer_id                The Google Ads customer ID.
    -location_ids               The location criterion IDs, e.g. specify 21167 for New York.
    -language_id                The language criterion ID, e.g. specify 1000 for English.
    -keyword_texts              The keyword texts, as a seed for ideas.
    -page_url                   [optional] URL of a page related to your business.

=cut