Generate Forecast Metrics

Forecast metrics provide metrics for proposed or existing campaigns, ad groups, and keywords, including:

  • Impressions
  • Click through rate
  • Average cost per click
  • Clicks
  • Cost

Experiment with different configurations of campaigns, ad groups, and keywords to optimize each of these metrics. Data such as historical quality score and click through rate may be used in the forecast to simulate expected performance, such as the conversion rate.

Forecast materics are usually used after historical metrics. Historical metrics reduce a large keyword list to a more manageable size. Forecast metrics provide a more exact estimate of future campaign performance. Start with historical metrics for keywords. Once the list is manageable, start with forecast metrics to optimize the performance of your campaign.

Generating metrics

To generate forecast metrics:

  1. Create a KeywordPlan, KeywordPlanCampaigns, KeywordPlanAdGroups, KeywordPlanKeywords, and KeywordPlanNegativeKeywords.
  2. Call KeywordPlanService.GenerateForecastMetrics with that keyword plan.

Create a keyword plan

This code example:

  1. Creates a KeywordPlan and sets the time interval for the forecast.
  2. Adds a KeywordPlanCampaign to the KeywordPlan that sets the CPC bid, the network, the location to target, and the language to target.
  3. Adds KeywordPlanAdGroups to the KeywordPlanCampaign and sets the CPC bid on the ad group.
  4. Adds KeywordPlanKeywords to the KeywordPlanAdGroups with CPC bids set on each keyword.
  5. Adds a KeywordPlanNegativeKeyword to the KeywordPlanCampaign to exclude the keyword from the campaign.

Here are some tips when creating your keyword plan.

  • Create the ad groups based on themes such as creative relevance, product category, or cost per click.
  • Include common negative keywords. For example if you are not in recruitment, exclude the keyword 'jobs'.
  • Use an account which is related to the campaign. Don’t forecast from an unrelated account. We factor in things like quality score and creative content into the forecast.
  • If a campaign is unrelated to the rest of your account, use a new clean account for the forecast.
  • Repeat forecasts with different horizons to get a holistic picture.

Java

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

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.v3.enums.KeywordMatchTypeEnum.KeywordMatchType;
import com.google.ads.googleads.v3.enums.KeywordPlanForecastIntervalEnum.KeywordPlanForecastInterval;
import com.google.ads.googleads.v3.enums.KeywordPlanNetworkEnum.KeywordPlanNetwork;
import com.google.ads.googleads.v3.errors.GoogleAdsError;
import com.google.ads.googleads.v3.errors.GoogleAdsException;
import com.google.ads.googleads.v3.resources.KeywordPlan;
import com.google.ads.googleads.v3.resources.KeywordPlanAdGroup;
import com.google.ads.googleads.v3.resources.KeywordPlanCampaign;
import com.google.ads.googleads.v3.resources.KeywordPlanForecastPeriod;
import com.google.ads.googleads.v3.resources.KeywordPlanGeoTarget;
import com.google.ads.googleads.v3.resources.KeywordPlanKeyword;
import com.google.ads.googleads.v3.resources.KeywordPlanNegativeKeyword;
import com.google.ads.googleads.v3.services.KeywordPlanAdGroupOperation;
import com.google.ads.googleads.v3.services.KeywordPlanAdGroupServiceClient;
import com.google.ads.googleads.v3.services.KeywordPlanCampaignOperation;
import com.google.ads.googleads.v3.services.KeywordPlanCampaignServiceClient;
import com.google.ads.googleads.v3.services.KeywordPlanKeywordOperation;
import com.google.ads.googleads.v3.services.KeywordPlanKeywordServiceClient;
import com.google.ads.googleads.v3.services.KeywordPlanNegativeKeywordOperation;
import com.google.ads.googleads.v3.services.KeywordPlanNegativeKeywordServiceClient;
import com.google.ads.googleads.v3.services.KeywordPlanOperation;
import com.google.ads.googleads.v3.services.KeywordPlanServiceClient;
import com.google.ads.googleads.v3.services.MutateKeywordPlanAdGroupsResponse;
import com.google.ads.googleads.v3.services.MutateKeywordPlanCampaignsResponse;
import com.google.ads.googleads.v3.services.MutateKeywordPlanKeywordResult;
import com.google.ads.googleads.v3.services.MutateKeywordPlanKeywordsResponse;
import com.google.ads.googleads.v3.services.MutateKeywordPlanNegativeKeywordsResponse;
import com.google.ads.googleads.v3.services.MutateKeywordPlansResponse;
import com.google.ads.googleads.v3.utils.ResourceNames;
import com.google.protobuf.Int64Value;
import com.google.protobuf.StringValue;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Creates a keyword plan, which can be reused for retrieving forecast metrics and historic metrics.
 */
public class AddKeywordPlan {

  private static class AddKeywordPlanParams extends CodeSampleParams {

    @Parameter(
        names = ArgumentNames.CUSTOMER_ID,
        description = "The customer in which to create a new keyword plan.")
    public Long customerId;
  }

  public static void main(String[] args) {
    AddKeywordPlanParams params = new AddKeywordPlanParams();
    if (!params.parseArguments(args)) {

      // Optional, specify the customer ID under which to create a new keyword plan.
      params.customerId = Long.valueOf("INSERT_CUSTOMER_ID");
    }
    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 AddKeywordPlan().runExample(googleAdsClient, params.customerId);
    } 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 code example.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   */
  private void runExample(GoogleAdsClient googleAdsClient, Long customerId) {
    String keywordPlanResource = createKeywordPlan(googleAdsClient, customerId);
    String planCampaignResource =
        createKeywordPlanCampaign(googleAdsClient, customerId, keywordPlanResource);
    String planAdGroupResource =
        createKeywordPlanAdGroup(googleAdsClient, customerId, planCampaignResource);
    createKeywordPlanKeywords(googleAdsClient, customerId, planAdGroupResource);
    createKeywordPlanNegativeKeywords(googleAdsClient, customerId, planCampaignResource);
  }

  /**
   * Creates a keyword plan.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   */
  private static String createKeywordPlan(GoogleAdsClient googleAdsClient, Long customerId) {
    KeywordPlan plan =
        KeywordPlan.newBuilder()
            .setName(
                StringValue.of("Keyword plan for traffic estimate #" + System.currentTimeMillis()))
            .setForecastPeriod(
                KeywordPlanForecastPeriod.newBuilder()
                    .setDateInterval(KeywordPlanForecastInterval.NEXT_QUARTER)
                    .build())
            .build();

    KeywordPlanOperation op = KeywordPlanOperation.newBuilder().setCreate(plan).build();

    try (KeywordPlanServiceClient client =
        googleAdsClient.getLatestVersion().createKeywordPlanServiceClient()) {
      // Adds the keyword plan.
      MutateKeywordPlansResponse response =
          client.mutateKeywordPlans(String.valueOf(customerId), Arrays.asList(op));

      // Displays the results.
      String resourceName = response.getResults(0).getResourceName();
      System.out.printf("Created keyword plan: %s%n", resourceName);
      return resourceName;
    }
  }

  /**
   * Creates a campaign for the keyword plan.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @param keywordPlanResource the keyword plan resource name.
   */
  private static String createKeywordPlanCampaign(
      GoogleAdsClient googleAdsClient, Long customerId, String keywordPlanResource) {
    // Creates a keyword plan campaign.
    KeywordPlanCampaign.Builder campaign =
        KeywordPlanCampaign.newBuilder()
            .setName(StringValue.of("Keyword plan campaign #" + System.currentTimeMillis()))
            .setCpcBidMicros(Int64Value.of(1_000_000L))
            .setKeywordPlanNetwork(KeywordPlanNetwork.GOOGLE_SEARCH)
            .setKeywordPlan(StringValue.of(keywordPlanResource));

    // See https://developers.google.com/adwords/api/docs/appendix/geotargeting
    // for the list of geo target IDs.
    campaign.addGeoTargets(
        KeywordPlanGeoTarget.newBuilder()
            // Geo-target constant 2840 is for USA.
            .setGeoTargetConstant(StringValue.of(ResourceNames.geoTargetConstant(2840)))
            .build());

    // See https://developers.google.com/adwords/api/docs/appendix/codes-formats#languages
    // for the list of language criteria IDs.
    //
    // Language criteria 1000 is for English.
    campaign.addLanguageConstants(StringValue.of(ResourceNames.languageConstant(1000)));

    KeywordPlanCampaignOperation op =
        KeywordPlanCampaignOperation.newBuilder().setCreate(campaign).build();

    try (KeywordPlanCampaignServiceClient client =
        googleAdsClient.getLatestVersion().createKeywordPlanCampaignServiceClient()) {
      // Adds the campaign.
      MutateKeywordPlanCampaignsResponse response =
          client.mutateKeywordPlanCampaigns(String.valueOf(customerId), Arrays.asList(op));

      // Displays the result.
      String resourceName = response.getResults(0).getResourceName();
      System.out.printf("Created campaign for keyword plan: %s%n", resourceName);
      return resourceName;
    }
  }

