Share your feedback about the AdWords API! Take our annual survey.

Optimization Samples

The code samples below provide examples of common optimization functions using the AdWords API. Client Library.

Get keyword traffic estimates

// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     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.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.v201809;

using System;
using System.Collections.Generic;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201809
{
    /// <summary>
    /// This code example gets keyword traffic estimates.
    /// </summary>
    public class EstimateKeywordTraffic : 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)
        {
            EstimateKeywordTraffic codeExample = new EstimateKeywordTraffic();
            Console.WriteLine(codeExample.Description);
            try
            {
                codeExample.Run(new AdWordsUser());
            }
            catch (Exception e)
            {
                Console.WriteLine("An exception occurred while running this code example. {0}",
                    ExampleUtilities.FormatException(e));
            }
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get { return "This code example gets keyword traffic estimates."; }
        }

        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        public void Run(AdWordsUser user)
        {
            using (TrafficEstimatorService trafficEstimatorService =
                (TrafficEstimatorService) user.GetService(AdWordsService.v201809
                    .TrafficEstimatorService))
            {
                // Create keywords. Refer to the TrafficEstimatorService documentation for the
                // maximum number of keywords that can be passed in a single request.
                //   https://developers.google.com/adwords/api/docs/reference/latest/TrafficEstimatorService
                Keyword keyword1 = new Keyword
                {
                    text = "mars cruise",
                    matchType = KeywordMatchType.BROAD
                };

                Keyword keyword2 = new Keyword
                {
                    text = "cheap cruise",
                    matchType = KeywordMatchType.PHRASE
                };

                Keyword keyword3 = new Keyword
                {
                    text = "cruise",
                    matchType = KeywordMatchType.EXACT
                };

                Keyword[] keywords = new Keyword[]
                {
                    keyword1,
                    keyword2,
                    keyword3
                };

                // Create a keyword estimate request for each keyword.
                List<KeywordEstimateRequest> keywordEstimateRequests =
                    new List<KeywordEstimateRequest>();

                foreach (Keyword keyword in keywords)
                {
                    KeywordEstimateRequest keywordEstimateRequest = new KeywordEstimateRequest
                    {
                        keyword = keyword
                    };
                    keywordEstimateRequests.Add(keywordEstimateRequest);
                }

                // Create negative keywords.
                Keyword negativeKeyword1 = new Keyword
                {
                    text = "moon walk",
                    matchType = KeywordMatchType.BROAD
                };

                KeywordEstimateRequest negativeKeywordEstimateRequest = new KeywordEstimateRequest
                {
                    keyword = negativeKeyword1,
                    isNegative = true
                };
                keywordEstimateRequests.Add(negativeKeywordEstimateRequest);

                // Create ad group estimate requests.
                AdGroupEstimateRequest adGroupEstimateRequest = new AdGroupEstimateRequest
                {
                    keywordEstimateRequests = keywordEstimateRequests.ToArray(),
                    maxCpc = new Money
                    {
                        microAmount = 1000000
                    }
                };

                // Create campaign estimate requests.
                CampaignEstimateRequest campaignEstimateRequest = new CampaignEstimateRequest
                {
                    adGroupEstimateRequests = new AdGroupEstimateRequest[]
                    {
                        adGroupEstimateRequest
                    }
                };

                // Optional: Set additional criteria for filtering estimates.
                // See http://code.google.com/apis/adwords/docs/appendix/countrycodes.html
                // for a detailed list of country codes.
                Location countryCriterion = new Location
                {
                    id = 2840 //US
                };

                // See http://code.google.com/apis/adwords/docs/appendix/languagecodes.html
                // for a detailed list of language codes.
                Language languageCriterion = new Language
                {
                    id = 1000 //en
                };

                campaignEstimateRequest.criteria = new Criterion[]
                {
                    countryCriterion,
                    languageCriterion
                };

                try
                {
                    // Create the selector.
                    TrafficEstimatorSelector selector = new TrafficEstimatorSelector()
                    {
                        campaignEstimateRequests = new CampaignEstimateRequest[]
                        {
                            campaignEstimateRequest
                        },

                        // Optional: Request a list of campaign level estimates segmented by
                        // platform.
                        platformEstimateRequested = true
                    };

                    // Get traffic estimates.
                    TrafficEstimatorResult result = trafficEstimatorService.get(selector);

                    // Display traffic estimates.
                    if (result != null && result.campaignEstimates != null &&
                        result.campaignEstimates.Length > 0)
                    {
                        CampaignEstimate campaignEstimate = result.campaignEstimates[0];

                        // Display the campaign level estimates segmented by platform.
                        if (campaignEstimate.platformEstimates != null)
                        {
                            foreach (PlatformCampaignEstimate platformEstimate in campaignEstimate
                                .platformEstimates)
                            {
                                string platformMessage = string.Format(
                                    "Results for the platform with ID: " + "{0} and name : {1}.",
                                    platformEstimate.platform.id,
                                    platformEstimate.platform.platformName);

                                DisplayMeanEstimates(platformMessage, platformEstimate.minEstimate,
                                    platformEstimate.maxEstimate);
                            }
                        }

                        // Display the keyword estimates.
                        if (campaignEstimate.adGroupEstimates != null &&
                            campaignEstimate.adGroupEstimates.Length > 0)
                        {
                            AdGroupEstimate adGroupEstimate = campaignEstimate.adGroupEstimates[0];

                            if (adGroupEstimate.keywordEstimates != null)
                            {
                                for (int i = 0; i < adGroupEstimate.keywordEstimates.Length; i++)
                                {
                                    Keyword keyword = keywordEstimateRequests[i].keyword;
                                    KeywordEstimate keywordEstimate =
                                        adGroupEstimate.keywordEstimates[i];

                                    if (keywordEstimateRequests[i].isNegative)
                                    {
                                        continue;
                                    }

                                    string kwdMessage = string.Format(
                                        "Results for the keyword with text = '{0}' " +
                                        "and match type = '{1}':", keyword.text, keyword.matchType);
                                    DisplayMeanEstimates(kwdMessage, keywordEstimate.min,
                                        keywordEstimate.max);
                                }
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("No traffic estimates were returned.");
                    }

                    trafficEstimatorService.Close();
                }
                catch (Exception e)
                {
                    throw new System.ApplicationException("Failed to retrieve traffic estimates.",
                        e);
                }
            }
        }

        /// <summary>
        /// Displays the mean estimates.
        /// </summary>
        /// <param name="message">The message to display.</param>
        /// <param name="minEstimate">The minimum stats estimate.</param>
        /// <param name="maxEstimate">The maximum stats estimate.</param>
        private void DisplayMeanEstimates(string message, StatsEstimate minEstimate,
            StatsEstimate maxEstimate)
        {
            // Find the mean of the min and max values.
            long meanAverageCpc = 0;
            double meanAveragePosition = 0;
            float meanClicks = 0;
            long meanTotalCost = 0;

            if (minEstimate != null && maxEstimate != null)
            {
                if (minEstimate.averageCpc != null && maxEstimate.averageCpc != null)
                {
                    meanAverageCpc = (minEstimate.averageCpc.microAmount +
                        maxEstimate.averageCpc.microAmount) / 2;
                }

                if (minEstimate.averagePositionSpecified && maxEstimate.averagePositionSpecified)
                {
                    meanAveragePosition =
                        (minEstimate.averagePosition + maxEstimate.averagePosition) / 2;
                }

                if (minEstimate.clicksPerDaySpecified && maxEstimate.clicksPerDaySpecified)
                {
                    meanClicks = (minEstimate.clicksPerDay + maxEstimate.clicksPerDay) / 2;
                }

                if (minEstimate.totalCost != null && maxEstimate.totalCost != null)
                {
                    meanTotalCost = (minEstimate.totalCost.microAmount +
                        maxEstimate.totalCost.microAmount) / 2;
                }
            }

            Console.WriteLine(message);
            Console.WriteLine("  Estimated average CPC: {0}", meanAverageCpc);
            Console.WriteLine("  Estimated ad position: {0:0.00}", meanAveragePosition);
            Console.WriteLine("  Estimated daily clicks: {0}", meanClicks);
            Console.WriteLine("  Estimated daily cost: {0}", meanTotalCost);
        }
    }
}

