Account Management Samples

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

Create new account under an AdWords manager

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

"""This example illustrates how to create an account.

Note by default this account will only be accessible via its parent AdWords
manager account..

The LoadFromStorage method is pulling credentials and properties from a
"googleads.yaml" file. By default, it looks for this file in your home
directory. For more information, see the "Caching authentication information"
section of our README.

"""


from datetime import datetime
from googleads import adwords


def main(client):
  # Initialize appropriate service.
  managed_customer_service = client.GetService(
      'ManagedCustomerService', version='v201708')

  today = datetime.today().strftime('%Y%m%d %H:%M:%S')
  # Construct operations and add campaign.
  operations = [{
      'operator': 'ADD',
      'operand': {
          'name': 'Account created with ManagedCustomerService on %s' % today,
          'currencyCode': 'EUR',
          'dateTimeZone': 'Europe/London',
      }
  }]

  # Create the account. It is possible to create multiple accounts with one
  # request by sending an array of operations.
  accounts = managed_customer_service.mutate(operations)

  # Display results.
  for account in accounts['value']:
    print ('Account with customer ID "%s" was successfully created.'
           % account['customerId'])


if __name__ == '__main__':
  # Initialize client object.
  adwords_client = adwords.AdWordsClient.LoadFromStorage()
  main(adwords_client)

Get all account changes during the past 24 hours

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

"""This example gets the changes in the account during the last 24 hours.

The LoadFromStorage method is pulling credentials and properties from a
"googleads.yaml" file. By default, it looks for this file in your home
directory. For more information, see the "Caching authentication information"
section of our README.

"""


import datetime
from googleads import adwords


def main(client):
  # Initialize appropriate service.
  customer_sync_service = client.GetService(
      'CustomerSyncService', version='v201708')
  campaign_service = client.GetService('CampaignService', version='v201708')

  # Construct selector and get all campaigns.
  selector = {
      'fields': ['Id', 'Name', 'Status']
  }
  campaigns = campaign_service.get(selector)
  campaign_ids = []
  if 'entries' in campaigns:
    for campaign in campaigns['entries']:
      campaign_ids.append(campaign['id'])
  else:
    print 'No campaigns were found.'
    return

  # Construct selector and get all changes.
  today = datetime.datetime.today()
  yesterday = today - datetime.timedelta(1)
  selector = {
      'dateTimeRange': {
          'min': yesterday.strftime('%Y%m%d %H%M%S'),
          'max': today.strftime('%Y%m%d %H%M%S')
      },
      'campaignIds': campaign_ids
  }
  account_changes = customer_sync_service.get(selector)

  # Display results.
  if account_changes:
    if 'lastChangeTimestamp' in account_changes:
      print 'Most recent changes: %s' % account_changes['lastChangeTimestamp']
    if account_changes['changedCampaigns']:
      for data in account_changes['changedCampaigns']:
        print ('Campaign with id "%s" has change status "%s".'
               % (data['campaignId'], data['campaignChangeStatus']))
        if (data['campaignChangeStatus'] != 'NEW' and
            data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'):
          if 'addedCampaignCriteria' in data:
            print ('  Added campaign criteria: %s' %
                   data['addedCampaignCriteria'])
          if 'removedCampaignCriteria' in data:
            print ('  Removed campaign criteria: %s' %
                   data['removedCampaignCriteria'])
          if 'changedAdGroups' in data:
            for ad_group_data in data['changedAdGroups']:
              print ('  Ad group with id "%s" has change status "%s".'
                     % (ad_group_data['adGroupId'],
                        ad_group_data['adGroupChangeStatus']))
              if ad_group_data['adGroupChangeStatus'] != 'NEW':
                if 'changedAds' in ad_group_data:
                  print '    Changed ads: %s' % ad_group_data['changedAds']
                if 'changedCriteria' in ad_group_data:
                  print ('    Changed criteria: %s' %
                         ad_group_data['changedCriteria'])
                if 'removedCriteria' in ad_group_data:
                  print ('    Removed criteria: %s' %
                         ad_group_data['removedCriteria'])
  else:
    print 'No changes were found.'


if __name__ == '__main__':
  # Initialize client object.
  adwords_client = adwords.AdWordsClient.LoadFromStorage()
  main(adwords_client)

Get the account hierarchy under the current account

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

"""This example gets the account hierarchy under the current account.

The LoadFromStorage method is pulling credentials and properties from a
"googleads.yaml" file. By default, it looks for this file in your home
directory. For more information, see the "Caching authentication information"
section of our README.

"""
from googleads import adwords


PAGE_SIZE = 500


def DisplayAccountTree(account, accounts, links, depth=0):
  """Displays an account tree.

  Args:
    account: dict The account to display.
    accounts: dict Map from customerId to account.
    links: dict Map from customerId to child links.
    depth: int Depth of the current account in the tree.
  """
  prefix = '-' * depth * 2
  print '%s%s, %s' % (prefix, account['customerId'], account['name'])
  if account['customerId'] in links:
    for child_link in links[account['customerId']]:
      child_account = accounts[child_link['clientCustomerId']]
      DisplayAccountTree(child_account, accounts, links, depth + 1)


def main(client):
  # Initialize appropriate service.
  managed_customer_service = client.GetService(
      'ManagedCustomerService', version='v201708')

  # Construct selector to get all accounts.
  offset = 0
  selector = {
      'fields': ['CustomerId', 'Name'],
      'paging': {
          'startIndex': str(offset),
          'numberResults': str(PAGE_SIZE)
      }
  }
  more_pages = True
  accounts = {}
  child_links = {}
  parent_links = {}
  root_account = None

  while more_pages:
    # Get serviced account graph.
    page = managed_customer_service.get(selector)
    if 'entries' in page and page['entries']:
      # Create map from customerId to parent and child links.
      if 'links' in page:
        for link in page['links']:
          if link['managerCustomerId'] not in child_links:
            child_links[link['managerCustomerId']] = []
          child_links[link['managerCustomerId']].append(link)
          if link['clientCustomerId'] not in parent_links:
            parent_links[link['clientCustomerId']] = []
          parent_links[link['clientCustomerId']].append(link)
      # Map from customerID to account.
      for account in page['entries']:
        accounts[account['customerId']] = account
    offset += PAGE_SIZE
    selector['paging']['startIndex'] = str(offset)
    more_pages = offset < int(page['totalNumEntries'])

  # Find the root account.
  for customer_id in accounts:
    if customer_id not in parent_links:
      root_account = accounts[customer_id]

  # Display account tree.
  if root_account:
    print 'CustomerId, Name'
    DisplayAccountTree(root_account, accounts, child_links, 0)
  else:
    print 'Unable to determine a root account'


if __name__ == '__main__':
  # Initialize client object.
  adwords_client = adwords.AdWordsClient.LoadFromStorage()
  main(adwords_client)

Send feedback about...

AdWords API
AdWords API
Need help? Visit our support page.