  /**
   * Creates the ad group for the keyword plan.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @param planCampaignResource plan campaign resource name.
   */
  private static String createKeywordPlanAdGroup(
      GoogleAdsClient googleAdsClient, Long customerId, String planCampaignResource) {
    // Creates the keyword plan ad group.
    KeywordPlanAdGroup.Builder adGroup =
        KeywordPlanAdGroup.newBuilder()
            .setKeywordPlanCampaign(StringValue.of(planCampaignResource))
            .setName(StringValue.of("Keyword plan ad group #" + System.currentTimeMillis()))
            .setCpcBidMicros(Int64Value.of(2_500_000L));

    KeywordPlanAdGroupOperation op =
        KeywordPlanAdGroupOperation.newBuilder().setCreate(adGroup).build();
    try (KeywordPlanAdGroupServiceClient client =
        googleAdsClient.getLatestVersion().createKeywordPlanAdGroupServiceClient()) {
      // Adds the ad group.
      MutateKeywordPlanAdGroupsResponse response =
          client.mutateKeywordPlanAdGroups(String.valueOf(customerId), Arrays.asList(op));

      // Displays the result.
      String resourceName = response.getResults(0).getResourceName();
      System.out.println("Created ad group for keyword plan: " + resourceName);
      return resourceName;
    }
  }

  /**
   * Creates keywords for the keyword plan.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @param planAdGroupResource plan ad group resource name.
   */
  private static void createKeywordPlanKeywords(
      GoogleAdsClient googleAdsClient, Long customerId, String planAdGroupResource) {
    // Creates the keywords for keyword plan.
    KeywordPlanKeyword keyword1 =
        KeywordPlanKeyword.newBuilder()
            .setKeywordPlanAdGroup(StringValue.of(planAdGroupResource))
            .setCpcBidMicros(Int64Value.of(2_000_000L))
            .setMatchType(KeywordMatchType.BROAD)
            .setText(StringValue.of("mars cruise"))
            .build();
    KeywordPlanKeyword keyword2 =
        KeywordPlanKeyword.newBuilder()
            .setKeywordPlanAdGroup(StringValue.of(planAdGroupResource))
            .setCpcBidMicros(Int64Value.of(1_500_000L))
            .setMatchType(KeywordMatchType.PHRASE)
            .setText(StringValue.of("cheap cruise"))
            .build();
    KeywordPlanKeyword keyword3 =
        KeywordPlanKeyword.newBuilder()
            .setKeywordPlanAdGroup(StringValue.of(planAdGroupResource))
            .setCpcBidMicros(Int64Value.of(1_990_000L))
            .setMatchType(KeywordMatchType.EXACT)
            .setText(StringValue.of("jupiter cruise"))
            .build();

    // Creates an operation for each plan keyword.
    List<KeywordPlanKeywordOperation> operations =
        Stream.of(keyword1, keyword2, keyword3)
            .map(kw -> KeywordPlanKeywordOperation.newBuilder().setCreate(kw).build())
            .collect(Collectors.toList());

    try (KeywordPlanKeywordServiceClient client =
        googleAdsClient.getLatestVersion().createKeywordPlanKeywordServiceClient()) {
      // Adds the keywords.
      MutateKeywordPlanKeywordsResponse response =
          client.mutateKeywordPlanKeywords(String.valueOf(customerId), operations);
      // Displays the results.
      for (MutateKeywordPlanKeywordResult result : response.getResultsList()) {
        System.out.printf("Created keyword for keyword plan: %s%n", result.getResourceName());
      }
    }
  }

  /**
   * Creates negative keywords for the keyword plan.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @param planCampaignResource plan campaign resource name.
   */
  private void createKeywordPlanNegativeKeywords(
      GoogleAdsClient googleAdsClient, Long customerId, String planCampaignResource) {
    KeywordPlanNegativeKeyword negativeKeyword =
        KeywordPlanNegativeKeyword.newBuilder()
            .setKeywordPlanCampaign(StringValue.of(planCampaignResource))
            .setMatchType(KeywordMatchType.BROAD)
            .setText(StringValue.of("moon walk"))
            .build();
    KeywordPlanNegativeKeywordOperation op =
        KeywordPlanNegativeKeywordOperation.newBuilder().setCreate(negativeKeyword).build();

    try (KeywordPlanNegativeKeywordServiceClient client =
        googleAdsClient.getLatestVersion().createKeywordPlanNegativeKeywordServiceClient()) {
      // Adds the negative keyword.
      MutateKeywordPlanNegativeKeywordsResponse response =
          client.mutateKeywordPlanNegativeKeywords(String.valueOf(customerId), Arrays.asList(op));

      // Displays the result.
      String resourceName = response.getResults(0).getResourceName();
      System.out.printf("Created negative keyword for keyword plan: %s%n", resourceName);
    }
  }
}

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

using System;
using System.Collections.Generic;
using static Google.Ads.GoogleAds.V4.Enums.KeywordMatchTypeEnum.Types;
using static Google.Ads.GoogleAds.V4.Enums.KeywordPlanForecastIntervalEnum.Types;
using static Google.Ads.GoogleAds.V4.Enums.KeywordPlanNetworkEnum.Types;