Get bid landscapes for an ad group

// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     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.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.v201809;

using System;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201809
{
    /// <summary>
    /// This code example gets bid landscapes for an ad group. To get ad groups,
    /// run GetAdGroups.cs.
    /// </summary>
    public class GetAdGroupBidSimulations : 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)
        {
            GetAdGroupBidSimulations codeExample = new GetAdGroupBidSimulations();
            Console.WriteLine(codeExample.Description);
            try
            {
                long adGroupId = long.Parse("INSERT_ADGROUP_ID_HERE");
                codeExample.Run(new AdWordsUser(), adGroupId);
            }
            catch (Exception e)
            {
                Console.WriteLine("An exception occurred while running this code example. {0}",
                    ExampleUtilities.FormatException(e));
            }
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get
            {
                return "This code example gets bid landscapes for an ad group. " +
                    "To get ad groups, run GetAdGroups.cs";
            }
        }

        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">Id of the ad group for which bid simulations are
        /// retrieved.</param>
        public void Run(AdWordsUser user, long adGroupId)
        {
            using (DataService dataService =
                (DataService) user.GetService(AdWordsService.v201809.DataService))
            {
                // Create the selector.
                Selector selector = new Selector()
                {
                    fields = new string[]
                    {
                        AdGroupBidLandscape.Fields.AdGroupId,
                        AdGroupBidLandscape.Fields.LandscapeType,
                        AdGroupBidLandscape.Fields.LandscapeCurrent,
                        AdGroupBidLandscape.Fields.StartDate,
                        AdGroupBidLandscape.Fields.EndDate,
                        BidLandscapeLandscapePoint.Fields.Bid,
                        BidLandscapeLandscapePoint.Fields.LocalClicks,
                        BidLandscapeLandscapePoint.Fields.LocalCost,
                        BidLandscapeLandscapePoint.Fields.LocalImpressions
                    },
                    predicates = new Predicate[]
                    {
                        Predicate.Equals(AdGroupBidLandscape.Fields.AdGroupId, adGroupId)
                    }
                };

                try
                {
                    // Get bid landscape for ad group.
                    AdGroupBidLandscapePage page = dataService.getAdGroupBidLandscape(selector);
                    if (page != null && page.entries != null && page.entries.Length > 0)
                    {
                        foreach (AdGroupBidLandscape bidLandscape in page.entries)
                        {
                            Console.WriteLine(
                                "Found ad group bid landscape with ad group id '{0}', " +
                                "type '{1}', current: '{2}', start date '{3}', " +
                                "end date '{4}', and landscape points",
                                bidLandscape.adGroupId, bidLandscape.type,
                                bidLandscape.landscapeCurrent, bidLandscape.startDate,
                                bidLandscape.endDate);
                            foreach (BidLandscapeLandscapePoint point in bidLandscape
                                .landscapePoints)
                            {
                                Console.WriteLine(
                                    "- bid: {0} => clicks: {1}, cost: {2}, impressions: {3}",
                                    point.bid.microAmount, point.clicks, point.cost.microAmount,
                                    point.impressions);
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("No ad group bid landscapes were found.");
                    }
                }
                catch (Exception e)
                {
                    throw new System.ApplicationException("Failed to get ad group bid landscapes.",
                        e);
                }
            }
        }
    }
}

