The AdWords API will sunset on April 27, 2022. Migrate to the Google Ads API to take advantage of the latest Google Ads features.

Account Management Samples

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

Accept an invitation for linking to a manager account

// 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 accepts a pending invitation to link your AdWords
    /// account to a Google Merchant Center account.
    /// </summary>
    public class AcceptServiceLink : 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)
        {
            AcceptServiceLink codeExample = new AcceptServiceLink();
            Console.WriteLine(codeExample.Description);
            try
            {
                long serviceLinkId = long.Parse("INSERT_SERVICE_LINK_ID_HERE");
                codeExample.Run(new AdWordsUser(), serviceLinkId);
            }
            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 accepts a pending invitation to link your AdWords account " +
                    "to a Google Merchant Center account.";
            }
        }

        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="serviceLinkId">The service link ID to accept.</param>
        public void Run(AdWordsUser user, long serviceLinkId)
        {
            using (CustomerService customerService =
                (CustomerService) user.GetService(AdWordsService.v201809.CustomerService))
            {
                // Create the operation to set the status to ACTIVE.
                ServiceLinkOperation op = new ServiceLinkOperation
                {
                    @operator = Operator.SET
                };
                ServiceLink serviceLink = new ServiceLink
                {
                    serviceLinkId = serviceLinkId,
                    serviceType = ServiceType.MERCHANT_CENTER,
                    linkStatus = ServiceLinkLinkStatus.ACTIVE
                };
                op.operand = serviceLink;

                try
                {
                    // Update the service link.
                    ServiceLink[] mutatedServiceLinks = customerService.mutateServiceLinks(
                        new ServiceLinkOperation[]
                        {
                            op
                        });

                    // Display the results.
                    foreach (ServiceLink mutatedServiceLink in mutatedServiceLinks)
                    {
                        Console.WriteLine(
                            "Service link with service link ID {0}, type '{1}' updated to " +
                            "status: {2}.", mutatedServiceLink.serviceLinkId,
                            mutatedServiceLink.serviceType, mutatedServiceLink.linkStatus);
                    }

                }
                catch (Exception e)
                {
                    throw new System.ApplicationException("Failed to update service link.", e);
                }
            }
        }
    }
}

Create a new account under an AdWords manager

// 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 illustrates how to create an account. Note by default,
    /// this account will only be accessible via its parent AdWords manager
    /// account.
    /// </summary>
    public class CreateAccount : 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)
        {
            CreateAccount codeExample = new CreateAccount();
            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 illustrates how to create an account. Note by default " +
                    "this account will only be accessible via its parent AdWords manager account.";
            }
        }

        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        public void Run(AdWordsUser user)
        {
            using (ManagedCustomerService managedCustomerService =
                (ManagedCustomerService) user.GetService(AdWordsService.v201809
                    .ManagedCustomerService))
            {
                // Create account.
                ManagedCustomer customer = new ManagedCustomer
                {
                    name = "Customer created with ManagedCustomerService on " +
                        new DateTime().ToString(),
                    currencyCode = "EUR",
                    dateTimeZone = "Europe/London"
                };

                // Create operations.
                ManagedCustomerOperation operation = new ManagedCustomerOperation
                {
                    operand = customer,
                    @operator = Operator.ADD
                };

                try
                {
                    ManagedCustomerOperation[] operations = new ManagedCustomerOperation[]
                    {
                        operation
                    };
                    // Add account.
                    ManagedCustomerReturnValue result = managedCustomerService.mutate(operations);

                    // Display accounts.
                    if (result.value != null && result.value.Length > 0)
                    {
                        ManagedCustomer customerResult = result.value[0];
                        Console.WriteLine("Account with customer ID \"{0}\" was created.",
                            customerResult.customerId);
                    }
                    else
                    {
                        Console.WriteLine("No accounts were created.");
                    }
                }
                catch (Exception e)
                {
                    throw new System.ApplicationException("Failed to create accounts.", e);
                }
            }
        }
    }
}

Get all account changes during the past 24 hours