namespace Google.Ads.GoogleAds.Examples.V4
{
    /// <summary>
    /// This code example creates a keyword plan, which can be reused for retrieving forecast
    /// metrics and historic metrics.
    /// </summary>
    public class AddKeywordPlan : 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)
        {
            AddKeywordPlan codeExample = new AddKeywordPlan();
            Console.WriteLine(codeExample.Description);

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

            codeExample.Run(new GoogleAdsClient(), customerId);
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get
            {
                return "This code example creates a keyword plan, which can be reused for " +
                    "retrieving forecast metrics and historic metrics.";
            }
        }

        /// <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>
        public void Run(GoogleAdsClient client, long customerId)
        {
            try
            {
                string keywordPlanResource = CreateKeywordPlan(client, customerId);
                string planCampaignResource = CreateKeywordPlanCampaign(client, customerId,
                    keywordPlanResource);
                string planAdGroupResource = CreateKeywordPlanAdGroup(client, customerId,
                    planCampaignResource);
                CreateKeywordPlanAdGroupKeywords(client, customerId, planAdGroupResource);
                CreateKeywordPlanCampaignNegativeKeywords(client, customerId, planCampaignResource);
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }

        /// <summary>
        /// Creates the keyword plan.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <returns>The newly created keyword plan resource.</returns>
        private string CreateKeywordPlan(GoogleAdsClient client, long customerId)
        {
            // Get the KeywordPlanService.
            KeywordPlanServiceClient serviceClient = client.GetService(
                Services.V4.KeywordPlanService);

            // Create a keyword plan for next quarter forecast.
            KeywordPlan keywordPlan = new KeywordPlan()
            {
                Name = "Keyword plan for traffic estimate #" + ExampleUtilities.GetRandomString(),
                ForecastPeriod = new KeywordPlanForecastPeriod()
                {
                    DateInterval = KeywordPlanForecastInterval.NextQuarter
                }
            };

            KeywordPlanOperation operation = new KeywordPlanOperation()
            {
                Create = keywordPlan
            };

            // Add the keyword plan.
            MutateKeywordPlansResponse response = serviceClient.MutateKeywordPlans(
                customerId.ToString(), new KeywordPlanOperation[] { operation });

            // Display the results.
            String planResource = response.Results[0].ResourceName;
            Console.WriteLine($"Created keyword plan: {planResource}.");
            return planResource;
        }

        /// <summary>
        /// Creates the campaign for the keyword plan.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="keywordPlanResource">The keyword plan resource.</param>
        /// <returns>The newly created campaign resource.</returns>
        private string CreateKeywordPlanCampaign(GoogleAdsClient client, long customerId,
            String keywordPlanResource)
        {
            // Get the KeywordPlanCampaignService.
            KeywordPlanCampaignServiceClient serviceClient = client.GetService(
                Services.V4.KeywordPlanCampaignService);

            // Create a keyword plan campaign.
            KeywordPlanCampaign campaign = new KeywordPlanCampaign()
            {
                Name = "Keyword plan campaign #" + ExampleUtilities.GetRandomString(),
                CpcBidMicros = 1_000_000L,
                KeywordPlanNetwork = KeywordPlanNetwork.GoogleSearch,
                KeywordPlan = keywordPlanResource
            };

            // See https://developers.google.com/adwords/api/docs/appendix/geotargeting
            // for the list of geo target IDs.
            campaign.GeoTargets.Add(new KeywordPlanGeoTarget()
            {
                GeoTargetConstant = ResourceNames.GeoTargetConstant(2840) /* USA */
            });

            // See https://developers.google.com/adwords/api/docs/appendix/codes-formats#languages
            // for the list of language criteria IDs.
            campaign.LanguageConstants.Add(ResourceNames.LanguageConstant(1000)); /* English */

            KeywordPlanCampaignOperation operation = new KeywordPlanCampaignOperation()
            {
                Create = campaign
            };

            // Add the campaign.
            MutateKeywordPlanCampaignsResponse response =
                serviceClient.MutateKeywordPlanCampaigns(customerId.ToString(),
                    new KeywordPlanCampaignOperation[] { operation });

            // Display the result.
            String planCampaignResource = response.Results[0].ResourceName;
            Console.WriteLine($"Created campaign for keyword plan: {planCampaignResource}.");
            return planCampaignResource;
        }

        /// <summary>
        /// Creates the ad group for the keyword plan.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="planCampaignResource">The resource name of the campaign under which the
        /// ad group is created.</param>
        /// <returns>The newly created ad group resource.</returns>
        private string CreateKeywordPlanAdGroup(GoogleAdsClient client, long customerId,
            string planCampaignResource)
        {
            // Get the KeywordPlanAdGroupService.
            KeywordPlanAdGroupServiceClient serviceClient = client.GetService(
                Services.V4.KeywordPlanAdGroupService);

            // Create the keyword plan ad group.
            KeywordPlanAdGroup adGroup = new KeywordPlanAdGroup()
            {
                KeywordPlanCampaign = planCampaignResource,
                Name = "Keyword plan ad group #" + ExampleUtilities.GetRandomString(),
                CpcBidMicros = 2_500_000L
            };

            KeywordPlanAdGroupOperation operation = new KeywordPlanAdGroupOperation()
            {
                Create = adGroup
            };

            // Add the ad group.
            MutateKeywordPlanAdGroupsResponse response =
                serviceClient.MutateKeywordPlanAdGroups(
                    customerId.ToString(), new KeywordPlanAdGroupOperation[] { operation });

            // Display the result.
            String planAdGroupResource = response.Results[0].ResourceName;
            Console.WriteLine($"Created ad group for keyword plan: {planAdGroupResource}.");
            return planAdGroupResource;
        }

        /// <summary>
        /// Creates keywords for the keyword plan.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="planAdGroupResource">The resource name of the ad group under which the
        /// keyword is created.</param>
        private static void CreateKeywordPlanAdGroupKeywords(GoogleAdsClient client,
            long customerId, string planAdGroupResource)
        {
            // Get the KeywordPlanAdGroupKeywordService.
            KeywordPlanAdGroupKeywordServiceClient serviceClient = client.GetService(
                Services.V4.KeywordPlanAdGroupKeywordService);

            // Create the adgroup level keywords for keyword plan.
            KeywordPlanAdGroupKeyword kpAdGroupKeyword1 = new KeywordPlanAdGroupKeyword()
            {
                KeywordPlanAdGroup = planAdGroupResource,
                CpcBidMicros = 2_000_000L,
                MatchType = KeywordMatchType.Broad,
                Text = "mars cruise"
            };

            KeywordPlanAdGroupKeyword kpAdGroupKeyword2 = new KeywordPlanAdGroupKeyword()
            {
                KeywordPlanAdGroup = planAdGroupResource,
                CpcBidMicros = 1_500_000L,
                MatchType = KeywordMatchType.Phrase,
                Text = "cheap cruise"
            };

            KeywordPlanAdGroupKeyword kpAdGroupKeyword3 = new KeywordPlanAdGroupKeyword()
            {
                KeywordPlanAdGroup = planAdGroupResource,
                CpcBidMicros = 1_990_000L,
                MatchType = KeywordMatchType.Exact,
                Text = "jupiter cruise"
            };

            KeywordPlanAdGroupKeyword[] kpAdGroupKeywords = new KeywordPlanAdGroupKeyword[]
            {
                kpAdGroupKeyword1,
                kpAdGroupKeyword2,
                kpAdGroupKeyword3
            };

            // Create an operation for each plan keyword.
            List<KeywordPlanAdGroupKeywordOperation> operations =
                new List<KeywordPlanAdGroupKeywordOperation>();

            foreach (KeywordPlanAdGroupKeyword kpAdGroupKeyword in kpAdGroupKeywords)
            {
                operations.Add(new KeywordPlanAdGroupKeywordOperation
                {
                    Create = kpAdGroupKeyword
                });
            }

            // Add the keywords.
            MutateKeywordPlanAdGroupKeywordsResponse response =
                serviceClient.MutateKeywordPlanAdGroupKeywords(customerId.ToString(), operations);

            // Display the results.
            foreach (MutateKeywordPlanAdGroupKeywordResult result in response.Results)
            {
                Console.WriteLine(
                    $"Created ad group keyword for keyword plan: {result.ResourceName}.");
            }
            return;
        }

        /// <summary>
        /// Creates campaign negative keywords for the keyword plan.
        /// </summary>
        /// <param name="client">he Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="planCampaignResource">The resource name of the campaign under which the
        /// negative keyword is created.</param>
        private static void CreateKeywordPlanCampaignNegativeKeywords(GoogleAdsClient client,
            long customerId, string planCampaignResource)
        {
            // Get the KeywordPlanCampaignKeywordService.
            KeywordPlanCampaignKeywordServiceClient service = client.GetService(
                Services.V4.KeywordPlanCampaignKeywordService);

            // Create the campaign negative keyword for the keyword plan.
            KeywordPlanCampaignKeyword kpCampaignNegativeKeyword = new KeywordPlanCampaignKeyword()
            {
                KeywordPlanCampaign = planCampaignResource,
                MatchType = KeywordMatchType.Broad,
                Text = "moon walk",
                Negative = true
            };

            KeywordPlanCampaignKeywordOperation operation = new KeywordPlanCampaignKeywordOperation
            {
                Create = kpCampaignNegativeKeyword
            };

            // Add the campaign negative keyword.
            MutateKeywordPlanCampaignKeywordsResponse response =
                service.MutateKeywordPlanCampaignKeywords(customerId.ToString(), 
                    new KeywordPlanCampaignKeywordOperation[] { operation });

            // Display the result.
            MutateKeywordPlanCampaignKeywordResult result = response.Results[0];
            Console.WriteLine("Created campaign negative keyword for keyword plan: " +
                $"{result.ResourceName}.");
            return;
        }
    }
}
 

PHP

<?php

/**
 * 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.
 */

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\OAuth2TokenBuilder;
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\Util\V4\ResourceNames;
use Google\Ads\GoogleAds\V4\Enums\KeywordMatchTypeEnum\KeywordMatchType;
use Google\Ads\GoogleAds\V4\Enums\KeywordPlanForecastIntervalEnum\KeywordPlanForecastInterval;
use Google\Ads\GoogleAds\V4\Enums\KeywordPlanNetworkEnum\KeywordPlanNetwork;
use Google\Ads\GoogleAds\V4\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V4\Resources\KeywordPlan;
use Google\Ads\GoogleAds\V4\Resources\KeywordPlanAdGroup;
use Google\Ads\GoogleAds\V4\Resources\KeywordPlanAdGroupKeyword;
use Google\Ads\GoogleAds\V4\Resources\KeywordPlanCampaign;
use Google\Ads\GoogleAds\V4\Resources\KeywordPlanCampaignKeyword;
use Google\Ads\GoogleAds\V4\Resources\KeywordPlanForecastPeriod;
use Google\Ads\GoogleAds\V4\Resources\KeywordPlanGeoTarget;
use Google\Ads\GoogleAds\V4\Services\KeywordPlanAdGroupKeywordOperation;
use Google\Ads\GoogleAds\V4\Services\KeywordPlanAdGroupOperation;
use Google\Ads\GoogleAds\V4\Services\KeywordPlanCampaignKeywordOperation;
use Google\Ads\GoogleAds\V4\Services\KeywordPlanCampaignOperation;
use Google\Ads\GoogleAds\V4\Services\KeywordPlanOperation;
use Google\ApiCore\ApiException;
use Google\Protobuf\Int64Value;
use Google\Protobuf\StringValue;