Get all mobile bid modifier landscapes for a campaign

// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     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.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.v201809;

using System;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201809
{
    /// <summary>
    /// This code example gets all available campaign mobile bid modifier
    /// landscapes for a given campaign. To get campaigns, run GetCampaigns.cs.
    /// </summary>
    public class GetCampaignCriterionBidModifierSimulations : 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)
        {
            GetCampaignCriterionBidModifierSimulations codeExample =
                new GetCampaignCriterionBidModifierSimulations();
            Console.WriteLine(codeExample.Description);
            try
            {
                long campaignId = long.Parse("INSERT_CAMPAIGN_ID_HERE");
                codeExample.Run(new AdWordsUser(), campaignId);
            }
            catch (Exception e)
            {
                Console.WriteLine("An exception occurred while running this code example. {0}",
                    ExampleUtilities.FormatException(e));
            }
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get
            {
                return "This code example gets all available campaign mobile bid modifier " +
                    "landscapes for a given campaign. To get campaigns, run GetCampaigns.cs.";
            }
        }

        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaignId">Id of the campaign for which bid simulations are
        /// retrieved.</param>
        public void Run(AdWordsUser user, long campaignId)
        {
            using (DataService dataService =
                (DataService) user.GetService(AdWordsService.v201809.DataService))
            {
                // Create selector.
                Selector selector = new Selector()
                {
                    fields = new string[]
                    {
                        CriterionBidLandscape.Fields.CampaignId,
                        CriterionBidLandscape.Fields.CriterionId,
                        CriterionBidLandscape.Fields.StartDate,
                        CriterionBidLandscape.Fields.EndDate,
                        BidLandscapeLandscapePoint.Fields.LocalClicks,
                        BidLandscapeLandscapePoint.Fields.LocalCost,
                        BidLandscapeLandscapePoint.Fields.LocalImpressions,
                        BidLandscapeLandscapePoint.Fields.TotalLocalClicks,
                        BidLandscapeLandscapePoint.Fields.TotalLocalCost,
                        BidLandscapeLandscapePoint.Fields.TotalLocalImpressions,
                        BidLandscapeLandscapePoint.Fields.RequiredBudget,
                        BidLandscapeLandscapePoint.Fields.BidModifier,
                    },
                    predicates = new Predicate[]
                    {
                        Predicate.Equals(CriterionBidLandscape.Fields.CampaignId, campaignId)
                    },
                    paging = Paging.Default
                };

                int landscapePointsInLastResponse = 0;
                int landscapePointsFound = 0;

                try
                {
                    CriterionBidLandscapePage page = null;

                    do
                    {
                        // When retrieving bid landscape, page.totalNumEntities cannot be used to
                        // determine if there are more entries, since it shows only the total number
                        // of bid landscapes and not the number of bid landscape points. So you need
                        // to iterate until you no longer get back any bid landscapes.

                        // Get bid landscape for campaign.
                        page = dataService.getCampaignCriterionBidLandscape(selector);

                        landscapePointsInLastResponse = 0;

                        if (page != null && page.entries != null)
                        {
                            foreach (CriterionBidLandscape bidLandscape in page.entries)
                            {
                                Console.WriteLine(
                                    "Found campaign-level criterion bid modifier landscapes for " +
                                    "criterion with ID {0}, start date '{1}', end date '{2}', " +
                                    "and landscape points:",bidLandscape.criterionId,
                                    bidLandscape.startDate, bidLandscape.endDate);

                                foreach (BidLandscapeLandscapePoint point in bidLandscape
                                    .landscapePoints)
                                {
                                    Console.WriteLine(
                                        "- bid modifier: {0:0.00} => clicks: {1}, cost: {2}, " +
                                        "impressions: {3}, total clicks: {4}, total cost: {5}, " +
                                        "total impressions: {6}, and required budget: {7}",
                                        point.bidModifier, point.clicks, point.cost.microAmount,
                                        point.impressions, point.totalLocalClicks,
                                        point.totalLocalCost.microAmount,
                                        point.totalLocalImpressions,
                                        point.requiredBudget.microAmount);
                                    landscapePointsInLastResponse++;
                                    landscapePointsFound++;
                                }
                            }
                        }

                        // Offset by the number of landscape points, NOT the number
                        // of entries (bid landscapes) in the last response.
                        selector.paging.IncreaseOffsetBy(landscapePointsInLastResponse);
                    } while (landscapePointsInLastResponse > 0);

                    Console.WriteLine("Number of bid landscape points found: {0}",
                        landscapePointsFound);
                }
                catch (Exception e)
                {
                    throw new System.ApplicationException("Failed to get campaign bid landscapes.",
                        e);
                }
            }
        }
    }
}