// 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;
using System.Text;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201809
{
    /// <summary>
    /// This code example gets the changes in the account during the last 24
    /// hours.
    /// </summary>
    public class GetAccountChanges : 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)
        {
            GetAccountChanges codeExample = new GetAccountChanges();
            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 the changes in the account during the last 24 hours.";
            }
        }

        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        public void Run(AdWordsUser user)
        {
            using (CustomerSyncService customerSyncService =
                (CustomerSyncService) user.GetService(AdWordsService.v201809.CustomerSyncService))
            {
                // The date time string should be of the form  yyyyMMdd HHmmss zzz
                string minDateTime =
                    DateTime.Now.AddDays(-1).ToUniversalTime().ToString("yyyyMMdd HHmmss") + " UTC";
                string maxDateTime = DateTime.Now.ToUniversalTime().ToString("yyyyMMdd HHmmss") +
                    " UTC";

                // Create date time range.
                DateTimeRange dateTimeRange = new DateTimeRange
                {
                    min = minDateTime,
                    max = maxDateTime
                };

                try
                {
                    // Create the selector.
                    CustomerSyncSelector selector = new CustomerSyncSelector
                    {
                        dateTimeRange = dateTimeRange,
                        campaignIds = GetAllCampaignIds(user)
                    };

                    // Get all account changes for campaign.
                    CustomerChangeData accountChanges = customerSyncService.get(selector);

                    // Display the changes.
                    if (accountChanges != null && accountChanges.changedCampaigns != null)
                    {
                        Console.WriteLine("Displaying changes up to: {0}",
                            accountChanges.lastChangeTimestamp);
                        foreach (CampaignChangeData campaignChanges in accountChanges
                            .changedCampaigns)
                        {
                            Console.WriteLine("Campaign with id \"{0}\" was changed:",
                                campaignChanges.campaignId);
                            Console.WriteLine("  Campaign changed status: {0}",
                                campaignChanges.campaignChangeStatus);
                            if (campaignChanges.campaignChangeStatus != ChangeStatus.NEW)
                            {
                                Console.WriteLine("  Added campaign criteria: {0}",
                                    GetFormattedList(campaignChanges.addedCampaignCriteria));
                                Console.WriteLine("  Removed campaign criteria: {0}",
                                    GetFormattedList(campaignChanges.removedCampaignCriteria));

                                if (campaignChanges.changedAdGroups != null)
                                {
                                    foreach (AdGroupChangeData adGroupChanges in campaignChanges
                                        .changedAdGroups)
                                    {
                                        Console.WriteLine("  Ad group with id \"{0}\" was changed:",
                                            adGroupChanges.adGroupId);
                                        Console.WriteLine("    Ad group changed status: {0}",
                                            adGroupChanges.adGroupChangeStatus);
                                        if (adGroupChanges.adGroupChangeStatus != ChangeStatus.NEW)
                                        {
                                            Console.WriteLine("    Ads changed: {0}",
                                                GetFormattedList(adGroupChanges.changedAds));
                                            Console.WriteLine("    Criteria changed: {0}",
                                                GetFormattedList(adGroupChanges.changedCriteria));
                                            Console.WriteLine("    Criteria removed: {0}",
                                                GetFormattedList(adGroupChanges.removedCriteria));
                                        }
                                    }
                                }
                            }

                            Console.WriteLine();
                        }
                    }
                    else
                    {
                        Console.WriteLine("No account changes were found.");
                    }
                }
                catch (Exception e)
                {
                    throw new System.ApplicationException("Failed to get account changes.", e);
                }
            }
        }

        /// <summary>
        /// Formats a list of ids as a comma separated string.
        /// </summary>
        /// <param name="ids">The list of ids.</param>
        /// <returns>The comma separed formatted string, enclosed in square braces.
        /// </returns>
        private string GetFormattedList(long[] ids)
        {
            StringBuilder builder = new StringBuilder();
            if (ids != null)
            {
                foreach (long id in ids)
                {
                    builder.AppendFormat("{0}, ", id);
                }
            }

            return "[" + builder.ToString().TrimEnd(',', ' ') + "]";
        }

        /// <summary>
        /// Gets all campaign ids in the account.
        /// </summary>
        /// <param name="user">The user for which campaigns are retrieved.</param>
        /// <returns>The list of campaign ids.</returns>
        private long[] GetAllCampaignIds(AdWordsUser user)
        {
            // Get the CampaignService.
            using (CampaignService campaignService =
                (CampaignService) user.GetService(AdWordsService.v201809.CampaignService))
            {
                List<long> allCampaigns = new List<long>();

                // Create the selector.
                Selector selector = new Selector()
                {
                    fields = new string[]
                    {
                        Campaign.Fields.Id
                    }
                };

                // Get all campaigns.
                CampaignPage page = campaignService.get(selector);

                // Return the results.
                if (page != null && page.entries != null)
                {
                    foreach (Campaign campaign in page.entries)
                    {
                        allCampaigns.Add(campaign.id);
                    }
                }

                return allCampaigns.ToArray();
            }
        }
    }
}

Get the account hierarchy under the current account