/**
 * This class creates a keyword plan, which can be reused for retrieving forecast metrics and
 * historic metrics.
 */
class AddKeywordPlan
{
    private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';

    public static function main()
    {
        // Either pass the required parameters for this example on the command line, or insert
        // them into the constants above.
        $options = (new ArgumentParser())->parseCommandArguments([
            ArgumentNames::CUSTOMER_ID => GetOpt::REQUIRED_ARGUMENT
        ]);

        // Generate a refreshable OAuth2 credential for authentication.
        $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();

        // Construct a Google Ads client configured from a properties file and the
        // OAuth2 credentials above.
        $googleAdsClient = (new GoogleAdsClientBuilder())
            ->fromFile()
            ->withOAuth2Credential($oAuth2Credential)
            ->build();

        try {
            self::runExample(
                $googleAdsClient,
                $options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID
            );
        } 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
     */
    public static function runExample(GoogleAdsClient $googleAdsClient, int $customerId)
    {
        $keywordPlanResource = self::createKeywordPlan(
            $googleAdsClient,
            $customerId
        );

        $planCampaignResource = self::createKeywordPlanCampaign(
            $googleAdsClient,
            $customerId,
            $keywordPlanResource
        );

        $planAdGroupResource = self::createKeywordPlanAdGroup(
            $googleAdsClient,
            $customerId,
            $planCampaignResource
        );

        self::createKeywordPlanAdGroupKeywords(
            $googleAdsClient,
            $customerId,
            $planAdGroupResource
        );

        self::createKeywordPlanNegativeCampaignKeywords(
            $googleAdsClient,
            $customerId,
            $planCampaignResource
        );
    }

    /**
     * Creates a keyword plan.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @return string the newly created keyword plan resource
     */
    private static function createKeywordPlan(
        GoogleAdsClient $googleAdsClient,
        int $customerId
    ) {
        // Creates a keyword plan.
        $keywordPlan = new KeywordPlan([
            'name' => new StringValue(
                ['value' => 'Keyword plan for traffic estimate #' . uniqid()]
            ),
            'forecast_period' => new KeywordPlanForecastPeriod([
                'date_interval' => KeywordPlanForecastInterval::NEXT_QUARTER
            ])
        ]);

        // Creates a keyword plan operation.
        $keywordPlanOperation = new KeywordPlanOperation();
        $keywordPlanOperation->setCreate($keywordPlan);

        // Issues a mutate request to add the keyword plan.
        $keywordPlanServiceClient = $googleAdsClient->getKeywordPlanServiceClient();
        $response = $keywordPlanServiceClient->mutateKeywordPlans(
            $customerId,
            [$keywordPlanOperation]
        );

        $resourceName = $response->getResults()[0]->getResourceName();
        printf("Created keyword plan: '%s'%s", $resourceName, PHP_EOL);

        return $resourceName;
    }

    /**
     * Creates the campaign for the keyword plan.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @param string $keywordPlanResource the keyword plan resource
     * @return string the newly created campaign resource
     */
    private static function createKeywordPlanCampaign(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        string $keywordPlanResource
    ) {
        // Creates a keyword plan campaign.
        $keywordPlanCampaign = new KeywordPlanCampaign([
            'name' => new StringValue(['value' => 'Keyword plan campaign #' . uniqid()]),
            'cpc_bid_micros' => new Int64Value(['value' => 1000000]),
            'keyword_plan_network' => KeywordPlanNetwork::GOOGLE_SEARCH,
            'keyword_plan' => new StringValue(['value' => $keywordPlanResource]),
        ]);

        // See https://developers.google.com/adwords/api/docs/appendix/geotargeting
        // for the list of geo target IDs.
        $keywordPlanCampaign->setGeoTargets([
            new KeywordPlanGeoTarget([
                'geo_target_constant' => new StringValue(
                    ['value' => ResourceNames::forGeoTargetConstant(2840)] // USA
                )
            ])
        ]);

        // See https://developers.google.com/adwords/api/docs/appendix/codes-formats#languages
        // for the list of language criteria IDs.
        $keywordPlanCampaign->setLanguageConstants([
            new StringValue(['value' => ResourceNames::forLanguageConstant(1000)]) // English
        ]);

        // Creates a keyword plan campaign operation.
        $keywordPlanCampaignOperation = new KeywordPlanCampaignOperation();
        $keywordPlanCampaignOperation->setCreate($keywordPlanCampaign);

        $keywordPlanCampaignServiceClient =
            $googleAdsClient->getKeywordPlanCampaignServiceClient();
        $response = $keywordPlanCampaignServiceClient->mutateKeywordPlanCampaigns(
            $customerId,
            [$keywordPlanCampaignOperation]
        );

        $planCampaignResource = $response->getResults()[0]->getResourceName();
        printf("Created campaign for keyword plan: '%s'%s", $planCampaignResource, PHP_EOL);

        return $planCampaignResource;
    }

    /**
     * Creates the ad group for the keyword plan.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @param string $planCampaignResource the resource name of the campaign under which the
     *     ad group is created
     * @return string the newly created ad group resource
     */

    private static function createKeywordPlanAdGroup(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        string $planCampaignResource
    ) {
        // Creates a keyword plan ad group.
        $keywordPlanAdGroup = new KeywordPlanAdGroup([
            'name' => new StringValue(['value' => 'Keyword plan ad group #' . uniqid()]),
            'cpc_bid_micros' => new Int64Value(['value' => 2500000]),
            'keyword_plan_campaign' => new StringValue(['value' => $planCampaignResource])
        ]);

        // Creates a keyword plan ad group operation.
        $keywordPlanAdGroupOperation = new KeywordPlanAdGroupOperation();
        $keywordPlanAdGroupOperation->setCreate($keywordPlanAdGroup);

        $keywordPlanAdGroupServiceClient = $googleAdsClient->getKeywordPlanAdGroupServiceClient();
        $response = $keywordPlanAdGroupServiceClient->mutateKeywordPlanAdGroups(
            $customerId,
            [$keywordPlanAdGroupOperation]
        );

        $planAdGroupResource = $response->getResults()[0]->getResourceName();
        printf("Created ad group for keyword plan: '%s'%s", $planAdGroupResource, PHP_EOL);

        return $planAdGroupResource;
    }

    /**
     * Creates ad group keywords for the keyword plan.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @param string $planAdGroupResource the resource name of the ad group under which the
     *     keywords are created
     */
    private static function createKeywordPlanAdGroupKeywords(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        string $planAdGroupResource
    ) {
        // Creates the ad group keywords for the keyword plan.
        $keywordPlanAdGroupKeyword1 = new KeywordPlanAdGroupKeyword([
            'text' => new StringValue(['value' => 'mars cruise']),
            'cpc_bid_micros' => new Int64Value(['value' => 2000000]),
            'match_type' => KeywordMatchType::BROAD,
            'keyword_plan_ad_group' => new StringValue(['value' => $planAdGroupResource])
        ]);

        $keywordPlanAdGroupKeyword2 = new KeywordPlanAdGroupKeyword([
            'text' => new StringValue(['value' => 'cheap cruise']),
            'cpc_bid_micros' => new Int64Value(['value' => 15000000]),
            'match_type' => KeywordMatchType::PHRASE,
            'keyword_plan_ad_group' => new StringValue(['value' => $planAdGroupResource])
        ]);

        $keywordPlanAdGroupKeyword3 = new KeywordPlanAdGroupKeyword([
            'text' => new StringValue(['value' => 'jupiter cruise']),
            'cpc_bid_micros' => new Int64Value(['value' => 1990000]),
            'match_type' => KeywordMatchType::EXACT,
            'keyword_plan_ad_group' => new StringValue(['value' => $planAdGroupResource])
        ]);

        $keywordPlanAdGroupKeywords =
            [$keywordPlanAdGroupKeyword1, $keywordPlanAdGroupKeyword2, $keywordPlanAdGroupKeyword3];

        // Creates an array of keyword plan ad group keyword operations.
        $keywordPlanAdGroupKeywordOperations = [];

        foreach ($keywordPlanAdGroupKeywords as $keyword) {
            $keywordPlanAdGroupKeywordOperation = new KeywordPlanAdGroupKeywordOperation();
            $keywordPlanAdGroupKeywordOperation->setCreate($keyword);
            $keywordPlanAdGroupKeywordOperations[] = $keywordPlanAdGroupKeywordOperation;
        }

        $keywordPlanAdGroupKeywordServiceClient =
            $googleAdsClient->getKeywordPlanAdGroupKeywordServiceClient();

        // Adds the keyword plan ad group keywords.
        $response = $keywordPlanAdGroupKeywordServiceClient->mutateKeywordPlanAdGroupKeywords(
            $customerId,
            $keywordPlanAdGroupKeywordOperations
        );

        /** @var KeywordPlanAdGroupKeyword $result */
        foreach ($response->getResults() as $result) {
            printf(
                "Created ad group keyword for keyword plan: '%s'%s",
                $result->getResourceName(),
                PHP_EOL
            );
        }
    }

    /**
     * Creates negative campaign keywords for the keyword plan.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @param string $planCampaignResource the resource name of the campaign under which
     *     the keywords are created
     */
    private static function createKeywordPlanNegativeCampaignKeywords(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        string $planCampaignResource
    ) {
        // Creates a negative campaign keyword for the keyword plan.
        $keywordPlanCampaignKeyword = new KeywordPlanCampaignKeyword([
            'text' => new StringValue(['value' => 'moon walk']),
            'match_type' => KeywordMatchType::BROAD,
            'keyword_plan_campaign' => new StringValue(['value' => $planCampaignResource]),
            'negative' => true
        ]);

        $keywordPlanCampaignKeywordOperation = new KeywordPlanCampaignKeywordOperation();
        $keywordPlanCampaignKeywordOperation->setCreate($keywordPlanCampaignKeyword);

        $keywordPlanCampaignKeywordServiceClient =
            $googleAdsClient->getKeywordPlanCampaignKeywordServiceClient();

        // Adds the negative campaign keyword.
        $response = $keywordPlanCampaignKeywordServiceClient->mutateKeywordPlanCampaignKeywords(
            $customerId,
            [$keywordPlanCampaignKeywordOperation]
        );

        /** @var KeywordPlanCampaignKeyword $result */
        foreach ($response->getResults() as $result) {
            printf(
                "Created negative campaign keyword for keyword plan: '%s'%s",
                $result->getResourceName(),
                PHP_EOL
            );
        }
    }
}

AddKeywordPlan::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 creates a keyword plan.

Keyword plans can be reused for retrieving forecast metrics and historic
metrics.
"""


import argparse
import sys
import uuid

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


def main(client, customer_id):
    """Adds a keyword plan, campaign, ad group, etc. to the customer account