Get a bid landscape for an ad group and criterion

// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     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.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.Util.Reports.v201809;
using Google.Api.Ads.AdWords.v201809;

using System;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201809
{
    /// <summary>
    /// This code example gets a bid landscape for an ad group and a keyword.
    /// To get ad groups, run GetAdGroups.cs. To get keywords, run
    /// GetKeywords.cs.
    /// </summary>
    public class GetKeywordBidSimulations : 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)
        {
            GetKeywordBidSimulations codeExample = new GetKeywordBidSimulations();
            Console.WriteLine(codeExample.Description);
            try
            {
                long adGroupId = long.Parse("INSERT_ADGROUP_ID_HERE");
                long keywordId = long.Parse("INSERT_KEYWORD_ID_HERE");
                codeExample.Run(new AdWordsUser(), adGroupId, keywordId);
            }
            catch (Exception e)
            {
                Console.WriteLine("An exception occurred while running this code example. {0}",
                    ExampleUtilities.FormatException(e));
            }
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get
            {
                return "This code example gets a bid landscape for an ad group and a keyword. " +
                    "To get ad groups, run GetAdGroups.cs. To get keywords, run GetKeywords.cs.";
            }
        }

        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">Id of the ad group for which keyword bid
        /// simulations are retrieved.</param>
        /// <param name="keywordId">Id of the keyword for which bid simulations are
        /// retrieved.</param>
        public void Run(AdWordsUser user, long adGroupId, long keywordId)
        {
            using (DataService dataService =
                (DataService) user.GetService(AdWordsService.v201809.DataService))
            {

                // Create the query.
                SelectQuery query = new SelectQueryBuilder()
                    .Select(CriterionBidLandscape.Fields.AdGroupId,
                        CriterionBidLandscape.Fields.CriterionId,
                        CriterionBidLandscape.Fields.StartDate,
                        CriterionBidLandscape.Fields.EndDate,
                        BidLandscapeLandscapePoint.Fields.Bid,
                        BidLandscapeLandscapePoint.Fields.LocalClicks,
                        BidLandscapeLandscapePoint.Fields.LocalCost,
                        BidLandscapeLandscapePoint.Fields.LocalImpressions,
                        BidLandscapeLandscapePoint.Fields.BiddableConversions,
                        BidLandscapeLandscapePoint.Fields.BiddableConversionsValue)
                    .Where(CriterionBidLandscape.Fields.AdGroupId).Equals(adGroupId)
                    .Where(CriterionBidLandscape.Fields.CriterionId).Equals(keywordId)
                    .DefaultLimit().Build();

                CriterionBidLandscapePage page = new CriterionBidLandscapePage();
                int landscapePointsFound = 0;

                try
                {
                    do
                    {
                        // Get bid landscape for keywords.
                        page = dataService.queryCriterionBidLandscape(query);

                        // Display bid landscapes.
                        if (page != null && page.entries != null)
                        {
                            foreach (CriterionBidLandscape bidLandscape in page.entries)
                            {
                                Console.WriteLine(
                                    "Found criterion bid landscape with ad group id '{0}', " +
                                    "keyword id '{1}', start date '{2}', end date '{3}', and " +
                                    "landscape points:",
                                    bidLandscape.adGroupId, bidLandscape.criterionId,
                                    bidLandscape.startDate, bidLandscape.endDate);
                                foreach (BidLandscapeLandscapePoint bidLandscapePoint in
                                    bidLandscape.landscapePoints)
                                {
                                    Console.WriteLine(
                                        "- bid: {0} => clicks: {1}, cost: {2}, impressions: {3}, " +
                                        "biddable conversions: {4:0.00}, biddable conversions " +
                                        "value:{5:0.00}",
                                        bidLandscapePoint.bid.microAmount, bidLandscapePoint.clicks,
                                        bidLandscapePoint.cost.microAmount,
                                        bidLandscapePoint.impressions,
                                        bidLandscapePoint.biddableConversions,
                                        bidLandscapePoint.biddableConversionsValue);
                                    landscapePointsFound++;
                                }
                            }
                        }

                        query.NextPage(page);
                    } while (query.HasNextPage(page));

                    Console.WriteLine("Number of keyword bid landscape points found: {0}",
                        landscapePointsFound);
                }
                catch (Exception e)
                {
                    throw new System.ApplicationException(
                        "Failed to retrieve keyword bid landscapes.", e);
                }
            }
        }
    }
}