// 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;
using System.Text;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201809
{
    /// <summary>
    /// This code example illustrates how to retrieve the account hierarchy under
    /// an account. This code example won't work with Test Accounts. See
    /// https://developers.google.com/adwords/api/docs/test-accounts
    /// </summary>
    public class GetAccountHierarchy : 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)
        {
            GetAccountHierarchy codeExample = new GetAccountHierarchy();
            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 illustrates how to retrieve the account hierarchy under" +
                    " an account. This code example won't work with Test Accounts. See " +
                    "https://developers.google.com/adwords/api/docs/test-accounts";
            }
        }

        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        public void Run(AdWordsUser user)
        {
            using (ManagedCustomerService managedCustomerService =
                (ManagedCustomerService) user.GetService(AdWordsService.v201809
                    .ManagedCustomerService))
            {
                // Create selector.
                Selector selector = new Selector
                {
                    fields = new string[]
                    {
                        ManagedCustomer.Fields.CustomerId,
                        ManagedCustomer.Fields.Name
                    },
                    paging = Paging.Default
                };

                // Map from customerId to customer node.
                Dictionary<long, ManagedCustomerTreeNode> customerIdToCustomerNode =
                    new Dictionary<long, ManagedCustomerTreeNode>();

                // Temporary cache to save links.
                List<ManagedCustomerLink> allLinks = new List<ManagedCustomerLink>();

                ManagedCustomerPage page = null;
                try
                {
                    do
                    {
                        page = managedCustomerService.get(selector);

                        if (page.entries != null)
                        {
                            // Create account tree nodes for each customer.
                            foreach (ManagedCustomer customer in page.entries)
                            {
                                ManagedCustomerTreeNode node = new ManagedCustomerTreeNode
                                {
                                    Account = customer
                                };
                                customerIdToCustomerNode.Add(customer.customerId, node);
                            }

                            if (page.links != null)
                            {
                                allLinks.AddRange(page.links);
                            }
                        }

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

                    // For each link, connect nodes in tree.
                    foreach (ManagedCustomerLink link in allLinks)
                    {
                        ManagedCustomerTreeNode managerNode =
                            customerIdToCustomerNode[link.managerCustomerId];
                        ManagedCustomerTreeNode childNode =
                            customerIdToCustomerNode[link.clientCustomerId];
                        childNode.ParentNode = managerNode;
                        if (managerNode != null)
                        {
                            managerNode.ChildAccounts.Add(childNode);
                        }
                    }

                    // Find the root account node in the tree.
                    ManagedCustomerTreeNode rootNode = null;
                    foreach (ManagedCustomerTreeNode node in customerIdToCustomerNode.Values)
                    {
                        if (node.ParentNode == null)
                        {
                            rootNode = node;
                            break;
                        }
                    }

                    // Display account tree.
                    Console.WriteLine("CustomerId, Name");
                    Console.WriteLine(rootNode.ToTreeString(0, new StringBuilder()));
                }
                catch (Exception e)
                {
                    throw new System.ApplicationException("Failed to create ad groups.", e);
                }
            }
        }

        /// <summary>
        /// Example implementation of a node that would exist in an account tree. 
        /// </summary>
        private class ManagedCustomerTreeNode
        {
            /// <summary>
            /// The parent node.
            /// </summary>
            private ManagedCustomerTreeNode parentNode;

            /// <summary>
            /// The account associated with this node.
            /// </summary>
            private ManagedCustomer account;

            /// <summary>
            /// The list of child accounts.
            /// </summary>
            private List<ManagedCustomerTreeNode> childAccounts =
                new List<ManagedCustomerTreeNode>();

            /// <summary>
            /// Gets or sets the parent node.
            /// </summary>
            public ManagedCustomerTreeNode ParentNode
            {
                get { return parentNode; }
                set { parentNode = value; }
            }

            /// <summary>
            /// Gets or sets the account.
            /// </summary>
            public ManagedCustomer Account
            {
                get { return account; }
                set { account = value; }
            }

            /// <summary>
            /// Gets the child accounts.
            /// </summary>
            public List<ManagedCustomerTreeNode> ChildAccounts
            {
                get { return childAccounts; }
            }

            /// <summary>
            /// Returns a <see cref="System.String"/> that represents this instance.
            /// </summary>
            /// <returns>
            /// A <see cref="System.String"/> that represents this instance.
            /// </returns>
            public override string ToString()
            {
                return string.Format("{0}, {1}", account.customerId, account.name);
            }

            /// <summary>
            /// Returns a string representation of the current level of the tree and
            /// recursively returns the string representation of the levels below it.
            /// </summary>
            /// <param name="depth">The depth of the node.</param>
            /// <param name="sb">The String Builder containing the tree
            /// representation.</param>
            /// <returns>The tree string representation.</returns>
            public StringBuilder ToTreeString(int depth, StringBuilder sb)
            {
                sb.Append('-', depth * 2);
                sb.Append(this);
                sb.AppendLine();
                foreach (ManagedCustomerTreeNode childAccount in childAccounts)
                {
                    childAccount.ToTreeString(depth + 1, sb);
                }

                return sb;
            }
        }
    }
}