    Also handles errors from the API and prints them.

    Args:
        client: An initialized instance of GoogleAdsClient
        customer_id: A str of the customer_id to use in requests.
    """
    try:
        add_keyword_plan(client, customer_id)
    except GoogleAdsException as ex:
        print('Request with ID "{}" failed with status "{}" and includes the '
              'following errors:'.format(ex.request_id, ex.error.code().name))
        for error in ex.failure.errors:
            print('\tError with message "{}".'.format(error.message))
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print('\t\tOn field: {}'.format(
                        field_path_element.field_name))
        sys.exit(1)


def add_keyword_plan(client, customer_id):
    """Adds a keyword plan, campaign, ad group, etc. to the customer account.

    Args:
        client: An initialized instance of GoogleAdsClient
        customer_id: A str of the customer_id to use in requests.

    Raises:
        GoogleAdsException: If an error is returned from the API.
    """
    keyword_plan = create_keyword_plan(client, customer_id)
    keyword_plan_campaign = create_keyword_plan_campaign(client, customer_id,
                                                         keyword_plan)
    keyword_plan_ad_group = create_keyword_plan_ad_group(client, customer_id,
                                                         keyword_plan_campaign)
    create_keyword_plan_keywords(client, customer_id, keyword_plan_ad_group)
    create_keyword_plan_negative_keywords(client, customer_id,
                                          keyword_plan_campaign)


def create_keyword_plan(client, customer_id):
    """Adds a keyword plan to the given customer account.

    Args:
        client: An initialized instance of GoogleAdsClient
        customer_id: A str of the customer_id to use in requests.

    Returns:
        A str of the resource_name for the newly created keyword plan.

    Raises:
        GoogleAdsException: If an error is returned from the API.
    """
    operation = client.get_type('KeywordPlanOperation', version='v3')
    keyword_plan = operation.create

    keyword_plan.name.value = ('Keyword plan for traffic estimate {}'.format(
        uuid.uuid4()))

    forecast_interval = client.get_type('KeywordPlanForecastIntervalEnum',
                                        version='v3').NEXT_QUARTER
    keyword_plan.forecast_period.date_interval = forecast_interval

    keyword_plan_service = client.get_service('KeywordPlanService',
                                              version='v3')
    response = keyword_plan_service.mutate_keyword_plans(customer_id,
                                                         [operation])
    resource_name = response.results[0].resource_name

    print('Created keyword plan with resource name: {}'.format(resource_name))

    return resource_name


def create_keyword_plan_campaign(client, customer_id, keyword_plan):
    """Adds a keyword plan campaign to the given keyword plan.

    Args:
        client: An initialized instance of GoogleAdsClient
        customer_id: A str of the customer_id to use in requests.
        keyword_plan: A str of the keyword plan resource_name this keyword plan
            campaign should be attributed to.create_keyword_plan.

    Returns:
        A str of the resource_name for the newly created keyword plan campaign.

    Raises:
        GoogleAdsException: If an error is returned from the API.
    """
    operation = client.get_type('KeywordPlanCampaignOperation', version='v3')
    keyword_plan_campaign = operation.create

    keyword_plan_campaign.name.value = 'Keyword plan campaign {}'.format(
        uuid.uuid4())
    keyword_plan_campaign.cpc_bid_micros.value = 1000000
    keyword_plan_campaign.keyword_plan.value = keyword_plan

    keyword_plan_network = client.get_type('KeywordPlanNetworkEnum',
                                           version='v3')
    network = keyword_plan_network.GOOGLE_SEARCH
    keyword_plan_campaign.keyword_plan_network = network

    geo_target = client.get_type('KeywordPlanGeoTarget', version='v3')
    # Constant for U.S. Other geo target constants can be referenced here:
    # https://developers.google.com/adwords/api/docs/appendix/geotargeting
    geo_target.geo_target_constant.value = 'geoTargetConstants/2840'
    keyword_plan_campaign.geo_targets.extend([geo_target])

    language = client.get_type('StringValue', version='v3')
    # Constant for English
    language.value = 'languageConstants/1000'
    keyword_plan_campaign.language_constants.extend([language])

    keyword_plan_campaign_service = client.get_service(
        'KeywordPlanCampaignService', version='v3')
    response = keyword_plan_campaign_service.mutate_keyword_plan_campaigns(
        customer_id, [operation])

    resource_name = response.results[0].resource_name

    print('Created keyword plan campaign with resource name: {}'.format(
        resource_name))

    return resource_name


def create_keyword_plan_ad_group(client, customer_id, keyword_plan_campaign):
    """Adds a keyword plan ad group to the given keyword plan campaign.

    Args:
        client: An initialized instance of GoogleAdsClient
        customer_id: A str of the customer_id to use in requests.
        keyword_plan_campaign: A str of the keyword plan campaign resource_name
            this keyword plan ad group should be attributed to.

    Returns:
        A str of the resource_name for the newly created keyword plan ad group.

    Raises:
        GoogleAdsException: If an error is returned from the API.
    """
    operation = client.get_type('KeywordPlanAdGroupOperation', version='v3')
    keyword_plan_ad_group = operation.create

    keyword_plan_ad_group.name.value = 'Keyword plan ad group {}'.format(
        uuid.uuid4())
    keyword_plan_ad_group.cpc_bid_micros.value = 2500000
    keyword_plan_ad_group.keyword_plan_campaign.value = keyword_plan_campaign

    keyword_plan_ad_group_service = client.get_service(
        'KeywordPlanAdGroupService', version='v3')
    response = keyword_plan_ad_group_service.mutate_keyword_plan_ad_groups(
        customer_id, [operation])

    resource_name = response.results[0].resource_name

    print('Created keyword plan ad group with resource name: {}'.format(
        resource_name))

    return resource_name


def create_keyword_plan_keywords(client, customer_id, plan_ad_group):
    """Adds keyword plan keywords to the given keyword plan ad group.

    Args:
        client: An initialized instance of GoogleAdsClient
        customer_id: A str of the customer_id to use in requests.
        keyword_plan_ad_group: A str of the keyword plan ad group resource_name
            these keyword plan keywords should be attributed to.