Get keywords related to a seed keyword

// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     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.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.v201809;

using System;
using System.Collections.Generic;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201809
{
    /// <summary>
    /// This code example retrieves keywords that are related to a given keyword.
    /// </summary>
    public class GetKeywordIdeas : 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)
        {
            GetKeywordIdeas codeExample = new GetKeywordIdeas();
            Console.WriteLine(codeExample.Description);
            try
            {
                long adGroupId = long.Parse("INSERT_ADGROUP_ID_HERE");
                codeExample.Run(new AdWordsUser(), adGroupId);
            }
            catch (Exception e)
            {
                Console.WriteLine("An exception occurred while running this code example. {0}",
                    ExampleUtilities.FormatException(e));
            }
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get
            {
                return "This code example retrieves keywords that are related to a given keyword.";
            }
        }

        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">ID of the ad group to use for generating ideas.</param>
        public void Run(AdWordsUser user, long? adGroupId)
        {
            using (TargetingIdeaService targetingIdeaService =
                (TargetingIdeaService) user.GetService(AdWordsService.v201809.TargetingIdeaService))
            {
                // Create selector.
                TargetingIdeaSelector selector = new TargetingIdeaSelector
                {
                    requestType = RequestType.IDEAS,
                    ideaType = IdeaType.KEYWORD,
                    requestedAttributeTypes = new AttributeType[]
                    {
                        AttributeType.KEYWORD_TEXT,
                        AttributeType.SEARCH_VOLUME,
                        AttributeType.AVERAGE_CPC,
                        AttributeType.COMPETITION,
                        AttributeType.CATEGORY_PRODUCTS_AND_SERVICES
                    }
                };


                List<SearchParameter> searchParameters = new List<SearchParameter>();

                // Create related to query search parameter.
                RelatedToQuerySearchParameter relatedToQuerySearchParameter =
                    new RelatedToQuerySearchParameter
                    {
                        queries = new string[]
                        {
                            "bakery",
                            "pastries",
                            "birthday cake"
                        }
                    };
                searchParameters.Add(relatedToQuerySearchParameter);

                // Add a language search parameter (optional).
                // The ID can be found in the documentation:
                //   https://developers.google.com/adwords/api/docs/appendix/languagecodes
                LanguageSearchParameter languageParameter = new LanguageSearchParameter();
                Language english = new Language
                {
                    id = 1000
                };
                languageParameter.languages = new Language[]
                {
                    english
                };
                searchParameters.Add(languageParameter);

                // Add network search parameter (optional).
                NetworkSetting networkSetting = new NetworkSetting
                {
                    targetGoogleSearch = true,
                    targetSearchNetwork = false,
                    targetContentNetwork = false,
                    targetPartnerSearchNetwork = false
                };

                NetworkSearchParameter networkSearchParameter = new NetworkSearchParameter
                {
                    networkSetting = networkSetting
                };
                searchParameters.Add(networkSearchParameter);

                // Optional: Use an existing ad group to generate ideas.
                if (adGroupId != null)
                {
                    SeedAdGroupIdSearchParameter seedAdGroupIdSearchParameter =
                        new SeedAdGroupIdSearchParameter
                        {
                            adGroupId = adGroupId.Value
                        };
                    searchParameters.Add(seedAdGroupIdSearchParameter);
                }

                // Set the search parameters.
                selector.searchParameters = searchParameters.ToArray();

                // Set selector paging (required for targeting idea service).
                selector.paging = Paging.Default;

                TargetingIdeaPage page = new TargetingIdeaPage();

                try
                {
                    int i = 0;
                    do
                    {
                        // Get related keywords.
                        page = targetingIdeaService.get(selector);

                        // Display related keywords.
                        if (page.entries != null && page.entries.Length > 0)
                        {
                            foreach (TargetingIdea targetingIdea in page.entries)
                            {
                                Dictionary<AttributeType, Google.Api.Ads.AdWords.v201809.Attribute>
                                    ideas = targetingIdea.data.ToDict();

                                string keyword =
                                    (ideas[AttributeType.KEYWORD_TEXT] as StringAttribute).value;
                                IntegerSetAttribute categorySet =
                                    ideas[AttributeType.CATEGORY_PRODUCTS_AND_SERVICES] as
                                        IntegerSetAttribute;

                                string categories = "";

                                if (categorySet != null && categorySet.value != null)
                                {
                                    categories = string.Join(", ", categorySet.value);
                                }

                                long averageMonthlySearches =
                                    (ideas[AttributeType.SEARCH_VOLUME] as LongAttribute).value;

                                Money averageCpc =
                                    (ideas[AttributeType.AVERAGE_CPC] as MoneyAttribute).value;
                                double competition =
                                    (ideas[AttributeType.COMPETITION] as DoubleAttribute).value;
                                Console.WriteLine(
                                    "Keyword with text '{0}', average monthly search volume {1}, " +
                                    "average CPC {2}, and competition {3:F2} was found with " +
                                    "categories: {4}", keyword, averageMonthlySearches,
                                    averageCpc?.microAmount, competition, categories);

                                Console.WriteLine(
                                    "Keyword with text '{0}', and average monthly search volume " +
                                    "'{1}' was found with categories: {2}", keyword,
                                    averageMonthlySearches, categories);
                                i++;
                            }
                        }

                        selector.paging.IncreaseOffset();
                    } while (selector.paging.startIndex < page.totalNumEntries);

                    Console.WriteLine("Number of related keywords found: {0}",
                        page.totalNumEntries);
                }
                catch (Exception e)
                {
                    throw new System.ApplicationException("Failed to retrieve related keywords.",
                        e);
                }
            }
        }
    }
}

Enviar comentarios sobre…

¿Necesitas ayuda? Visita nuestra página de asistencia.