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

Add Keyword Plan

C#
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V2.Errors;
using Google.Ads.GoogleAds.V2.Resources;
using Google.Ads.GoogleAds.V2.Services;

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

namespace Google.Ads.GoogleAds.Examples.V2
{
    /// <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);
                CreateKeywordPlanKeywords(client, customerId, planAdGroupResource);
                CreateKeywordPlanNegativeKeywords(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}");
            }
        }

        /// <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.V2.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.V2.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.V2.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 CreateKeywordPlanKeywords(GoogleAdsClient client, long customerId,
            string planAdGroupResource)
        {
            // Get the KeywordPlanKeywordService.
            KeywordPlanKeywordServiceClient serviceClient = client.GetService(
                Services.V2.KeywordPlanKeywordService);

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

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

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

            KeywordPlanKeyword[] keywordPlanKeywords = new KeywordPlanKeyword[]
            {
                keywordPlanKeyword1,
                keywordPlanKeyword2,
                keywordPlanKeyword3
            };

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

            foreach (KeywordPlanKeyword keywordPlanKeyword in keywordPlanKeywords)
            {
                operations.Add(new KeywordPlanKeywordOperation
                {
                    Create = keywordPlanKeyword
                });
            }

            // Add the keywords.
            MutateKeywordPlanKeywordsResponse response =
                serviceClient.MutateKeywordPlanKeywords(customerId.ToString(), operations);

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

        /// <summary>
        /// Creates 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
        /// keyword is created.</param>
        private static void CreateKeywordPlanNegativeKeywords(GoogleAdsClient client,
            long customerId, string planCampaignResource)
        {
            // Get the KeywordPlanNegativeKeywordService.
            KeywordPlanNegativeKeywordServiceClient serviceClient = client.GetService(
                Services.V2.KeywordPlanNegativeKeywordService);

            // Create the negative keyword for the keyword plan.
            KeywordPlanNegativeKeyword keywordPlanNegativeKeyword = new KeywordPlanNegativeKeyword()
            {
                KeywordPlanCampaign = planCampaignResource,
                MatchType = KeywordMatchType.Broad,
                Text = "moon walk"
            };

            KeywordPlanNegativeKeywordOperation operation = new KeywordPlanNegativeKeywordOperation
            {
                Create = keywordPlanNegativeKeyword
            };

            // Add the negative keyword.
            MutateKeywordPlanNegativeKeywordsResponse response =
                serviceClient.MutateKeywordPlanNegativeKeywords(customerId.ToString(),
                    new KeywordPlanNegativeKeywordOperation[] { operation });

            // Display the result.
            MutateKeywordPlanNegativeKeywordResult planNegativeKeywordResult = response.Results[0];
            Console.WriteLine("Created negative keyword for keyword plan: " +
                $"{planNegativeKeywordResult.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\V2\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V2\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Lib\V2\GoogleAdsException;
use Google\Ads\GoogleAds\Util\V2\ResourceNames;
use Google\Ads\GoogleAds\V2\Enums\KeywordMatchTypeEnum\KeywordMatchType;
use Google\Ads\GoogleAds\V2\Enums\KeywordPlanForecastIntervalEnum\KeywordPlanForecastInterval;
use Google\Ads\GoogleAds\V2\Enums\KeywordPlanNetworkEnum\KeywordPlanNetwork;
use Google\Ads\GoogleAds\V2\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V2\Resources\KeywordPlan;
use Google\Ads\GoogleAds\V2\Resources\KeywordPlanAdGroup;
use Google\Ads\GoogleAds\V2\Resources\KeywordPlanCampaign;
use Google\Ads\GoogleAds\V2\Resources\KeywordPlanForecastPeriod;
use Google\Ads\GoogleAds\V2\Resources\KeywordPlanGeoTarget;
use Google\Ads\GoogleAds\V2\Resources\KeywordPlanKeyword;
use Google\Ads\GoogleAds\V2\Resources\KeywordPlanNegativeKeyword;
use Google\Ads\GoogleAds\V2\Services\KeywordPlanAdGroupOperation;
use Google\Ads\GoogleAds\V2\Services\KeywordPlanCampaignOperation;
use Google\Ads\GoogleAds\V2\Services\KeywordPlanKeywordOperation;
use Google\Ads\GoogleAds\V2\Services\KeywordPlanNegativeKeywordOperation;
use Google\Ads\GoogleAds\V2\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
{
    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
                );
            }
        } catch (ApiException $apiException) {
            printf(
                "ApiException was thrown with message '%s'.%s",
                $apiException->getMessage(),
                PHP_EOL
            );
        }
    }

    /**
     * Runs the example.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the 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::createKeywordPlanKeywords(
            $googleAdsClient,
            $customerId,
            $planAdGroupResource
        );

        self::createKeywordPlanNegativeKeywords(
            $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 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 createKeywordPlanKeywords(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        string $planAdGroupResource
    ) {
        // Creates the keywords for the keyword plan.
        $keywordPlanKeyword1 = new KeywordPlanKeyword([
            '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])
        ]);

        $keywordPlanKeyword2 = new KeywordPlanKeyword([
            '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])
        ]);

        $keywordPlanKeyword3 = new KeywordPlanKeyword([
            '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])
        ]);

        $keywordPlanKeywords = [$keywordPlanKeyword1, $keywordPlanKeyword2, $keywordPlanKeyword3];

        // Creates an array of keyword plan keyword operations.
        $keywordPlanKeywordOperations = [];

        foreach ($keywordPlanKeywords as $keyword) {
            $keywordPlanKeywordOperation = new KeywordPlanKeywordOperation();
            $keywordPlanKeywordOperation->setCreate($keyword);
            $keywordPlanKeywordOperations[] = $keywordPlanKeywordOperation;
        }

        $keywordPlanKeywordServiceClient = $googleAdsClient->getKeywordPlanKeywordServiceClient();

        // Adds the keyword plan keywords.
        $response = $keywordPlanKeywordServiceClient->mutateKeywordPlanKeywords(
            $customerId,
            $keywordPlanKeywordOperations
        );

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

    /**
     * Creates negative 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 createKeywordPlanNegativeKeywords(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        string $planCampaignResource
    ) {
        // Creates a negative keyword for the keyword plan.
        $keywordPlanNegativeKeyword = new KeywordPlanNegativeKeyword([
            'text' => new StringValue(['value' => 'moon walk']),
            'match_type' => KeywordMatchType::BROAD,
            'keyword_plan_campaign' => new StringValue(['value' => $planCampaignResource])
        ]);

        $keywordPlanNegativeKeywordOperation = new KeywordPlanNegativeKeywordOperation();
        $keywordPlanNegativeKeywordOperation->setCreate($keywordPlanNegativeKeyword);

        $keywordPlanNegativeKeywordServiceClient =
            $googleAdsClient->getKeywordPlanNegativeKeywordServiceClient();

        // Adds the negative keyword.
        $response = $keywordPlanNegativeKeywordServiceClient->mutateKeywordPlanNegativeKeywords(
            $customerId,
            [$keywordPlanNegativeKeywordOperation]
        );

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

AddKeywordPlan::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 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
  rescue Google::Gax::RetryError => e
    STDERR.printf("Error: '%s'\n\tCause: '%s'\n\tCode: %d\n\tDetails: '%s'\n" \
        "\tRequest-Id: '%s'\n", e.message, e.cause.message, e.cause.code,
                  e.cause.details, e.cause.metadata['request-id'])
  end
end

Send feedback about...

Google Ads API Beta
Google Ads API Beta
Need help? Visit our support page.