    Raises:
        GoogleAdsException: If an error is returned from the API.
    """
    match_types = client.get_type('KeywordMatchTypeEnum', version='v3')

    keyword_plan_keyword1 = client.get_type('KeywordPlanKeyword', version='v3')
    keyword_plan_keyword1.text.value = 'mars cruise'
    keyword_plan_keyword1.cpc_bid_micros.value = 2000000
    keyword_plan_keyword1.match_type = match_types.BROAD
    keyword_plan_keyword1.keyword_plan_ad_group.value = plan_ad_group

    keyword_plan_keyword2 = client.get_type('KeywordPlanKeyword', version='v3')
    keyword_plan_keyword2.text.value = 'cheap cruise'
    keyword_plan_keyword2.cpc_bid_micros.value = 1500000
    keyword_plan_keyword2.match_type = match_types.PHRASE
    keyword_plan_keyword2.keyword_plan_ad_group.value = plan_ad_group

    keyword_plan_keyword3 = client.get_type('KeywordPlanKeyword', version='v3')
    keyword_plan_keyword3.text.value = 'jupiter cruise'
    keyword_plan_keyword3.cpc_bid_micros.value = 1990000
    keyword_plan_keyword3.match_type = match_types.EXACT
    keyword_plan_keyword3.keyword_plan_ad_group.value = plan_ad_group

    operations = []
    for keyword in [keyword_plan_keyword1,
                    keyword_plan_keyword2,
                    keyword_plan_keyword3]:
        operation = client.get_type('KeywordPlanKeywordOperation', version='v3')
        operation.create.CopyFrom(keyword)
        operations.append(operation)

    keyword_plan_keyword_service = client.get_service(
        'KeywordPlanKeywordService', version='v3')
    response = keyword_plan_keyword_service.mutate_keyword_plan_keywords(
        customer_id, operations)

    for result in response.results:
        print('Created keyword plan keyword with resource name: {}'.format(
            result.resource_name))


def create_keyword_plan_negative_keywords(client, customer_id, plan_campaign):
    """Adds a keyword plan negative keyword to the given keyword plan campaign.

    Args:
        client: An initialized instance of GoogleAdsClient
        customer_id: A str of the customer_id to use in requests.
        keyword_plan_campaign: A str of the keyword plan campaign resource_name
            this keyword plan negative keyword should be attributed to.

    Raises:
        GoogleAdsException: If an error is returned from the API.
    """
    match_types = client.get_type('KeywordMatchTypeEnum', version='v3')
    operation = client.get_type('KeywordPlanNegativeKeywordOperation',
                                version='v3')
    keyword_plan_negative_keyword = operation.create

    keyword_plan_negative_keyword.text.value = 'moon walk'
    keyword_plan_negative_keyword.match_type = match_types.BROAD
    keyword_plan_negative_keyword.keyword_plan_campaign.value = plan_campaign

    keyword_plan_negative_keyword_service = client.get_service(
        'KeywordPlanNegativeKeywordService', version='v3')
    response = (keyword_plan_negative_keyword_service
                    .mutate_keyword_plan_negative_keywords(
                        customer_id, [operation]))

    print('Created keyword plan negative keyword with resource name: {}'.format(
        response.results[0].resource_name))


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='Creates a keyword plan for specified customer.')
    # 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.')
    args = parser.parse_args()

    main(google_ads_client, args.customer_id)
 

Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# 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 creates a keyword plan, which can be reused for retrieving
# forecase metrics and historic metrics.

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

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

  keyword_plan = create_keyword_plan(client, customer_id)
  plan_campaign = create_keyword_plan_campaign(
    client,
    customer_id,
    keyword_plan,
  )
  plan_ad_group = create_keyword_plan_ad_group(
    client,
    customer_id,
    plan_campaign,
  )
  create_keyword_plan_keywords(client, customer_id, plan_ad_group)
  create_keyword_plan_negative_keywords(client, customer_id, plan_campaign)
end

def create_keyword_plan(client, customer_id)
  operation = client.operation.create_resource.keyword_plan do |kp|
    kp.name = "Keyword plan for traffic estimate ##{(Time.new.to_f * 1000).to_i}"
    kp.forecast_period = client.resource.keyword_plan_forecast_period do |fp|
      fp.date_interval = :NEXT_QUARTER
    end
  end

  keyword_plan_service = client.service.keyword_plan
  response = keyword_plan_service.mutate_keyword_plans(customer_id, [operation])

  resource_name = response.results.first.resource_name
  puts "Created keyword plan: #{resource_name}"

  resource_name
end

def create_keyword_plan_campaign(client, customer_id, keyword_plan)
  operation = client.operation.create_resource.keyword_plan_campaign do |kpc|
    kpc.name = "Keyword plan campaign ##{(Time.new.to_f * 1000).to_i}"
    kpc.cpc_bid_micros = 1_000_000
    kpc.keyword_plan_network = :GOOGLE_SEARCH
    kpc.keyword_plan = keyword_plan

    kpc.geo_targets << client.resource.keyword_plan_geo_target do |gt|
      gt.geo_target_constant = client.path.geo_target_constant(2840) # US
    end

    kpc.language_constants << client.path.language_constant(1000) # English
  end

  kp_campaign_service_client = client.service.keyword_plan_campaign
  response = kp_campaign_service_client.mutate_keyword_plan_campaigns(
    customer_id,
    [operation],
  )

  resource_name = response.results.first.resource_name
  puts "Created campaign for keyword plan: #{resource_name}"

  resource_name
end

def create_keyword_plan_ad_group(client, customer_id, plan_campaign)
  operation = client.operation.create_resource.keyword_plan_ad_group do |kpag|
    kpag.name = "Keyword plan ad group ##{(Time.new.to_f * 1000).to_i}"
    kpag.cpc_bid_micros = 2_500_000
    kpag.keyword_plan_campaign = plan_campaign
  end

  kp_ad_group_service = client.service.keyword_plan_ad_group
  response = kp_ad_group_service.mutate_keyword_plan_ad_groups(
    customer_id,
    [operation],
  )

  resource_name = response.results.first.resource_name
  puts "Created ad group for keyword plan: #{resource_name}"

  resource_name
end

def create_keyword_plan_keywords(client, customer_id, plan_ad_group)
  kp_keyword1 = client.resource.keyword_plan_keyword do |kpk|
    kpk.text = "mars cruise"
    kpk.cpc_bid_micros = 2_000_000
    kpk.match_type = :BROAD
    kpk.keyword_plan_ad_group = plan_ad_group
  end

  kp_keyword2 = client.resource.keyword_plan_keyword do |kpk|
    kpk.text = "cheap cruise"
    kpk.cpc_bid_micros = 1_500_000
    kpk.match_type = :PHRASE
    kpk.keyword_plan_ad_group = plan_ad_group
  end

  kp_keyword3 = client.resource.keyword_plan_keyword do |kpk|
    kpk.text = "jupiter cruise"
    kpk.cpc_bid_micros = 1_990_000
    kpk.match_type = :EXACT
    kpk.keyword_plan_ad_group = plan_ad_group
  end

  operations = [kp_keyword1, kp_keyword2, kp_keyword3].map do |keyword|
    client.operation.create_resource.keyword_plan_keyword(keyword)
  end

  kp_keyword_service = client.service.keyword_plan_keyword
  response = kp_keyword_service.mutate_keyword_plan_keywords(
    customer_id,
    operations,
  )

  response.results.each do |result|
    puts "Created keyword for keyword plan: #{result.resource_name}"
  end
end

def create_keyword_plan_negative_keywords(client, customer_id, plan_campaign)
  operation = client.operation.create_resource.keyword_plan_negative_keyword do |kpnk|
    kpnk.text = "moon walk"
    kpnk.match_type = :BROAD
    kpnk.keyword_plan_campaign = plan_campaign
  end

  kp_negative_keyword_service = client.service.keyword_plan_negative_keyword
  response = kp_negative_keyword_service.mutate_keyword_plan_negative_keywords(
    customer_id,
    [operation],
  )

  puts "Created negative keyword for keyword plan: " +
      "#{response.results.first.resource_name}"
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'

  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.separator ''
    opts.separator 'Help:'

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

  begin
    add_keyword_plan(options.fetch(:customer_id).tr("-", ""))
  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 creates a keyword plan, which can be reused for retrieving
# forecast metrics and historic metrics.

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::Resources::KeywordPlan;
use Google::Ads::GoogleAds::V4::Resources::KeywordPlanForecastPeriod;
use Google::Ads::GoogleAds::V4::Resources::KeywordPlanCampaign;
use Google::Ads::GoogleAds::V4::Resources::KeywordPlanGeoTarget;
use Google::Ads::GoogleAds::V4::Resources::KeywordPlanAdGroup;
use Google::Ads::GoogleAds::V4::Resources::KeywordPlanAdGroupKeyword;
use Google::Ads::GoogleAds::V4::Resources::KeywordPlanCampaignKeyword;
use Google::Ads::GoogleAds::V4::Enums::KeywordPlanForecastIntervalEnum
  qw(NEXT_QUARTER);
use Google::Ads::GoogleAds::V4::Enums::KeywordPlanNetworkEnum qw(GOOGLE_SEARCH);
use Google::Ads::GoogleAds::V4::Enums::KeywordMatchTypeEnum
  qw(BROAD PHRASE EXACT);
use
  Google::Ads::GoogleAds::V4::Services::KeywordPlanService::KeywordPlanOperation;
use
  Google::Ads::GoogleAds::V4::Services::KeywordPlanCampaignService::KeywordPlanCampaignOperation;
use
  Google::Ads::GoogleAds::V4::Services::KeywordPlanAdGroupService::KeywordPlanAdGroupOperation;
use
  Google::Ads::GoogleAds::V4::Services::KeywordPlanAdGroupKeywordService::KeywordPlanAdGroupKeywordOperation;
use
  Google::Ads::GoogleAds::V4::Services::KeywordPlanCampaignKeywordService::KeywordPlanCampaignKeywordOperation;
use Google::Ads::GoogleAds::V4::Utils::ResourceNames;

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

# 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";

sub add_keyword_plan {
  my ($api_client, $customer_id) = @_;

  my $keyword_plan_resource = create_keyword_plan($api_client, $customer_id);

  my $keyword_plan_campaign_resource =
    create_keyword_plan_campaign($api_client, $customer_id,
    $keyword_plan_resource);

  my $keyword_plan_ad_group_resource =
    create_keyword_plan_ad_group($api_client, $customer_id,
    $keyword_plan_campaign_resource);

  create_keyword_plan_ad_group_keywords($api_client, $customer_id,
    $keyword_plan_ad_group_resource);

  create_keyword_plan_negative_campaign_keywords($api_client, $customer_id,
    $keyword_plan_campaign_resource);

  return 1;
}

# Creates a keyword plan.
sub create_keyword_plan {
  my ($api_client, $customer_id) = @_;

  # Create a keyword plan.
  my $keyword_plan = Google::Ads::GoogleAds::V4::Resources::KeywordPlan->new({
      name => "Keyword plan for traffic estimate #" . uniqid(),
      forecastPeriod =>
        Google::Ads::GoogleAds::V4::Resources::KeywordPlanForecastPeriod->new({
          dateInterval => NEXT_QUARTER
        })});

  # Create a keyword plan operation.
  my $keyword_plan_operation =
    Google::Ads::GoogleAds::V4::Services::KeywordPlanService::KeywordPlanOperation
    ->new({
      create => $keyword_plan
    });

  # Add the keyword plan.
  my $keyword_plan_resource = $api_client->KeywordPlanService()->mutate({
      customerId => $customer_id,
      operations => [$keyword_plan_operation]})->{results}[0]{resourceName};

  printf "Created keyword plan: '%s'.\n", $keyword_plan_resource;

  return $keyword_plan_resource;
}

# Creates the campaign for the keyword plan.
sub create_keyword_plan_campaign {
  my ($api_client, $customer_id, $keyword_plan_resource) = @_;

  # Create a keyword plan campaign.
  my $keyword_plan_campaign =
    Google::Ads::GoogleAds::V4::Resources::KeywordPlanCampaign->new({
      name               => "Keyword plan campaign #" . uniqid(),
      cpcBidMicros       => 1000000,
      keywordPlanNetwork => GOOGLE_SEARCH,
      keywordPlan        => $keyword_plan_resource
    });

  # See https://developers.google.com/adwords/api/docs/appendix/geotargeting
  # for the list of geo target IDs.
  $keyword_plan_campaign->{geoTargets} = [
    Google::Ads::GoogleAds::V4::Resources::KeywordPlanGeoTarget->new({
        # Geo target constant 2840 is for USA.
        geoTargetConstant =>
          Google::Ads::GoogleAds::V4::Utils::ResourceNames::geo_target_constant(
          2840)})];

  # See https://developers.google.com/adwords/api/docs/appendix/codes-formats#languages
  # for the list of language criteria IDs.
  $keyword_plan_campaign->{languageConstants} = [
    # Language criteria 1000 is for English.
    Google::Ads::GoogleAds::V4::Utils::ResourceNames::language_constant(1000)];

  # Create a keyword plan campaign operation
  my $keyword_plan_campaign_operation =
    Google::Ads::GoogleAds::V4::Services::KeywordPlanCampaignService::KeywordPlanCampaignOperation
    ->new({
      create => $keyword_plan_campaign
    });

  # Add the keyword plan campaign.
  my $keyword_plan_campaign_resource =
    $api_client->KeywordPlanCampaignService()->mutate({
      customerId => $customer_id,
      operations => [$keyword_plan_campaign_operation]}
  )->{results}[0]{resourceName};

  printf "Created campaign for keyword plan: '%s'.\n",
    $keyword_plan_campaign_resource;

  return $keyword_plan_campaign_resource;
}

# Creates the ad group for the keyword plan.
sub create_keyword_plan_ad_group {
  my ($api_client, $customer_id, $keyword_plan_campaign_resource) = @_;

  # Create a keyword plan ad group.
  my $keyword_plan_ad_group =
    Google::Ads::GoogleAds::V4::Resources::KeywordPlanAdGroup->new({
      name                => "Keyword plan ad group #" . uniqid(),
      cpcBidMicros        => 2500000,
      keywordPlanCampaign => $keyword_plan_campaign_resource
    });

  # Create a keyword plan ad group operation.
  my $keyword_plan_ad_group_operation =
    Google::Ads::GoogleAds::V4::Services::KeywordPlanAdGroupService::KeywordPlanAdGroupOperation
    ->new({
      create => $keyword_plan_ad_group
    });

  # Add the keyword plan ad group.
  my $keyword_plan_ad_group_resource =
    $api_client->KeywordPlanAdGroupService()->mutate({
      customerId => $customer_id,
      operations => [$keyword_plan_ad_group_operation]}
  )->{results}[0]{resourceName};

  printf "Created ad group for keyword plan: '%s'.\n",
    $keyword_plan_ad_group_resource;

  return $keyword_plan_ad_group_resource;
}

# Creates ad group keywords for the keyword plan.
sub create_keyword_plan_ad_group_keywords {
  my ($api_client, $customer_id, $keyword_plan_ad_group_resource) = @_;

  # Create the ad group keywords for the keyword plan.
  my $keyword_plan_ad_group_keyword1 =
    Google::Ads::GoogleAds::V4::Resources::KeywordPlanAdGroupKeyword->new({
      text               => "mars cruise",
      cpcBidMicros       => 2000000,
      matchType          => BROAD,
      keywordPlanAdGroup => $keyword_plan_ad_group_resource
    });

  my $keyword_plan_ad_group_keyword2 =
    Google::Ads::GoogleAds::V4::Resources::KeywordPlanAdGroupKeyword->new({
      text               => "cheap cruise",
      cpcBidMicros       => 1500000,
      matchType          => PHRASE,
      keywordPlanAdGroup => $keyword_plan_ad_group_resource
    });

  my $keyword_plan_ad_group_keyword3 =
    Google::Ads::GoogleAds::V4::Resources::KeywordPlanAdGroupKeyword->new({
      text               => "jupiter cruise",
      cpcBidMicros       => 1990000,
      matchType          => EXACT,
      keywordPlanAdGroup => $keyword_plan_ad_group_resource
    });

  # Create an array of keyword plan ad group keyword operations.
  my $operations = [
    map(
      Google::Ads::GoogleAds::V4::Services::KeywordPlanAdGroupKeywordService::KeywordPlanAdGroupKeywordOperation
        ->new(
        {create => $_}
        ),
      (
        $keyword_plan_ad_group_keyword1, $keyword_plan_ad_group_keyword2,
        $keyword_plan_ad_group_keyword3
      ))];

  # Add the keyword plan ad group keywords.
  my $response = $api_client->KeywordPlanAdGroupKeywordService()->mutate({
    customerId => $customer_id,
    operations => $operations
  });

  foreach my $result (@{$response->{results}}) {
    printf "Created ad group keyword for keyword plan: '%s'.\n",
      $result->{resourceName};
  }
}

# Creates negative campaign keywords for the keyword plan.
sub create_keyword_plan_negative_campaign_keywords {
  my ($api_client, $customer_id, $keyword_plan_campaign_resource) = @_;

  # Create a negative campaign keyword for the keyword plan.
  my $keyword_plan_campaign_keyword =
    Google::Ads::GoogleAds::V4::Resources::KeywordPlanCampaignKeyword->new({
      text                => "moon walk",
      matchType           => BROAD,
      negative            => "true",
      keywordPlanCampaign => $keyword_plan_campaign_resource
    });

  # Create a keyword plan campaign keyword operation.
  my $operation =
    Google::Ads::GoogleAds::V4::Services::KeywordPlanCampaignKeywordService::KeywordPlanCampaignKeywordOperation
    ->new({
      create => $keyword_plan_campaign_keyword
    });

  # Add the keyword plan negative campaign keyword.
  my $response = $api_client->KeywordPlanCampaignKeywordService()->mutate({
      customerId => $customer_id,
      operations => [$operation]});

  printf "Created negative campaign keyword for keyword plan: '%s'.\n",
    $response->{results}[0]{resourceName};
}

# 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);

# 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);

# Call the example.
add_keyword_plan($api_client, $customer_id =~ s/-//gr);

=pod

=head1 NAME

add_keyword_plan

=head1 DESCRIPTION

This example creates a keyword plan, which can be reused for retrieving forecast metrics
and historic metrics.

=head1 SYNOPSIS

add_keyword_plan.pl [options]

    -help                       Show the help message.
    -customer_id                The Google Ads customer ID.

=cut
 

Generate the metrics

The prerequisite to this code example is that a KeywordPlan needs to already exist. This code example:

  1. Makes a request to KeywordPlanService.GenerateForecastMetrics after creating the KeywordPlan.
  2. Iterates through each of the KeywordPlanKeywordForecasts and displays each of the forecast metrics.

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

using System;

namespace Google.Ads.GoogleAds.Examples.V4
{
    /// <summary>
    /// This code example generates forecast metrics for a keyword plan. To create a keyword plan,
    /// run AddKeywordPlan.cs.
    /// </summary>
    public class GenerateForecastMetrics : 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)
        {
            GenerateForecastMetrics codeExample = new GenerateForecastMetrics();
            Console.WriteLine(codeExample.Description);

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

            // The keyword plan ID.
            long keywordPlanId = long.Parse("INSERT_KEYWORD_PLAN_ID_HERE");

            codeExample.Run(new GoogleAdsClient(), customerId, keywordPlanId);
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get
            {
                return "This code example generates forecast metrics for a keyword plan. To " +
                    "create a keyword plan, run AddKeywordPlan.cs.";
            }
        }

        /// <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="keywordPlanId">The keyword plan ID.</param>
        public void Run(GoogleAdsClient client, long customerId, long keywordPlanId)
        {
            KeywordPlanServiceClient kpServiceClient =
                client.GetService(Services.V4.KeywordPlanService);
            string keywordPlanResource = ResourceNames.KeywordPlan(customerId, keywordPlanId);

            try
            {
                GenerateForecastMetricsResponse response = kpServiceClient.GenerateForecastMetrics(
                    keywordPlanResource);
                int i = 0;
                foreach (KeywordPlanKeywordForecast forecast in response.KeywordForecasts)
                {
                    ForecastMetrics metrics = forecast.KeywordForecast;
                    Console.WriteLine($"{++i}) Keyword ID: {forecast.KeywordPlanAdGroupKeyword}");
                    Console.WriteLine($"Estimated daily clicks: {metrics.Clicks}");
                    Console.WriteLine($"Estimated daily impressions: {metrics.Impressions}");
                    Console.WriteLine($"Estimated average cpc (micros): {metrics.AverageCpc}\n");
                }
            }
            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 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.
 */

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\OAuth2TokenBuilder;
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\Util\V4\ResourceNames;
use Google\Ads\GoogleAds\V4\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V4\Services\KeywordPlanKeywordForecast;
use Google\ApiCore\ApiException;

/**
 * This code example generates forecast metrics for a keyword plan. To create a keyword plan,
 * run AddKeywordPlan.php.
 */
class GenerateForecastMetrics
{
    private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
    private const KEYWORD_PLAN_ID = 'INSERT_KEYWORD_PLAN_ID_HERE';

    public static function main()
    {
        // Either pass the required parameters for this example on the command line, or insert
        // them into the constants above.
        $options = (new ArgumentParser())->parseCommandArguments([
            ArgumentNames::CUSTOMER_ID => GetOpt::REQUIRED_ARGUMENT,
            ArgumentNames::KEYWORD_PLAN_ID => GetOpt::REQUIRED_ARGUMENT
        ]);

        // Generate a refreshable OAuth2 credential for authentication.
        $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();

        // Construct a Google Ads client configured from a properties file and the
        // OAuth2 credentials above.
        $googleAdsClient = (new GoogleAdsClientBuilder())
            ->fromFile()
            ->withOAuth2Credential($oAuth2Credential)
            ->build();

        try {
            self::runExample(
                $googleAdsClient,
                $options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID,
                $options[ArgumentNames::KEYWORD_PLAN_ID] ?: self::KEYWORD_PLAN_ID
            );
        } 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 $keywordPlanId the keyword plan ID
     */
    public static function runExample(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        int $keywordPlanId
    ) {
        $keywordPlanServiceClient = $googleAdsClient->getKeywordPlanServiceClient();

        // Issues a request to generate forecast metrics based on the specific keyword plan ID.
        $generateForecastMetricsResponse = $keywordPlanServiceClient->generateForecastMetrics(
            ResourceNames::forKeywordPlan($customerId, $keywordPlanId)
        );

        $i = 0;
        foreach ($generateForecastMetricsResponse->getKeywordForecasts() as $forecast) {
            /** @var KeywordPlanKeywordForecast $forecast */

            $metrics = $forecast->getKeywordForecast();
            printf(
                "%d) Keyword ID: %s%s",
                ++$i,
                $forecast->getKeywordPlanAdGroupKeyword()->getValue(),
                PHP_EOL
            );
            printf(
                "Estimated daily clicks: %s%s",
                is_null($metrics->getClicks()) ? 'null' : sprintf("%.2f", $metrics->getClicks()->getValue()),
                PHP_EOL
            );
            printf(
                "Estimated daily impressions: %s%s",
                is_null($metrics->getImpressions())
                    ? 'null' : sprintf("%.2f", $metrics->getImpressions()->getValue()),
                PHP_EOL
            );
            printf(
                "Estimated average cpc (micros): %s%s",
                is_null($metrics->getAverageCpc()) ? 'null' : $metrics->getAverageCpc()->getValue(),
                PHP_EOL
            );
        }
    }
}

GenerateForecastMetrics::main();

Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# 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 forecast metrics for a keyword plan. To create a
# keyword plan, run add_keyword_plan.rb.

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

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

  kp_service = client.service.keyword_plan
  response = kp_service.generate_forecast_metrics(
    client.path.keyword_plan(customer_id, keyword_plan_id)
  )

  response.keyword_forecasts.each_with_index do |forecast, i|
    metrics = forecast.keyword_forecast
    puts "#{i + 1}) Keyword ID: #{forecast.keyword_plan_ad_group_keyword}"
    clicks = if metrics.clicks.nil?
               "unspecified"
             else
               format("%.2f", metrics.clicks)
             end
    puts "Estimated daily clicks: #{clicks}"
    impressions = if metrics.impressions.nil?
                    "unspecified"
                  else
                    format("%.2f", metrics.impressions)
                  end
    puts "Estimated daily impressions: #{impressions}"
    cpc = if metrics.average_cpc.nil?
            "unspecified"
          else
            metrics.average_cpc
          end
    puts "Estimated average cpc (micros): #{cpc}"
  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[:keyword_plan_id] = 'INSERT_KEYWORD_PLAN_ID_HERE'

  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('-k', '--keyword-plan-id KEYWORD-PLAN-ID', String,
        'Keyword Plan ID') do |v|
      options[:keyword_plan_id] = v
    end

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

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

  begin
    generate_forecast_metrics(
      options.fetch(:customer_id).tr("-", ""),
      options.fetch(:keyword_plan_id)
    )
  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

Migrating from the AdWords API

KeywordPlanService.GenerateForecastMetrics replaces the AdWords API's TargetingIdeaService.get method.

Mapping to the UI

KeywordPlanService.GenerateForecastMetrics has similar functionality in the UI's Keyword Planner. However, the API requires that you create a KeywordPlan first.

Keyword Planner UI Google Ads API
Enter Keywords KeywordPlanKeyword
Locations KeywordPlanCampaign.geo_targets
Language KeywordPlanCampaign.language_constants
Search Networks KeywordPlanCampaign.keyword_plan_network
CPC Bid
Date Range KeywordPlanForecastPeriod